Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/AST/ItaniumMangle.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// Implements C++ name mangling according to the Itanium C++ ABI,
10
// which is used in GCC 3.2 and newer (and many compilers that are
11
// ABI-compatible with GCC):
12
//
13
//   http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling
14
//
15
//===----------------------------------------------------------------------===//
16
17
#include "clang/AST/ASTContext.h"
18
#include "clang/AST/Attr.h"
19
#include "clang/AST/Decl.h"
20
#include "clang/AST/DeclCXX.h"
21
#include "clang/AST/DeclObjC.h"
22
#include "clang/AST/DeclOpenMP.h"
23
#include "clang/AST/DeclTemplate.h"
24
#include "clang/AST/Expr.h"
25
#include "clang/AST/ExprCXX.h"
26
#include "clang/AST/ExprConcepts.h"
27
#include "clang/AST/ExprObjC.h"
28
#include "clang/AST/Mangle.h"
29
#include "clang/AST/TypeLoc.h"
30
#include "clang/Basic/ABI.h"
31
#include "clang/Basic/DiagnosticAST.h"
32
#include "clang/Basic/Module.h"
33
#include "clang/Basic/SourceManager.h"
34
#include "clang/Basic/TargetInfo.h"
35
#include "clang/Basic/Thunk.h"
36
#include "llvm/ADT/StringExtras.h"
37
#include "llvm/Support/ErrorHandling.h"
38
#include "llvm/Support/raw_ostream.h"
39
#include "llvm/TargetParser/RISCVTargetParser.h"
40
#include <optional>
41
42
using namespace clang;
43
44
namespace {
45
46
0
static bool isLocalContainerContext(const DeclContext *DC) {
47
0
  return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
48
0
}
49
50
0
static const FunctionDecl *getStructor(const FunctionDecl *fn) {
51
0
  if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
52
0
    return ftd->getTemplatedDecl();
53
54
0
  return fn;
55
0
}
56
57
0
static const NamedDecl *getStructor(const NamedDecl *decl) {
58
0
  const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
59
0
  return (fn ? getStructor(fn) : decl);
60
0
}
61
62
0
static bool isLambda(const NamedDecl *ND) {
63
0
  const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
64
0
  if (!Record)
65
0
    return false;
66
67
0
  return Record->isLambda();
68
0
}
69
70
static const unsigned UnknownArity = ~0U;
71
72
class ItaniumMangleContextImpl : public ItaniumMangleContext {
73
  typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
74
  llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
75
  llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
76
  const DiscriminatorOverrideTy DiscriminatorOverride = nullptr;
77
  NamespaceDecl *StdNamespace = nullptr;
78
79
  bool NeedsUniqueInternalLinkageNames = false;
80
81
public:
82
  explicit ItaniumMangleContextImpl(
83
      ASTContext &Context, DiagnosticsEngine &Diags,
84
      DiscriminatorOverrideTy DiscriminatorOverride, bool IsAux = false)
85
      : ItaniumMangleContext(Context, Diags, IsAux),
86
69
        DiscriminatorOverride(DiscriminatorOverride) {}
87
88
  /// @name Mangler Entry Points
89
  /// @{
90
91
  bool shouldMangleCXXName(const NamedDecl *D) override;
92
0
  bool shouldMangleStringLiteral(const StringLiteral *) override {
93
0
    return false;
94
0
  }
95
96
  bool isUniqueInternalLinkageDecl(const NamedDecl *ND) override;
97
0
  void needsUniqueInternalLinkageNames() override {
98
0
    NeedsUniqueInternalLinkageNames = true;
99
0
  }
100
101
  void mangleCXXName(GlobalDecl GD, raw_ostream &) override;
102
  void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
103
                   raw_ostream &) override;
104
  void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
105
                          const ThisAdjustment &ThisAdjustment,
106
                          raw_ostream &) override;
107
  void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
108
                                raw_ostream &) override;
109
  void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
110
  void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
111
  void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
112
                           const CXXRecordDecl *Type, raw_ostream &) override;
113
  void mangleCXXRTTI(QualType T, raw_ostream &) override;
114
  void mangleCXXRTTIName(QualType T, raw_ostream &,
115
                         bool NormalizeIntegers) override;
116
  void mangleCanonicalTypeName(QualType T, raw_ostream &,
117
                               bool NormalizeIntegers) override;
118
119
  void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
120
  void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
121
  void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
122
  void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
123
  void mangleDynamicAtExitDestructor(const VarDecl *D,
124
                                     raw_ostream &Out) override;
125
  void mangleDynamicStermFinalizer(const VarDecl *D, raw_ostream &Out) override;
126
  void mangleSEHFilterExpression(GlobalDecl EnclosingDecl,
127
                                 raw_ostream &Out) override;
128
  void mangleSEHFinallyBlock(GlobalDecl EnclosingDecl,
129
                             raw_ostream &Out) override;
130
  void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
131
  void mangleItaniumThreadLocalWrapper(const VarDecl *D,
132
                                       raw_ostream &) override;
133
134
  void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
135
136
  void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) override;
137
138
  void mangleModuleInitializer(const Module *Module, raw_ostream &) override;
139
140
0
  bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
141
    // Lambda closure types are already numbered.
142
0
    if (isLambda(ND))
143
0
      return false;
144
145
    // Anonymous tags are already numbered.
146
0
    if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
147
0
      if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
148
0
        return false;
149
0
    }
150
151
    // Use the canonical number for externally visible decls.
152
0
    if (ND->isExternallyVisible()) {
153
0
      unsigned discriminator = getASTContext().getManglingNumber(ND, isAux());
154
0
      if (discriminator == 1)
155
0
        return false;
156
0
      disc = discriminator - 2;
157
0
      return true;
158
0
    }
159
160
    // Make up a reasonable number for internal decls.
161
0
    unsigned &discriminator = Uniquifier[ND];
162
0
    if (!discriminator) {
163
0
      const DeclContext *DC = getEffectiveDeclContext(ND);
164
0
      discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
165
0
    }
166
0
    if (discriminator == 1)
167
0
      return false;
168
0
    disc = discriminator-2;
169
0
    return true;
170
0
  }
171
172
0
  std::string getLambdaString(const CXXRecordDecl *Lambda) override {
173
    // This function matches the one in MicrosoftMangle, which returns
174
    // the string that is used in lambda mangled names.
175
0
    assert(Lambda->isLambda() && "RD must be a lambda!");
176
0
    std::string Name("<lambda");
177
0
    Decl *LambdaContextDecl = Lambda->getLambdaContextDecl();
178
0
    unsigned LambdaManglingNumber = Lambda->getLambdaManglingNumber();
179
0
    unsigned LambdaId;
180
0
    const ParmVarDecl *Parm = dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
181
0
    const FunctionDecl *Func =
182
0
        Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
183
184
0
    if (Func) {
185
0
      unsigned DefaultArgNo =
186
0
          Func->getNumParams() - Parm->getFunctionScopeIndex();
187
0
      Name += llvm::utostr(DefaultArgNo);
188
0
      Name += "_";
189
0
    }
190
191
0
    if (LambdaManglingNumber)
192
0
      LambdaId = LambdaManglingNumber;
193
0
    else
194
0
      LambdaId = getAnonymousStructIdForDebugInfo(Lambda);
195
196
0
    Name += llvm::utostr(LambdaId);
197
0
    Name += '>';
198
0
    return Name;
199
0
  }
200
201
0
  DiscriminatorOverrideTy getDiscriminatorOverride() const override {
202
0
    return DiscriminatorOverride;
203
0
  }
204
205
  NamespaceDecl *getStdNamespace();
206
207
  const DeclContext *getEffectiveDeclContext(const Decl *D);
208
0
  const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
209
0
    return getEffectiveDeclContext(cast<Decl>(DC));
210
0
  }
211
212
  bool isInternalLinkageDecl(const NamedDecl *ND);
213
214
  /// @}
215
};
216
217
/// Manage the mangling of a single name.
218
class CXXNameMangler {
219
  ItaniumMangleContextImpl &Context;
220
  raw_ostream &Out;
221
  /// Normalize integer types for cross-language CFI support with other
222
  /// languages that can't represent and encode C/C++ integer types.
223
  bool NormalizeIntegers = false;
224
225
  bool NullOut = false;
226
  /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
227
  /// This mode is used when mangler creates another mangler recursively to
228
  /// calculate ABI tags for the function return value or the variable type.
229
  /// Also it is required to avoid infinite recursion in some cases.
230
  bool DisableDerivedAbiTags = false;
231
232
  /// The "structor" is the top-level declaration being mangled, if
233
  /// that's not a template specialization; otherwise it's the pattern
234
  /// for that specialization.
235
  const NamedDecl *Structor;
236
  unsigned StructorType = 0;
237
238
  // An offset to add to all template parameter depths while mangling. Used
239
  // when mangling a template parameter list to see if it matches a template
240
  // template parameter exactly.
241
  unsigned TemplateDepthOffset = 0;
242
243
  /// The next substitution sequence number.
244
  unsigned SeqID = 0;
245
246
  class FunctionTypeDepthState {
247
    unsigned Bits = 0;
248
249
    enum { InResultTypeMask = 1 };
250
251
  public:
252
0
    FunctionTypeDepthState() = default;
253
254
    /// The number of function types we're inside.
255
0
    unsigned getDepth() const {
256
0
      return Bits >> 1;
257
0
    }
258
259
    /// True if we're in the return type of the innermost function type.
260
0
    bool isInResultType() const {
261
0
      return Bits & InResultTypeMask;
262
0
    }
263
264
0
    FunctionTypeDepthState push() {
265
0
      FunctionTypeDepthState tmp = *this;
266
0
      Bits = (Bits & ~InResultTypeMask) + 2;
267
0
      return tmp;
268
0
    }
269
270
0
    void enterResultType() {
271
0
      Bits |= InResultTypeMask;
272
0
    }
273
274
0
    void leaveResultType() {
275
0
      Bits &= ~InResultTypeMask;
276
0
    }
277
278
0
    void pop(FunctionTypeDepthState saved) {
279
0
      assert(getDepth() == saved.getDepth() + 1);
280
0
      Bits = saved.Bits;
281
0
    }
282
283
  } FunctionTypeDepth;
284
285
  // abi_tag is a gcc attribute, taking one or more strings called "tags".
286
  // The goal is to annotate against which version of a library an object was
287
  // built and to be able to provide backwards compatibility ("dual abi").
288
  // For more information see docs/ItaniumMangleAbiTags.rst.
289
  typedef SmallVector<StringRef, 4> AbiTagList;
290
291
  // State to gather all implicit and explicit tags used in a mangled name.
292
  // Must always have an instance of this while emitting any name to keep
293
  // track.
294
  class AbiTagState final {
295
  public:
296
0
    explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
297
0
      Parent = LinkHead;
298
0
      LinkHead = this;
299
0
    }
300
301
    // No copy, no move.
302
    AbiTagState(const AbiTagState &) = delete;
303
    AbiTagState &operator=(const AbiTagState &) = delete;
304
305
0
    ~AbiTagState() { pop(); }
306
307
    void write(raw_ostream &Out, const NamedDecl *ND,
308
0
               const AbiTagList *AdditionalAbiTags) {
309
0
      ND = cast<NamedDecl>(ND->getCanonicalDecl());
310
0
      if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
311
0
        assert(
312
0
            !AdditionalAbiTags &&
313
0
            "only function and variables need a list of additional abi tags");
314
0
        if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
315
0
          if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
316
0
            UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
317
0
                               AbiTag->tags().end());
318
0
          }
319
          // Don't emit abi tags for namespaces.
320
0
          return;
321
0
        }
322
0
      }
323
324
0
      AbiTagList TagList;
325
0
      if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
326
0
        UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
327
0
                           AbiTag->tags().end());
328
0
        TagList.insert(TagList.end(), AbiTag->tags().begin(),
329
0
                       AbiTag->tags().end());
330
0
      }
331
332
0
      if (AdditionalAbiTags) {
333
0
        UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
334
0
                           AdditionalAbiTags->end());
335
0
        TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
336
0
                       AdditionalAbiTags->end());
337
0
      }
338
339
0
      llvm::sort(TagList);
340
0
      TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
341
342
0
      writeSortedUniqueAbiTags(Out, TagList);
343
0
    }
344
345
0
    const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
346
0
    void setUsedAbiTags(const AbiTagList &AbiTags) {
347
0
      UsedAbiTags = AbiTags;
348
0
    }
349
350
0
    const AbiTagList &getEmittedAbiTags() const {
351
0
      return EmittedAbiTags;
352
0
    }
353
354
0
    const AbiTagList &getSortedUniqueUsedAbiTags() {
355
0
      llvm::sort(UsedAbiTags);
356
0
      UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
357
0
                        UsedAbiTags.end());
358
0
      return UsedAbiTags;
359
0
    }
360
361
  private:
362
    //! All abi tags used implicitly or explicitly.
363
    AbiTagList UsedAbiTags;
364
    //! All explicit abi tags (i.e. not from namespace).
365
    AbiTagList EmittedAbiTags;
366
367
    AbiTagState *&LinkHead;
368
    AbiTagState *Parent = nullptr;
369
370
0
    void pop() {
371
0
      assert(LinkHead == this &&
372
0
             "abi tag link head must point to us on destruction");
373
0
      if (Parent) {
374
0
        Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
375
0
                                   UsedAbiTags.begin(), UsedAbiTags.end());
376
0
        Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
377
0
                                      EmittedAbiTags.begin(),
378
0
                                      EmittedAbiTags.end());
379
0
      }
380
0
      LinkHead = Parent;
381
0
    }
382
383
0
    void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
384
0
      for (const auto &Tag : AbiTags) {
385
0
        EmittedAbiTags.push_back(Tag);
386
0
        Out << "B";
387
0
        Out << Tag.size();
388
0
        Out << Tag;
389
0
      }
390
0
    }
391
  };
392
393
  AbiTagState *AbiTags = nullptr;
394
  AbiTagState AbiTagsRoot;
395
396
  llvm::DenseMap<uintptr_t, unsigned> Substitutions;
397
  llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
398
399
0
  ASTContext &getASTContext() const { return Context.getASTContext(); }
400
401
0
  bool isCompatibleWith(LangOptions::ClangABI Ver) {
402
0
    return Context.getASTContext().getLangOpts().getClangABICompat() <= Ver;
403
0
  }
404
405
  bool isStd(const NamespaceDecl *NS);
406
  bool isStdNamespace(const DeclContext *DC);
407
408
  const RecordDecl *GetLocalClassDecl(const Decl *D);
409
  bool isSpecializedAs(QualType S, llvm::StringRef Name, QualType A);
410
  bool isStdCharSpecialization(const ClassTemplateSpecializationDecl *SD,
411
                               llvm::StringRef Name, bool HasAllocator);
412
413
public:
414
  CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
415
                 const NamedDecl *D = nullptr, bool NullOut_ = false)
416
      : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
417
0
        AbiTagsRoot(AbiTags) {
418
    // These can't be mangled without a ctor type or dtor type.
419
0
    assert(!D || (!isa<CXXDestructorDecl>(D) &&
420
0
                  !isa<CXXConstructorDecl>(D)));
421
0
  }
422
  CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
423
                 const CXXConstructorDecl *D, CXXCtorType Type)
424
      : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
425
0
        AbiTagsRoot(AbiTags) {}
426
  CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
427
                 const CXXDestructorDecl *D, CXXDtorType Type)
428
      : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
429
0
        AbiTagsRoot(AbiTags) {}
430
431
  CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
432
                 bool NormalizeIntegers_)
433
      : Context(C), Out(Out_), NormalizeIntegers(NormalizeIntegers_),
434
0
        NullOut(false), Structor(nullptr), AbiTagsRoot(AbiTags) {}
435
  CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
436
      : Context(Outer.Context), Out(Out_), Structor(Outer.Structor),
437
        StructorType(Outer.StructorType), SeqID(Outer.SeqID),
438
        FunctionTypeDepth(Outer.FunctionTypeDepth), AbiTagsRoot(AbiTags),
439
        Substitutions(Outer.Substitutions),
440
0
        ModuleSubstitutions(Outer.ModuleSubstitutions) {}
441
442
  CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
443
0
      : CXXNameMangler(Outer, (raw_ostream &)Out_) {
444
0
    NullOut = true;
445
0
  }
446
447
  struct WithTemplateDepthOffset { unsigned Offset; };
448
  CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out,
449
                 WithTemplateDepthOffset Offset)
450
0
      : CXXNameMangler(C, Out) {
451
0
    TemplateDepthOffset = Offset.Offset;
452
0
  }
453
454
0
  raw_ostream &getStream() { return Out; }
455
456
0
  void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
457
  static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
458
459
  void mangle(GlobalDecl GD);
460
  void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
461
  void mangleNumber(const llvm::APSInt &I);
462
  void mangleNumber(int64_t Number);
463
  void mangleFloat(const llvm::APFloat &F);
464
  void mangleFunctionEncoding(GlobalDecl GD);
465
  void mangleSeqID(unsigned SeqID);
466
  void mangleName(GlobalDecl GD);
467
  void mangleType(QualType T);
468
  void mangleNameOrStandardSubstitution(const NamedDecl *ND);
469
  void mangleLambdaSig(const CXXRecordDecl *Lambda);
470
  void mangleModuleNamePrefix(StringRef Name, bool IsPartition = false);
471
472
private:
473
474
  bool mangleSubstitution(const NamedDecl *ND);
475
  bool mangleSubstitution(NestedNameSpecifier *NNS);
476
  bool mangleSubstitution(QualType T);
477
  bool mangleSubstitution(TemplateName Template);
478
  bool mangleSubstitution(uintptr_t Ptr);
479
480
  void mangleExistingSubstitution(TemplateName name);
481
482
  bool mangleStandardSubstitution(const NamedDecl *ND);
483
484
0
  void addSubstitution(const NamedDecl *ND) {
485
0
    ND = cast<NamedDecl>(ND->getCanonicalDecl());
486
487
0
    addSubstitution(reinterpret_cast<uintptr_t>(ND));
488
0
  }
489
0
  void addSubstitution(NestedNameSpecifier *NNS) {
490
0
    NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS);
491
492
0
    addSubstitution(reinterpret_cast<uintptr_t>(NNS));
493
0
  }
494
  void addSubstitution(QualType T);
495
  void addSubstitution(TemplateName Template);
496
  void addSubstitution(uintptr_t Ptr);
497
  // Destructive copy substitutions from other mangler.
498
  void extendSubstitutions(CXXNameMangler* Other);
499
500
  void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
501
                              bool recursive = false);
502
  void mangleUnresolvedName(NestedNameSpecifier *qualifier,
503
                            DeclarationName name,
504
                            const TemplateArgumentLoc *TemplateArgs,
505
                            unsigned NumTemplateArgs,
506
                            unsigned KnownArity = UnknownArity);
507
508
  void mangleFunctionEncodingBareType(const FunctionDecl *FD);
509
510
  void mangleNameWithAbiTags(GlobalDecl GD,
511
                             const AbiTagList *AdditionalAbiTags);
512
  void mangleModuleName(const NamedDecl *ND);
513
  void mangleTemplateName(const TemplateDecl *TD,
514
                          ArrayRef<TemplateArgument> Args);
515
  void mangleUnqualifiedName(GlobalDecl GD, const DeclContext *DC,
516
0
                             const AbiTagList *AdditionalAbiTags) {
517
0
    mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName(), DC,
518
0
                          UnknownArity, AdditionalAbiTags);
519
0
  }
520
  void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name,
521
                             const DeclContext *DC, unsigned KnownArity,
522
                             const AbiTagList *AdditionalAbiTags);
523
  void mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,
524
                          const AbiTagList *AdditionalAbiTags);
525
  void mangleUnscopedTemplateName(GlobalDecl GD, const DeclContext *DC,
526
                                  const AbiTagList *AdditionalAbiTags);
527
  void mangleSourceName(const IdentifierInfo *II);
528
  void mangleRegCallName(const IdentifierInfo *II);
529
  void mangleDeviceStubName(const IdentifierInfo *II);
530
  void mangleSourceNameWithAbiTags(
531
      const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
532
  void mangleLocalName(GlobalDecl GD,
533
                       const AbiTagList *AdditionalAbiTags);
534
  void mangleBlockForPrefix(const BlockDecl *Block);
535
  void mangleUnqualifiedBlock(const BlockDecl *Block);
536
  void mangleTemplateParamDecl(const NamedDecl *Decl);
537
  void mangleTemplateParameterList(const TemplateParameterList *Params);
538
  void mangleTypeConstraint(const ConceptDecl *Concept,
539
                            ArrayRef<TemplateArgument> Arguments);
540
  void mangleTypeConstraint(const TypeConstraint *Constraint);
541
  void mangleRequiresClause(const Expr *RequiresClause);
542
  void mangleLambda(const CXXRecordDecl *Lambda);
543
  void mangleNestedName(GlobalDecl GD, const DeclContext *DC,
544
                        const AbiTagList *AdditionalAbiTags,
545
                        bool NoFunction=false);
546
  void mangleNestedName(const TemplateDecl *TD,
547
                        ArrayRef<TemplateArgument> Args);
548
  void mangleNestedNameWithClosurePrefix(GlobalDecl GD,
549
                                         const NamedDecl *PrefixND,
550
                                         const AbiTagList *AdditionalAbiTags);
551
  void manglePrefix(NestedNameSpecifier *qualifier);
552
  void manglePrefix(const DeclContext *DC, bool NoFunction=false);
553
  void manglePrefix(QualType type);
554
  void mangleTemplatePrefix(GlobalDecl GD, bool NoFunction=false);
555
  void mangleTemplatePrefix(TemplateName Template);
556
  const NamedDecl *getClosurePrefix(const Decl *ND);
557
  void mangleClosurePrefix(const NamedDecl *ND, bool NoFunction = false);
558
  bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
559
                                      StringRef Prefix = "");
560
  void mangleOperatorName(DeclarationName Name, unsigned Arity);
561
  void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
562
  void mangleVendorQualifier(StringRef qualifier);
563
  void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
564
  void mangleRefQualifier(RefQualifierKind RefQualifier);
565
566
  void mangleObjCMethodName(const ObjCMethodDecl *MD);
567
568
  // Declare manglers for every type class.
569
#define ABSTRACT_TYPE(CLASS, PARENT)
570
#define NON_CANONICAL_TYPE(CLASS, PARENT)
571
#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
572
#include "clang/AST/TypeNodes.inc"
573
574
  void mangleType(const TagType*);
575
  void mangleType(TemplateName);
576
  static StringRef getCallingConvQualifierName(CallingConv CC);
577
  void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
578
  void mangleExtFunctionInfo(const FunctionType *T);
579
  void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
580
                              const FunctionDecl *FD = nullptr);
581
  void mangleNeonVectorType(const VectorType *T);
582
  void mangleNeonVectorType(const DependentVectorType *T);
583
  void mangleAArch64NeonVectorType(const VectorType *T);
584
  void mangleAArch64NeonVectorType(const DependentVectorType *T);
585
  void mangleAArch64FixedSveVectorType(const VectorType *T);
586
  void mangleAArch64FixedSveVectorType(const DependentVectorType *T);
587
  void mangleRISCVFixedRVVVectorType(const VectorType *T);
588
  void mangleRISCVFixedRVVVectorType(const DependentVectorType *T);
589
590
  void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
591
  void mangleFloatLiteral(QualType T, const llvm::APFloat &V);
592
  void mangleFixedPointLiteral();
593
  void mangleNullPointer(QualType T);
594
595
  void mangleMemberExprBase(const Expr *base, bool isArrow);
596
  void mangleMemberExpr(const Expr *base, bool isArrow,
597
                        NestedNameSpecifier *qualifier,
598
                        NamedDecl *firstQualifierLookup,
599
                        DeclarationName name,
600
                        const TemplateArgumentLoc *TemplateArgs,
601
                        unsigned NumTemplateArgs,
602
                        unsigned knownArity);
603
  void mangleCastExpression(const Expr *E, StringRef CastEncoding);
604
  void mangleInitListElements(const InitListExpr *InitList);
605
  void mangleRequirement(SourceLocation RequiresExprLoc,
606
                         const concepts::Requirement *Req);
607
  void mangleExpression(const Expr *E, unsigned Arity = UnknownArity,
608
                        bool AsTemplateArg = false);
609
  void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
610
  void mangleCXXDtorType(CXXDtorType T);
611
612
  struct TemplateArgManglingInfo;
613
  void mangleTemplateArgs(TemplateName TN,
614
                          const TemplateArgumentLoc *TemplateArgs,
615
                          unsigned NumTemplateArgs);
616
  void mangleTemplateArgs(TemplateName TN, ArrayRef<TemplateArgument> Args);
617
  void mangleTemplateArgs(TemplateName TN, const TemplateArgumentList &AL);
618
  void mangleTemplateArg(TemplateArgManglingInfo &Info, unsigned Index,
619
                         TemplateArgument A);
620
  void mangleTemplateArg(TemplateArgument A, bool NeedExactType);
621
  void mangleTemplateArgExpr(const Expr *E);
622
  void mangleValueInTemplateArg(QualType T, const APValue &V, bool TopLevel,
623
                                bool NeedExactType = false);
624
625
  void mangleTemplateParameter(unsigned Depth, unsigned Index);
626
627
  void mangleFunctionParam(const ParmVarDecl *parm);
628
629
  void writeAbiTags(const NamedDecl *ND,
630
                    const AbiTagList *AdditionalAbiTags);
631
632
  // Returns sorted unique list of ABI tags.
633
  AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
634
  // Returns sorted unique list of ABI tags.
635
  AbiTagList makeVariableTypeTags(const VarDecl *VD);
636
};
637
638
}
639
640
0
NamespaceDecl *ItaniumMangleContextImpl::getStdNamespace() {
641
0
  if (!StdNamespace) {
642
0
    StdNamespace = NamespaceDecl::Create(
643
0
        getASTContext(), getASTContext().getTranslationUnitDecl(),
644
0
        /*Inline=*/false, SourceLocation(), SourceLocation(),
645
0
        &getASTContext().Idents.get("std"),
646
0
        /*PrevDecl=*/nullptr, /*Nested=*/false);
647
0
    StdNamespace->setImplicit();
648
0
  }
649
0
  return StdNamespace;
650
0
}
651
652
/// Retrieve the declaration context that should be used when mangling the given
653
/// declaration.
654
const DeclContext *
655
0
ItaniumMangleContextImpl::getEffectiveDeclContext(const Decl *D) {
656
  // The ABI assumes that lambda closure types that occur within
657
  // default arguments live in the context of the function. However, due to
658
  // the way in which Clang parses and creates function declarations, this is
659
  // not the case: the lambda closure type ends up living in the context
660
  // where the function itself resides, because the function declaration itself
661
  // had not yet been created. Fix the context here.
662
0
  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
663
0
    if (RD->isLambda())
664
0
      if (ParmVarDecl *ContextParam =
665
0
              dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
666
0
        return ContextParam->getDeclContext();
667
0
  }
668
669
  // Perform the same check for block literals.
670
0
  if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
671
0
    if (ParmVarDecl *ContextParam =
672
0
            dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
673
0
      return ContextParam->getDeclContext();
674
0
  }
675
676
  // On ARM and AArch64, the va_list tag is always mangled as if in the std
677
  // namespace. We do not represent va_list as actually being in the std
678
  // namespace in C because this would result in incorrect debug info in C,
679
  // among other things. It is important for both languages to have the same
680
  // mangling in order for -fsanitize=cfi-icall to work.
681
0
  if (D == getASTContext().getVaListTagDecl()) {
682
0
    const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
683
0
    if (T.isARM() || T.isThumb() || T.isAArch64())
684
0
      return getStdNamespace();
685
0
  }
686
687
0
  const DeclContext *DC = D->getDeclContext();
688
0
  if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
689
0
      isa<OMPDeclareMapperDecl>(DC)) {
690
0
    return getEffectiveDeclContext(cast<Decl>(DC));
691
0
  }
692
693
0
  if (const auto *VD = dyn_cast<VarDecl>(D))
694
0
    if (VD->isExternC())
695
0
      return getASTContext().getTranslationUnitDecl();
696
697
0
  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
698
0
    if (FD->isExternC())
699
0
      return getASTContext().getTranslationUnitDecl();
700
    // Member-like constrained friends are mangled as if they were members of
701
    // the enclosing class.
702
0
    if (FD->isMemberLikeConstrainedFriend() &&
703
0
        getASTContext().getLangOpts().getClangABICompat() >
704
0
            LangOptions::ClangABI::Ver17)
705
0
      return D->getLexicalDeclContext()->getRedeclContext();
706
0
  }
707
708
0
  return DC->getRedeclContext();
709
0
}
710
711
0
bool ItaniumMangleContextImpl::isInternalLinkageDecl(const NamedDecl *ND) {
712
0
  if (ND && ND->getFormalLinkage() == Linkage::Internal &&
713
0
      !ND->isExternallyVisible() &&
714
0
      getEffectiveDeclContext(ND)->isFileContext() &&
715
0
      !ND->isInAnonymousNamespace())
716
0
    return true;
717
0
  return false;
718
0
}
719
720
// Check if this Function Decl needs a unique internal linkage name.
721
bool ItaniumMangleContextImpl::isUniqueInternalLinkageDecl(
722
0
    const NamedDecl *ND) {
723
0
  if (!NeedsUniqueInternalLinkageNames || !ND)
724
0
    return false;
725
726
0
  const auto *FD = dyn_cast<FunctionDecl>(ND);
727
0
  if (!FD)
728
0
    return false;
729
730
  // For C functions without prototypes, return false as their
731
  // names should not be mangled.
732
0
  if (!FD->getType()->getAs<FunctionProtoType>())
733
0
    return false;
734
735
0
  if (isInternalLinkageDecl(ND))
736
0
    return true;
737
738
0
  return false;
739
0
}
740
741
0
bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
742
0
  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
743
0
    LanguageLinkage L = FD->getLanguageLinkage();
744
    // Overloadable functions need mangling.
745
0
    if (FD->hasAttr<OverloadableAttr>())
746
0
      return true;
747
748
    // "main" is not mangled.
749
0
    if (FD->isMain())
750
0
      return false;
751
752
    // The Windows ABI expects that we would never mangle "typical"
753
    // user-defined entry points regardless of visibility or freestanding-ness.
754
    //
755
    // N.B. This is distinct from asking about "main".  "main" has a lot of
756
    // special rules associated with it in the standard while these
757
    // user-defined entry points are outside of the purview of the standard.
758
    // For example, there can be only one definition for "main" in a standards
759
    // compliant program; however nothing forbids the existence of wmain and
760
    // WinMain in the same translation unit.
761
0
    if (FD->isMSVCRTEntryPoint())
762
0
      return false;
763
764
    // C++ functions and those whose names are not a simple identifier need
765
    // mangling.
766
0
    if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
767
0
      return true;
768
769
    // C functions are not mangled.
770
0
    if (L == CLanguageLinkage)
771
0
      return false;
772
0
  }
773
774
  // Otherwise, no mangling is done outside C++ mode.
775
0
  if (!getASTContext().getLangOpts().CPlusPlus)
776
0
    return false;
777
778
0
  if (const auto *VD = dyn_cast<VarDecl>(D)) {
779
    // Decompositions are mangled.
780
0
    if (isa<DecompositionDecl>(VD))
781
0
      return true;
782
783
    // C variables are not mangled.
784
0
    if (VD->isExternC())
785
0
      return false;
786
787
    // Variables at global scope are not mangled unless they have internal
788
    // linkage or are specializations or are attached to a named module.
789
0
    const DeclContext *DC = getEffectiveDeclContext(D);
790
    // Check for extern variable declared locally.
791
0
    if (DC->isFunctionOrMethod() && D->hasLinkage())
792
0
      while (!DC->isFileContext())
793
0
        DC = getEffectiveParentContext(DC);
794
0
    if (DC->isTranslationUnit() && D->getFormalLinkage() != Linkage::Internal &&
795
0
        !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
796
0
        !isa<VarTemplateSpecializationDecl>(VD) &&
797
0
        !VD->getOwningModuleForLinkage())
798
0
      return false;
799
0
  }
800
801
0
  return true;
802
0
}
803
804
void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
805
0
                                  const AbiTagList *AdditionalAbiTags) {
806
0
  assert(AbiTags && "require AbiTagState");
807
0
  AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
808
0
}
809
810
void CXXNameMangler::mangleSourceNameWithAbiTags(
811
0
    const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
812
0
  mangleSourceName(ND->getIdentifier());
813
0
  writeAbiTags(ND, AdditionalAbiTags);
814
0
}
815
816
0
void CXXNameMangler::mangle(GlobalDecl GD) {
817
  // <mangled-name> ::= _Z <encoding>
818
  //            ::= <data name>
819
  //            ::= <special-name>
820
0
  Out << "_Z";
821
0
  if (isa<FunctionDecl>(GD.getDecl()))
822
0
    mangleFunctionEncoding(GD);
823
0
  else if (isa<VarDecl, FieldDecl, MSGuidDecl, TemplateParamObjectDecl,
824
0
               BindingDecl>(GD.getDecl()))
825
0
    mangleName(GD);
826
0
  else if (const IndirectFieldDecl *IFD =
827
0
               dyn_cast<IndirectFieldDecl>(GD.getDecl()))
828
0
    mangleName(IFD->getAnonField());
829
0
  else
830
0
    llvm_unreachable("unexpected kind of global decl");
831
0
}
832
833
0
void CXXNameMangler::mangleFunctionEncoding(GlobalDecl GD) {
834
0
  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
835
  // <encoding> ::= <function name> <bare-function-type>
836
837
  // Don't mangle in the type if this isn't a decl we should typically mangle.
838
0
  if (!Context.shouldMangleDeclName(FD)) {
839
0
    mangleName(GD);
840
0
    return;
841
0
  }
842
843
0
  AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
844
0
  if (ReturnTypeAbiTags.empty()) {
845
    // There are no tags for return type, the simplest case. Enter the function
846
    // parameter scope before mangling the name, because a template using
847
    // constrained `auto` can have references to its parameters within its
848
    // template argument list:
849
    //
850
    //   template<typename T> void f(T x, C<decltype(x)> auto)
851
    // ... is mangled as ...
852
    //   template<typename T, C<decltype(param 1)> U> void f(T, U)
853
0
    FunctionTypeDepthState Saved = FunctionTypeDepth.push();
854
0
    mangleName(GD);
855
0
    FunctionTypeDepth.pop(Saved);
856
0
    mangleFunctionEncodingBareType(FD);
857
0
    return;
858
0
  }
859
860
  // Mangle function name and encoding to temporary buffer.
861
  // We have to output name and encoding to the same mangler to get the same
862
  // substitution as it will be in final mangling.
863
0
  SmallString<256> FunctionEncodingBuf;
864
0
  llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
865
0
  CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
866
  // Output name of the function.
867
0
  FunctionEncodingMangler.disableDerivedAbiTags();
868
869
0
  FunctionTypeDepthState Saved = FunctionTypeDepth.push();
870
0
  FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
871
0
  FunctionTypeDepth.pop(Saved);
872
873
  // Remember length of the function name in the buffer.
874
0
  size_t EncodingPositionStart = FunctionEncodingStream.str().size();
875
0
  FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
876
877
  // Get tags from return type that are not present in function name or
878
  // encoding.
879
0
  const AbiTagList &UsedAbiTags =
880
0
      FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
881
0
  AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
882
0
  AdditionalAbiTags.erase(
883
0
      std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
884
0
                          UsedAbiTags.begin(), UsedAbiTags.end(),
885
0
                          AdditionalAbiTags.begin()),
886
0
      AdditionalAbiTags.end());
887
888
  // Output name with implicit tags and function encoding from temporary buffer.
889
0
  Saved = FunctionTypeDepth.push();
890
0
  mangleNameWithAbiTags(FD, &AdditionalAbiTags);
891
0
  FunctionTypeDepth.pop(Saved);
892
0
  Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
893
894
  // Function encoding could create new substitutions so we have to add
895
  // temp mangled substitutions to main mangler.
896
0
  extendSubstitutions(&FunctionEncodingMangler);
897
0
}
898
899
0
void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
900
0
  if (FD->hasAttr<EnableIfAttr>()) {
901
0
    FunctionTypeDepthState Saved = FunctionTypeDepth.push();
902
0
    Out << "Ua9enable_ifI";
903
0
    for (AttrVec::const_iterator I = FD->getAttrs().begin(),
904
0
                                 E = FD->getAttrs().end();
905
0
         I != E; ++I) {
906
0
      EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
907
0
      if (!EIA)
908
0
        continue;
909
0
      if (isCompatibleWith(LangOptions::ClangABI::Ver11)) {
910
        // Prior to Clang 12, we hardcoded the X/E around enable-if's argument,
911
        // even though <template-arg> should not include an X/E around
912
        // <expr-primary>.
913
0
        Out << 'X';
914
0
        mangleExpression(EIA->getCond());
915
0
        Out << 'E';
916
0
      } else {
917
0
        mangleTemplateArgExpr(EIA->getCond());
918
0
      }
919
0
    }
920
0
    Out << 'E';
921
0
    FunctionTypeDepth.pop(Saved);
922
0
  }
923
924
  // When mangling an inheriting constructor, the bare function type used is
925
  // that of the inherited constructor.
926
0
  if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
927
0
    if (auto Inherited = CD->getInheritedConstructor())
928
0
      FD = Inherited.getConstructor();
929
930
  // Whether the mangling of a function type includes the return type depends on
931
  // the context and the nature of the function. The rules for deciding whether
932
  // the return type is included are:
933
  //
934
  //   1. Template functions (names or types) have return types encoded, with
935
  //   the exceptions listed below.
936
  //   2. Function types not appearing as part of a function name mangling,
937
  //   e.g. parameters, pointer types, etc., have return type encoded, with the
938
  //   exceptions listed below.
939
  //   3. Non-template function names do not have return types encoded.
940
  //
941
  // The exceptions mentioned in (1) and (2) above, for which the return type is
942
  // never included, are
943
  //   1. Constructors.
944
  //   2. Destructors.
945
  //   3. Conversion operator functions, e.g. operator int.
946
0
  bool MangleReturnType = false;
947
0
  if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
948
0
    if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
949
0
          isa<CXXConversionDecl>(FD)))
950
0
      MangleReturnType = true;
951
952
    // Mangle the type of the primary template.
953
0
    FD = PrimaryTemplate->getTemplatedDecl();
954
0
  }
955
956
0
  mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
957
0
                         MangleReturnType, FD);
958
0
}
959
960
/// Return whether a given namespace is the 'std' namespace.
961
0
bool CXXNameMangler::isStd(const NamespaceDecl *NS) {
962
0
  if (!Context.getEffectiveParentContext(NS)->isTranslationUnit())
963
0
    return false;
964
965
0
  const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
966
0
  return II && II->isStr("std");
967
0
}
968
969
// isStdNamespace - Return whether a given decl context is a toplevel 'std'
970
// namespace.
971
0
bool CXXNameMangler::isStdNamespace(const DeclContext *DC) {
972
0
  if (!DC->isNamespace())
973
0
    return false;
974
975
0
  return isStd(cast<NamespaceDecl>(DC));
976
0
}
977
978
static const GlobalDecl
979
0
isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs) {
980
0
  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
981
  // Check if we have a function template.
982
0
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
983
0
    if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
984
0
      TemplateArgs = FD->getTemplateSpecializationArgs();
985
0
      return GD.getWithDecl(TD);
986
0
    }
987
0
  }
988
989
  // Check if we have a class template.
990
0
  if (const ClassTemplateSpecializationDecl *Spec =
991
0
        dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
992
0
    TemplateArgs = &Spec->getTemplateArgs();
993
0
    return GD.getWithDecl(Spec->getSpecializedTemplate());
994
0
  }
995
996
  // Check if we have a variable template.
997
0
  if (const VarTemplateSpecializationDecl *Spec =
998
0
          dyn_cast<VarTemplateSpecializationDecl>(ND)) {
999
0
    TemplateArgs = &Spec->getTemplateArgs();
1000
0
    return GD.getWithDecl(Spec->getSpecializedTemplate());
1001
0
  }
1002
1003
0
  return GlobalDecl();
1004
0
}
1005
1006
0
static TemplateName asTemplateName(GlobalDecl GD) {
1007
0
  const TemplateDecl *TD = dyn_cast_or_null<TemplateDecl>(GD.getDecl());
1008
0
  return TemplateName(const_cast<TemplateDecl*>(TD));
1009
0
}
1010
1011
0
void CXXNameMangler::mangleName(GlobalDecl GD) {
1012
0
  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1013
0
  if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1014
    // Variables should have implicit tags from its type.
1015
0
    AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
1016
0
    if (VariableTypeAbiTags.empty()) {
1017
      // Simple case no variable type tags.
1018
0
      mangleNameWithAbiTags(VD, nullptr);
1019
0
      return;
1020
0
    }
1021
1022
    // Mangle variable name to null stream to collect tags.
1023
0
    llvm::raw_null_ostream NullOutStream;
1024
0
    CXXNameMangler VariableNameMangler(*this, NullOutStream);
1025
0
    VariableNameMangler.disableDerivedAbiTags();
1026
0
    VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
1027
1028
    // Get tags from variable type that are not present in its name.
1029
0
    const AbiTagList &UsedAbiTags =
1030
0
        VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
1031
0
    AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
1032
0
    AdditionalAbiTags.erase(
1033
0
        std::set_difference(VariableTypeAbiTags.begin(),
1034
0
                            VariableTypeAbiTags.end(), UsedAbiTags.begin(),
1035
0
                            UsedAbiTags.end(), AdditionalAbiTags.begin()),
1036
0
        AdditionalAbiTags.end());
1037
1038
    // Output name with implicit tags.
1039
0
    mangleNameWithAbiTags(VD, &AdditionalAbiTags);
1040
0
  } else {
1041
0
    mangleNameWithAbiTags(GD, nullptr);
1042
0
  }
1043
0
}
1044
1045
0
const RecordDecl *CXXNameMangler::GetLocalClassDecl(const Decl *D) {
1046
0
  const DeclContext *DC = Context.getEffectiveDeclContext(D);
1047
0
  while (!DC->isNamespace() && !DC->isTranslationUnit()) {
1048
0
    if (isLocalContainerContext(DC))
1049
0
      return dyn_cast<RecordDecl>(D);
1050
0
    D = cast<Decl>(DC);
1051
0
    DC = Context.getEffectiveDeclContext(D);
1052
0
  }
1053
0
  return nullptr;
1054
0
}
1055
1056
void CXXNameMangler::mangleNameWithAbiTags(GlobalDecl GD,
1057
0
                                           const AbiTagList *AdditionalAbiTags) {
1058
0
  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1059
  //  <name> ::= [<module-name>] <nested-name>
1060
  //         ::= [<module-name>] <unscoped-name>
1061
  //         ::= [<module-name>] <unscoped-template-name> <template-args>
1062
  //         ::= <local-name>
1063
  //
1064
0
  const DeclContext *DC = Context.getEffectiveDeclContext(ND);
1065
1066
  // If this is an extern variable declared locally, the relevant DeclContext
1067
  // is that of the containing namespace, or the translation unit.
1068
  // FIXME: This is a hack; extern variables declared locally should have
1069
  // a proper semantic declaration context!
1070
0
  if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
1071
0
    while (!DC->isNamespace() && !DC->isTranslationUnit())
1072
0
      DC = Context.getEffectiveParentContext(DC);
1073
0
  else if (GetLocalClassDecl(ND)) {
1074
0
    mangleLocalName(GD, AdditionalAbiTags);
1075
0
    return;
1076
0
  }
1077
1078
0
  assert(!isa<LinkageSpecDecl>(DC) && "context cannot be LinkageSpecDecl");
1079
1080
0
  if (isLocalContainerContext(DC)) {
1081
0
    mangleLocalName(GD, AdditionalAbiTags);
1082
0
    return;
1083
0
  }
1084
1085
  // Closures can require a nested-name mangling even if they're semantically
1086
  // in the global namespace.
1087
0
  if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
1088
0
    mangleNestedNameWithClosurePrefix(GD, PrefixND, AdditionalAbiTags);
1089
0
    return;
1090
0
  }
1091
1092
0
  if (DC->isTranslationUnit() || isStdNamespace(DC)) {
1093
    // Check if we have a template.
1094
0
    const TemplateArgumentList *TemplateArgs = nullptr;
1095
0
    if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
1096
0
      mangleUnscopedTemplateName(TD, DC, AdditionalAbiTags);
1097
0
      mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
1098
0
      return;
1099
0
    }
1100
1101
0
    mangleUnscopedName(GD, DC, AdditionalAbiTags);
1102
0
    return;
1103
0
  }
1104
1105
0
  mangleNestedName(GD, DC, AdditionalAbiTags);
1106
0
}
1107
1108
0
void CXXNameMangler::mangleModuleName(const NamedDecl *ND) {
1109
0
  if (ND->isExternallyVisible())
1110
0
    if (Module *M = ND->getOwningModuleForLinkage())
1111
0
      mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());
1112
0
}
1113
1114
// <module-name> ::= <module-subname>
1115
//     ::= <module-name> <module-subname>
1116
//     ::= <substitution>
1117
// <module-subname> ::= W <source-name>
1118
//        ::= W P <source-name>
1119
0
void CXXNameMangler::mangleModuleNamePrefix(StringRef Name, bool IsPartition) {
1120
  //  <substitution> ::= S <seq-id> _
1121
0
  auto It = ModuleSubstitutions.find(Name);
1122
0
  if (It != ModuleSubstitutions.end()) {
1123
0
    Out << 'S';
1124
0
    mangleSeqID(It->second);
1125
0
    return;
1126
0
  }
1127
1128
  // FIXME: Preserve hierarchy in module names rather than flattening
1129
  // them to strings; use Module*s as substitution keys.
1130
0
  auto Parts = Name.rsplit('.');
1131
0
  if (Parts.second.empty())
1132
0
    Parts.second = Parts.first;
1133
0
  else {
1134
0
    mangleModuleNamePrefix(Parts.first, IsPartition);
1135
0
    IsPartition = false;
1136
0
  }
1137
1138
0
  Out << 'W';
1139
0
  if (IsPartition)
1140
0
    Out << 'P';
1141
0
  Out << Parts.second.size() << Parts.second;
1142
0
  ModuleSubstitutions.insert({Name, SeqID++});
1143
0
}
1144
1145
void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
1146
0
                                        ArrayRef<TemplateArgument> Args) {
1147
0
  const DeclContext *DC = Context.getEffectiveDeclContext(TD);
1148
1149
0
  if (DC->isTranslationUnit() || isStdNamespace(DC)) {
1150
0
    mangleUnscopedTemplateName(TD, DC, nullptr);
1151
0
    mangleTemplateArgs(asTemplateName(TD), Args);
1152
0
  } else {
1153
0
    mangleNestedName(TD, Args);
1154
0
  }
1155
0
}
1156
1157
void CXXNameMangler::mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,
1158
0
                                        const AbiTagList *AdditionalAbiTags) {
1159
  //  <unscoped-name> ::= <unqualified-name>
1160
  //                  ::= St <unqualified-name>   # ::std::
1161
1162
0
  assert(!isa<LinkageSpecDecl>(DC) && "unskipped LinkageSpecDecl");
1163
0
  if (isStdNamespace(DC))
1164
0
    Out << "St";
1165
1166
0
  mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1167
0
}
1168
1169
void CXXNameMangler::mangleUnscopedTemplateName(
1170
0
    GlobalDecl GD, const DeclContext *DC, const AbiTagList *AdditionalAbiTags) {
1171
0
  const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
1172
  //     <unscoped-template-name> ::= <unscoped-name>
1173
  //                              ::= <substitution>
1174
0
  if (mangleSubstitution(ND))
1175
0
    return;
1176
1177
  // <template-template-param> ::= <template-param>
1178
0
  if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1179
0
    assert(!AdditionalAbiTags &&
1180
0
           "template template param cannot have abi tags");
1181
0
    mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
1182
0
  } else if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND)) {
1183
0
    mangleUnscopedName(GD, DC, AdditionalAbiTags);
1184
0
  } else {
1185
0
    mangleUnscopedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
1186
0
                       AdditionalAbiTags);
1187
0
  }
1188
1189
0
  addSubstitution(ND);
1190
0
}
1191
1192
0
void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
1193
  // ABI:
1194
  //   Floating-point literals are encoded using a fixed-length
1195
  //   lowercase hexadecimal string corresponding to the internal
1196
  //   representation (IEEE on Itanium), high-order bytes first,
1197
  //   without leading zeroes. For example: "Lf bf800000 E" is -1.0f
1198
  //   on Itanium.
1199
  // The 'without leading zeroes' thing seems to be an editorial
1200
  // mistake; see the discussion on cxx-abi-dev beginning on
1201
  // 2012-01-16.
1202
1203
  // Our requirements here are just barely weird enough to justify
1204
  // using a custom algorithm instead of post-processing APInt::toString().
1205
1206
0
  llvm::APInt valueBits = f.bitcastToAPInt();
1207
0
  unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
1208
0
  assert(numCharacters != 0);
1209
1210
  // Allocate a buffer of the right number of characters.
1211
0
  SmallVector<char, 20> buffer(numCharacters);
1212
1213
  // Fill the buffer left-to-right.
1214
0
  for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
1215
    // The bit-index of the next hex digit.
1216
0
    unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
1217
1218
    // Project out 4 bits starting at 'digitIndex'.
1219
0
    uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
1220
0
    hexDigit >>= (digitBitIndex % 64);
1221
0
    hexDigit &= 0xF;
1222
1223
    // Map that over to a lowercase hex digit.
1224
0
    static const char charForHex[16] = {
1225
0
      '0', '1', '2', '3', '4', '5', '6', '7',
1226
0
      '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1227
0
    };
1228
0
    buffer[stringIndex] = charForHex[hexDigit];
1229
0
  }
1230
1231
0
  Out.write(buffer.data(), numCharacters);
1232
0
}
1233
1234
0
void CXXNameMangler::mangleFloatLiteral(QualType T, const llvm::APFloat &V) {
1235
0
  Out << 'L';
1236
0
  mangleType(T);
1237
0
  mangleFloat(V);
1238
0
  Out << 'E';
1239
0
}
1240
1241
0
void CXXNameMangler::mangleFixedPointLiteral() {
1242
0
  DiagnosticsEngine &Diags = Context.getDiags();
1243
0
  unsigned DiagID = Diags.getCustomDiagID(
1244
0
      DiagnosticsEngine::Error, "cannot mangle fixed point literals yet");
1245
0
  Diags.Report(DiagID);
1246
0
}
1247
1248
0
void CXXNameMangler::mangleNullPointer(QualType T) {
1249
  //  <expr-primary> ::= L <type> 0 E
1250
0
  Out << 'L';
1251
0
  mangleType(T);
1252
0
  Out << "0E";
1253
0
}
1254
1255
0
void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1256
0
  if (Value.isSigned() && Value.isNegative()) {
1257
0
    Out << 'n';
1258
0
    Value.abs().print(Out, /*signed*/ false);
1259
0
  } else {
1260
0
    Value.print(Out, /*signed*/ false);
1261
0
  }
1262
0
}
1263
1264
0
void CXXNameMangler::mangleNumber(int64_t Number) {
1265
  //  <number> ::= [n] <non-negative decimal integer>
1266
0
  if (Number < 0) {
1267
0
    Out << 'n';
1268
0
    Number = -Number;
1269
0
  }
1270
1271
0
  Out << Number;
1272
0
}
1273
1274
0
void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1275
  //  <call-offset>  ::= h <nv-offset> _
1276
  //                 ::= v <v-offset> _
1277
  //  <nv-offset>    ::= <offset number>        # non-virtual base override
1278
  //  <v-offset>     ::= <offset number> _ <virtual offset number>
1279
  //                      # virtual base override, with vcall offset
1280
0
  if (!Virtual) {
1281
0
    Out << 'h';
1282
0
    mangleNumber(NonVirtual);
1283
0
    Out << '_';
1284
0
    return;
1285
0
  }
1286
1287
0
  Out << 'v';
1288
0
  mangleNumber(NonVirtual);
1289
0
  Out << '_';
1290
0
  mangleNumber(Virtual);
1291
0
  Out << '_';
1292
0
}
1293
1294
0
void CXXNameMangler::manglePrefix(QualType type) {
1295
0
  if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
1296
0
    if (!mangleSubstitution(QualType(TST, 0))) {
1297
0
      mangleTemplatePrefix(TST->getTemplateName());
1298
1299
      // FIXME: GCC does not appear to mangle the template arguments when
1300
      // the template in question is a dependent template name. Should we
1301
      // emulate that badness?
1302
0
      mangleTemplateArgs(TST->getTemplateName(), TST->template_arguments());
1303
0
      addSubstitution(QualType(TST, 0));
1304
0
    }
1305
0
  } else if (const auto *DTST =
1306
0
                 type->getAs<DependentTemplateSpecializationType>()) {
1307
0
    if (!mangleSubstitution(QualType(DTST, 0))) {
1308
0
      TemplateName Template = getASTContext().getDependentTemplateName(
1309
0
          DTST->getQualifier(), DTST->getIdentifier());
1310
0
      mangleTemplatePrefix(Template);
1311
1312
      // FIXME: GCC does not appear to mangle the template arguments when
1313
      // the template in question is a dependent template name. Should we
1314
      // emulate that badness?
1315
0
      mangleTemplateArgs(Template, DTST->template_arguments());
1316
0
      addSubstitution(QualType(DTST, 0));
1317
0
    }
1318
0
  } else {
1319
    // We use the QualType mangle type variant here because it handles
1320
    // substitutions.
1321
0
    mangleType(type);
1322
0
  }
1323
0
}
1324
1325
/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1326
///
1327
/// \param recursive - true if this is being called recursively,
1328
///   i.e. if there is more prefix "to the right".
1329
void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
1330
0
                                            bool recursive) {
1331
1332
  // x, ::x
1333
  // <unresolved-name> ::= [gs] <base-unresolved-name>
1334
1335
  // T::x / decltype(p)::x
1336
  // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1337
1338
  // T::N::x /decltype(p)::N::x
1339
  // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1340
  //                       <base-unresolved-name>
1341
1342
  // A::x, N::y, A<T>::z; "gs" means leading "::"
1343
  // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1344
  //                       <base-unresolved-name>
1345
1346
0
  switch (qualifier->getKind()) {
1347
0
  case NestedNameSpecifier::Global:
1348
0
    Out << "gs";
1349
1350
    // We want an 'sr' unless this is the entire NNS.
1351
0
    if (recursive)
1352
0
      Out << "sr";
1353
1354
    // We never want an 'E' here.
1355
0
    return;
1356
1357
0
  case NestedNameSpecifier::Super:
1358
0
    llvm_unreachable("Can't mangle __super specifier");
1359
1360
0
  case NestedNameSpecifier::Namespace:
1361
0
    if (qualifier->getPrefix())
1362
0
      mangleUnresolvedPrefix(qualifier->getPrefix(),
1363
0
                             /*recursive*/ true);
1364
0
    else
1365
0
      Out << "sr";
1366
0
    mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
1367
0
    break;
1368
0
  case NestedNameSpecifier::NamespaceAlias:
1369
0
    if (qualifier->getPrefix())
1370
0
      mangleUnresolvedPrefix(qualifier->getPrefix(),
1371
0
                             /*recursive*/ true);
1372
0
    else
1373
0
      Out << "sr";
1374
0
    mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
1375
0
    break;
1376
1377
0
  case NestedNameSpecifier::TypeSpec:
1378
0
  case NestedNameSpecifier::TypeSpecWithTemplate: {
1379
0
    const Type *type = qualifier->getAsType();
1380
1381
    // We only want to use an unresolved-type encoding if this is one of:
1382
    //   - a decltype
1383
    //   - a template type parameter
1384
    //   - a template template parameter with arguments
1385
    // In all of these cases, we should have no prefix.
1386
0
    if (qualifier->getPrefix()) {
1387
0
      mangleUnresolvedPrefix(qualifier->getPrefix(),
1388
0
                             /*recursive*/ true);
1389
0
    } else {
1390
      // Otherwise, all the cases want this.
1391
0
      Out << "sr";
1392
0
    }
1393
1394
0
    if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
1395
0
      return;
1396
1397
0
    break;
1398
0
  }
1399
1400
0
  case NestedNameSpecifier::Identifier:
1401
    // Member expressions can have these without prefixes.
1402
0
    if (qualifier->getPrefix())
1403
0
      mangleUnresolvedPrefix(qualifier->getPrefix(),
1404
0
                             /*recursive*/ true);
1405
0
    else
1406
0
      Out << "sr";
1407
1408
0
    mangleSourceName(qualifier->getAsIdentifier());
1409
    // An Identifier has no type information, so we can't emit abi tags for it.
1410
0
    break;
1411
0
  }
1412
1413
  // If this was the innermost part of the NNS, and we fell out to
1414
  // here, append an 'E'.
1415
0
  if (!recursive)
1416
0
    Out << 'E';
1417
0
}
1418
1419
/// Mangle an unresolved-name, which is generally used for names which
1420
/// weren't resolved to specific entities.
1421
void CXXNameMangler::mangleUnresolvedName(
1422
    NestedNameSpecifier *qualifier, DeclarationName name,
1423
    const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1424
0
    unsigned knownArity) {
1425
0
  if (qualifier) mangleUnresolvedPrefix(qualifier);
1426
0
  switch (name.getNameKind()) {
1427
    // <base-unresolved-name> ::= <simple-id>
1428
0
    case DeclarationName::Identifier:
1429
0
      mangleSourceName(name.getAsIdentifierInfo());
1430
0
      break;
1431
    // <base-unresolved-name> ::= dn <destructor-name>
1432
0
    case DeclarationName::CXXDestructorName:
1433
0
      Out << "dn";
1434
0
      mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
1435
0
      break;
1436
    // <base-unresolved-name> ::= on <operator-name>
1437
0
    case DeclarationName::CXXConversionFunctionName:
1438
0
    case DeclarationName::CXXLiteralOperatorName:
1439
0
    case DeclarationName::CXXOperatorName:
1440
0
      Out << "on";
1441
0
      mangleOperatorName(name, knownArity);
1442
0
      break;
1443
0
    case DeclarationName::CXXConstructorName:
1444
0
      llvm_unreachable("Can't mangle a constructor name!");
1445
0
    case DeclarationName::CXXUsingDirective:
1446
0
      llvm_unreachable("Can't mangle a using directive name!");
1447
0
    case DeclarationName::CXXDeductionGuideName:
1448
0
      llvm_unreachable("Can't mangle a deduction guide name!");
1449
0
    case DeclarationName::ObjCMultiArgSelector:
1450
0
    case DeclarationName::ObjCOneArgSelector:
1451
0
    case DeclarationName::ObjCZeroArgSelector:
1452
0
      llvm_unreachable("Can't mangle Objective-C selector names here!");
1453
0
  }
1454
1455
  // The <simple-id> and on <operator-name> productions end in an optional
1456
  // <template-args>.
1457
0
  if (TemplateArgs)
1458
0
    mangleTemplateArgs(TemplateName(), TemplateArgs, NumTemplateArgs);
1459
0
}
1460
1461
void CXXNameMangler::mangleUnqualifiedName(
1462
    GlobalDecl GD, DeclarationName Name, const DeclContext *DC,
1463
0
    unsigned KnownArity, const AbiTagList *AdditionalAbiTags) {
1464
0
  const NamedDecl *ND = cast_or_null<NamedDecl>(GD.getDecl());
1465
  //  <unqualified-name> ::= [<module-name>] [F] <operator-name>
1466
  //                     ::= <ctor-dtor-name>
1467
  //                     ::= [<module-name>] [F] <source-name>
1468
  //                     ::= [<module-name>] DC <source-name>* E
1469
1470
0
  if (ND && DC && DC->isFileContext())
1471
0
    mangleModuleName(ND);
1472
1473
  // A member-like constrained friend is mangled with a leading 'F'.
1474
  // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
1475
0
  auto *FD = dyn_cast<FunctionDecl>(ND);
1476
0
  auto *FTD = dyn_cast<FunctionTemplateDecl>(ND);
1477
0
  if ((FD && FD->isMemberLikeConstrainedFriend()) ||
1478
0
      (FTD && FTD->getTemplatedDecl()->isMemberLikeConstrainedFriend())) {
1479
0
    if (!isCompatibleWith(LangOptions::ClangABI::Ver17))
1480
0
      Out << 'F';
1481
0
  }
1482
1483
0
  unsigned Arity = KnownArity;
1484
0
  switch (Name.getNameKind()) {
1485
0
  case DeclarationName::Identifier: {
1486
0
    const IdentifierInfo *II = Name.getAsIdentifierInfo();
1487
1488
    // We mangle decomposition declarations as the names of their bindings.
1489
0
    if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
1490
      // FIXME: Non-standard mangling for decomposition declarations:
1491
      //
1492
      //  <unqualified-name> ::= DC <source-name>* E
1493
      //
1494
      // Proposed on cxx-abi-dev on 2016-08-12
1495
0
      Out << "DC";
1496
0
      for (auto *BD : DD->bindings())
1497
0
        mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1498
0
      Out << 'E';
1499
0
      writeAbiTags(ND, AdditionalAbiTags);
1500
0
      break;
1501
0
    }
1502
1503
0
    if (auto *GD = dyn_cast<MSGuidDecl>(ND)) {
1504
      // We follow MSVC in mangling GUID declarations as if they were variables
1505
      // with a particular reserved name. Continue the pretense here.
1506
0
      SmallString<sizeof("_GUID_12345678_1234_1234_1234_1234567890ab")> GUID;
1507
0
      llvm::raw_svector_ostream GUIDOS(GUID);
1508
0
      Context.mangleMSGuidDecl(GD, GUIDOS);
1509
0
      Out << GUID.size() << GUID;
1510
0
      break;
1511
0
    }
1512
1513
0
    if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
1514
      // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
1515
0
      Out << "TA";
1516
0
      mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
1517
0
                               TPO->getValue(), /*TopLevel=*/true);
1518
0
      break;
1519
0
    }
1520
1521
0
    if (II) {
1522
      // Match GCC's naming convention for internal linkage symbols, for
1523
      // symbols that are not actually visible outside of this TU. GCC
1524
      // distinguishes between internal and external linkage symbols in
1525
      // its mangling, to support cases like this that were valid C++ prior
1526
      // to DR426:
1527
      //
1528
      //   void test() { extern void foo(); }
1529
      //   static void foo();
1530
      //
1531
      // Don't bother with the L marker for names in anonymous namespaces; the
1532
      // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
1533
      // matches GCC anyway, because GCC does not treat anonymous namespaces as
1534
      // implying internal linkage.
1535
0
      if (Context.isInternalLinkageDecl(ND))
1536
0
        Out << 'L';
1537
1538
0
      bool IsRegCall = FD &&
1539
0
                       FD->getType()->castAs<FunctionType>()->getCallConv() ==
1540
0
                           clang::CC_X86RegCall;
1541
0
      bool IsDeviceStub =
1542
0
          FD && FD->hasAttr<CUDAGlobalAttr>() &&
1543
0
          GD.getKernelReferenceKind() == KernelReferenceKind::Stub;
1544
0
      if (IsDeviceStub)
1545
0
        mangleDeviceStubName(II);
1546
0
      else if (IsRegCall)
1547
0
        mangleRegCallName(II);
1548
0
      else
1549
0
        mangleSourceName(II);
1550
1551
0
      writeAbiTags(ND, AdditionalAbiTags);
1552
0
      break;
1553
0
    }
1554
1555
    // Otherwise, an anonymous entity.  We must have a declaration.
1556
0
    assert(ND && "mangling empty name without declaration");
1557
1558
0
    if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1559
0
      if (NS->isAnonymousNamespace()) {
1560
        // This is how gcc mangles these names.
1561
0
        Out << "12_GLOBAL__N_1";
1562
0
        break;
1563
0
      }
1564
0
    }
1565
1566
0
    if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1567
      // We must have an anonymous union or struct declaration.
1568
0
      const RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
1569
1570
      // Itanium C++ ABI 5.1.2:
1571
      //
1572
      //   For the purposes of mangling, the name of an anonymous union is
1573
      //   considered to be the name of the first named data member found by a
1574
      //   pre-order, depth-first, declaration-order walk of the data members of
1575
      //   the anonymous union. If there is no such data member (i.e., if all of
1576
      //   the data members in the union are unnamed), then there is no way for
1577
      //   a program to refer to the anonymous union, and there is therefore no
1578
      //   need to mangle its name.
1579
0
      assert(RD->isAnonymousStructOrUnion()
1580
0
             && "Expected anonymous struct or union!");
1581
0
      const FieldDecl *FD = RD->findFirstNamedDataMember();
1582
1583
      // It's actually possible for various reasons for us to get here
1584
      // with an empty anonymous struct / union.  Fortunately, it
1585
      // doesn't really matter what name we generate.
1586
0
      if (!FD) break;
1587
0
      assert(FD->getIdentifier() && "Data member name isn't an identifier!");
1588
1589
0
      mangleSourceName(FD->getIdentifier());
1590
      // Not emitting abi tags: internal name anyway.
1591
0
      break;
1592
0
    }
1593
1594
    // Class extensions have no name as a category, and it's possible
1595
    // for them to be the semantic parent of certain declarations
1596
    // (primarily, tag decls defined within declarations).  Such
1597
    // declarations will always have internal linkage, so the name
1598
    // doesn't really matter, but we shouldn't crash on them.  For
1599
    // safety, just handle all ObjC containers here.
1600
0
    if (isa<ObjCContainerDecl>(ND))
1601
0
      break;
1602
1603
    // We must have an anonymous struct.
1604
0
    const TagDecl *TD = cast<TagDecl>(ND);
1605
0
    if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1606
0
      assert(TD->getDeclContext() == D->getDeclContext() &&
1607
0
             "Typedef should not be in another decl context!");
1608
0
      assert(D->getDeclName().getAsIdentifierInfo() &&
1609
0
             "Typedef was not named!");
1610
0
      mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1611
0
      assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
1612
      // Explicit abi tags are still possible; take from underlying type, not
1613
      // from typedef.
1614
0
      writeAbiTags(TD, nullptr);
1615
0
      break;
1616
0
    }
1617
1618
    // <unnamed-type-name> ::= <closure-type-name>
1619
    //
1620
    // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1621
    // <lambda-sig> ::= <template-param-decl>* <parameter-type>+
1622
    //     # Parameter types or 'v' for 'void'.
1623
0
    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1624
0
      std::optional<unsigned> DeviceNumber =
1625
0
          Context.getDiscriminatorOverride()(Context.getASTContext(), Record);
1626
1627
      // If we have a device-number via the discriminator, use that to mangle
1628
      // the lambda, otherwise use the typical lambda-mangling-number. In either
1629
      // case, a '0' should be mangled as a normal unnamed class instead of as a
1630
      // lambda.
1631
0
      if (Record->isLambda() &&
1632
0
          ((DeviceNumber && *DeviceNumber > 0) ||
1633
0
           (!DeviceNumber && Record->getLambdaManglingNumber() > 0))) {
1634
0
        assert(!AdditionalAbiTags &&
1635
0
               "Lambda type cannot have additional abi tags");
1636
0
        mangleLambda(Record);
1637
0
        break;
1638
0
      }
1639
0
    }
1640
1641
0
    if (TD->isExternallyVisible()) {
1642
0
      unsigned UnnamedMangle =
1643
0
          getASTContext().getManglingNumber(TD, Context.isAux());
1644
0
      Out << "Ut";
1645
0
      if (UnnamedMangle > 1)
1646
0
        Out << UnnamedMangle - 2;
1647
0
      Out << '_';
1648
0
      writeAbiTags(TD, AdditionalAbiTags);
1649
0
      break;
1650
0
    }
1651
1652
    // Get a unique id for the anonymous struct. If it is not a real output
1653
    // ID doesn't matter so use fake one.
1654
0
    unsigned AnonStructId =
1655
0
        NullOut ? 0
1656
0
                : Context.getAnonymousStructId(TD, dyn_cast<FunctionDecl>(DC));
1657
1658
    // Mangle it as a source name in the form
1659
    // [n] $_<id>
1660
    // where n is the length of the string.
1661
0
    SmallString<8> Str;
1662
0
    Str += "$_";
1663
0
    Str += llvm::utostr(AnonStructId);
1664
1665
0
    Out << Str.size();
1666
0
    Out << Str;
1667
0
    break;
1668
0
  }
1669
1670
0
  case DeclarationName::ObjCZeroArgSelector:
1671
0
  case DeclarationName::ObjCOneArgSelector:
1672
0
  case DeclarationName::ObjCMultiArgSelector:
1673
0
    llvm_unreachable("Can't mangle Objective-C selector names here!");
1674
1675
0
  case DeclarationName::CXXConstructorName: {
1676
0
    const CXXRecordDecl *InheritedFrom = nullptr;
1677
0
    TemplateName InheritedTemplateName;
1678
0
    const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1679
0
    if (auto Inherited =
1680
0
            cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1681
0
      InheritedFrom = Inherited.getConstructor()->getParent();
1682
0
      InheritedTemplateName =
1683
0
          TemplateName(Inherited.getConstructor()->getPrimaryTemplate());
1684
0
      InheritedTemplateArgs =
1685
0
          Inherited.getConstructor()->getTemplateSpecializationArgs();
1686
0
    }
1687
1688
0
    if (ND == Structor)
1689
      // If the named decl is the C++ constructor we're mangling, use the type
1690
      // we were given.
1691
0
      mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
1692
0
    else
1693
      // Otherwise, use the complete constructor name. This is relevant if a
1694
      // class with a constructor is declared within a constructor.
1695
0
      mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1696
1697
    // FIXME: The template arguments are part of the enclosing prefix or
1698
    // nested-name, but it's more convenient to mangle them here.
1699
0
    if (InheritedTemplateArgs)
1700
0
      mangleTemplateArgs(InheritedTemplateName, *InheritedTemplateArgs);
1701
1702
0
    writeAbiTags(ND, AdditionalAbiTags);
1703
0
    break;
1704
0
  }
1705
1706
0
  case DeclarationName::CXXDestructorName:
1707
0
    if (ND == Structor)
1708
      // If the named decl is the C++ destructor we're mangling, use the type we
1709
      // were given.
1710
0
      mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1711
0
    else
1712
      // Otherwise, use the complete destructor name. This is relevant if a
1713
      // class with a destructor is declared within a destructor.
1714
0
      mangleCXXDtorType(Dtor_Complete);
1715
0
    assert(ND);
1716
0
    writeAbiTags(ND, AdditionalAbiTags);
1717
0
    break;
1718
1719
0
  case DeclarationName::CXXOperatorName:
1720
0
    if (ND && Arity == UnknownArity) {
1721
0
      Arity = cast<FunctionDecl>(ND)->getNumParams();
1722
1723
      // If we have a member function, we need to include the 'this' pointer.
1724
0
      if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1725
0
        if (MD->isImplicitObjectMemberFunction())
1726
0
          Arity++;
1727
0
    }
1728
0
    [[fallthrough]];
1729
0
  case DeclarationName::CXXConversionFunctionName:
1730
0
  case DeclarationName::CXXLiteralOperatorName:
1731
0
    mangleOperatorName(Name, Arity);
1732
0
    writeAbiTags(ND, AdditionalAbiTags);
1733
0
    break;
1734
1735
0
  case DeclarationName::CXXDeductionGuideName:
1736
0
    llvm_unreachable("Can't mangle a deduction guide name!");
1737
1738
0
  case DeclarationName::CXXUsingDirective:
1739
0
    llvm_unreachable("Can't mangle a using directive name!");
1740
0
  }
1741
0
}
1742
1743
0
void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
1744
  // <source-name> ::= <positive length number> __regcall3__ <identifier>
1745
  // <number> ::= [n] <non-negative decimal integer>
1746
  // <identifier> ::= <unqualified source code identifier>
1747
0
  if (getASTContext().getLangOpts().RegCall4)
1748
0
    Out << II->getLength() + sizeof("__regcall4__") - 1 << "__regcall4__"
1749
0
        << II->getName();
1750
0
  else
1751
0
    Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1752
0
        << II->getName();
1753
0
}
1754
1755
0
void CXXNameMangler::mangleDeviceStubName(const IdentifierInfo *II) {
1756
  // <source-name> ::= <positive length number> __device_stub__ <identifier>
1757
  // <number> ::= [n] <non-negative decimal integer>
1758
  // <identifier> ::= <unqualified source code identifier>
1759
0
  Out << II->getLength() + sizeof("__device_stub__") - 1 << "__device_stub__"
1760
0
      << II->getName();
1761
0
}
1762
1763
0
void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1764
  // <source-name> ::= <positive length number> <identifier>
1765
  // <number> ::= [n] <non-negative decimal integer>
1766
  // <identifier> ::= <unqualified source code identifier>
1767
0
  Out << II->getLength() << II->getName();
1768
0
}
1769
1770
void CXXNameMangler::mangleNestedName(GlobalDecl GD,
1771
                                      const DeclContext *DC,
1772
                                      const AbiTagList *AdditionalAbiTags,
1773
0
                                      bool NoFunction) {
1774
0
  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1775
  // <nested-name>
1776
  //   ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1777
  //   ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1778
  //       <template-args> E
1779
1780
0
  Out << 'N';
1781
0
  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1782
0
    Qualifiers MethodQuals = Method->getMethodQualifiers();
1783
    // We do not consider restrict a distinguishing attribute for overloading
1784
    // purposes so we must not mangle it.
1785
0
    if (Method->isExplicitObjectMemberFunction())
1786
0
      Out << 'H';
1787
0
    MethodQuals.removeRestrict();
1788
0
    mangleQualifiers(MethodQuals);
1789
0
    mangleRefQualifier(Method->getRefQualifier());
1790
0
  }
1791
1792
  // Check if we have a template.
1793
0
  const TemplateArgumentList *TemplateArgs = nullptr;
1794
0
  if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
1795
0
    mangleTemplatePrefix(TD, NoFunction);
1796
0
    mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
1797
0
  } else {
1798
0
    manglePrefix(DC, NoFunction);
1799
0
    mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1800
0
  }
1801
1802
0
  Out << 'E';
1803
0
}
1804
void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1805
0
                                      ArrayRef<TemplateArgument> Args) {
1806
  // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1807
1808
0
  Out << 'N';
1809
1810
0
  mangleTemplatePrefix(TD);
1811
0
  mangleTemplateArgs(asTemplateName(TD), Args);
1812
1813
0
  Out << 'E';
1814
0
}
1815
1816
void CXXNameMangler::mangleNestedNameWithClosurePrefix(
1817
    GlobalDecl GD, const NamedDecl *PrefixND,
1818
0
    const AbiTagList *AdditionalAbiTags) {
1819
  // A <closure-prefix> represents a variable or field, not a regular
1820
  // DeclContext, so needs special handling. In this case we're mangling a
1821
  // limited form of <nested-name>:
1822
  //
1823
  // <nested-name> ::= N <closure-prefix> <closure-type-name> E
1824
1825
0
  Out << 'N';
1826
1827
0
  mangleClosurePrefix(PrefixND);
1828
0
  mangleUnqualifiedName(GD, nullptr, AdditionalAbiTags);
1829
1830
0
  Out << 'E';
1831
0
}
1832
1833
0
static GlobalDecl getParentOfLocalEntity(const DeclContext *DC) {
1834
0
  GlobalDecl GD;
1835
  // The Itanium spec says:
1836
  // For entities in constructors and destructors, the mangling of the
1837
  // complete object constructor or destructor is used as the base function
1838
  // name, i.e. the C1 or D1 version.
1839
0
  if (auto *CD = dyn_cast<CXXConstructorDecl>(DC))
1840
0
    GD = GlobalDecl(CD, Ctor_Complete);
1841
0
  else if (auto *DD = dyn_cast<CXXDestructorDecl>(DC))
1842
0
    GD = GlobalDecl(DD, Dtor_Complete);
1843
0
  else
1844
0
    GD = GlobalDecl(cast<FunctionDecl>(DC));
1845
0
  return GD;
1846
0
}
1847
1848
void CXXNameMangler::mangleLocalName(GlobalDecl GD,
1849
0
                                     const AbiTagList *AdditionalAbiTags) {
1850
0
  const Decl *D = GD.getDecl();
1851
  // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1852
  //              := Z <function encoding> E s [<discriminator>]
1853
  // <local-name> := Z <function encoding> E d [ <parameter number> ]
1854
  //                 _ <entity name>
1855
  // <discriminator> := _ <non-negative number>
1856
0
  assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
1857
0
  const RecordDecl *RD = GetLocalClassDecl(D);
1858
0
  const DeclContext *DC = Context.getEffectiveDeclContext(RD ? RD : D);
1859
1860
0
  Out << 'Z';
1861
1862
0
  {
1863
0
    AbiTagState LocalAbiTags(AbiTags);
1864
1865
0
    if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1866
0
      mangleObjCMethodName(MD);
1867
0
    else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1868
0
      mangleBlockForPrefix(BD);
1869
0
    else
1870
0
      mangleFunctionEncoding(getParentOfLocalEntity(DC));
1871
1872
    // Implicit ABI tags (from namespace) are not available in the following
1873
    // entity; reset to actually emitted tags, which are available.
1874
0
    LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1875
0
  }
1876
1877
0
  Out << 'E';
1878
1879
  // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1880
  // be a bug that is fixed in trunk.
1881
1882
0
  if (RD) {
1883
    // The parameter number is omitted for the last parameter, 0 for the
1884
    // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1885
    // <entity name> will of course contain a <closure-type-name>: Its
1886
    // numbering will be local to the particular argument in which it appears
1887
    // -- other default arguments do not affect its encoding.
1888
0
    const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1889
0
    if (CXXRD && CXXRD->isLambda()) {
1890
0
      if (const ParmVarDecl *Parm
1891
0
              = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
1892
0
        if (const FunctionDecl *Func
1893
0
              = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1894
0
          Out << 'd';
1895
0
          unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1896
0
          if (Num > 1)
1897
0
            mangleNumber(Num - 2);
1898
0
          Out << '_';
1899
0
        }
1900
0
      }
1901
0
    }
1902
1903
    // Mangle the name relative to the closest enclosing function.
1904
    // equality ok because RD derived from ND above
1905
0
    if (D == RD)  {
1906
0
      mangleUnqualifiedName(RD, DC, AdditionalAbiTags);
1907
0
    } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1908
0
      if (const NamedDecl *PrefixND = getClosurePrefix(BD))
1909
0
        mangleClosurePrefix(PrefixND, true /*NoFunction*/);
1910
0
      else
1911
0
        manglePrefix(Context.getEffectiveDeclContext(BD), true /*NoFunction*/);
1912
0
      assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1913
0
      mangleUnqualifiedBlock(BD);
1914
0
    } else {
1915
0
      const NamedDecl *ND = cast<NamedDecl>(D);
1916
0
      mangleNestedName(GD, Context.getEffectiveDeclContext(ND),
1917
0
                       AdditionalAbiTags, true /*NoFunction*/);
1918
0
    }
1919
0
  } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1920
    // Mangle a block in a default parameter; see above explanation for
1921
    // lambdas.
1922
0
    if (const ParmVarDecl *Parm
1923
0
            = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1924
0
      if (const FunctionDecl *Func
1925
0
            = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1926
0
        Out << 'd';
1927
0
        unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1928
0
        if (Num > 1)
1929
0
          mangleNumber(Num - 2);
1930
0
        Out << '_';
1931
0
      }
1932
0
    }
1933
1934
0
    assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1935
0
    mangleUnqualifiedBlock(BD);
1936
0
  } else {
1937
0
    mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
1938
0
  }
1939
1940
0
  if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1941
0
    unsigned disc;
1942
0
    if (Context.getNextDiscriminator(ND, disc)) {
1943
0
      if (disc < 10)
1944
0
        Out << '_' << disc;
1945
0
      else
1946
0
        Out << "__" << disc << '_';
1947
0
    }
1948
0
  }
1949
0
}
1950
1951
0
void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1952
0
  if (GetLocalClassDecl(Block)) {
1953
0
    mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1954
0
    return;
1955
0
  }
1956
0
  const DeclContext *DC = Context.getEffectiveDeclContext(Block);
1957
0
  if (isLocalContainerContext(DC)) {
1958
0
    mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1959
0
    return;
1960
0
  }
1961
0
  if (const NamedDecl *PrefixND = getClosurePrefix(Block))
1962
0
    mangleClosurePrefix(PrefixND);
1963
0
  else
1964
0
    manglePrefix(DC);
1965
0
  mangleUnqualifiedBlock(Block);
1966
0
}
1967
1968
0
void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1969
  // When trying to be ABI-compatibility with clang 12 and before, mangle a
1970
  // <data-member-prefix> now, with no substitutions and no <template-args>.
1971
0
  if (Decl *Context = Block->getBlockManglingContextDecl()) {
1972
0
    if (isCompatibleWith(LangOptions::ClangABI::Ver12) &&
1973
0
        (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1974
0
        Context->getDeclContext()->isRecord()) {
1975
0
      const auto *ND = cast<NamedDecl>(Context);
1976
0
      if (ND->getIdentifier()) {
1977
0
        mangleSourceNameWithAbiTags(ND);
1978
0
        Out << 'M';
1979
0
      }
1980
0
    }
1981
0
  }
1982
1983
  // If we have a block mangling number, use it.
1984
0
  unsigned Number = Block->getBlockManglingNumber();
1985
  // Otherwise, just make up a number. It doesn't matter what it is because
1986
  // the symbol in question isn't externally visible.
1987
0
  if (!Number)
1988
0
    Number = Context.getBlockId(Block, false);
1989
0
  else {
1990
    // Stored mangling numbers are 1-based.
1991
0
    --Number;
1992
0
  }
1993
0
  Out << "Ub";
1994
0
  if (Number > 0)
1995
0
    Out << Number - 1;
1996
0
  Out << '_';
1997
0
}
1998
1999
// <template-param-decl>
2000
//   ::= Ty                                  # template type parameter
2001
//   ::= Tk <concept name> [<template-args>] # constrained type parameter
2002
//   ::= Tn <type>                           # template non-type parameter
2003
//   ::= Tt <template-param-decl>* E [Q <requires-clause expr>]
2004
//                                           # template template parameter
2005
//   ::= Tp <template-param-decl>            # template parameter pack
2006
0
void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) {
2007
  // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
2008
0
  if (auto *Ty = dyn_cast<TemplateTypeParmDecl>(Decl)) {
2009
0
    if (Ty->isParameterPack())
2010
0
      Out << "Tp";
2011
0
    const TypeConstraint *Constraint = Ty->getTypeConstraint();
2012
0
    if (Constraint && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
2013
      // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
2014
0
      Out << "Tk";
2015
0
      mangleTypeConstraint(Constraint);
2016
0
    } else {
2017
0
      Out << "Ty";
2018
0
    }
2019
0
  } else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Decl)) {
2020
0
    if (Tn->isExpandedParameterPack()) {
2021
0
      for (unsigned I = 0, N = Tn->getNumExpansionTypes(); I != N; ++I) {
2022
0
        Out << "Tn";
2023
0
        mangleType(Tn->getExpansionType(I));
2024
0
      }
2025
0
    } else {
2026
0
      QualType T = Tn->getType();
2027
0
      if (Tn->isParameterPack()) {
2028
0
        Out << "Tp";
2029
0
        if (auto *PackExpansion = T->getAs<PackExpansionType>())
2030
0
          T = PackExpansion->getPattern();
2031
0
      }
2032
0
      Out << "Tn";
2033
0
      mangleType(T);
2034
0
    }
2035
0
  } else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Decl)) {
2036
0
    if (Tt->isExpandedParameterPack()) {
2037
0
      for (unsigned I = 0, N = Tt->getNumExpansionTemplateParameters(); I != N;
2038
0
           ++I)
2039
0
        mangleTemplateParameterList(Tt->getExpansionTemplateParameters(I));
2040
0
    } else {
2041
0
      if (Tt->isParameterPack())
2042
0
        Out << "Tp";
2043
0
      mangleTemplateParameterList(Tt->getTemplateParameters());
2044
0
    }
2045
0
  }
2046
0
}
2047
2048
void CXXNameMangler::mangleTemplateParameterList(
2049
0
    const TemplateParameterList *Params) {
2050
0
  Out << "Tt";
2051
0
  for (auto *Param : *Params)
2052
0
    mangleTemplateParamDecl(Param);
2053
0
  mangleRequiresClause(Params->getRequiresClause());
2054
0
  Out << "E";
2055
0
}
2056
2057
void CXXNameMangler::mangleTypeConstraint(
2058
0
    const ConceptDecl *Concept, ArrayRef<TemplateArgument> Arguments) {
2059
0
  const DeclContext *DC = Context.getEffectiveDeclContext(Concept);
2060
0
  if (!Arguments.empty())
2061
0
    mangleTemplateName(Concept, Arguments);
2062
0
  else if (DC->isTranslationUnit() || isStdNamespace(DC))
2063
0
    mangleUnscopedName(Concept, DC, nullptr);
2064
0
  else
2065
0
    mangleNestedName(Concept, DC, nullptr);
2066
0
}
2067
2068
0
void CXXNameMangler::mangleTypeConstraint(const TypeConstraint *Constraint) {
2069
0
  llvm::SmallVector<TemplateArgument, 8> Args;
2070
0
  if (Constraint->getTemplateArgsAsWritten()) {
2071
0
    for (const TemplateArgumentLoc &ArgLoc :
2072
0
         Constraint->getTemplateArgsAsWritten()->arguments())
2073
0
      Args.push_back(ArgLoc.getArgument());
2074
0
  }
2075
0
  return mangleTypeConstraint(Constraint->getNamedConcept(), Args);
2076
0
}
2077
2078
0
void CXXNameMangler::mangleRequiresClause(const Expr *RequiresClause) {
2079
  // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
2080
0
  if (RequiresClause && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
2081
0
    Out << 'Q';
2082
0
    mangleExpression(RequiresClause);
2083
0
  }
2084
0
}
2085
2086
0
void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
2087
  // When trying to be ABI-compatibility with clang 12 and before, mangle a
2088
  // <data-member-prefix> now, with no substitutions.
2089
0
  if (Decl *Context = Lambda->getLambdaContextDecl()) {
2090
0
    if (isCompatibleWith(LangOptions::ClangABI::Ver12) &&
2091
0
        (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
2092
0
        !isa<ParmVarDecl>(Context)) {
2093
0
      if (const IdentifierInfo *Name
2094
0
            = cast<NamedDecl>(Context)->getIdentifier()) {
2095
0
        mangleSourceName(Name);
2096
0
        const TemplateArgumentList *TemplateArgs = nullptr;
2097
0
        if (GlobalDecl TD = isTemplate(cast<NamedDecl>(Context), TemplateArgs))
2098
0
          mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2099
0
        Out << 'M';
2100
0
      }
2101
0
    }
2102
0
  }
2103
2104
0
  Out << "Ul";
2105
0
  mangleLambdaSig(Lambda);
2106
0
  Out << "E";
2107
2108
  // The number is omitted for the first closure type with a given
2109
  // <lambda-sig> in a given context; it is n-2 for the nth closure type
2110
  // (in lexical order) with that same <lambda-sig> and context.
2111
  //
2112
  // The AST keeps track of the number for us.
2113
  //
2114
  // In CUDA/HIP, to ensure the consistent lamba numbering between the device-
2115
  // and host-side compilations, an extra device mangle context may be created
2116
  // if the host-side CXX ABI has different numbering for lambda. In such case,
2117
  // if the mangle context is that device-side one, use the device-side lambda
2118
  // mangling number for this lambda.
2119
0
  std::optional<unsigned> DeviceNumber =
2120
0
      Context.getDiscriminatorOverride()(Context.getASTContext(), Lambda);
2121
0
  unsigned Number =
2122
0
      DeviceNumber ? *DeviceNumber : Lambda->getLambdaManglingNumber();
2123
2124
0
  assert(Number > 0 && "Lambda should be mangled as an unnamed class");
2125
0
  if (Number > 1)
2126
0
    mangleNumber(Number - 2);
2127
0
  Out << '_';
2128
0
}
2129
2130
0
void CXXNameMangler::mangleLambdaSig(const CXXRecordDecl *Lambda) {
2131
  // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/31.
2132
0
  for (auto *D : Lambda->getLambdaExplicitTemplateParameters())
2133
0
    mangleTemplateParamDecl(D);
2134
2135
  // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
2136
0
  if (auto *TPL = Lambda->getGenericLambdaTemplateParameterList())
2137
0
    mangleRequiresClause(TPL->getRequiresClause());
2138
2139
0
  auto *Proto =
2140
0
      Lambda->getLambdaTypeInfo()->getType()->castAs<FunctionProtoType>();
2141
0
  mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
2142
0
                         Lambda->getLambdaStaticInvoker());
2143
0
}
2144
2145
0
void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
2146
0
  switch (qualifier->getKind()) {
2147
0
  case NestedNameSpecifier::Global:
2148
    // nothing
2149
0
    return;
2150
2151
0
  case NestedNameSpecifier::Super:
2152
0
    llvm_unreachable("Can't mangle __super specifier");
2153
2154
0
  case NestedNameSpecifier::Namespace:
2155
0
    mangleName(qualifier->getAsNamespace());
2156
0
    return;
2157
2158
0
  case NestedNameSpecifier::NamespaceAlias:
2159
0
    mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
2160
0
    return;
2161
2162
0
  case NestedNameSpecifier::TypeSpec:
2163
0
  case NestedNameSpecifier::TypeSpecWithTemplate:
2164
0
    manglePrefix(QualType(qualifier->getAsType(), 0));
2165
0
    return;
2166
2167
0
  case NestedNameSpecifier::Identifier:
2168
    // Clang 14 and before did not consider this substitutable.
2169
0
    bool Clang14Compat = isCompatibleWith(LangOptions::ClangABI::Ver14);
2170
0
    if (!Clang14Compat && mangleSubstitution(qualifier))
2171
0
      return;
2172
2173
    // Member expressions can have these without prefixes, but that
2174
    // should end up in mangleUnresolvedPrefix instead.
2175
0
    assert(qualifier->getPrefix());
2176
0
    manglePrefix(qualifier->getPrefix());
2177
2178
0
    mangleSourceName(qualifier->getAsIdentifier());
2179
2180
0
    if (!Clang14Compat)
2181
0
      addSubstitution(qualifier);
2182
0
    return;
2183
0
  }
2184
2185
0
  llvm_unreachable("unexpected nested name specifier");
2186
0
}
2187
2188
0
void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
2189
  //  <prefix> ::= <prefix> <unqualified-name>
2190
  //           ::= <template-prefix> <template-args>
2191
  //           ::= <closure-prefix>
2192
  //           ::= <template-param>
2193
  //           ::= # empty
2194
  //           ::= <substitution>
2195
2196
0
  assert(!isa<LinkageSpecDecl>(DC) && "prefix cannot be LinkageSpecDecl");
2197
2198
0
  if (DC->isTranslationUnit())
2199
0
    return;
2200
2201
0
  if (NoFunction && isLocalContainerContext(DC))
2202
0
    return;
2203
2204
0
  assert(!isLocalContainerContext(DC));
2205
2206
0
  const NamedDecl *ND = cast<NamedDecl>(DC);
2207
0
  if (mangleSubstitution(ND))
2208
0
    return;
2209
2210
  // Check if we have a template-prefix or a closure-prefix.
2211
0
  const TemplateArgumentList *TemplateArgs = nullptr;
2212
0
  if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
2213
0
    mangleTemplatePrefix(TD);
2214
0
    mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2215
0
  } else if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
2216
0
    mangleClosurePrefix(PrefixND, NoFunction);
2217
0
    mangleUnqualifiedName(ND, nullptr, nullptr);
2218
0
  } else {
2219
0
    const DeclContext *DC = Context.getEffectiveDeclContext(ND);
2220
0
    manglePrefix(DC, NoFunction);
2221
0
    mangleUnqualifiedName(ND, DC, nullptr);
2222
0
  }
2223
2224
0
  addSubstitution(ND);
2225
0
}
2226
2227
0
void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
2228
  // <template-prefix> ::= <prefix> <template unqualified-name>
2229
  //                   ::= <template-param>
2230
  //                   ::= <substitution>
2231
0
  if (TemplateDecl *TD = Template.getAsTemplateDecl())
2232
0
    return mangleTemplatePrefix(TD);
2233
2234
0
  DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
2235
0
  assert(Dependent && "unexpected template name kind");
2236
2237
  // Clang 11 and before mangled the substitution for a dependent template name
2238
  // after already having emitted (a substitution for) the prefix.
2239
0
  bool Clang11Compat = isCompatibleWith(LangOptions::ClangABI::Ver11);
2240
0
  if (!Clang11Compat && mangleSubstitution(Template))
2241
0
    return;
2242
2243
0
  if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
2244
0
    manglePrefix(Qualifier);
2245
2246
0
  if (Clang11Compat && mangleSubstitution(Template))
2247
0
    return;
2248
2249
0
  if (const IdentifierInfo *Id = Dependent->getIdentifier())
2250
0
    mangleSourceName(Id);
2251
0
  else
2252
0
    mangleOperatorName(Dependent->getOperator(), UnknownArity);
2253
2254
0
  addSubstitution(Template);
2255
0
}
2256
2257
void CXXNameMangler::mangleTemplatePrefix(GlobalDecl GD,
2258
0
                                          bool NoFunction) {
2259
0
  const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
2260
  // <template-prefix> ::= <prefix> <template unqualified-name>
2261
  //                   ::= <template-param>
2262
  //                   ::= <substitution>
2263
  // <template-template-param> ::= <template-param>
2264
  //                               <substitution>
2265
2266
0
  if (mangleSubstitution(ND))
2267
0
    return;
2268
2269
  // <template-template-param> ::= <template-param>
2270
0
  if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
2271
0
    mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
2272
0
  } else {
2273
0
    const DeclContext *DC = Context.getEffectiveDeclContext(ND);
2274
0
    manglePrefix(DC, NoFunction);
2275
0
    if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND))
2276
0
      mangleUnqualifiedName(GD, DC, nullptr);
2277
0
    else
2278
0
      mangleUnqualifiedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
2279
0
                            nullptr);
2280
0
  }
2281
2282
0
  addSubstitution(ND);
2283
0
}
2284
2285
0
const NamedDecl *CXXNameMangler::getClosurePrefix(const Decl *ND) {
2286
0
  if (isCompatibleWith(LangOptions::ClangABI::Ver12))
2287
0
    return nullptr;
2288
2289
0
  const NamedDecl *Context = nullptr;
2290
0
  if (auto *Block = dyn_cast<BlockDecl>(ND)) {
2291
0
    Context = dyn_cast_or_null<NamedDecl>(Block->getBlockManglingContextDecl());
2292
0
  } else if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
2293
0
    if (RD->isLambda())
2294
0
      Context = dyn_cast_or_null<NamedDecl>(RD->getLambdaContextDecl());
2295
0
  }
2296
0
  if (!Context)
2297
0
    return nullptr;
2298
2299
  // Only lambdas within the initializer of a non-local variable or non-static
2300
  // data member get a <closure-prefix>.
2301
0
  if ((isa<VarDecl>(Context) && cast<VarDecl>(Context)->hasGlobalStorage()) ||
2302
0
      isa<FieldDecl>(Context))
2303
0
    return Context;
2304
2305
0
  return nullptr;
2306
0
}
2307
2308
0
void CXXNameMangler::mangleClosurePrefix(const NamedDecl *ND, bool NoFunction) {
2309
  //  <closure-prefix> ::= [ <prefix> ] <unqualified-name> M
2310
  //                   ::= <template-prefix> <template-args> M
2311
0
  if (mangleSubstitution(ND))
2312
0
    return;
2313
2314
0
  const TemplateArgumentList *TemplateArgs = nullptr;
2315
0
  if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
2316
0
    mangleTemplatePrefix(TD, NoFunction);
2317
0
    mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
2318
0
  } else {
2319
0
    const auto *DC = Context.getEffectiveDeclContext(ND);
2320
0
    manglePrefix(DC, NoFunction);
2321
0
    mangleUnqualifiedName(ND, DC, nullptr);
2322
0
  }
2323
2324
0
  Out << 'M';
2325
2326
0
  addSubstitution(ND);
2327
0
}
2328
2329
/// Mangles a template name under the production <type>.  Required for
2330
/// template template arguments.
2331
///   <type> ::= <class-enum-type>
2332
///          ::= <template-param>
2333
///          ::= <substitution>
2334
0
void CXXNameMangler::mangleType(TemplateName TN) {
2335
0
  if (mangleSubstitution(TN))
2336
0
    return;
2337
2338
0
  TemplateDecl *TD = nullptr;
2339
2340
0
  switch (TN.getKind()) {
2341
0
  case TemplateName::QualifiedTemplate:
2342
0
  case TemplateName::UsingTemplate:
2343
0
  case TemplateName::Template:
2344
0
    TD = TN.getAsTemplateDecl();
2345
0
    goto HaveDecl;
2346
2347
0
  HaveDecl:
2348
0
    if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TD))
2349
0
      mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
2350
0
    else
2351
0
      mangleName(TD);
2352
0
    break;
2353
2354
0
  case TemplateName::OverloadedTemplate:
2355
0
  case TemplateName::AssumedTemplate:
2356
0
    llvm_unreachable("can't mangle an overloaded template name as a <type>");
2357
2358
0
  case TemplateName::DependentTemplate: {
2359
0
    const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
2360
0
    assert(Dependent->isIdentifier());
2361
2362
    // <class-enum-type> ::= <name>
2363
    // <name> ::= <nested-name>
2364
0
    mangleUnresolvedPrefix(Dependent->getQualifier());
2365
0
    mangleSourceName(Dependent->getIdentifier());
2366
0
    break;
2367
0
  }
2368
2369
0
  case TemplateName::SubstTemplateTemplateParm: {
2370
    // Substituted template parameters are mangled as the substituted
2371
    // template.  This will check for the substitution twice, which is
2372
    // fine, but we have to return early so that we don't try to *add*
2373
    // the substitution twice.
2374
0
    SubstTemplateTemplateParmStorage *subst
2375
0
      = TN.getAsSubstTemplateTemplateParm();
2376
0
    mangleType(subst->getReplacement());
2377
0
    return;
2378
0
  }
2379
2380
0
  case TemplateName::SubstTemplateTemplateParmPack: {
2381
    // FIXME: not clear how to mangle this!
2382
    // template <template <class> class T...> class A {
2383
    //   template <template <class> class U...> void foo(B<T,U> x...);
2384
    // };
2385
0
    Out << "_SUBSTPACK_";
2386
0
    break;
2387
0
  }
2388
0
  }
2389
2390
0
  addSubstitution(TN);
2391
0
}
2392
2393
bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
2394
0
                                                    StringRef Prefix) {
2395
  // Only certain other types are valid as prefixes;  enumerate them.
2396
0
  switch (Ty->getTypeClass()) {
2397
0
  case Type::Builtin:
2398
0
  case Type::Complex:
2399
0
  case Type::Adjusted:
2400
0
  case Type::Decayed:
2401
0
  case Type::Pointer:
2402
0
  case Type::BlockPointer:
2403
0
  case Type::LValueReference:
2404
0
  case Type::RValueReference:
2405
0
  case Type::MemberPointer:
2406
0
  case Type::ConstantArray:
2407
0
  case Type::IncompleteArray:
2408
0
  case Type::VariableArray:
2409
0
  case Type::DependentSizedArray:
2410
0
  case Type::DependentAddressSpace:
2411
0
  case Type::DependentVector:
2412
0
  case Type::DependentSizedExtVector:
2413
0
  case Type::Vector:
2414
0
  case Type::ExtVector:
2415
0
  case Type::ConstantMatrix:
2416
0
  case Type::DependentSizedMatrix:
2417
0
  case Type::FunctionProto:
2418
0
  case Type::FunctionNoProto:
2419
0
  case Type::Paren:
2420
0
  case Type::Attributed:
2421
0
  case Type::BTFTagAttributed:
2422
0
  case Type::Auto:
2423
0
  case Type::DeducedTemplateSpecialization:
2424
0
  case Type::PackExpansion:
2425
0
  case Type::ObjCObject:
2426
0
  case Type::ObjCInterface:
2427
0
  case Type::ObjCObjectPointer:
2428
0
  case Type::ObjCTypeParam:
2429
0
  case Type::Atomic:
2430
0
  case Type::Pipe:
2431
0
  case Type::MacroQualified:
2432
0
  case Type::BitInt:
2433
0
  case Type::DependentBitInt:
2434
0
    llvm_unreachable("type is illegal as a nested name specifier");
2435
2436
0
  case Type::SubstTemplateTypeParmPack:
2437
    // FIXME: not clear how to mangle this!
2438
    // template <class T...> class A {
2439
    //   template <class U...> void foo(decltype(T::foo(U())) x...);
2440
    // };
2441
0
    Out << "_SUBSTPACK_";
2442
0
    break;
2443
2444
  // <unresolved-type> ::= <template-param>
2445
  //                   ::= <decltype>
2446
  //                   ::= <template-template-param> <template-args>
2447
  // (this last is not official yet)
2448
0
  case Type::TypeOfExpr:
2449
0
  case Type::TypeOf:
2450
0
  case Type::Decltype:
2451
0
  case Type::TemplateTypeParm:
2452
0
  case Type::UnaryTransform:
2453
0
  case Type::SubstTemplateTypeParm:
2454
0
  unresolvedType:
2455
    // Some callers want a prefix before the mangled type.
2456
0
    Out << Prefix;
2457
2458
    // This seems to do everything we want.  It's not really
2459
    // sanctioned for a substituted template parameter, though.
2460
0
    mangleType(Ty);
2461
2462
    // We never want to print 'E' directly after an unresolved-type,
2463
    // so we return directly.
2464
0
    return true;
2465
2466
0
  case Type::Typedef:
2467
0
    mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
2468
0
    break;
2469
2470
0
  case Type::UnresolvedUsing:
2471
0
    mangleSourceNameWithAbiTags(
2472
0
        cast<UnresolvedUsingType>(Ty)->getDecl());
2473
0
    break;
2474
2475
0
  case Type::Enum:
2476
0
  case Type::Record:
2477
0
    mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
2478
0
    break;
2479
2480
0
  case Type::TemplateSpecialization: {
2481
0
    const TemplateSpecializationType *TST =
2482
0
        cast<TemplateSpecializationType>(Ty);
2483
0
    TemplateName TN = TST->getTemplateName();
2484
0
    switch (TN.getKind()) {
2485
0
    case TemplateName::Template:
2486
0
    case TemplateName::QualifiedTemplate: {
2487
0
      TemplateDecl *TD = TN.getAsTemplateDecl();
2488
2489
      // If the base is a template template parameter, this is an
2490
      // unresolved type.
2491
0
      assert(TD && "no template for template specialization type");
2492
0
      if (isa<TemplateTemplateParmDecl>(TD))
2493
0
        goto unresolvedType;
2494
2495
0
      mangleSourceNameWithAbiTags(TD);
2496
0
      break;
2497
0
    }
2498
2499
0
    case TemplateName::OverloadedTemplate:
2500
0
    case TemplateName::AssumedTemplate:
2501
0
    case TemplateName::DependentTemplate:
2502
0
      llvm_unreachable("invalid base for a template specialization type");
2503
2504
0
    case TemplateName::SubstTemplateTemplateParm: {
2505
0
      SubstTemplateTemplateParmStorage *subst =
2506
0
          TN.getAsSubstTemplateTemplateParm();
2507
0
      mangleExistingSubstitution(subst->getReplacement());
2508
0
      break;
2509
0
    }
2510
2511
0
    case TemplateName::SubstTemplateTemplateParmPack: {
2512
      // FIXME: not clear how to mangle this!
2513
      // template <template <class U> class T...> class A {
2514
      //   template <class U...> void foo(decltype(T<U>::foo) x...);
2515
      // };
2516
0
      Out << "_SUBSTPACK_";
2517
0
      break;
2518
0
    }
2519
0
    case TemplateName::UsingTemplate: {
2520
0
      TemplateDecl *TD = TN.getAsTemplateDecl();
2521
0
      assert(TD && !isa<TemplateTemplateParmDecl>(TD));
2522
0
      mangleSourceNameWithAbiTags(TD);
2523
0
      break;
2524
0
    }
2525
0
    }
2526
2527
    // Note: we don't pass in the template name here. We are mangling the
2528
    // original source-level template arguments, so we shouldn't consider
2529
    // conversions to the corresponding template parameter.
2530
    // FIXME: Other compilers mangle partially-resolved template arguments in
2531
    // unresolved-qualifier-levels.
2532
0
    mangleTemplateArgs(TemplateName(), TST->template_arguments());
2533
0
    break;
2534
0
  }
2535
2536
0
  case Type::InjectedClassName:
2537
0
    mangleSourceNameWithAbiTags(
2538
0
        cast<InjectedClassNameType>(Ty)->getDecl());
2539
0
    break;
2540
2541
0
  case Type::DependentName:
2542
0
    mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2543
0
    break;
2544
2545
0
  case Type::DependentTemplateSpecialization: {
2546
0
    const DependentTemplateSpecializationType *DTST =
2547
0
        cast<DependentTemplateSpecializationType>(Ty);
2548
0
    TemplateName Template = getASTContext().getDependentTemplateName(
2549
0
        DTST->getQualifier(), DTST->getIdentifier());
2550
0
    mangleSourceName(DTST->getIdentifier());
2551
0
    mangleTemplateArgs(Template, DTST->template_arguments());
2552
0
    break;
2553
0
  }
2554
2555
0
  case Type::Using:
2556
0
    return mangleUnresolvedTypeOrSimpleId(cast<UsingType>(Ty)->desugar(),
2557
0
                                          Prefix);
2558
0
  case Type::Elaborated:
2559
0
    return mangleUnresolvedTypeOrSimpleId(
2560
0
        cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
2561
0
  }
2562
2563
0
  return false;
2564
0
}
2565
2566
0
void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2567
0
  switch (Name.getNameKind()) {
2568
0
  case DeclarationName::CXXConstructorName:
2569
0
  case DeclarationName::CXXDestructorName:
2570
0
  case DeclarationName::CXXDeductionGuideName:
2571
0
  case DeclarationName::CXXUsingDirective:
2572
0
  case DeclarationName::Identifier:
2573
0
  case DeclarationName::ObjCMultiArgSelector:
2574
0
  case DeclarationName::ObjCOneArgSelector:
2575
0
  case DeclarationName::ObjCZeroArgSelector:
2576
0
    llvm_unreachable("Not an operator name");
2577
2578
0
  case DeclarationName::CXXConversionFunctionName:
2579
    // <operator-name> ::= cv <type>    # (cast)
2580
0
    Out << "cv";
2581
0
    mangleType(Name.getCXXNameType());
2582
0
    break;
2583
2584
0
  case DeclarationName::CXXLiteralOperatorName:
2585
0
    Out << "li";
2586
0
    mangleSourceName(Name.getCXXLiteralIdentifier());
2587
0
    return;
2588
2589
0
  case DeclarationName::CXXOperatorName:
2590
0
    mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2591
0
    break;
2592
0
  }
2593
0
}
2594
2595
void
2596
0
CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2597
0
  switch (OO) {
2598
  // <operator-name> ::= nw     # new
2599
0
  case OO_New: Out << "nw"; break;
2600
  //              ::= na        # new[]
2601
0
  case OO_Array_New: Out << "na"; break;
2602
  //              ::= dl        # delete
2603
0
  case OO_Delete: Out << "dl"; break;
2604
  //              ::= da        # delete[]
2605
0
  case OO_Array_Delete: Out << "da"; break;
2606
  //              ::= ps        # + (unary)
2607
  //              ::= pl        # + (binary or unknown)
2608
0
  case OO_Plus:
2609
0
    Out << (Arity == 1? "ps" : "pl"); break;
2610
  //              ::= ng        # - (unary)
2611
  //              ::= mi        # - (binary or unknown)
2612
0
  case OO_Minus:
2613
0
    Out << (Arity == 1? "ng" : "mi"); break;
2614
  //              ::= ad        # & (unary)
2615
  //              ::= an        # & (binary or unknown)
2616
0
  case OO_Amp:
2617
0
    Out << (Arity == 1? "ad" : "an"); break;
2618
  //              ::= de        # * (unary)
2619
  //              ::= ml        # * (binary or unknown)
2620
0
  case OO_Star:
2621
    // Use binary when unknown.
2622
0
    Out << (Arity == 1? "de" : "ml"); break;
2623
  //              ::= co        # ~
2624
0
  case OO_Tilde: Out << "co"; break;
2625
  //              ::= dv        # /
2626
0
  case OO_Slash: Out << "dv"; break;
2627
  //              ::= rm        # %
2628
0
  case OO_Percent: Out << "rm"; break;
2629
  //              ::= or        # |
2630
0
  case OO_Pipe: Out << "or"; break;
2631
  //              ::= eo        # ^
2632
0
  case OO_Caret: Out << "eo"; break;
2633
  //              ::= aS        # =
2634
0
  case OO_Equal: Out << "aS"; break;
2635
  //              ::= pL        # +=
2636
0
  case OO_PlusEqual: Out << "pL"; break;
2637
  //              ::= mI        # -=
2638
0
  case OO_MinusEqual: Out << "mI"; break;
2639
  //              ::= mL        # *=
2640
0
  case OO_StarEqual: Out << "mL"; break;
2641
  //              ::= dV        # /=
2642
0
  case OO_SlashEqual: Out << "dV"; break;
2643
  //              ::= rM        # %=
2644
0
  case OO_PercentEqual: Out << "rM"; break;
2645
  //              ::= aN        # &=
2646
0
  case OO_AmpEqual: Out << "aN"; break;
2647
  //              ::= oR        # |=
2648
0
  case OO_PipeEqual: Out << "oR"; break;
2649
  //              ::= eO        # ^=
2650
0
  case OO_CaretEqual: Out << "eO"; break;
2651
  //              ::= ls        # <<
2652
0
  case OO_LessLess: Out << "ls"; break;
2653
  //              ::= rs        # >>
2654
0
  case OO_GreaterGreater: Out << "rs"; break;
2655
  //              ::= lS        # <<=
2656
0
  case OO_LessLessEqual: Out << "lS"; break;
2657
  //              ::= rS        # >>=
2658
0
  case OO_GreaterGreaterEqual: Out << "rS"; break;
2659
  //              ::= eq        # ==
2660
0
  case OO_EqualEqual: Out << "eq"; break;
2661
  //              ::= ne        # !=
2662
0
  case OO_ExclaimEqual: Out << "ne"; break;
2663
  //              ::= lt        # <
2664
0
  case OO_Less: Out << "lt"; break;
2665
  //              ::= gt        # >
2666
0
  case OO_Greater: Out << "gt"; break;
2667
  //              ::= le        # <=
2668
0
  case OO_LessEqual: Out << "le"; break;
2669
  //              ::= ge        # >=
2670
0
  case OO_GreaterEqual: Out << "ge"; break;
2671
  //              ::= nt        # !
2672
0
  case OO_Exclaim: Out << "nt"; break;
2673
  //              ::= aa        # &&
2674
0
  case OO_AmpAmp: Out << "aa"; break;
2675
  //              ::= oo        # ||
2676
0
  case OO_PipePipe: Out << "oo"; break;
2677
  //              ::= pp        # ++
2678
0
  case OO_PlusPlus: Out << "pp"; break;
2679
  //              ::= mm        # --
2680
0
  case OO_MinusMinus: Out << "mm"; break;
2681
  //              ::= cm        # ,
2682
0
  case OO_Comma: Out << "cm"; break;
2683
  //              ::= pm        # ->*
2684
0
  case OO_ArrowStar: Out << "pm"; break;
2685
  //              ::= pt        # ->
2686
0
  case OO_Arrow: Out << "pt"; break;
2687
  //              ::= cl        # ()
2688
0
  case OO_Call: Out << "cl"; break;
2689
  //              ::= ix        # []
2690
0
  case OO_Subscript: Out << "ix"; break;
2691
2692
  //              ::= qu        # ?
2693
  // The conditional operator can't be overloaded, but we still handle it when
2694
  // mangling expressions.
2695
0
  case OO_Conditional: Out << "qu"; break;
2696
  // Proposal on cxx-abi-dev, 2015-10-21.
2697
  //              ::= aw        # co_await
2698
0
  case OO_Coawait: Out << "aw"; break;
2699
  // Proposed in cxx-abi github issue 43.
2700
  //              ::= ss        # <=>
2701
0
  case OO_Spaceship: Out << "ss"; break;
2702
2703
0
  case OO_None:
2704
0
  case NUM_OVERLOADED_OPERATORS:
2705
0
    llvm_unreachable("Not an overloaded operator");
2706
0
  }
2707
0
}
2708
2709
0
void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
2710
  // Vendor qualifiers come first and if they are order-insensitive they must
2711
  // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
2712
2713
  // <type> ::= U <addrspace-expr>
2714
0
  if (DAST) {
2715
0
    Out << "U2ASI";
2716
0
    mangleExpression(DAST->getAddrSpaceExpr());
2717
0
    Out << "E";
2718
0
  }
2719
2720
  // Address space qualifiers start with an ordinary letter.
2721
0
  if (Quals.hasAddressSpace()) {
2722
    // Address space extension:
2723
    //
2724
    //   <type> ::= U <target-addrspace>
2725
    //   <type> ::= U <OpenCL-addrspace>
2726
    //   <type> ::= U <CUDA-addrspace>
2727
2728
0
    SmallString<64> ASString;
2729
0
    LangAS AS = Quals.getAddressSpace();
2730
2731
0
    if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2732
      //  <target-addrspace> ::= "AS" <address-space-number>
2733
0
      unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
2734
0
      if (TargetAS != 0 ||
2735
0
          Context.getASTContext().getTargetAddressSpace(LangAS::Default) != 0)
2736
0
        ASString = "AS" + llvm::utostr(TargetAS);
2737
0
    } else {
2738
0
      switch (AS) {
2739
0
      default: llvm_unreachable("Not a language specific address space");
2740
      //  <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2741
      //                                "private"| "generic" | "device" |
2742
      //                                "host" ]
2743
0
      case LangAS::opencl_global:
2744
0
        ASString = "CLglobal";
2745
0
        break;
2746
0
      case LangAS::opencl_global_device:
2747
0
        ASString = "CLdevice";
2748
0
        break;
2749
0
      case LangAS::opencl_global_host:
2750
0
        ASString = "CLhost";
2751
0
        break;
2752
0
      case LangAS::opencl_local:
2753
0
        ASString = "CLlocal";
2754
0
        break;
2755
0
      case LangAS::opencl_constant:
2756
0
        ASString = "CLconstant";
2757
0
        break;
2758
0
      case LangAS::opencl_private:
2759
0
        ASString = "CLprivate";
2760
0
        break;
2761
0
      case LangAS::opencl_generic:
2762
0
        ASString = "CLgeneric";
2763
0
        break;
2764
      //  <SYCL-addrspace> ::= "SY" [ "global" | "local" | "private" |
2765
      //                              "device" | "host" ]
2766
0
      case LangAS::sycl_global:
2767
0
        ASString = "SYglobal";
2768
0
        break;
2769
0
      case LangAS::sycl_global_device:
2770
0
        ASString = "SYdevice";
2771
0
        break;
2772
0
      case LangAS::sycl_global_host:
2773
0
        ASString = "SYhost";
2774
0
        break;
2775
0
      case LangAS::sycl_local:
2776
0
        ASString = "SYlocal";
2777
0
        break;
2778
0
      case LangAS::sycl_private:
2779
0
        ASString = "SYprivate";
2780
0
        break;
2781
      //  <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2782
0
      case LangAS::cuda_device:
2783
0
        ASString = "CUdevice";
2784
0
        break;
2785
0
      case LangAS::cuda_constant:
2786
0
        ASString = "CUconstant";
2787
0
        break;
2788
0
      case LangAS::cuda_shared:
2789
0
        ASString = "CUshared";
2790
0
        break;
2791
      //  <ptrsize-addrspace> ::= [ "ptr32_sptr" | "ptr32_uptr" | "ptr64" ]
2792
0
      case LangAS::ptr32_sptr:
2793
0
        ASString = "ptr32_sptr";
2794
0
        break;
2795
0
      case LangAS::ptr32_uptr:
2796
0
        ASString = "ptr32_uptr";
2797
0
        break;
2798
0
      case LangAS::ptr64:
2799
0
        ASString = "ptr64";
2800
0
        break;
2801
0
      }
2802
0
    }
2803
0
    if (!ASString.empty())
2804
0
      mangleVendorQualifier(ASString);
2805
0
  }
2806
2807
  // The ARC ownership qualifiers start with underscores.
2808
  // Objective-C ARC Extension:
2809
  //
2810
  //   <type> ::= U "__strong"
2811
  //   <type> ::= U "__weak"
2812
  //   <type> ::= U "__autoreleasing"
2813
  //
2814
  // Note: we emit __weak first to preserve the order as
2815
  // required by the Itanium ABI.
2816
0
  if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
2817
0
    mangleVendorQualifier("__weak");
2818
2819
  // __unaligned (from -fms-extensions)
2820
0
  if (Quals.hasUnaligned())
2821
0
    mangleVendorQualifier("__unaligned");
2822
2823
  // Remaining ARC ownership qualifiers.
2824
0
  switch (Quals.getObjCLifetime()) {
2825
0
  case Qualifiers::OCL_None:
2826
0
    break;
2827
2828
0
  case Qualifiers::OCL_Weak:
2829
    // Do nothing as we already handled this case above.
2830
0
    break;
2831
2832
0
  case Qualifiers::OCL_Strong:
2833
0
    mangleVendorQualifier("__strong");
2834
0
    break;
2835
2836
0
  case Qualifiers::OCL_Autoreleasing:
2837
0
    mangleVendorQualifier("__autoreleasing");
2838
0
    break;
2839
2840
0
  case Qualifiers::OCL_ExplicitNone:
2841
    // The __unsafe_unretained qualifier is *not* mangled, so that
2842
    // __unsafe_unretained types in ARC produce the same manglings as the
2843
    // equivalent (but, naturally, unqualified) types in non-ARC, providing
2844
    // better ABI compatibility.
2845
    //
2846
    // It's safe to do this because unqualified 'id' won't show up
2847
    // in any type signatures that need to be mangled.
2848
0
    break;
2849
0
  }
2850
2851
  // <CV-qualifiers> ::= [r] [V] [K]    # restrict (C99), volatile, const
2852
0
  if (Quals.hasRestrict())
2853
0
    Out << 'r';
2854
0
  if (Quals.hasVolatile())
2855
0
    Out << 'V';
2856
0
  if (Quals.hasConst())
2857
0
    Out << 'K';
2858
0
}
2859
2860
0
void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2861
0
  Out << 'U' << name.size() << name;
2862
0
}
2863
2864
0
void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2865
  // <ref-qualifier> ::= R                # lvalue reference
2866
  //                 ::= O                # rvalue-reference
2867
0
  switch (RefQualifier) {
2868
0
  case RQ_None:
2869
0
    break;
2870
2871
0
  case RQ_LValue:
2872
0
    Out << 'R';
2873
0
    break;
2874
2875
0
  case RQ_RValue:
2876
0
    Out << 'O';
2877
0
    break;
2878
0
  }
2879
0
}
2880
2881
0
void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2882
0
  Context.mangleObjCMethodNameAsSourceName(MD, Out);
2883
0
}
2884
2885
static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
2886
0
                                ASTContext &Ctx) {
2887
0
  if (Quals)
2888
0
    return true;
2889
0
  if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2890
0
    return true;
2891
0
  if (Ty->isOpenCLSpecificType())
2892
0
    return true;
2893
  // From Clang 18.0 we correctly treat SVE types as substitution candidates.
2894
0
  if (Ty->isSVESizelessBuiltinType() &&
2895
0
      Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver17)
2896
0
    return true;
2897
0
  if (Ty->isBuiltinType())
2898
0
    return false;
2899
  // Through to Clang 6.0, we accidentally treated undeduced auto types as
2900
  // substitution candidates.
2901
0
  if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
2902
0
      isa<AutoType>(Ty))
2903
0
    return false;
2904
  // A placeholder type for class template deduction is substitutable with
2905
  // its corresponding template name; this is handled specially when mangling
2906
  // the type.
2907
0
  if (auto *DeducedTST = Ty->getAs<DeducedTemplateSpecializationType>())
2908
0
    if (DeducedTST->getDeducedType().isNull())
2909
0
      return false;
2910
0
  return true;
2911
0
}
2912
2913
0
void CXXNameMangler::mangleType(QualType T) {
2914
  // If our type is instantiation-dependent but not dependent, we mangle
2915
  // it as it was written in the source, removing any top-level sugar.
2916
  // Otherwise, use the canonical type.
2917
  //
2918
  // FIXME: This is an approximation of the instantiation-dependent name
2919
  // mangling rules, since we should really be using the type as written and
2920
  // augmented via semantic analysis (i.e., with implicit conversions and
2921
  // default template arguments) for any instantiation-dependent type.
2922
  // Unfortunately, that requires several changes to our AST:
2923
  //   - Instantiation-dependent TemplateSpecializationTypes will need to be
2924
  //     uniqued, so that we can handle substitutions properly
2925
  //   - Default template arguments will need to be represented in the
2926
  //     TemplateSpecializationType, since they need to be mangled even though
2927
  //     they aren't written.
2928
  //   - Conversions on non-type template arguments need to be expressed, since
2929
  //     they can affect the mangling of sizeof/alignof.
2930
  //
2931
  // FIXME: This is wrong when mapping to the canonical type for a dependent
2932
  // type discards instantiation-dependent portions of the type, such as for:
2933
  //
2934
  //   template<typename T, int N> void f(T (&)[sizeof(N)]);
2935
  //   template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2936
  //
2937
  // It's also wrong in the opposite direction when instantiation-dependent,
2938
  // canonically-equivalent types differ in some irrelevant portion of inner
2939
  // type sugar. In such cases, we fail to form correct substitutions, eg:
2940
  //
2941
  //   template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2942
  //
2943
  // We should instead canonicalize the non-instantiation-dependent parts,
2944
  // regardless of whether the type as a whole is dependent or instantiation
2945
  // dependent.
2946
0
  if (!T->isInstantiationDependentType() || T->isDependentType())
2947
0
    T = T.getCanonicalType();
2948
0
  else {
2949
    // Desugar any types that are purely sugar.
2950
0
    do {
2951
      // Don't desugar through template specialization types that aren't
2952
      // type aliases. We need to mangle the template arguments as written.
2953
0
      if (const TemplateSpecializationType *TST
2954
0
                                      = dyn_cast<TemplateSpecializationType>(T))
2955
0
        if (!TST->isTypeAlias())
2956
0
          break;
2957
2958
      // FIXME: We presumably shouldn't strip off ElaboratedTypes with
2959
      // instantation-dependent qualifiers. See
2960
      // https://github.com/itanium-cxx-abi/cxx-abi/issues/114.
2961
2962
0
      QualType Desugared
2963
0
        = T.getSingleStepDesugaredType(Context.getASTContext());
2964
0
      if (Desugared == T)
2965
0
        break;
2966
2967
0
      T = Desugared;
2968
0
    } while (true);
2969
0
  }
2970
0
  SplitQualType split = T.split();
2971
0
  Qualifiers quals = split.Quals;
2972
0
  const Type *ty = split.Ty;
2973
2974
0
  bool isSubstitutable =
2975
0
    isTypeSubstitutable(quals, ty, Context.getASTContext());
2976
0
  if (isSubstitutable && mangleSubstitution(T))
2977
0
    return;
2978
2979
  // If we're mangling a qualified array type, push the qualifiers to
2980
  // the element type.
2981
0
  if (quals && isa<ArrayType>(T)) {
2982
0
    ty = Context.getASTContext().getAsArrayType(T);
2983
0
    quals = Qualifiers();
2984
2985
    // Note that we don't update T: we want to add the
2986
    // substitution at the original type.
2987
0
  }
2988
2989
0
  if (quals || ty->isDependentAddressSpaceType()) {
2990
0
    if (const DependentAddressSpaceType *DAST =
2991
0
        dyn_cast<DependentAddressSpaceType>(ty)) {
2992
0
      SplitQualType splitDAST = DAST->getPointeeType().split();
2993
0
      mangleQualifiers(splitDAST.Quals, DAST);
2994
0
      mangleType(QualType(splitDAST.Ty, 0));
2995
0
    } else {
2996
0
      mangleQualifiers(quals);
2997
2998
      // Recurse:  even if the qualified type isn't yet substitutable,
2999
      // the unqualified type might be.
3000
0
      mangleType(QualType(ty, 0));
3001
0
    }
3002
0
  } else {
3003
0
    switch (ty->getTypeClass()) {
3004
0
#define ABSTRACT_TYPE(CLASS, PARENT)
3005
0
#define NON_CANONICAL_TYPE(CLASS, PARENT) \
3006
0
    case Type::CLASS: \
3007
0
      llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
3008
0
      return;
3009
0
#define TYPE(CLASS, PARENT) \
3010
0
    case Type::CLASS: \
3011
0
      mangleType(static_cast<const CLASS##Type*>(ty)); \
3012
0
      break;
3013
0
#include "clang/AST/TypeNodes.inc"
3014
0
    }
3015
0
  }
3016
3017
  // Add the substitution.
3018
0
  if (isSubstitutable)
3019
0
    addSubstitution(T);
3020
0
}
3021
3022
0
void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
3023
0
  if (!mangleStandardSubstitution(ND))
3024
0
    mangleName(ND);
3025
0
}
3026
3027
0
void CXXNameMangler::mangleType(const BuiltinType *T) {
3028
  //  <type>         ::= <builtin-type>
3029
  //  <builtin-type> ::= v  # void
3030
  //                 ::= w  # wchar_t
3031
  //                 ::= b  # bool
3032
  //                 ::= c  # char
3033
  //                 ::= a  # signed char
3034
  //                 ::= h  # unsigned char
3035
  //                 ::= s  # short
3036
  //                 ::= t  # unsigned short
3037
  //                 ::= i  # int
3038
  //                 ::= j  # unsigned int
3039
  //                 ::= l  # long
3040
  //                 ::= m  # unsigned long
3041
  //                 ::= x  # long long, __int64
3042
  //                 ::= y  # unsigned long long, __int64
3043
  //                 ::= n  # __int128
3044
  //                 ::= o  # unsigned __int128
3045
  //                 ::= f  # float
3046
  //                 ::= d  # double
3047
  //                 ::= e  # long double, __float80
3048
  //                 ::= g  # __float128
3049
  //                 ::= g  # __ibm128
3050
  // UNSUPPORTED:    ::= Dd # IEEE 754r decimal floating point (64 bits)
3051
  // UNSUPPORTED:    ::= De # IEEE 754r decimal floating point (128 bits)
3052
  // UNSUPPORTED:    ::= Df # IEEE 754r decimal floating point (32 bits)
3053
  //                 ::= Dh # IEEE 754r half-precision floating point (16 bits)
3054
  //                 ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
3055
  //                 ::= Di # char32_t
3056
  //                 ::= Ds # char16_t
3057
  //                 ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
3058
  //                 ::= [DS] DA  # N1169 fixed-point [_Sat] T _Accum
3059
  //                 ::= [DS] DR  # N1169 fixed-point [_Sat] T _Fract
3060
  //                 ::= u <source-name>    # vendor extended type
3061
  //
3062
  //  <fixed-point-size>
3063
  //                 ::= s # short
3064
  //                 ::= t # unsigned short
3065
  //                 ::= i # plain
3066
  //                 ::= j # unsigned
3067
  //                 ::= l # long
3068
  //                 ::= m # unsigned long
3069
0
  std::string type_name;
3070
  // Normalize integer types as vendor extended types:
3071
  // u<length>i<type size>
3072
  // u<length>u<type size>
3073
0
  if (NormalizeIntegers && T->isInteger()) {
3074
0
    if (T->isSignedInteger()) {
3075
0
      switch (getASTContext().getTypeSize(T)) {
3076
0
      case 8:
3077
        // Pick a representative for each integer size in the substitution
3078
        // dictionary. (Its actual defined size is not relevant.)
3079
0
        if (mangleSubstitution(BuiltinType::SChar))
3080
0
          break;
3081
0
        Out << "u2i8";
3082
0
        addSubstitution(BuiltinType::SChar);
3083
0
        break;
3084
0
      case 16:
3085
0
        if (mangleSubstitution(BuiltinType::Short))
3086
0
          break;
3087
0
        Out << "u3i16";
3088
0
        addSubstitution(BuiltinType::Short);
3089
0
        break;
3090
0
      case 32:
3091
0
        if (mangleSubstitution(BuiltinType::Int))
3092
0
          break;
3093
0
        Out << "u3i32";
3094
0
        addSubstitution(BuiltinType::Int);
3095
0
        break;
3096
0
      case 64:
3097
0
        if (mangleSubstitution(BuiltinType::Long))
3098
0
          break;
3099
0
        Out << "u3i64";
3100
0
        addSubstitution(BuiltinType::Long);
3101
0
        break;
3102
0
      case 128:
3103
0
        if (mangleSubstitution(BuiltinType::Int128))
3104
0
          break;
3105
0
        Out << "u4i128";
3106
0
        addSubstitution(BuiltinType::Int128);
3107
0
        break;
3108
0
      default:
3109
0
        llvm_unreachable("Unknown integer size for normalization");
3110
0
      }
3111
0
    } else {
3112
0
      switch (getASTContext().getTypeSize(T)) {
3113
0
      case 8:
3114
0
        if (mangleSubstitution(BuiltinType::UChar))
3115
0
          break;
3116
0
        Out << "u2u8";
3117
0
        addSubstitution(BuiltinType::UChar);
3118
0
        break;
3119
0
      case 16:
3120
0
        if (mangleSubstitution(BuiltinType::UShort))
3121
0
          break;
3122
0
        Out << "u3u16";
3123
0
        addSubstitution(BuiltinType::UShort);
3124
0
        break;
3125
0
      case 32:
3126
0
        if (mangleSubstitution(BuiltinType::UInt))
3127
0
          break;
3128
0
        Out << "u3u32";
3129
0
        addSubstitution(BuiltinType::UInt);
3130
0
        break;
3131
0
      case 64:
3132
0
        if (mangleSubstitution(BuiltinType::ULong))
3133
0
          break;
3134
0
        Out << "u3u64";
3135
0
        addSubstitution(BuiltinType::ULong);
3136
0
        break;
3137
0
      case 128:
3138
0
        if (mangleSubstitution(BuiltinType::UInt128))
3139
0
          break;
3140
0
        Out << "u4u128";
3141
0
        addSubstitution(BuiltinType::UInt128);
3142
0
        break;
3143
0
      default:
3144
0
        llvm_unreachable("Unknown integer size for normalization");
3145
0
      }
3146
0
    }
3147
0
    return;
3148
0
  }
3149
0
  switch (T->getKind()) {
3150
0
  case BuiltinType::Void:
3151
0
    Out << 'v';
3152
0
    break;
3153
0
  case BuiltinType::Bool:
3154
0
    Out << 'b';
3155
0
    break;
3156
0
  case BuiltinType::Char_U:
3157
0
  case BuiltinType::Char_S:
3158
0
    Out << 'c';
3159
0
    break;
3160
0
  case BuiltinType::UChar:
3161
0
    Out << 'h';
3162
0
    break;
3163
0
  case BuiltinType::UShort:
3164
0
    Out << 't';
3165
0
    break;
3166
0
  case BuiltinType::UInt:
3167
0
    Out << 'j';
3168
0
    break;
3169
0
  case BuiltinType::ULong:
3170
0
    Out << 'm';
3171
0
    break;
3172
0
  case BuiltinType::ULongLong:
3173
0
    Out << 'y';
3174
0
    break;
3175
0
  case BuiltinType::UInt128:
3176
0
    Out << 'o';
3177
0
    break;
3178
0
  case BuiltinType::SChar:
3179
0
    Out << 'a';
3180
0
    break;
3181
0
  case BuiltinType::WChar_S:
3182
0
  case BuiltinType::WChar_U:
3183
0
    Out << 'w';
3184
0
    break;
3185
0
  case BuiltinType::Char8:
3186
0
    Out << "Du";
3187
0
    break;
3188
0
  case BuiltinType::Char16:
3189
0
    Out << "Ds";
3190
0
    break;
3191
0
  case BuiltinType::Char32:
3192
0
    Out << "Di";
3193
0
    break;
3194
0
  case BuiltinType::Short:
3195
0
    Out << 's';
3196
0
    break;
3197
0
  case BuiltinType::Int:
3198
0
    Out << 'i';
3199
0
    break;
3200
0
  case BuiltinType::Long:
3201
0
    Out << 'l';
3202
0
    break;
3203
0
  case BuiltinType::LongLong:
3204
0
    Out << 'x';
3205
0
    break;
3206
0
  case BuiltinType::Int128:
3207
0
    Out << 'n';
3208
0
    break;
3209
0
  case BuiltinType::Float16:
3210
0
    Out << "DF16_";
3211
0
    break;
3212
0
  case BuiltinType::ShortAccum:
3213
0
    Out << "DAs";
3214
0
    break;
3215
0
  case BuiltinType::Accum:
3216
0
    Out << "DAi";
3217
0
    break;
3218
0
  case BuiltinType::LongAccum:
3219
0
    Out << "DAl";
3220
0
    break;
3221
0
  case BuiltinType::UShortAccum:
3222
0
    Out << "DAt";
3223
0
    break;
3224
0
  case BuiltinType::UAccum:
3225
0
    Out << "DAj";
3226
0
    break;
3227
0
  case BuiltinType::ULongAccum:
3228
0
    Out << "DAm";
3229
0
    break;
3230
0
  case BuiltinType::ShortFract:
3231
0
    Out << "DRs";
3232
0
    break;
3233
0
  case BuiltinType::Fract:
3234
0
    Out << "DRi";
3235
0
    break;
3236
0
  case BuiltinType::LongFract:
3237
0
    Out << "DRl";
3238
0
    break;
3239
0
  case BuiltinType::UShortFract:
3240
0
    Out << "DRt";
3241
0
    break;
3242
0
  case BuiltinType::UFract:
3243
0
    Out << "DRj";
3244
0
    break;
3245
0
  case BuiltinType::ULongFract:
3246
0
    Out << "DRm";
3247
0
    break;
3248
0
  case BuiltinType::SatShortAccum:
3249
0
    Out << "DSDAs";
3250
0
    break;
3251
0
  case BuiltinType::SatAccum:
3252
0
    Out << "DSDAi";
3253
0
    break;
3254
0
  case BuiltinType::SatLongAccum:
3255
0
    Out << "DSDAl";
3256
0
    break;
3257
0
  case BuiltinType::SatUShortAccum:
3258
0
    Out << "DSDAt";
3259
0
    break;
3260
0
  case BuiltinType::SatUAccum:
3261
0
    Out << "DSDAj";
3262
0
    break;
3263
0
  case BuiltinType::SatULongAccum:
3264
0
    Out << "DSDAm";
3265
0
    break;
3266
0
  case BuiltinType::SatShortFract:
3267
0
    Out << "DSDRs";
3268
0
    break;
3269
0
  case BuiltinType::SatFract:
3270
0
    Out << "DSDRi";
3271
0
    break;
3272
0
  case BuiltinType::SatLongFract:
3273
0
    Out << "DSDRl";
3274
0
    break;
3275
0
  case BuiltinType::SatUShortFract:
3276
0
    Out << "DSDRt";
3277
0
    break;
3278
0
  case BuiltinType::SatUFract:
3279
0
    Out << "DSDRj";
3280
0
    break;
3281
0
  case BuiltinType::SatULongFract:
3282
0
    Out << "DSDRm";
3283
0
    break;
3284
0
  case BuiltinType::Half:
3285
0
    Out << "Dh";
3286
0
    break;
3287
0
  case BuiltinType::Float:
3288
0
    Out << 'f';
3289
0
    break;
3290
0
  case BuiltinType::Double:
3291
0
    Out << 'd';
3292
0
    break;
3293
0
  case BuiltinType::LongDouble: {
3294
0
    const TargetInfo *TI =
3295
0
        getASTContext().getLangOpts().OpenMP &&
3296
0
                getASTContext().getLangOpts().OpenMPIsTargetDevice
3297
0
            ? getASTContext().getAuxTargetInfo()
3298
0
            : &getASTContext().getTargetInfo();
3299
0
    Out << TI->getLongDoubleMangling();
3300
0
    break;
3301
0
  }
3302
0
  case BuiltinType::Float128: {
3303
0
    const TargetInfo *TI =
3304
0
        getASTContext().getLangOpts().OpenMP &&
3305
0
                getASTContext().getLangOpts().OpenMPIsTargetDevice
3306
0
            ? getASTContext().getAuxTargetInfo()
3307
0
            : &getASTContext().getTargetInfo();
3308
0
    Out << TI->getFloat128Mangling();
3309
0
    break;
3310
0
  }
3311
0
  case BuiltinType::BFloat16: {
3312
0
    const TargetInfo *TI =
3313
0
        ((getASTContext().getLangOpts().OpenMP &&
3314
0
          getASTContext().getLangOpts().OpenMPIsTargetDevice) ||
3315
0
         getASTContext().getLangOpts().SYCLIsDevice)
3316
0
            ? getASTContext().getAuxTargetInfo()
3317
0
            : &getASTContext().getTargetInfo();
3318
0
    Out << TI->getBFloat16Mangling();
3319
0
    break;
3320
0
  }
3321
0
  case BuiltinType::Ibm128: {
3322
0
    const TargetInfo *TI = &getASTContext().getTargetInfo();
3323
0
    Out << TI->getIbm128Mangling();
3324
0
    break;
3325
0
  }
3326
0
  case BuiltinType::NullPtr:
3327
0
    Out << "Dn";
3328
0
    break;
3329
3330
0
#define BUILTIN_TYPE(Id, SingletonId)
3331
0
#define PLACEHOLDER_TYPE(Id, SingletonId) \
3332
0
  case BuiltinType::Id:
3333
0
#include "clang/AST/BuiltinTypes.def"
3334
0
  case BuiltinType::Dependent:
3335
0
    if (!NullOut)
3336
0
      llvm_unreachable("mangling a placeholder type");
3337
0
    break;
3338
0
  case BuiltinType::ObjCId:
3339
0
    Out << "11objc_object";
3340
0
    break;
3341
0
  case BuiltinType::ObjCClass:
3342
0
    Out << "10objc_class";
3343
0
    break;
3344
0
  case BuiltinType::ObjCSel:
3345
0
    Out << "13objc_selector";
3346
0
    break;
3347
0
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3348
0
  case BuiltinType::Id: \
3349
0
    type_name = "ocl_" #ImgType "_" #Suffix; \
3350
0
    Out << type_name.size() << type_name; \
3351
0
    break;
3352
0
#include "clang/Basic/OpenCLImageTypes.def"
3353
0
  case BuiltinType::OCLSampler:
3354
0
    Out << "11ocl_sampler";
3355
0
    break;
3356
0
  case BuiltinType::OCLEvent:
3357
0
    Out << "9ocl_event";
3358
0
    break;
3359
0
  case BuiltinType::OCLClkEvent:
3360
0
    Out << "12ocl_clkevent";
3361
0
    break;
3362
0
  case BuiltinType::OCLQueue:
3363
0
    Out << "9ocl_queue";
3364
0
    break;
3365
0
  case BuiltinType::OCLReserveID:
3366
0
    Out << "13ocl_reserveid";
3367
0
    break;
3368
0
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3369
0
  case BuiltinType::Id: \
3370
0
    type_name = "ocl_" #ExtType; \
3371
0
    Out << type_name.size() << type_name; \
3372
0
    break;
3373
0
#include "clang/Basic/OpenCLExtensionTypes.def"
3374
  // The SVE types are effectively target-specific.  The mangling scheme
3375
  // is defined in the appendices to the Procedure Call Standard for the
3376
  // Arm Architecture.
3377
0
#define SVE_VECTOR_TYPE(InternalName, MangledName, Id, SingletonId, NumEls,    \
3378
0
                        ElBits, IsSigned, IsFP, IsBF)                          \
3379
0
  case BuiltinType::Id:                                                        \
3380
0
    if (T->getKind() == BuiltinType::SveBFloat16 &&                            \
3381
0
        isCompatibleWith(LangOptions::ClangABI::Ver17)) {                      \
3382
      /* Prior to Clang 18.0 we used this incorrect mangled name */            \
3383
0
      type_name = "__SVBFloat16_t";                                            \
3384
0
      Out << "u" << type_name.size() << type_name;                             \
3385
0
    } else {                                                                   \
3386
0
      type_name = MangledName;                                                 \
3387
0
      Out << (type_name == InternalName ? "u" : "") << type_name.size()        \
3388
0
          << type_name;                                                        \
3389
0
    }                                                                          \
3390
0
    break;
3391
0
#define SVE_PREDICATE_TYPE(InternalName, MangledName, Id, SingletonId, NumEls) \
3392
0
  case BuiltinType::Id:                                                        \
3393
0
    type_name = MangledName;                                                   \
3394
0
    Out << (type_name == InternalName ? "u" : "") << type_name.size()          \
3395
0
        << type_name;                                                          \
3396
0
    break;
3397
0
#define SVE_OPAQUE_TYPE(InternalName, MangledName, Id, SingletonId)            \
3398
0
  case BuiltinType::Id:                                                        \
3399
0
    type_name = MangledName;                                                   \
3400
0
    Out << (type_name == InternalName ? "u" : "") << type_name.size()          \
3401
0
        << type_name;                                                          \
3402
0
    break;
3403
0
#include "clang/Basic/AArch64SVEACLETypes.def"
3404
0
#define PPC_VECTOR_TYPE(Name, Id, Size) \
3405
0
  case BuiltinType::Id: \
3406
0
    type_name = #Name; \
3407
0
    Out << 'u' << type_name.size() << type_name; \
3408
0
    break;
3409
0
#include "clang/Basic/PPCTypes.def"
3410
    // TODO: Check the mangling scheme for RISC-V V.
3411
0
#define RVV_TYPE(Name, Id, SingletonId)                                        \
3412
0
  case BuiltinType::Id:                                                        \
3413
0
    type_name = Name;                                                          \
3414
0
    Out << 'u' << type_name.size() << type_name;                               \
3415
0
    break;
3416
0
#include "clang/Basic/RISCVVTypes.def"
3417
0
#define WASM_REF_TYPE(InternalName, MangledName, Id, SingletonId, AS)          \
3418
0
  case BuiltinType::Id:                                                        \
3419
0
    type_name = MangledName;                                                   \
3420
0
    Out << 'u' << type_name.size() << type_name;                               \
3421
0
    break;
3422
0
#include "clang/Basic/WebAssemblyReferenceTypes.def"
3423
0
  }
3424
0
}
3425
3426
0
StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
3427
0
  switch (CC) {
3428
0
  case CC_C:
3429
0
    return "";
3430
3431
0
  case CC_X86VectorCall:
3432
0
  case CC_X86Pascal:
3433
0
  case CC_X86RegCall:
3434
0
  case CC_AAPCS:
3435
0
  case CC_AAPCS_VFP:
3436
0
  case CC_AArch64VectorCall:
3437
0
  case CC_AArch64SVEPCS:
3438
0
  case CC_AMDGPUKernelCall:
3439
0
  case CC_IntelOclBicc:
3440
0
  case CC_SpirFunction:
3441
0
  case CC_OpenCLKernel:
3442
0
  case CC_PreserveMost:
3443
0
  case CC_PreserveAll:
3444
0
  case CC_M68kRTD:
3445
    // FIXME: we should be mangling all of the above.
3446
0
    return "";
3447
3448
0
  case CC_X86ThisCall:
3449
    // FIXME: To match mingw GCC, thiscall should only be mangled in when it is
3450
    // used explicitly. At this point, we don't have that much information in
3451
    // the AST, since clang tends to bake the convention into the canonical
3452
    // function type. thiscall only rarely used explicitly, so don't mangle it
3453
    // for now.
3454
0
    return "";
3455
3456
0
  case CC_X86StdCall:
3457
0
    return "stdcall";
3458
0
  case CC_X86FastCall:
3459
0
    return "fastcall";
3460
0
  case CC_X86_64SysV:
3461
0
    return "sysv_abi";
3462
0
  case CC_Win64:
3463
0
    return "ms_abi";
3464
0
  case CC_Swift:
3465
0
    return "swiftcall";
3466
0
  case CC_SwiftAsync:
3467
0
    return "swiftasynccall";
3468
0
  }
3469
0
  llvm_unreachable("bad calling convention");
3470
0
}
3471
3472
0
void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
3473
  // Fast path.
3474
0
  if (T->getExtInfo() == FunctionType::ExtInfo())
3475
0
    return;
3476
3477
  // Vendor-specific qualifiers are emitted in reverse alphabetical order.
3478
  // This will get more complicated in the future if we mangle other
3479
  // things here; but for now, since we mangle ns_returns_retained as
3480
  // a qualifier on the result type, we can get away with this:
3481
0
  StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
3482
0
  if (!CCQualifier.empty())
3483
0
    mangleVendorQualifier(CCQualifier);
3484
3485
  // FIXME: regparm
3486
  // FIXME: noreturn
3487
0
}
3488
3489
void
3490
0
CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
3491
  // Vendor-specific qualifiers are emitted in reverse alphabetical order.
3492
3493
  // Note that these are *not* substitution candidates.  Demanglers might
3494
  // have trouble with this if the parameter type is fully substituted.
3495
3496
0
  switch (PI.getABI()) {
3497
0
  case ParameterABI::Ordinary:
3498
0
    break;
3499
3500
  // All of these start with "swift", so they come before "ns_consumed".
3501
0
  case ParameterABI::SwiftContext:
3502
0
  case ParameterABI::SwiftAsyncContext:
3503
0
  case ParameterABI::SwiftErrorResult:
3504
0
  case ParameterABI::SwiftIndirectResult:
3505
0
    mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
3506
0
    break;
3507
0
  }
3508
3509
0
  if (PI.isConsumed())
3510
0
    mangleVendorQualifier("ns_consumed");
3511
3512
0
  if (PI.isNoEscape())
3513
0
    mangleVendorQualifier("noescape");
3514
0
}
3515
3516
// <type>          ::= <function-type>
3517
// <function-type> ::= [<CV-qualifiers>] F [Y]
3518
//                      <bare-function-type> [<ref-qualifier>] E
3519
0
void CXXNameMangler::mangleType(const FunctionProtoType *T) {
3520
0
  mangleExtFunctionInfo(T);
3521
3522
  // Mangle CV-qualifiers, if present.  These are 'this' qualifiers,
3523
  // e.g. "const" in "int (A::*)() const".
3524
0
  mangleQualifiers(T->getMethodQuals());
3525
3526
  // Mangle instantiation-dependent exception-specification, if present,
3527
  // per cxx-abi-dev proposal on 2016-10-11.
3528
0
  if (T->hasInstantiationDependentExceptionSpec()) {
3529
0
    if (isComputedNoexcept(T->getExceptionSpecType())) {
3530
0
      Out << "DO";
3531
0
      mangleExpression(T->getNoexceptExpr());
3532
0
      Out << "E";
3533
0
    } else {
3534
0
      assert(T->getExceptionSpecType() == EST_Dynamic);
3535
0
      Out << "Dw";
3536
0
      for (auto ExceptTy : T->exceptions())
3537
0
        mangleType(ExceptTy);
3538
0
      Out << "E";
3539
0
    }
3540
0
  } else if (T->isNothrow()) {
3541
0
    Out << "Do";
3542
0
  }
3543
3544
0
  Out << 'F';
3545
3546
  // FIXME: We don't have enough information in the AST to produce the 'Y'
3547
  // encoding for extern "C" function types.
3548
0
  mangleBareFunctionType(T, /*MangleReturnType=*/true);
3549
3550
  // Mangle the ref-qualifier, if present.
3551
0
  mangleRefQualifier(T->getRefQualifier());
3552
3553
0
  Out << 'E';
3554
0
}
3555
3556
0
void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
3557
  // Function types without prototypes can arise when mangling a function type
3558
  // within an overloadable function in C. We mangle these as the absence of any
3559
  // parameter types (not even an empty parameter list).
3560
0
  Out << 'F';
3561
3562
0
  FunctionTypeDepthState saved = FunctionTypeDepth.push();
3563
3564
0
  FunctionTypeDepth.enterResultType();
3565
0
  mangleType(T->getReturnType());
3566
0
  FunctionTypeDepth.leaveResultType();
3567
3568
0
  FunctionTypeDepth.pop(saved);
3569
0
  Out << 'E';
3570
0
}
3571
3572
void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
3573
                                            bool MangleReturnType,
3574
0
                                            const FunctionDecl *FD) {
3575
  // Record that we're in a function type.  See mangleFunctionParam
3576
  // for details on what we're trying to achieve here.
3577
0
  FunctionTypeDepthState saved = FunctionTypeDepth.push();
3578
3579
  // <bare-function-type> ::= <signature type>+
3580
0
  if (MangleReturnType) {
3581
0
    FunctionTypeDepth.enterResultType();
3582
3583
    // Mangle ns_returns_retained as an order-sensitive qualifier here.
3584
0
    if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
3585
0
      mangleVendorQualifier("ns_returns_retained");
3586
3587
    // Mangle the return type without any direct ARC ownership qualifiers.
3588
0
    QualType ReturnTy = Proto->getReturnType();
3589
0
    if (ReturnTy.getObjCLifetime()) {
3590
0
      auto SplitReturnTy = ReturnTy.split();
3591
0
      SplitReturnTy.Quals.removeObjCLifetime();
3592
0
      ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
3593
0
    }
3594
0
    mangleType(ReturnTy);
3595
3596
0
    FunctionTypeDepth.leaveResultType();
3597
0
  }
3598
3599
0
  if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
3600
    //   <builtin-type> ::= v   # void
3601
0
    Out << 'v';
3602
0
  } else {
3603
0
    assert(!FD || FD->getNumParams() == Proto->getNumParams());
3604
0
    for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
3605
      // Mangle extended parameter info as order-sensitive qualifiers here.
3606
0
      if (Proto->hasExtParameterInfos() && FD == nullptr) {
3607
0
        mangleExtParameterInfo(Proto->getExtParameterInfo(I));
3608
0
      }
3609
3610
      // Mangle the type.
3611
0
      QualType ParamTy = Proto->getParamType(I);
3612
0
      mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
3613
3614
0
      if (FD) {
3615
0
        if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
3616
          // Attr can only take 1 character, so we can hardcode the length
3617
          // below.
3618
0
          assert(Attr->getType() <= 9 && Attr->getType() >= 0);
3619
0
          if (Attr->isDynamic())
3620
0
            Out << "U25pass_dynamic_object_size" << Attr->getType();
3621
0
          else
3622
0
            Out << "U17pass_object_size" << Attr->getType();
3623
0
        }
3624
0
      }
3625
0
    }
3626
3627
    // <builtin-type>      ::= z  # ellipsis
3628
0
    if (Proto->isVariadic())
3629
0
      Out << 'z';
3630
0
  }
3631
3632
0
  if (FD) {
3633
0
    FunctionTypeDepth.enterResultType();
3634
0
    mangleRequiresClause(FD->getTrailingRequiresClause());
3635
0
  }
3636
3637
0
  FunctionTypeDepth.pop(saved);
3638
0
}
3639
3640
// <type>            ::= <class-enum-type>
3641
// <class-enum-type> ::= <name>
3642
0
void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
3643
0
  mangleName(T->getDecl());
3644
0
}
3645
3646
// <type>            ::= <class-enum-type>
3647
// <class-enum-type> ::= <name>
3648
0
void CXXNameMangler::mangleType(const EnumType *T) {
3649
0
  mangleType(static_cast<const TagType*>(T));
3650
0
}
3651
0
void CXXNameMangler::mangleType(const RecordType *T) {
3652
0
  mangleType(static_cast<const TagType*>(T));
3653
0
}
3654
0
void CXXNameMangler::mangleType(const TagType *T) {
3655
0
  mangleName(T->getDecl());
3656
0
}
3657
3658
// <type>       ::= <array-type>
3659
// <array-type> ::= A <positive dimension number> _ <element type>
3660
//              ::= A [<dimension expression>] _ <element type>
3661
0
void CXXNameMangler::mangleType(const ConstantArrayType *T) {
3662
0
  Out << 'A' << T->getSize() << '_';
3663
0
  mangleType(T->getElementType());
3664
0
}
3665
0
void CXXNameMangler::mangleType(const VariableArrayType *T) {
3666
0
  Out << 'A';
3667
  // decayed vla types (size 0) will just be skipped.
3668
0
  if (T->getSizeExpr())
3669
0
    mangleExpression(T->getSizeExpr());
3670
0
  Out << '_';
3671
0
  mangleType(T->getElementType());
3672
0
}
3673
0
void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
3674
0
  Out << 'A';
3675
  // A DependentSizedArrayType might not have size expression as below
3676
  //
3677
  // template<int ...N> int arr[] = {N...};
3678
0
  if (T->getSizeExpr())
3679
0
    mangleExpression(T->getSizeExpr());
3680
0
  Out << '_';
3681
0
  mangleType(T->getElementType());
3682
0
}
3683
0
void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
3684
0
  Out << "A_";
3685
0
  mangleType(T->getElementType());
3686
0
}
3687
3688
// <type>                   ::= <pointer-to-member-type>
3689
// <pointer-to-member-type> ::= M <class type> <member type>
3690
0
void CXXNameMangler::mangleType(const MemberPointerType *T) {
3691
0
  Out << 'M';
3692
0
  mangleType(QualType(T->getClass(), 0));
3693
0
  QualType PointeeType = T->getPointeeType();
3694
0
  if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
3695
0
    mangleType(FPT);
3696
3697
    // Itanium C++ ABI 5.1.8:
3698
    //
3699
    //   The type of a non-static member function is considered to be different,
3700
    //   for the purposes of substitution, from the type of a namespace-scope or
3701
    //   static member function whose type appears similar. The types of two
3702
    //   non-static member functions are considered to be different, for the
3703
    //   purposes of substitution, if the functions are members of different
3704
    //   classes. In other words, for the purposes of substitution, the class of
3705
    //   which the function is a member is considered part of the type of
3706
    //   function.
3707
3708
    // Given that we already substitute member function pointers as a
3709
    // whole, the net effect of this rule is just to unconditionally
3710
    // suppress substitution on the function type in a member pointer.
3711
    // We increment the SeqID here to emulate adding an entry to the
3712
    // substitution table.
3713
0
    ++SeqID;
3714
0
  } else
3715
0
    mangleType(PointeeType);
3716
0
}
3717
3718
// <type>           ::= <template-param>
3719
0
void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
3720
0
  mangleTemplateParameter(T->getDepth(), T->getIndex());
3721
0
}
3722
3723
// <type>           ::= <template-param>
3724
0
void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
3725
  // FIXME: not clear how to mangle this!
3726
  // template <class T...> class A {
3727
  //   template <class U...> void foo(T(*)(U) x...);
3728
  // };
3729
0
  Out << "_SUBSTPACK_";
3730
0
}
3731
3732
// <type> ::= P <type>   # pointer-to
3733
0
void CXXNameMangler::mangleType(const PointerType *T) {
3734
0
  Out << 'P';
3735
0
  mangleType(T->getPointeeType());
3736
0
}
3737
0
void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
3738
0
  Out << 'P';
3739
0
  mangleType(T->getPointeeType());
3740
0
}
3741
3742
// <type> ::= R <type>   # reference-to
3743
0
void CXXNameMangler::mangleType(const LValueReferenceType *T) {
3744
0
  Out << 'R';
3745
0
  mangleType(T->getPointeeType());
3746
0
}
3747
3748
// <type> ::= O <type>   # rvalue reference-to (C++0x)
3749
0
void CXXNameMangler::mangleType(const RValueReferenceType *T) {
3750
0
  Out << 'O';
3751
0
  mangleType(T->getPointeeType());
3752
0
}
3753
3754
// <type> ::= C <type>   # complex pair (C 2000)
3755
0
void CXXNameMangler::mangleType(const ComplexType *T) {
3756
0
  Out << 'C';
3757
0
  mangleType(T->getElementType());
3758
0
}
3759
3760
// ARM's ABI for Neon vector types specifies that they should be mangled as
3761
// if they are structs (to match ARM's initial implementation).  The
3762
// vector type must be one of the special types predefined by ARM.
3763
0
void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
3764
0
  QualType EltType = T->getElementType();
3765
0
  assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3766
0
  const char *EltName = nullptr;
3767
0
  if (T->getVectorKind() == VectorKind::NeonPoly) {
3768
0
    switch (cast<BuiltinType>(EltType)->getKind()) {
3769
0
    case BuiltinType::SChar:
3770
0
    case BuiltinType::UChar:
3771
0
      EltName = "poly8_t";
3772
0
      break;
3773
0
    case BuiltinType::Short:
3774
0
    case BuiltinType::UShort:
3775
0
      EltName = "poly16_t";
3776
0
      break;
3777
0
    case BuiltinType::LongLong:
3778
0
    case BuiltinType::ULongLong:
3779
0
      EltName = "poly64_t";
3780
0
      break;
3781
0
    default: llvm_unreachable("unexpected Neon polynomial vector element type");
3782
0
    }
3783
0
  } else {
3784
0
    switch (cast<BuiltinType>(EltType)->getKind()) {
3785
0
    case BuiltinType::SChar:     EltName = "int8_t"; break;
3786
0
    case BuiltinType::UChar:     EltName = "uint8_t"; break;
3787
0
    case BuiltinType::Short:     EltName = "int16_t"; break;
3788
0
    case BuiltinType::UShort:    EltName = "uint16_t"; break;
3789
0
    case BuiltinType::Int:       EltName = "int32_t"; break;
3790
0
    case BuiltinType::UInt:      EltName = "uint32_t"; break;
3791
0
    case BuiltinType::LongLong:  EltName = "int64_t"; break;
3792
0
    case BuiltinType::ULongLong: EltName = "uint64_t"; break;
3793
0
    case BuiltinType::Double:    EltName = "float64_t"; break;
3794
0
    case BuiltinType::Float:     EltName = "float32_t"; break;
3795
0
    case BuiltinType::Half:      EltName = "float16_t"; break;
3796
0
    case BuiltinType::BFloat16:  EltName = "bfloat16_t"; break;
3797
0
    default:
3798
0
      llvm_unreachable("unexpected Neon vector element type");
3799
0
    }
3800
0
  }
3801
0
  const char *BaseName = nullptr;
3802
0
  unsigned BitSize = (T->getNumElements() *
3803
0
                      getASTContext().getTypeSize(EltType));
3804
0
  if (BitSize == 64)
3805
0
    BaseName = "__simd64_";
3806
0
  else {
3807
0
    assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
3808
0
    BaseName = "__simd128_";
3809
0
  }
3810
0
  Out << strlen(BaseName) + strlen(EltName);
3811
0
  Out << BaseName << EltName;
3812
0
}
3813
3814
0
void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
3815
0
  DiagnosticsEngine &Diags = Context.getDiags();
3816
0
  unsigned DiagID = Diags.getCustomDiagID(
3817
0
      DiagnosticsEngine::Error,
3818
0
      "cannot mangle this dependent neon vector type yet");
3819
0
  Diags.Report(T->getAttributeLoc(), DiagID);
3820
0
}
3821
3822
0
static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
3823
0
  switch (EltType->getKind()) {
3824
0
  case BuiltinType::SChar:
3825
0
    return "Int8";
3826
0
  case BuiltinType::Short:
3827
0
    return "Int16";
3828
0
  case BuiltinType::Int:
3829
0
    return "Int32";
3830
0
  case BuiltinType::Long:
3831
0
  case BuiltinType::LongLong:
3832
0
    return "Int64";
3833
0
  case BuiltinType::UChar:
3834
0
    return "Uint8";
3835
0
  case BuiltinType::UShort:
3836
0
    return "Uint16";
3837
0
  case BuiltinType::UInt:
3838
0
    return "Uint32";
3839
0
  case BuiltinType::ULong:
3840
0
  case BuiltinType::ULongLong:
3841
0
    return "Uint64";
3842
0
  case BuiltinType::Half:
3843
0
    return "Float16";
3844
0
  case BuiltinType::Float:
3845
0
    return "Float32";
3846
0
  case BuiltinType::Double:
3847
0
    return "Float64";
3848
0
  case BuiltinType::BFloat16:
3849
0
    return "Bfloat16";
3850
0
  default:
3851
0
    llvm_unreachable("Unexpected vector element base type");
3852
0
  }
3853
0
}
3854
3855
// AArch64's ABI for Neon vector types specifies that they should be mangled as
3856
// the equivalent internal name. The vector type must be one of the special
3857
// types predefined by ARM.
3858
0
void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
3859
0
  QualType EltType = T->getElementType();
3860
0
  assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3861
0
  unsigned BitSize =
3862
0
      (T->getNumElements() * getASTContext().getTypeSize(EltType));
3863
0
  (void)BitSize; // Silence warning.
3864
3865
0
  assert((BitSize == 64 || BitSize == 128) &&
3866
0
         "Neon vector type not 64 or 128 bits");
3867
3868
0
  StringRef EltName;
3869
0
  if (T->getVectorKind() == VectorKind::NeonPoly) {
3870
0
    switch (cast<BuiltinType>(EltType)->getKind()) {
3871
0
    case BuiltinType::UChar:
3872
0
      EltName = "Poly8";
3873
0
      break;
3874
0
    case BuiltinType::UShort:
3875
0
      EltName = "Poly16";
3876
0
      break;
3877
0
    case BuiltinType::ULong:
3878
0
    case BuiltinType::ULongLong:
3879
0
      EltName = "Poly64";
3880
0
      break;
3881
0
    default:
3882
0
      llvm_unreachable("unexpected Neon polynomial vector element type");
3883
0
    }
3884
0
  } else
3885
0
    EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
3886
3887
0
  std::string TypeName =
3888
0
      ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
3889
0
  Out << TypeName.length() << TypeName;
3890
0
}
3891
0
void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
3892
0
  DiagnosticsEngine &Diags = Context.getDiags();
3893
0
  unsigned DiagID = Diags.getCustomDiagID(
3894
0
      DiagnosticsEngine::Error,
3895
0
      "cannot mangle this dependent neon vector type yet");
3896
0
  Diags.Report(T->getAttributeLoc(), DiagID);
3897
0
}
3898
3899
// The AArch64 ACLE specifies that fixed-length SVE vector and predicate types
3900
// defined with the 'arm_sve_vector_bits' attribute map to the same AAPCS64
3901
// type as the sizeless variants.
3902
//
3903
// The mangling scheme for VLS types is implemented as a "pseudo" template:
3904
//
3905
//   '__SVE_VLS<<type>, <vector length>>'
3906
//
3907
// Combining the existing SVE type and a specific vector length (in bits).
3908
// For example:
3909
//
3910
//   typedef __SVInt32_t foo __attribute__((arm_sve_vector_bits(512)));
3911
//
3912
// is described as '__SVE_VLS<__SVInt32_t, 512u>' and mangled as:
3913
//
3914
//   "9__SVE_VLSI" + base type mangling + "Lj" + __ARM_FEATURE_SVE_BITS + "EE"
3915
//
3916
//   i.e. 9__SVE_VLSIu11__SVInt32_tLj512EE
3917
//
3918
// The latest ACLE specification (00bet5) does not contain details of this
3919
// mangling scheme, it will be specified in the next revision. The mangling
3920
// scheme is otherwise defined in the appendices to the Procedure Call Standard
3921
// for the Arm Architecture, see
3922
// https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst#appendix-c-mangling
3923
0
void CXXNameMangler::mangleAArch64FixedSveVectorType(const VectorType *T) {
3924
0
  assert((T->getVectorKind() == VectorKind::SveFixedLengthData ||
3925
0
          T->getVectorKind() == VectorKind::SveFixedLengthPredicate) &&
3926
0
         "expected fixed-length SVE vector!");
3927
3928
0
  QualType EltType = T->getElementType();
3929
0
  assert(EltType->isBuiltinType() &&
3930
0
         "expected builtin type for fixed-length SVE vector!");
3931
3932
0
  StringRef TypeName;
3933
0
  switch (cast<BuiltinType>(EltType)->getKind()) {
3934
0
  case BuiltinType::SChar:
3935
0
    TypeName = "__SVInt8_t";
3936
0
    break;
3937
0
  case BuiltinType::UChar: {
3938
0
    if (T->getVectorKind() == VectorKind::SveFixedLengthData)
3939
0
      TypeName = "__SVUint8_t";
3940
0
    else
3941
0
      TypeName = "__SVBool_t";
3942
0
    break;
3943
0
  }
3944
0
  case BuiltinType::Short:
3945
0
    TypeName = "__SVInt16_t";
3946
0
    break;
3947
0
  case BuiltinType::UShort:
3948
0
    TypeName = "__SVUint16_t";
3949
0
    break;
3950
0
  case BuiltinType::Int:
3951
0
    TypeName = "__SVInt32_t";
3952
0
    break;
3953
0
  case BuiltinType::UInt:
3954
0
    TypeName = "__SVUint32_t";
3955
0
    break;
3956
0
  case BuiltinType::Long:
3957
0
    TypeName = "__SVInt64_t";
3958
0
    break;
3959
0
  case BuiltinType::ULong:
3960
0
    TypeName = "__SVUint64_t";
3961
0
    break;
3962
0
  case BuiltinType::Half:
3963
0
    TypeName = "__SVFloat16_t";
3964
0
    break;
3965
0
  case BuiltinType::Float:
3966
0
    TypeName = "__SVFloat32_t";
3967
0
    break;
3968
0
  case BuiltinType::Double:
3969
0
    TypeName = "__SVFloat64_t";
3970
0
    break;
3971
0
  case BuiltinType::BFloat16:
3972
0
    TypeName = "__SVBfloat16_t";
3973
0
    break;
3974
0
  default:
3975
0
    llvm_unreachable("unexpected element type for fixed-length SVE vector!");
3976
0
  }
3977
3978
0
  unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width;
3979
3980
0
  if (T->getVectorKind() == VectorKind::SveFixedLengthPredicate)
3981
0
    VecSizeInBits *= 8;
3982
3983
0
  Out << "9__SVE_VLSI" << 'u' << TypeName.size() << TypeName << "Lj"
3984
0
      << VecSizeInBits << "EE";
3985
0
}
3986
3987
void CXXNameMangler::mangleAArch64FixedSveVectorType(
3988
0
    const DependentVectorType *T) {
3989
0
  DiagnosticsEngine &Diags = Context.getDiags();
3990
0
  unsigned DiagID = Diags.getCustomDiagID(
3991
0
      DiagnosticsEngine::Error,
3992
0
      "cannot mangle this dependent fixed-length SVE vector type yet");
3993
0
  Diags.Report(T->getAttributeLoc(), DiagID);
3994
0
}
3995
3996
0
void CXXNameMangler::mangleRISCVFixedRVVVectorType(const VectorType *T) {
3997
0
  assert(T->getVectorKind() == VectorKind::RVVFixedLengthData &&
3998
0
         "expected fixed-length RVV vector!");
3999
4000
0
  QualType EltType = T->getElementType();
4001
0
  assert(EltType->isBuiltinType() &&
4002
0
         "expected builtin type for fixed-length RVV vector!");
4003
4004
0
  SmallString<20> TypeNameStr;
4005
0
  llvm::raw_svector_ostream TypeNameOS(TypeNameStr);
4006
0
  TypeNameOS << "__rvv_";
4007
0
  switch (cast<BuiltinType>(EltType)->getKind()) {
4008
0
  case BuiltinType::SChar:
4009
0
    TypeNameOS << "int8";
4010
0
    break;
4011
0
  case BuiltinType::UChar:
4012
0
    TypeNameOS << "uint8";
4013
0
    break;
4014
0
  case BuiltinType::Short:
4015
0
    TypeNameOS << "int16";
4016
0
    break;
4017
0
  case BuiltinType::UShort:
4018
0
    TypeNameOS << "uint16";
4019
0
    break;
4020
0
  case BuiltinType::Int:
4021
0
    TypeNameOS << "int32";
4022
0
    break;
4023
0
  case BuiltinType::UInt:
4024
0
    TypeNameOS << "uint32";
4025
0
    break;
4026
0
  case BuiltinType::Long:
4027
0
    TypeNameOS << "int64";
4028
0
    break;
4029
0
  case BuiltinType::ULong:
4030
0
    TypeNameOS << "uint64";
4031
0
    break;
4032
0
  case BuiltinType::Float16:
4033
0
    TypeNameOS << "float16";
4034
0
    break;
4035
0
  case BuiltinType::Float:
4036
0
    TypeNameOS << "float32";
4037
0
    break;
4038
0
  case BuiltinType::Double:
4039
0
    TypeNameOS << "float64";
4040
0
    break;
4041
0
  default:
4042
0
    llvm_unreachable("unexpected element type for fixed-length RVV vector!");
4043
0
  }
4044
4045
0
  unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width;
4046
4047
  // Apend the LMUL suffix.
4048
0
  auto VScale = getASTContext().getTargetInfo().getVScaleRange(
4049
0
      getASTContext().getLangOpts());
4050
0
  unsigned VLen = VScale->first * llvm::RISCV::RVVBitsPerBlock;
4051
0
  TypeNameOS << 'm';
4052
0
  if (VecSizeInBits >= VLen)
4053
0
    TypeNameOS << (VecSizeInBits / VLen);
4054
0
  else
4055
0
    TypeNameOS << 'f' << (VLen / VecSizeInBits);
4056
4057
0
  TypeNameOS << "_t";
4058
4059
0
  Out << "9__RVV_VLSI" << 'u' << TypeNameStr.size() << TypeNameStr << "Lj"
4060
0
      << VecSizeInBits << "EE";
4061
0
}
4062
4063
void CXXNameMangler::mangleRISCVFixedRVVVectorType(
4064
0
    const DependentVectorType *T) {
4065
0
  DiagnosticsEngine &Diags = Context.getDiags();
4066
0
  unsigned DiagID = Diags.getCustomDiagID(
4067
0
      DiagnosticsEngine::Error,
4068
0
      "cannot mangle this dependent fixed-length RVV vector type yet");
4069
0
  Diags.Report(T->getAttributeLoc(), DiagID);
4070
0
}
4071
4072
// GNU extension: vector types
4073
// <type>                  ::= <vector-type>
4074
// <vector-type>           ::= Dv <positive dimension number> _
4075
//                                    <extended element type>
4076
//                         ::= Dv [<dimension expression>] _ <element type>
4077
// <extended element type> ::= <element type>
4078
//                         ::= p # AltiVec vector pixel
4079
//                         ::= b # Altivec vector bool
4080
0
void CXXNameMangler::mangleType(const VectorType *T) {
4081
0
  if ((T->getVectorKind() == VectorKind::Neon ||
4082
0
       T->getVectorKind() == VectorKind::NeonPoly)) {
4083
0
    llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
4084
0
    llvm::Triple::ArchType Arch =
4085
0
        getASTContext().getTargetInfo().getTriple().getArch();
4086
0
    if ((Arch == llvm::Triple::aarch64 ||
4087
0
         Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
4088
0
      mangleAArch64NeonVectorType(T);
4089
0
    else
4090
0
      mangleNeonVectorType(T);
4091
0
    return;
4092
0
  } else if (T->getVectorKind() == VectorKind::SveFixedLengthData ||
4093
0
             T->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
4094
0
    mangleAArch64FixedSveVectorType(T);
4095
0
    return;
4096
0
  } else if (T->getVectorKind() == VectorKind::RVVFixedLengthData) {
4097
0
    mangleRISCVFixedRVVVectorType(T);
4098
0
    return;
4099
0
  }
4100
0
  Out << "Dv" << T->getNumElements() << '_';
4101
0
  if (T->getVectorKind() == VectorKind::AltiVecPixel)
4102
0
    Out << 'p';
4103
0
  else if (T->getVectorKind() == VectorKind::AltiVecBool)
4104
0
    Out << 'b';
4105
0
  else
4106
0
    mangleType(T->getElementType());
4107
0
}
4108
4109
0
void CXXNameMangler::mangleType(const DependentVectorType *T) {
4110
0
  if ((T->getVectorKind() == VectorKind::Neon ||
4111
0
       T->getVectorKind() == VectorKind::NeonPoly)) {
4112
0
    llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
4113
0
    llvm::Triple::ArchType Arch =
4114
0
        getASTContext().getTargetInfo().getTriple().getArch();
4115
0
    if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
4116
0
        !Target.isOSDarwin())
4117
0
      mangleAArch64NeonVectorType(T);
4118
0
    else
4119
0
      mangleNeonVectorType(T);
4120
0
    return;
4121
0
  } else if (T->getVectorKind() == VectorKind::SveFixedLengthData ||
4122
0
             T->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
4123
0
    mangleAArch64FixedSveVectorType(T);
4124
0
    return;
4125
0
  } else if (T->getVectorKind() == VectorKind::RVVFixedLengthData) {
4126
0
    mangleRISCVFixedRVVVectorType(T);
4127
0
    return;
4128
0
  }
4129
4130
0
  Out << "Dv";
4131
0
  mangleExpression(T->getSizeExpr());
4132
0
  Out << '_';
4133
0
  if (T->getVectorKind() == VectorKind::AltiVecPixel)
4134
0
    Out << 'p';
4135
0
  else if (T->getVectorKind() == VectorKind::AltiVecBool)
4136
0
    Out << 'b';
4137
0
  else
4138
0
    mangleType(T->getElementType());
4139
0
}
4140
4141
0
void CXXNameMangler::mangleType(const ExtVectorType *T) {
4142
0
  mangleType(static_cast<const VectorType*>(T));
4143
0
}
4144
0
void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
4145
0
  Out << "Dv";
4146
0
  mangleExpression(T->getSizeExpr());
4147
0
  Out << '_';
4148
0
  mangleType(T->getElementType());
4149
0
}
4150
4151
0
void CXXNameMangler::mangleType(const ConstantMatrixType *T) {
4152
  // Mangle matrix types as a vendor extended type:
4153
  // u<Len>matrix_typeI<Rows><Columns><element type>E
4154
4155
0
  StringRef VendorQualifier = "matrix_type";
4156
0
  Out << "u" << VendorQualifier.size() << VendorQualifier;
4157
4158
0
  Out << "I";
4159
0
  auto &ASTCtx = getASTContext();
4160
0
  unsigned BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType());
4161
0
  llvm::APSInt Rows(BitWidth);
4162
0
  Rows = T->getNumRows();
4163
0
  mangleIntegerLiteral(ASTCtx.getSizeType(), Rows);
4164
0
  llvm::APSInt Columns(BitWidth);
4165
0
  Columns = T->getNumColumns();
4166
0
  mangleIntegerLiteral(ASTCtx.getSizeType(), Columns);
4167
0
  mangleType(T->getElementType());
4168
0
  Out << "E";
4169
0
}
4170
4171
0
void CXXNameMangler::mangleType(const DependentSizedMatrixType *T) {
4172
  // Mangle matrix types as a vendor extended type:
4173
  // u<Len>matrix_typeI<row expr><column expr><element type>E
4174
0
  StringRef VendorQualifier = "matrix_type";
4175
0
  Out << "u" << VendorQualifier.size() << VendorQualifier;
4176
4177
0
  Out << "I";
4178
0
  mangleTemplateArgExpr(T->getRowExpr());
4179
0
  mangleTemplateArgExpr(T->getColumnExpr());
4180
0
  mangleType(T->getElementType());
4181
0
  Out << "E";
4182
0
}
4183
4184
0
void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
4185
0
  SplitQualType split = T->getPointeeType().split();
4186
0
  mangleQualifiers(split.Quals, T);
4187
0
  mangleType(QualType(split.Ty, 0));
4188
0
}
4189
4190
0
void CXXNameMangler::mangleType(const PackExpansionType *T) {
4191
  // <type>  ::= Dp <type>          # pack expansion (C++0x)
4192
0
  Out << "Dp";
4193
0
  mangleType(T->getPattern());
4194
0
}
4195
4196
0
void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
4197
0
  mangleSourceName(T->getDecl()->getIdentifier());
4198
0
}
4199
4200
0
void CXXNameMangler::mangleType(const ObjCObjectType *T) {
4201
  // Treat __kindof as a vendor extended type qualifier.
4202
0
  if (T->isKindOfType())
4203
0
    Out << "U8__kindof";
4204
4205
0
  if (!T->qual_empty()) {
4206
    // Mangle protocol qualifiers.
4207
0
    SmallString<64> QualStr;
4208
0
    llvm::raw_svector_ostream QualOS(QualStr);
4209
0
    QualOS << "objcproto";
4210
0
    for (const auto *I : T->quals()) {
4211
0
      StringRef name = I->getName();
4212
0
      QualOS << name.size() << name;
4213
0
    }
4214
0
    Out << 'U' << QualStr.size() << QualStr;
4215
0
  }
4216
4217
0
  mangleType(T->getBaseType());
4218
4219
0
  if (T->isSpecialized()) {
4220
    // Mangle type arguments as I <type>+ E
4221
0
    Out << 'I';
4222
0
    for (auto typeArg : T->getTypeArgs())
4223
0
      mangleType(typeArg);
4224
0
    Out << 'E';
4225
0
  }
4226
0
}
4227
4228
0
void CXXNameMangler::mangleType(const BlockPointerType *T) {
4229
0
  Out << "U13block_pointer";
4230
0
  mangleType(T->getPointeeType());
4231
0
}
4232
4233
0
void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
4234
  // Mangle injected class name types as if the user had written the
4235
  // specialization out fully.  It may not actually be possible to see
4236
  // this mangling, though.
4237
0
  mangleType(T->getInjectedSpecializationType());
4238
0
}
4239
4240
0
void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
4241
0
  if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
4242
0
    mangleTemplateName(TD, T->template_arguments());
4243
0
  } else {
4244
0
    if (mangleSubstitution(QualType(T, 0)))
4245
0
      return;
4246
4247
0
    mangleTemplatePrefix(T->getTemplateName());
4248
4249
    // FIXME: GCC does not appear to mangle the template arguments when
4250
    // the template in question is a dependent template name. Should we
4251
    // emulate that badness?
4252
0
    mangleTemplateArgs(T->getTemplateName(), T->template_arguments());
4253
0
    addSubstitution(QualType(T, 0));
4254
0
  }
4255
0
}
4256
4257
0
void CXXNameMangler::mangleType(const DependentNameType *T) {
4258
  // Proposal by cxx-abi-dev, 2014-03-26
4259
  // <class-enum-type> ::= <name>    # non-dependent or dependent type name or
4260
  //                                 # dependent elaborated type specifier using
4261
  //                                 # 'typename'
4262
  //                   ::= Ts <name> # dependent elaborated type specifier using
4263
  //                                 # 'struct' or 'class'
4264
  //                   ::= Tu <name> # dependent elaborated type specifier using
4265
  //                                 # 'union'
4266
  //                   ::= Te <name> # dependent elaborated type specifier using
4267
  //                                 # 'enum'
4268
0
  switch (T->getKeyword()) {
4269
0
  case ElaboratedTypeKeyword::None:
4270
0
  case ElaboratedTypeKeyword::Typename:
4271
0
    break;
4272
0
  case ElaboratedTypeKeyword::Struct:
4273
0
  case ElaboratedTypeKeyword::Class:
4274
0
  case ElaboratedTypeKeyword::Interface:
4275
0
    Out << "Ts";
4276
0
    break;
4277
0
  case ElaboratedTypeKeyword::Union:
4278
0
    Out << "Tu";
4279
0
    break;
4280
0
  case ElaboratedTypeKeyword::Enum:
4281
0
    Out << "Te";
4282
0
    break;
4283
0
  }
4284
  // Typename types are always nested
4285
0
  Out << 'N';
4286
0
  manglePrefix(T->getQualifier());
4287
0
  mangleSourceName(T->getIdentifier());
4288
0
  Out << 'E';
4289
0
}
4290
4291
0
void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
4292
  // Dependently-scoped template types are nested if they have a prefix.
4293
0
  Out << 'N';
4294
4295
  // TODO: avoid making this TemplateName.
4296
0
  TemplateName Prefix =
4297
0
    getASTContext().getDependentTemplateName(T->getQualifier(),
4298
0
                                             T->getIdentifier());
4299
0
  mangleTemplatePrefix(Prefix);
4300
4301
  // FIXME: GCC does not appear to mangle the template arguments when
4302
  // the template in question is a dependent template name. Should we
4303
  // emulate that badness?
4304
0
  mangleTemplateArgs(Prefix, T->template_arguments());
4305
0
  Out << 'E';
4306
0
}
4307
4308
0
void CXXNameMangler::mangleType(const TypeOfType *T) {
4309
  // FIXME: this is pretty unsatisfactory, but there isn't an obvious
4310
  // "extension with parameters" mangling.
4311
0
  Out << "u6typeof";
4312
0
}
4313
4314
0
void CXXNameMangler::mangleType(const TypeOfExprType *T) {
4315
  // FIXME: this is pretty unsatisfactory, but there isn't an obvious
4316
  // "extension with parameters" mangling.
4317
0
  Out << "u6typeof";
4318
0
}
4319
4320
0
void CXXNameMangler::mangleType(const DecltypeType *T) {
4321
0
  Expr *E = T->getUnderlyingExpr();
4322
4323
  // type ::= Dt <expression> E  # decltype of an id-expression
4324
  //                             #   or class member access
4325
  //      ::= DT <expression> E  # decltype of an expression
4326
4327
  // This purports to be an exhaustive list of id-expressions and
4328
  // class member accesses.  Note that we do not ignore parentheses;
4329
  // parentheses change the semantics of decltype for these
4330
  // expressions (and cause the mangler to use the other form).
4331
0
  if (isa<DeclRefExpr>(E) ||
4332
0
      isa<MemberExpr>(E) ||
4333
0
      isa<UnresolvedLookupExpr>(E) ||
4334
0
      isa<DependentScopeDeclRefExpr>(E) ||
4335
0
      isa<CXXDependentScopeMemberExpr>(E) ||
4336
0
      isa<UnresolvedMemberExpr>(E))
4337
0
    Out << "Dt";
4338
0
  else
4339
0
    Out << "DT";
4340
0
  mangleExpression(E);
4341
0
  Out << 'E';
4342
0
}
4343
4344
0
void CXXNameMangler::mangleType(const UnaryTransformType *T) {
4345
  // If this is dependent, we need to record that. If not, we simply
4346
  // mangle it as the underlying type since they are equivalent.
4347
0
  if (T->isDependentType()) {
4348
0
    Out << "u";
4349
4350
0
    StringRef BuiltinName;
4351
0
    switch (T->getUTTKind()) {
4352
0
#define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait)                                  \
4353
0
  case UnaryTransformType::Enum:                                               \
4354
0
    BuiltinName = "__" #Trait;                                                 \
4355
0
    break;
4356
0
#include "clang/Basic/TransformTypeTraits.def"
4357
0
    }
4358
0
    Out << BuiltinName.size() << BuiltinName;
4359
0
  }
4360
4361
0
  Out << "I";
4362
0
  mangleType(T->getBaseType());
4363
0
  Out << "E";
4364
0
}
4365
4366
0
void CXXNameMangler::mangleType(const AutoType *T) {
4367
0
  assert(T->getDeducedType().isNull() &&
4368
0
         "Deduced AutoType shouldn't be handled here!");
4369
0
  assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
4370
0
         "shouldn't need to mangle __auto_type!");
4371
  // <builtin-type> ::= Da # auto
4372
  //                ::= Dc # decltype(auto)
4373
  //                ::= Dk # constrained auto
4374
  //                ::= DK # constrained decltype(auto)
4375
0
  if (T->isConstrained() && !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
4376
0
    Out << (T->isDecltypeAuto() ? "DK" : "Dk");
4377
0
    mangleTypeConstraint(T->getTypeConstraintConcept(),
4378
0
                         T->getTypeConstraintArguments());
4379
0
  } else {
4380
0
    Out << (T->isDecltypeAuto() ? "Dc" : "Da");
4381
0
  }
4382
0
}
4383
4384
0
void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
4385
0
  QualType Deduced = T->getDeducedType();
4386
0
  if (!Deduced.isNull())
4387
0
    return mangleType(Deduced);
4388
4389
0
  TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl();
4390
0
  assert(TD && "shouldn't form deduced TST unless we know we have a template");
4391
4392
0
  if (mangleSubstitution(TD))
4393
0
    return;
4394
4395
0
  mangleName(GlobalDecl(TD));
4396
0
  addSubstitution(TD);
4397
0
}
4398
4399
0
void CXXNameMangler::mangleType(const AtomicType *T) {
4400
  // <type> ::= U <source-name> <type>  # vendor extended type qualifier
4401
  // (Until there's a standardized mangling...)
4402
0
  Out << "U7_Atomic";
4403
0
  mangleType(T->getValueType());
4404
0
}
4405
4406
0
void CXXNameMangler::mangleType(const PipeType *T) {
4407
  // Pipe type mangling rules are described in SPIR 2.0 specification
4408
  // A.1 Data types and A.3 Summary of changes
4409
  // <type> ::= 8ocl_pipe
4410
0
  Out << "8ocl_pipe";
4411
0
}
4412
4413
0
void CXXNameMangler::mangleType(const BitIntType *T) {
4414
  // 5.1.5.2 Builtin types
4415
  // <type> ::= DB <number | instantiation-dependent expression> _
4416
  //        ::= DU <number | instantiation-dependent expression> _
4417
0
  Out << "D" << (T->isUnsigned() ? "U" : "B") << T->getNumBits() << "_";
4418
0
}
4419
4420
0
void CXXNameMangler::mangleType(const DependentBitIntType *T) {
4421
  // 5.1.5.2 Builtin types
4422
  // <type> ::= DB <number | instantiation-dependent expression> _
4423
  //        ::= DU <number | instantiation-dependent expression> _
4424
0
  Out << "D" << (T->isUnsigned() ? "U" : "B");
4425
0
  mangleExpression(T->getNumBitsExpr());
4426
0
  Out << "_";
4427
0
}
4428
4429
void CXXNameMangler::mangleIntegerLiteral(QualType T,
4430
0
                                          const llvm::APSInt &Value) {
4431
  //  <expr-primary> ::= L <type> <value number> E # integer literal
4432
0
  Out << 'L';
4433
4434
0
  mangleType(T);
4435
0
  if (T->isBooleanType()) {
4436
    // Boolean values are encoded as 0/1.
4437
0
    Out << (Value.getBoolValue() ? '1' : '0');
4438
0
  } else {
4439
0
    mangleNumber(Value);
4440
0
  }
4441
0
  Out << 'E';
4442
4443
0
}
4444
4445
0
void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
4446
  // Ignore member expressions involving anonymous unions.
4447
0
  while (const auto *RT = Base->getType()->getAs<RecordType>()) {
4448
0
    if (!RT->getDecl()->isAnonymousStructOrUnion())
4449
0
      break;
4450
0
    const auto *ME = dyn_cast<MemberExpr>(Base);
4451
0
    if (!ME)
4452
0
      break;
4453
0
    Base = ME->getBase();
4454
0
    IsArrow = ME->isArrow();
4455
0
  }
4456
4457
0
  if (Base->isImplicitCXXThis()) {
4458
    // Note: GCC mangles member expressions to the implicit 'this' as
4459
    // *this., whereas we represent them as this->. The Itanium C++ ABI
4460
    // does not specify anything here, so we follow GCC.
4461
0
    Out << "dtdefpT";
4462
0
  } else {
4463
0
    Out << (IsArrow ? "pt" : "dt");
4464
0
    mangleExpression(Base);
4465
0
  }
4466
0
}
4467
4468
/// Mangles a member expression.
4469
void CXXNameMangler::mangleMemberExpr(const Expr *base,
4470
                                      bool isArrow,
4471
                                      NestedNameSpecifier *qualifier,
4472
                                      NamedDecl *firstQualifierLookup,
4473
                                      DeclarationName member,
4474
                                      const TemplateArgumentLoc *TemplateArgs,
4475
                                      unsigned NumTemplateArgs,
4476
0
                                      unsigned arity) {
4477
  // <expression> ::= dt <expression> <unresolved-name>
4478
  //              ::= pt <expression> <unresolved-name>
4479
0
  if (base)
4480
0
    mangleMemberExprBase(base, isArrow);
4481
0
  mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
4482
0
}
4483
4484
/// Look at the callee of the given call expression and determine if
4485
/// it's a parenthesized id-expression which would have triggered ADL
4486
/// otherwise.
4487
0
static bool isParenthesizedADLCallee(const CallExpr *call) {
4488
0
  const Expr *callee = call->getCallee();
4489
0
  const Expr *fn = callee->IgnoreParens();
4490
4491
  // Must be parenthesized.  IgnoreParens() skips __extension__ nodes,
4492
  // too, but for those to appear in the callee, it would have to be
4493
  // parenthesized.
4494
0
  if (callee == fn) return false;
4495
4496
  // Must be an unresolved lookup.
4497
0
  const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
4498
0
  if (!lookup) return false;
4499
4500
0
  assert(!lookup->requiresADL());
4501
4502
  // Must be an unqualified lookup.
4503
0
  if (lookup->getQualifier()) return false;
4504
4505
  // Must not have found a class member.  Note that if one is a class
4506
  // member, they're all class members.
4507
0
  if (lookup->getNumDecls() > 0 &&
4508
0
      (*lookup->decls_begin())->isCXXClassMember())
4509
0
    return false;
4510
4511
  // Otherwise, ADL would have been triggered.
4512
0
  return true;
4513
0
}
4514
4515
0
void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
4516
0
  const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
4517
0
  Out << CastEncoding;
4518
0
  mangleType(ECE->getType());
4519
0
  mangleExpression(ECE->getSubExpr());
4520
0
}
4521
4522
0
void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
4523
0
  if (auto *Syntactic = InitList->getSyntacticForm())
4524
0
    InitList = Syntactic;
4525
0
  for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
4526
0
    mangleExpression(InitList->getInit(i));
4527
0
}
4528
4529
void CXXNameMangler::mangleRequirement(SourceLocation RequiresExprLoc,
4530
0
                                       const concepts::Requirement *Req) {
4531
0
  using concepts::Requirement;
4532
4533
  // TODO: We can't mangle the result of a failed substitution. It's not clear
4534
  // whether we should be mangling the original form prior to any substitution
4535
  // instead. See https://lists.isocpp.org/core/2023/04/14118.php
4536
0
  auto HandleSubstitutionFailure =
4537
0
      [&](SourceLocation Loc) {
4538
0
        DiagnosticsEngine &Diags = Context.getDiags();
4539
0
        unsigned DiagID = Diags.getCustomDiagID(
4540
0
            DiagnosticsEngine::Error, "cannot mangle this requires-expression "
4541
0
                                      "containing a substitution failure");
4542
0
        Diags.Report(Loc, DiagID);
4543
0
        Out << 'F';
4544
0
      };
4545
4546
0
  switch (Req->getKind()) {
4547
0
  case Requirement::RK_Type: {
4548
0
    const auto *TR = cast<concepts::TypeRequirement>(Req);
4549
0
    if (TR->isSubstitutionFailure())
4550
0
      return HandleSubstitutionFailure(
4551
0
          TR->getSubstitutionDiagnostic()->DiagLoc);
4552
4553
0
    Out << 'T';
4554
0
    mangleType(TR->getType()->getType());
4555
0
    break;
4556
0
  }
4557
4558
0
  case Requirement::RK_Simple:
4559
0
  case Requirement::RK_Compound: {
4560
0
    const auto *ER = cast<concepts::ExprRequirement>(Req);
4561
0
    if (ER->isExprSubstitutionFailure())
4562
0
      return HandleSubstitutionFailure(
4563
0
          ER->getExprSubstitutionDiagnostic()->DiagLoc);
4564
4565
0
    Out << 'X';
4566
0
    mangleExpression(ER->getExpr());
4567
4568
0
    if (ER->hasNoexceptRequirement())
4569
0
      Out << 'N';
4570
4571
0
    if (!ER->getReturnTypeRequirement().isEmpty()) {
4572
0
      if (ER->getReturnTypeRequirement().isSubstitutionFailure())
4573
0
        return HandleSubstitutionFailure(ER->getReturnTypeRequirement()
4574
0
                                             .getSubstitutionDiagnostic()
4575
0
                                             ->DiagLoc);
4576
4577
0
      Out << 'R';
4578
0
      mangleTypeConstraint(ER->getReturnTypeRequirement().getTypeConstraint());
4579
0
    }
4580
0
    break;
4581
0
  }
4582
4583
0
  case Requirement::RK_Nested:
4584
0
    const auto *NR = cast<concepts::NestedRequirement>(Req);
4585
0
    if (NR->hasInvalidConstraint()) {
4586
      // FIXME: NestedRequirement should track the location of its requires
4587
      // keyword.
4588
0
      return HandleSubstitutionFailure(RequiresExprLoc);
4589
0
    }
4590
4591
0
    Out << 'Q';
4592
0
    mangleExpression(NR->getConstraintExpr());
4593
0
    break;
4594
0
  }
4595
0
}
4596
4597
void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity,
4598
0
                                      bool AsTemplateArg) {
4599
  // <expression> ::= <unary operator-name> <expression>
4600
  //              ::= <binary operator-name> <expression> <expression>
4601
  //              ::= <trinary operator-name> <expression> <expression> <expression>
4602
  //              ::= cv <type> expression           # conversion with one argument
4603
  //              ::= cv <type> _ <expression>* E # conversion with a different number of arguments
4604
  //              ::= dc <type> <expression>         # dynamic_cast<type> (expression)
4605
  //              ::= sc <type> <expression>         # static_cast<type> (expression)
4606
  //              ::= cc <type> <expression>         # const_cast<type> (expression)
4607
  //              ::= rc <type> <expression>         # reinterpret_cast<type> (expression)
4608
  //              ::= st <type>                      # sizeof (a type)
4609
  //              ::= at <type>                      # alignof (a type)
4610
  //              ::= <template-param>
4611
  //              ::= <function-param>
4612
  //              ::= fpT                            # 'this' expression (part of <function-param>)
4613
  //              ::= sr <type> <unqualified-name>                   # dependent name
4614
  //              ::= sr <type> <unqualified-name> <template-args>   # dependent template-id
4615
  //              ::= ds <expression> <expression>                   # expr.*expr
4616
  //              ::= sZ <template-param>                            # size of a parameter pack
4617
  //              ::= sZ <function-param>    # size of a function parameter pack
4618
  //              ::= u <source-name> <template-arg>* E # vendor extended expression
4619
  //              ::= <expr-primary>
4620
  // <expr-primary> ::= L <type> <value number> E    # integer literal
4621
  //                ::= L <type> <value float> E     # floating literal
4622
  //                ::= L <type> <string type> E     # string literal
4623
  //                ::= L <nullptr type> E           # nullptr literal "LDnE"
4624
  //                ::= L <pointer type> 0 E         # null pointer template argument
4625
  //                ::= L <type> <real-part float> _ <imag-part float> E    # complex floating point literal (C99); not used by clang
4626
  //                ::= L <mangled-name> E           # external name
4627
0
  QualType ImplicitlyConvertedToType;
4628
4629
  // A top-level expression that's not <expr-primary> needs to be wrapped in
4630
  // X...E in a template arg.
4631
0
  bool IsPrimaryExpr = true;
4632
0
  auto NotPrimaryExpr = [&] {
4633
0
    if (AsTemplateArg && IsPrimaryExpr)
4634
0
      Out << 'X';
4635
0
    IsPrimaryExpr = false;
4636
0
  };
4637
4638
0
  auto MangleDeclRefExpr = [&](const NamedDecl *D) {
4639
0
    switch (D->getKind()) {
4640
0
    default:
4641
      //  <expr-primary> ::= L <mangled-name> E # external name
4642
0
      Out << 'L';
4643
0
      mangle(D);
4644
0
      Out << 'E';
4645
0
      break;
4646
4647
0
    case Decl::ParmVar:
4648
0
      NotPrimaryExpr();
4649
0
      mangleFunctionParam(cast<ParmVarDecl>(D));
4650
0
      break;
4651
4652
0
    case Decl::EnumConstant: {
4653
      // <expr-primary>
4654
0
      const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
4655
0
      mangleIntegerLiteral(ED->getType(), ED->getInitVal());
4656
0
      break;
4657
0
    }
4658
4659
0
    case Decl::NonTypeTemplateParm:
4660
0
      NotPrimaryExpr();
4661
0
      const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
4662
0
      mangleTemplateParameter(PD->getDepth(), PD->getIndex());
4663
0
      break;
4664
0
    }
4665
0
  };
4666
4667
  // 'goto recurse' is used when handling a simple "unwrapping" node which
4668
  // produces no output, where ImplicitlyConvertedToType and AsTemplateArg need
4669
  // to be preserved.
4670
0
recurse:
4671
0
  switch (E->getStmtClass()) {
4672
0
  case Expr::NoStmtClass:
4673
0
#define ABSTRACT_STMT(Type)
4674
0
#define EXPR(Type, Base)
4675
0
#define STMT(Type, Base) \
4676
0
  case Expr::Type##Class:
4677
0
#include "clang/AST/StmtNodes.inc"
4678
    // fallthrough
4679
4680
  // These all can only appear in local or variable-initialization
4681
  // contexts and so should never appear in a mangling.
4682
0
  case Expr::AddrLabelExprClass:
4683
0
  case Expr::DesignatedInitUpdateExprClass:
4684
0
  case Expr::ImplicitValueInitExprClass:
4685
0
  case Expr::ArrayInitLoopExprClass:
4686
0
  case Expr::ArrayInitIndexExprClass:
4687
0
  case Expr::NoInitExprClass:
4688
0
  case Expr::ParenListExprClass:
4689
0
  case Expr::MSPropertyRefExprClass:
4690
0
  case Expr::MSPropertySubscriptExprClass:
4691
0
  case Expr::TypoExprClass: // This should no longer exist in the AST by now.
4692
0
  case Expr::RecoveryExprClass:
4693
0
  case Expr::OMPArraySectionExprClass:
4694
0
  case Expr::OMPArrayShapingExprClass:
4695
0
  case Expr::OMPIteratorExprClass:
4696
0
  case Expr::CXXInheritedCtorInitExprClass:
4697
0
  case Expr::CXXParenListInitExprClass:
4698
0
    llvm_unreachable("unexpected statement kind");
4699
4700
0
  case Expr::ConstantExprClass:
4701
0
    E = cast<ConstantExpr>(E)->getSubExpr();
4702
0
    goto recurse;
4703
4704
  // FIXME: invent manglings for all these.
4705
0
  case Expr::BlockExprClass:
4706
0
  case Expr::ChooseExprClass:
4707
0
  case Expr::CompoundLiteralExprClass:
4708
0
  case Expr::ExtVectorElementExprClass:
4709
0
  case Expr::GenericSelectionExprClass:
4710
0
  case Expr::ObjCEncodeExprClass:
4711
0
  case Expr::ObjCIsaExprClass:
4712
0
  case Expr::ObjCIvarRefExprClass:
4713
0
  case Expr::ObjCMessageExprClass:
4714
0
  case Expr::ObjCPropertyRefExprClass:
4715
0
  case Expr::ObjCProtocolExprClass:
4716
0
  case Expr::ObjCSelectorExprClass:
4717
0
  case Expr::ObjCStringLiteralClass:
4718
0
  case Expr::ObjCBoxedExprClass:
4719
0
  case Expr::ObjCArrayLiteralClass:
4720
0
  case Expr::ObjCDictionaryLiteralClass:
4721
0
  case Expr::ObjCSubscriptRefExprClass:
4722
0
  case Expr::ObjCIndirectCopyRestoreExprClass:
4723
0
  case Expr::ObjCAvailabilityCheckExprClass:
4724
0
  case Expr::OffsetOfExprClass:
4725
0
  case Expr::PredefinedExprClass:
4726
0
  case Expr::ShuffleVectorExprClass:
4727
0
  case Expr::ConvertVectorExprClass:
4728
0
  case Expr::StmtExprClass:
4729
0
  case Expr::ArrayTypeTraitExprClass:
4730
0
  case Expr::ExpressionTraitExprClass:
4731
0
  case Expr::VAArgExprClass:
4732
0
  case Expr::CUDAKernelCallExprClass:
4733
0
  case Expr::AsTypeExprClass:
4734
0
  case Expr::PseudoObjectExprClass:
4735
0
  case Expr::AtomicExprClass:
4736
0
  case Expr::SourceLocExprClass:
4737
0
  case Expr::BuiltinBitCastExprClass:
4738
0
  {
4739
0
    NotPrimaryExpr();
4740
0
    if (!NullOut) {
4741
      // As bad as this diagnostic is, it's better than crashing.
4742
0
      DiagnosticsEngine &Diags = Context.getDiags();
4743
0
      unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
4744
0
                                       "cannot yet mangle expression type %0");
4745
0
      Diags.Report(E->getExprLoc(), DiagID)
4746
0
        << E->getStmtClassName() << E->getSourceRange();
4747
0
      return;
4748
0
    }
4749
0
    break;
4750
0
  }
4751
4752
0
  case Expr::CXXUuidofExprClass: {
4753
0
    NotPrimaryExpr();
4754
0
    const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
4755
    // As of clang 12, uuidof uses the vendor extended expression
4756
    // mangling. Previously, it used a special-cased nonstandard extension.
4757
0
    if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {
4758
0
      Out << "u8__uuidof";
4759
0
      if (UE->isTypeOperand())
4760
0
        mangleType(UE->getTypeOperand(Context.getASTContext()));
4761
0
      else
4762
0
        mangleTemplateArgExpr(UE->getExprOperand());
4763
0
      Out << 'E';
4764
0
    } else {
4765
0
      if (UE->isTypeOperand()) {
4766
0
        QualType UuidT = UE->getTypeOperand(Context.getASTContext());
4767
0
        Out << "u8__uuidoft";
4768
0
        mangleType(UuidT);
4769
0
      } else {
4770
0
        Expr *UuidExp = UE->getExprOperand();
4771
0
        Out << "u8__uuidofz";
4772
0
        mangleExpression(UuidExp);
4773
0
      }
4774
0
    }
4775
0
    break;
4776
0
  }
4777
4778
  // Even gcc-4.5 doesn't mangle this.
4779
0
  case Expr::BinaryConditionalOperatorClass: {
4780
0
    NotPrimaryExpr();
4781
0
    DiagnosticsEngine &Diags = Context.getDiags();
4782
0
    unsigned DiagID =
4783
0
      Diags.getCustomDiagID(DiagnosticsEngine::Error,
4784
0
                "?: operator with omitted middle operand cannot be mangled");
4785
0
    Diags.Report(E->getExprLoc(), DiagID)
4786
0
      << E->getStmtClassName() << E->getSourceRange();
4787
0
    return;
4788
0
  }
4789
4790
  // These are used for internal purposes and cannot be meaningfully mangled.
4791
0
  case Expr::OpaqueValueExprClass:
4792
0
    llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
4793
4794
0
  case Expr::InitListExprClass: {
4795
0
    NotPrimaryExpr();
4796
0
    Out << "il";
4797
0
    mangleInitListElements(cast<InitListExpr>(E));
4798
0
    Out << "E";
4799
0
    break;
4800
0
  }
4801
4802
0
  case Expr::DesignatedInitExprClass: {
4803
0
    NotPrimaryExpr();
4804
0
    auto *DIE = cast<DesignatedInitExpr>(E);
4805
0
    for (const auto &Designator : DIE->designators()) {
4806
0
      if (Designator.isFieldDesignator()) {
4807
0
        Out << "di";
4808
0
        mangleSourceName(Designator.getFieldName());
4809
0
      } else if (Designator.isArrayDesignator()) {
4810
0
        Out << "dx";
4811
0
        mangleExpression(DIE->getArrayIndex(Designator));
4812
0
      } else {
4813
0
        assert(Designator.isArrayRangeDesignator() &&
4814
0
               "unknown designator kind");
4815
0
        Out << "dX";
4816
0
        mangleExpression(DIE->getArrayRangeStart(Designator));
4817
0
        mangleExpression(DIE->getArrayRangeEnd(Designator));
4818
0
      }
4819
0
    }
4820
0
    mangleExpression(DIE->getInit());
4821
0
    break;
4822
0
  }
4823
4824
0
  case Expr::CXXDefaultArgExprClass:
4825
0
    E = cast<CXXDefaultArgExpr>(E)->getExpr();
4826
0
    goto recurse;
4827
4828
0
  case Expr::CXXDefaultInitExprClass:
4829
0
    E = cast<CXXDefaultInitExpr>(E)->getExpr();
4830
0
    goto recurse;
4831
4832
0
  case Expr::CXXStdInitializerListExprClass:
4833
0
    E = cast<CXXStdInitializerListExpr>(E)->getSubExpr();
4834
0
    goto recurse;
4835
4836
0
  case Expr::SubstNonTypeTemplateParmExprClass:
4837
0
    E = cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement();
4838
0
    goto recurse;
4839
4840
0
  case Expr::UserDefinedLiteralClass:
4841
    // We follow g++'s approach of mangling a UDL as a call to the literal
4842
    // operator.
4843
0
  case Expr::CXXMemberCallExprClass: // fallthrough
4844
0
  case Expr::CallExprClass: {
4845
0
    NotPrimaryExpr();
4846
0
    const CallExpr *CE = cast<CallExpr>(E);
4847
4848
    // <expression> ::= cp <simple-id> <expression>* E
4849
    // We use this mangling only when the call would use ADL except
4850
    // for being parenthesized.  Per discussion with David
4851
    // Vandervoorde, 2011.04.25.
4852
0
    if (isParenthesizedADLCallee(CE)) {
4853
0
      Out << "cp";
4854
      // The callee here is a parenthesized UnresolvedLookupExpr with
4855
      // no qualifier and should always get mangled as a <simple-id>
4856
      // anyway.
4857
4858
    // <expression> ::= cl <expression>* E
4859
0
    } else {
4860
0
      Out << "cl";
4861
0
    }
4862
4863
0
    unsigned CallArity = CE->getNumArgs();
4864
0
    for (const Expr *Arg : CE->arguments())
4865
0
      if (isa<PackExpansionExpr>(Arg))
4866
0
        CallArity = UnknownArity;
4867
4868
0
    mangleExpression(CE->getCallee(), CallArity);
4869
0
    for (const Expr *Arg : CE->arguments())
4870
0
      mangleExpression(Arg);
4871
0
    Out << 'E';
4872
0
    break;
4873
0
  }
4874
4875
0
  case Expr::CXXNewExprClass: {
4876
0
    NotPrimaryExpr();
4877
0
    const CXXNewExpr *New = cast<CXXNewExpr>(E);
4878
0
    if (New->isGlobalNew()) Out << "gs";
4879
0
    Out << (New->isArray() ? "na" : "nw");
4880
0
    for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
4881
0
           E = New->placement_arg_end(); I != E; ++I)
4882
0
      mangleExpression(*I);
4883
0
    Out << '_';
4884
0
    mangleType(New->getAllocatedType());
4885
0
    if (New->hasInitializer()) {
4886
0
      if (New->getInitializationStyle() == CXXNewInitializationStyle::List)
4887
0
        Out << "il";
4888
0
      else
4889
0
        Out << "pi";
4890
0
      const Expr *Init = New->getInitializer();
4891
0
      if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
4892
        // Directly inline the initializers.
4893
0
        for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
4894
0
                                                  E = CCE->arg_end();
4895
0
             I != E; ++I)
4896
0
          mangleExpression(*I);
4897
0
      } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
4898
0
        for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
4899
0
          mangleExpression(PLE->getExpr(i));
4900
0
      } else if (New->getInitializationStyle() ==
4901
0
                     CXXNewInitializationStyle::List &&
4902
0
                 isa<InitListExpr>(Init)) {
4903
        // Only take InitListExprs apart for list-initialization.
4904
0
        mangleInitListElements(cast<InitListExpr>(Init));
4905
0
      } else
4906
0
        mangleExpression(Init);
4907
0
    }
4908
0
    Out << 'E';
4909
0
    break;
4910
0
  }
4911
4912
0
  case Expr::CXXPseudoDestructorExprClass: {
4913
0
    NotPrimaryExpr();
4914
0
    const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
4915
0
    if (const Expr *Base = PDE->getBase())
4916
0
      mangleMemberExprBase(Base, PDE->isArrow());
4917
0
    NestedNameSpecifier *Qualifier = PDE->getQualifier();
4918
0
    if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
4919
0
      if (Qualifier) {
4920
0
        mangleUnresolvedPrefix(Qualifier,
4921
0
                               /*recursive=*/true);
4922
0
        mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
4923
0
        Out << 'E';
4924
0
      } else {
4925
0
        Out << "sr";
4926
0
        if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
4927
0
          Out << 'E';
4928
0
      }
4929
0
    } else if (Qualifier) {
4930
0
      mangleUnresolvedPrefix(Qualifier);
4931
0
    }
4932
    // <base-unresolved-name> ::= dn <destructor-name>
4933
0
    Out << "dn";
4934
0
    QualType DestroyedType = PDE->getDestroyedType();
4935
0
    mangleUnresolvedTypeOrSimpleId(DestroyedType);
4936
0
    break;
4937
0
  }
4938
4939
0
  case Expr::MemberExprClass: {
4940
0
    NotPrimaryExpr();
4941
0
    const MemberExpr *ME = cast<MemberExpr>(E);
4942
0
    mangleMemberExpr(ME->getBase(), ME->isArrow(),
4943
0
                     ME->getQualifier(), nullptr,
4944
0
                     ME->getMemberDecl()->getDeclName(),
4945
0
                     ME->getTemplateArgs(), ME->getNumTemplateArgs(),
4946
0
                     Arity);
4947
0
    break;
4948
0
  }
4949
4950
0
  case Expr::UnresolvedMemberExprClass: {
4951
0
    NotPrimaryExpr();
4952
0
    const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
4953
0
    mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
4954
0
                     ME->isArrow(), ME->getQualifier(), nullptr,
4955
0
                     ME->getMemberName(),
4956
0
                     ME->getTemplateArgs(), ME->getNumTemplateArgs(),
4957
0
                     Arity);
4958
0
    break;
4959
0
  }
4960
4961
0
  case Expr::CXXDependentScopeMemberExprClass: {
4962
0
    NotPrimaryExpr();
4963
0
    const CXXDependentScopeMemberExpr *ME
4964
0
      = cast<CXXDependentScopeMemberExpr>(E);
4965
0
    mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
4966
0
                     ME->isArrow(), ME->getQualifier(),
4967
0
                     ME->getFirstQualifierFoundInScope(),
4968
0
                     ME->getMember(),
4969
0
                     ME->getTemplateArgs(), ME->getNumTemplateArgs(),
4970
0
                     Arity);
4971
0
    break;
4972
0
  }
4973
4974
0
  case Expr::UnresolvedLookupExprClass: {
4975
0
    NotPrimaryExpr();
4976
0
    const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
4977
0
    mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
4978
0
                         ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
4979
0
                         Arity);
4980
0
    break;
4981
0
  }
4982
4983
0
  case Expr::CXXUnresolvedConstructExprClass: {
4984
0
    NotPrimaryExpr();
4985
0
    const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
4986
0
    unsigned N = CE->getNumArgs();
4987
4988
0
    if (CE->isListInitialization()) {
4989
0
      assert(N == 1 && "unexpected form for list initialization");
4990
0
      auto *IL = cast<InitListExpr>(CE->getArg(0));
4991
0
      Out << "tl";
4992
0
      mangleType(CE->getType());
4993
0
      mangleInitListElements(IL);
4994
0
      Out << "E";
4995
0
      break;
4996
0
    }
4997
4998
0
    Out << "cv";
4999
0
    mangleType(CE->getType());
5000
0
    if (N != 1) Out << '_';
5001
0
    for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
5002
0
    if (N != 1) Out << 'E';
5003
0
    break;
5004
0
  }
5005
5006
0
  case Expr::CXXConstructExprClass: {
5007
    // An implicit cast is silent, thus may contain <expr-primary>.
5008
0
    const auto *CE = cast<CXXConstructExpr>(E);
5009
0
    if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
5010
0
      assert(
5011
0
          CE->getNumArgs() >= 1 &&
5012
0
          (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
5013
0
          "implicit CXXConstructExpr must have one argument");
5014
0
      E = cast<CXXConstructExpr>(E)->getArg(0);
5015
0
      goto recurse;
5016
0
    }
5017
0
    NotPrimaryExpr();
5018
0
    Out << "il";
5019
0
    for (auto *E : CE->arguments())
5020
0
      mangleExpression(E);
5021
0
    Out << "E";
5022
0
    break;
5023
0
  }
5024
5025
0
  case Expr::CXXTemporaryObjectExprClass: {
5026
0
    NotPrimaryExpr();
5027
0
    const auto *CE = cast<CXXTemporaryObjectExpr>(E);
5028
0
    unsigned N = CE->getNumArgs();
5029
0
    bool List = CE->isListInitialization();
5030
5031
0
    if (List)
5032
0
      Out << "tl";
5033
0
    else
5034
0
      Out << "cv";
5035
0
    mangleType(CE->getType());
5036
0
    if (!List && N != 1)
5037
0
      Out << '_';
5038
0
    if (CE->isStdInitListInitialization()) {
5039
      // We implicitly created a std::initializer_list<T> for the first argument
5040
      // of a constructor of type U in an expression of the form U{a, b, c}.
5041
      // Strip all the semantic gunk off the initializer list.
5042
0
      auto *SILE =
5043
0
          cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
5044
0
      auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
5045
0
      mangleInitListElements(ILE);
5046
0
    } else {
5047
0
      for (auto *E : CE->arguments())
5048
0
        mangleExpression(E);
5049
0
    }
5050
0
    if (List || N != 1)
5051
0
      Out << 'E';
5052
0
    break;
5053
0
  }
5054
5055
0
  case Expr::CXXScalarValueInitExprClass:
5056
0
    NotPrimaryExpr();
5057
0
    Out << "cv";
5058
0
    mangleType(E->getType());
5059
0
    Out << "_E";
5060
0
    break;
5061
5062
0
  case Expr::CXXNoexceptExprClass:
5063
0
    NotPrimaryExpr();
5064
0
    Out << "nx";
5065
0
    mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
5066
0
    break;
5067
5068
0
  case Expr::UnaryExprOrTypeTraitExprClass: {
5069
    // Non-instantiation-dependent traits are an <expr-primary> integer literal.
5070
0
    const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
5071
5072
0
    if (!SAE->isInstantiationDependent()) {
5073
      // Itanium C++ ABI:
5074
      //   If the operand of a sizeof or alignof operator is not
5075
      //   instantiation-dependent it is encoded as an integer literal
5076
      //   reflecting the result of the operator.
5077
      //
5078
      //   If the result of the operator is implicitly converted to a known
5079
      //   integer type, that type is used for the literal; otherwise, the type
5080
      //   of std::size_t or std::ptrdiff_t is used.
5081
      //
5082
      // FIXME: We still include the operand in the profile in this case. This
5083
      // can lead to mangling collisions between function templates that we
5084
      // consider to be different.
5085
0
      QualType T = (ImplicitlyConvertedToType.isNull() ||
5086
0
                    !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
5087
0
                                                    : ImplicitlyConvertedToType;
5088
0
      llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
5089
0
      mangleIntegerLiteral(T, V);
5090
0
      break;
5091
0
    }
5092
5093
0
    NotPrimaryExpr(); // But otherwise, they are not.
5094
5095
0
    auto MangleAlignofSizeofArg = [&] {
5096
0
      if (SAE->isArgumentType()) {
5097
0
        Out << 't';
5098
0
        mangleType(SAE->getArgumentType());
5099
0
      } else {
5100
0
        Out << 'z';
5101
0
        mangleExpression(SAE->getArgumentExpr());
5102
0
      }
5103
0
    };
5104
5105
0
    switch(SAE->getKind()) {
5106
0
    case UETT_SizeOf:
5107
0
      Out << 's';
5108
0
      MangleAlignofSizeofArg();
5109
0
      break;
5110
0
    case UETT_PreferredAlignOf:
5111
      // As of clang 12, we mangle __alignof__ differently than alignof. (They
5112
      // have acted differently since Clang 8, but were previously mangled the
5113
      // same.)
5114
0
      if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {
5115
0
        Out << "u11__alignof__";
5116
0
        if (SAE->isArgumentType())
5117
0
          mangleType(SAE->getArgumentType());
5118
0
        else
5119
0
          mangleTemplateArgExpr(SAE->getArgumentExpr());
5120
0
        Out << 'E';
5121
0
        break;
5122
0
      }
5123
0
      [[fallthrough]];
5124
0
    case UETT_AlignOf:
5125
0
      Out << 'a';
5126
0
      MangleAlignofSizeofArg();
5127
0
      break;
5128
0
    case UETT_DataSizeOf: {
5129
0
      DiagnosticsEngine &Diags = Context.getDiags();
5130
0
      unsigned DiagID =
5131
0
          Diags.getCustomDiagID(DiagnosticsEngine::Error,
5132
0
                                "cannot yet mangle __datasizeof expression");
5133
0
      Diags.Report(DiagID);
5134
0
      return;
5135
0
    }
5136
0
    case UETT_VecStep: {
5137
0
      DiagnosticsEngine &Diags = Context.getDiags();
5138
0
      unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
5139
0
                                     "cannot yet mangle vec_step expression");
5140
0
      Diags.Report(DiagID);
5141
0
      return;
5142
0
    }
5143
0
    case UETT_OpenMPRequiredSimdAlign: {
5144
0
      DiagnosticsEngine &Diags = Context.getDiags();
5145
0
      unsigned DiagID = Diags.getCustomDiagID(
5146
0
          DiagnosticsEngine::Error,
5147
0
          "cannot yet mangle __builtin_omp_required_simd_align expression");
5148
0
      Diags.Report(DiagID);
5149
0
      return;
5150
0
    }
5151
0
    case UETT_VectorElements: {
5152
0
      DiagnosticsEngine &Diags = Context.getDiags();
5153
0
      unsigned DiagID = Diags.getCustomDiagID(
5154
0
          DiagnosticsEngine::Error,
5155
0
          "cannot yet mangle __builtin_vectorelements expression");
5156
0
      Diags.Report(DiagID);
5157
0
      return;
5158
0
    }
5159
0
    }
5160
0
    break;
5161
0
  }
5162
5163
0
  case Expr::TypeTraitExprClass: {
5164
    //  <expression> ::= u <source-name> <template-arg>* E # vendor extension
5165
0
    const TypeTraitExpr *TTE = cast<TypeTraitExpr>(E);
5166
0
    NotPrimaryExpr();
5167
0
    Out << 'u';
5168
0
    llvm::StringRef Spelling = getTraitSpelling(TTE->getTrait());
5169
0
    Out << Spelling.size() << Spelling;
5170
0
    for (TypeSourceInfo *TSI : TTE->getArgs()) {
5171
0
      mangleType(TSI->getType());
5172
0
    }
5173
0
    Out << 'E';
5174
0
    break;
5175
0
  }
5176
5177
0
  case Expr::CXXThrowExprClass: {
5178
0
    NotPrimaryExpr();
5179
0
    const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
5180
    //  <expression> ::= tw <expression>  # throw expression
5181
    //               ::= tr               # rethrow
5182
0
    if (TE->getSubExpr()) {
5183
0
      Out << "tw";
5184
0
      mangleExpression(TE->getSubExpr());
5185
0
    } else {
5186
0
      Out << "tr";
5187
0
    }
5188
0
    break;
5189
0
  }
5190
5191
0
  case Expr::CXXTypeidExprClass: {
5192
0
    NotPrimaryExpr();
5193
0
    const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
5194
    //  <expression> ::= ti <type>        # typeid (type)
5195
    //               ::= te <expression>  # typeid (expression)
5196
0
    if (TIE->isTypeOperand()) {
5197
0
      Out << "ti";
5198
0
      mangleType(TIE->getTypeOperand(Context.getASTContext()));
5199
0
    } else {
5200
0
      Out << "te";
5201
0
      mangleExpression(TIE->getExprOperand());
5202
0
    }
5203
0
    break;
5204
0
  }
5205
5206
0
  case Expr::CXXDeleteExprClass: {
5207
0
    NotPrimaryExpr();
5208
0
    const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
5209
    //  <expression> ::= [gs] dl <expression>  # [::] delete expr
5210
    //               ::= [gs] da <expression>  # [::] delete [] expr
5211
0
    if (DE->isGlobalDelete()) Out << "gs";
5212
0
    Out << (DE->isArrayForm() ? "da" : "dl");
5213
0
    mangleExpression(DE->getArgument());
5214
0
    break;
5215
0
  }
5216
5217
0
  case Expr::UnaryOperatorClass: {
5218
0
    NotPrimaryExpr();
5219
0
    const UnaryOperator *UO = cast<UnaryOperator>(E);
5220
0
    mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
5221
0
                       /*Arity=*/1);
5222
0
    mangleExpression(UO->getSubExpr());
5223
0
    break;
5224
0
  }
5225
5226
0
  case Expr::ArraySubscriptExprClass: {
5227
0
    NotPrimaryExpr();
5228
0
    const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
5229
5230
    // Array subscript is treated as a syntactically weird form of
5231
    // binary operator.
5232
0
    Out << "ix";
5233
0
    mangleExpression(AE->getLHS());
5234
0
    mangleExpression(AE->getRHS());
5235
0
    break;
5236
0
  }
5237
5238
0
  case Expr::MatrixSubscriptExprClass: {
5239
0
    NotPrimaryExpr();
5240
0
    const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(E);
5241
0
    Out << "ixix";
5242
0
    mangleExpression(ME->getBase());
5243
0
    mangleExpression(ME->getRowIdx());
5244
0
    mangleExpression(ME->getColumnIdx());
5245
0
    break;
5246
0
  }
5247
5248
0
  case Expr::CompoundAssignOperatorClass: // fallthrough
5249
0
  case Expr::BinaryOperatorClass: {
5250
0
    NotPrimaryExpr();
5251
0
    const BinaryOperator *BO = cast<BinaryOperator>(E);
5252
0
    if (BO->getOpcode() == BO_PtrMemD)
5253
0
      Out << "ds";
5254
0
    else
5255
0
      mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
5256
0
                         /*Arity=*/2);
5257
0
    mangleExpression(BO->getLHS());
5258
0
    mangleExpression(BO->getRHS());
5259
0
    break;
5260
0
  }
5261
5262
0
  case Expr::CXXRewrittenBinaryOperatorClass: {
5263
0
    NotPrimaryExpr();
5264
    // The mangled form represents the original syntax.
5265
0
    CXXRewrittenBinaryOperator::DecomposedForm Decomposed =
5266
0
        cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm();
5267
0
    mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode),
5268
0
                       /*Arity=*/2);
5269
0
    mangleExpression(Decomposed.LHS);
5270
0
    mangleExpression(Decomposed.RHS);
5271
0
    break;
5272
0
  }
5273
5274
0
  case Expr::ConditionalOperatorClass: {
5275
0
    NotPrimaryExpr();
5276
0
    const ConditionalOperator *CO = cast<ConditionalOperator>(E);
5277
0
    mangleOperatorName(OO_Conditional, /*Arity=*/3);
5278
0
    mangleExpression(CO->getCond());
5279
0
    mangleExpression(CO->getLHS(), Arity);
5280
0
    mangleExpression(CO->getRHS(), Arity);
5281
0
    break;
5282
0
  }
5283
5284
0
  case Expr::ImplicitCastExprClass: {
5285
0
    ImplicitlyConvertedToType = E->getType();
5286
0
    E = cast<ImplicitCastExpr>(E)->getSubExpr();
5287
0
    goto recurse;
5288
0
  }
5289
5290
0
  case Expr::ObjCBridgedCastExprClass: {
5291
0
    NotPrimaryExpr();
5292
    // Mangle ownership casts as a vendor extended operator __bridge,
5293
    // __bridge_transfer, or __bridge_retain.
5294
0
    StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
5295
0
    Out << "v1U" << Kind.size() << Kind;
5296
0
    mangleCastExpression(E, "cv");
5297
0
    break;
5298
0
  }
5299
5300
0
  case Expr::CStyleCastExprClass:
5301
0
    NotPrimaryExpr();
5302
0
    mangleCastExpression(E, "cv");
5303
0
    break;
5304
5305
0
  case Expr::CXXFunctionalCastExprClass: {
5306
0
    NotPrimaryExpr();
5307
0
    auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
5308
    // FIXME: Add isImplicit to CXXConstructExpr.
5309
0
    if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
5310
0
      if (CCE->getParenOrBraceRange().isInvalid())
5311
0
        Sub = CCE->getArg(0)->IgnoreImplicit();
5312
0
    if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
5313
0
      Sub = StdInitList->getSubExpr()->IgnoreImplicit();
5314
0
    if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
5315
0
      Out << "tl";
5316
0
      mangleType(E->getType());
5317
0
      mangleInitListElements(IL);
5318
0
      Out << "E";
5319
0
    } else {
5320
0
      mangleCastExpression(E, "cv");
5321
0
    }
5322
0
    break;
5323
0
  }
5324
5325
0
  case Expr::CXXStaticCastExprClass:
5326
0
    NotPrimaryExpr();
5327
0
    mangleCastExpression(E, "sc");
5328
0
    break;
5329
0
  case Expr::CXXDynamicCastExprClass:
5330
0
    NotPrimaryExpr();
5331
0
    mangleCastExpression(E, "dc");
5332
0
    break;
5333
0
  case Expr::CXXReinterpretCastExprClass:
5334
0
    NotPrimaryExpr();
5335
0
    mangleCastExpression(E, "rc");
5336
0
    break;
5337
0
  case Expr::CXXConstCastExprClass:
5338
0
    NotPrimaryExpr();
5339
0
    mangleCastExpression(E, "cc");
5340
0
    break;
5341
0
  case Expr::CXXAddrspaceCastExprClass:
5342
0
    NotPrimaryExpr();
5343
0
    mangleCastExpression(E, "ac");
5344
0
    break;
5345
5346
0
  case Expr::CXXOperatorCallExprClass: {
5347
0
    NotPrimaryExpr();
5348
0
    const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
5349
0
    unsigned NumArgs = CE->getNumArgs();
5350
    // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
5351
    // (the enclosing MemberExpr covers the syntactic portion).
5352
0
    if (CE->getOperator() != OO_Arrow)
5353
0
      mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
5354
    // Mangle the arguments.
5355
0
    for (unsigned i = 0; i != NumArgs; ++i)
5356
0
      mangleExpression(CE->getArg(i));
5357
0
    break;
5358
0
  }
5359
5360
0
  case Expr::ParenExprClass:
5361
0
    E = cast<ParenExpr>(E)->getSubExpr();
5362
0
    goto recurse;
5363
5364
0
  case Expr::ConceptSpecializationExprClass: {
5365
0
    auto *CSE = cast<ConceptSpecializationExpr>(E);
5366
0
    if (isCompatibleWith(LangOptions::ClangABI::Ver17)) {
5367
      // Clang 17 and before mangled concept-ids as if they resolved to an
5368
      // entity, meaning that references to enclosing template arguments don't
5369
      // work.
5370
0
      Out << "L_Z";
5371
0
      mangleTemplateName(CSE->getNamedConcept(), CSE->getTemplateArguments());
5372
0
      Out << 'E';
5373
0
      break;
5374
0
    }
5375
    // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
5376
0
    NotPrimaryExpr();
5377
0
    mangleUnresolvedName(
5378
0
        CSE->getNestedNameSpecifierLoc().getNestedNameSpecifier(),
5379
0
        CSE->getConceptNameInfo().getName(),
5380
0
        CSE->getTemplateArgsAsWritten()->getTemplateArgs(),
5381
0
        CSE->getTemplateArgsAsWritten()->getNumTemplateArgs());
5382
0
    break;
5383
0
  }
5384
5385
0
  case Expr::RequiresExprClass: {
5386
    // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24.
5387
0
    auto *RE = cast<RequiresExpr>(E);
5388
    // This is a primary-expression in the C++ grammar, but does not have an
5389
    // <expr-primary> mangling (starting with 'L').
5390
0
    NotPrimaryExpr();
5391
0
    if (RE->getLParenLoc().isValid()) {
5392
0
      Out << "rQ";
5393
0
      FunctionTypeDepthState saved = FunctionTypeDepth.push();
5394
0
      if (RE->getLocalParameters().empty()) {
5395
0
        Out << 'v';
5396
0
      } else {
5397
0
        for (ParmVarDecl *Param : RE->getLocalParameters()) {
5398
0
          mangleType(Context.getASTContext().getSignatureParameterType(
5399
0
              Param->getType()));
5400
0
        }
5401
0
      }
5402
0
      Out << '_';
5403
5404
      // The rest of the mangling is in the immediate scope of the parameters.
5405
0
      FunctionTypeDepth.enterResultType();
5406
0
      for (const concepts::Requirement *Req : RE->getRequirements())
5407
0
        mangleRequirement(RE->getExprLoc(), Req);
5408
0
      FunctionTypeDepth.pop(saved);
5409
0
      Out << 'E';
5410
0
    } else {
5411
0
      Out << "rq";
5412
0
      for (const concepts::Requirement *Req : RE->getRequirements())
5413
0
        mangleRequirement(RE->getExprLoc(), Req);
5414
0
      Out << 'E';
5415
0
    }
5416
0
    break;
5417
0
  }
5418
5419
0
  case Expr::DeclRefExprClass:
5420
    // MangleDeclRefExpr helper handles primary-vs-nonprimary
5421
0
    MangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl());
5422
0
    break;
5423
5424
0
  case Expr::SubstNonTypeTemplateParmPackExprClass:
5425
0
    NotPrimaryExpr();
5426
    // FIXME: not clear how to mangle this!
5427
    // template <unsigned N...> class A {
5428
    //   template <class U...> void foo(U (&x)[N]...);
5429
    // };
5430
0
    Out << "_SUBSTPACK_";
5431
0
    break;
5432
5433
0
  case Expr::FunctionParmPackExprClass: {
5434
0
    NotPrimaryExpr();
5435
    // FIXME: not clear how to mangle this!
5436
0
    const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
5437
0
    Out << "v110_SUBSTPACK";
5438
0
    MangleDeclRefExpr(FPPE->getParameterPack());
5439
0
    break;
5440
0
  }
5441
5442
0
  case Expr::DependentScopeDeclRefExprClass: {
5443
0
    NotPrimaryExpr();
5444
0
    const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
5445
0
    mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
5446
0
                         DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
5447
0
                         Arity);
5448
0
    break;
5449
0
  }
5450
5451
0
  case Expr::CXXBindTemporaryExprClass:
5452
0
    E = cast<CXXBindTemporaryExpr>(E)->getSubExpr();
5453
0
    goto recurse;
5454
5455
0
  case Expr::ExprWithCleanupsClass:
5456
0
    E = cast<ExprWithCleanups>(E)->getSubExpr();
5457
0
    goto recurse;
5458
5459
0
  case Expr::FloatingLiteralClass: {
5460
    // <expr-primary>
5461
0
    const FloatingLiteral *FL = cast<FloatingLiteral>(E);
5462
0
    mangleFloatLiteral(FL->getType(), FL->getValue());
5463
0
    break;
5464
0
  }
5465
5466
0
  case Expr::FixedPointLiteralClass:
5467
    // Currently unimplemented -- might be <expr-primary> in future?
5468
0
    mangleFixedPointLiteral();
5469
0
    break;
5470
5471
0
  case Expr::CharacterLiteralClass:
5472
    // <expr-primary>
5473
0
    Out << 'L';
5474
0
    mangleType(E->getType());
5475
0
    Out << cast<CharacterLiteral>(E)->getValue();
5476
0
    Out << 'E';
5477
0
    break;
5478
5479
  // FIXME. __objc_yes/__objc_no are mangled same as true/false
5480
0
  case Expr::ObjCBoolLiteralExprClass:
5481
    // <expr-primary>
5482
0
    Out << "Lb";
5483
0
    Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
5484
0
    Out << 'E';
5485
0
    break;
5486
5487
0
  case Expr::CXXBoolLiteralExprClass:
5488
    // <expr-primary>
5489
0
    Out << "Lb";
5490
0
    Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
5491
0
    Out << 'E';
5492
0
    break;
5493
5494
0
  case Expr::IntegerLiteralClass: {
5495
    // <expr-primary>
5496
0
    llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
5497
0
    if (E->getType()->isSignedIntegerType())
5498
0
      Value.setIsSigned(true);
5499
0
    mangleIntegerLiteral(E->getType(), Value);
5500
0
    break;
5501
0
  }
5502
5503
0
  case Expr::ImaginaryLiteralClass: {
5504
    // <expr-primary>
5505
0
    const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
5506
    // Mangle as if a complex literal.
5507
    // Proposal from David Vandevoorde, 2010.06.30.
5508
0
    Out << 'L';
5509
0
    mangleType(E->getType());
5510
0
    if (const FloatingLiteral *Imag =
5511
0
          dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
5512
      // Mangle a floating-point zero of the appropriate type.
5513
0
      mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
5514
0
      Out << '_';
5515
0
      mangleFloat(Imag->getValue());
5516
0
    } else {
5517
0
      Out << "0_";
5518
0
      llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
5519
0
      if (IE->getSubExpr()->getType()->isSignedIntegerType())
5520
0
        Value.setIsSigned(true);
5521
0
      mangleNumber(Value);
5522
0
    }
5523
0
    Out << 'E';
5524
0
    break;
5525
0
  }
5526
5527
0
  case Expr::StringLiteralClass: {
5528
    // <expr-primary>
5529
    // Revised proposal from David Vandervoorde, 2010.07.15.
5530
0
    Out << 'L';
5531
0
    assert(isa<ConstantArrayType>(E->getType()));
5532
0
    mangleType(E->getType());
5533
0
    Out << 'E';
5534
0
    break;
5535
0
  }
5536
5537
0
  case Expr::GNUNullExprClass:
5538
    // <expr-primary>
5539
    // Mangle as if an integer literal 0.
5540
0
    mangleIntegerLiteral(E->getType(), llvm::APSInt(32));
5541
0
    break;
5542
5543
0
  case Expr::CXXNullPtrLiteralExprClass: {
5544
    // <expr-primary>
5545
0
    Out << "LDnE";
5546
0
    break;
5547
0
  }
5548
5549
0
  case Expr::LambdaExprClass: {
5550
    // A lambda-expression can't appear in the signature of an
5551
    // externally-visible declaration, so there's no standard mangling for
5552
    // this, but mangling as a literal of the closure type seems reasonable.
5553
0
    Out << "L";
5554
0
    mangleType(Context.getASTContext().getRecordType(cast<LambdaExpr>(E)->getLambdaClass()));
5555
0
    Out << "E";
5556
0
    break;
5557
0
  }
5558
5559
0
  case Expr::PackExpansionExprClass:
5560
0
    NotPrimaryExpr();
5561
0
    Out << "sp";
5562
0
    mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
5563
0
    break;
5564
5565
0
  case Expr::SizeOfPackExprClass: {
5566
0
    NotPrimaryExpr();
5567
0
    auto *SPE = cast<SizeOfPackExpr>(E);
5568
0
    if (SPE->isPartiallySubstituted()) {
5569
0
      Out << "sP";
5570
0
      for (const auto &A : SPE->getPartialArguments())
5571
0
        mangleTemplateArg(A, false);
5572
0
      Out << "E";
5573
0
      break;
5574
0
    }
5575
5576
0
    Out << "sZ";
5577
0
    const NamedDecl *Pack = SPE->getPack();
5578
0
    if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
5579
0
      mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
5580
0
    else if (const NonTypeTemplateParmDecl *NTTP
5581
0
                = dyn_cast<NonTypeTemplateParmDecl>(Pack))
5582
0
      mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex());
5583
0
    else if (const TemplateTemplateParmDecl *TempTP
5584
0
                                    = dyn_cast<TemplateTemplateParmDecl>(Pack))
5585
0
      mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex());
5586
0
    else
5587
0
      mangleFunctionParam(cast<ParmVarDecl>(Pack));
5588
0
    break;
5589
0
  }
5590
5591
0
  case Expr::MaterializeTemporaryExprClass:
5592
0
    E = cast<MaterializeTemporaryExpr>(E)->getSubExpr();
5593
0
    goto recurse;
5594
5595
0
  case Expr::CXXFoldExprClass: {
5596
0
    NotPrimaryExpr();
5597
0
    auto *FE = cast<CXXFoldExpr>(E);
5598
0
    if (FE->isLeftFold())
5599
0
      Out << (FE->getInit() ? "fL" : "fl");
5600
0
    else
5601
0
      Out << (FE->getInit() ? "fR" : "fr");
5602
5603
0
    if (FE->getOperator() == BO_PtrMemD)
5604
0
      Out << "ds";
5605
0
    else
5606
0
      mangleOperatorName(
5607
0
          BinaryOperator::getOverloadedOperator(FE->getOperator()),
5608
0
          /*Arity=*/2);
5609
5610
0
    if (FE->getLHS())
5611
0
      mangleExpression(FE->getLHS());
5612
0
    if (FE->getRHS())
5613
0
      mangleExpression(FE->getRHS());
5614
0
    break;
5615
0
  }
5616
5617
0
  case Expr::CXXThisExprClass:
5618
0
    NotPrimaryExpr();
5619
0
    Out << "fpT";
5620
0
    break;
5621
5622
0
  case Expr::CoawaitExprClass:
5623
    // FIXME: Propose a non-vendor mangling.
5624
0
    NotPrimaryExpr();
5625
0
    Out << "v18co_await";
5626
0
    mangleExpression(cast<CoawaitExpr>(E)->getOperand());
5627
0
    break;
5628
5629
0
  case Expr::DependentCoawaitExprClass:
5630
    // FIXME: Propose a non-vendor mangling.
5631
0
    NotPrimaryExpr();
5632
0
    Out << "v18co_await";
5633
0
    mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
5634
0
    break;
5635
5636
0
  case Expr::CoyieldExprClass:
5637
    // FIXME: Propose a non-vendor mangling.
5638
0
    NotPrimaryExpr();
5639
0
    Out << "v18co_yield";
5640
0
    mangleExpression(cast<CoawaitExpr>(E)->getOperand());
5641
0
    break;
5642
0
  case Expr::SYCLUniqueStableNameExprClass: {
5643
0
    const auto *USN = cast<SYCLUniqueStableNameExpr>(E);
5644
0
    NotPrimaryExpr();
5645
5646
0
    Out << "u33__builtin_sycl_unique_stable_name";
5647
0
    mangleType(USN->getTypeSourceInfo()->getType());
5648
5649
0
    Out << "E";
5650
0
    break;
5651
0
  }
5652
0
  }
5653
5654
0
  if (AsTemplateArg && !IsPrimaryExpr)
5655
0
    Out << 'E';
5656
0
}
5657
5658
/// Mangle an expression which refers to a parameter variable.
5659
///
5660
/// <expression>     ::= <function-param>
5661
/// <function-param> ::= fp <top-level CV-qualifiers> _      # L == 0, I == 0
5662
/// <function-param> ::= fp <top-level CV-qualifiers>
5663
///                      <parameter-2 non-negative number> _ # L == 0, I > 0
5664
/// <function-param> ::= fL <L-1 non-negative number>
5665
///                      p <top-level CV-qualifiers> _       # L > 0, I == 0
5666
/// <function-param> ::= fL <L-1 non-negative number>
5667
///                      p <top-level CV-qualifiers>
5668
///                      <I-1 non-negative number> _         # L > 0, I > 0
5669
///
5670
/// L is the nesting depth of the parameter, defined as 1 if the
5671
/// parameter comes from the innermost function prototype scope
5672
/// enclosing the current context, 2 if from the next enclosing
5673
/// function prototype scope, and so on, with one special case: if
5674
/// we've processed the full parameter clause for the innermost
5675
/// function type, then L is one less.  This definition conveniently
5676
/// makes it irrelevant whether a function's result type was written
5677
/// trailing or leading, but is otherwise overly complicated; the
5678
/// numbering was first designed without considering references to
5679
/// parameter in locations other than return types, and then the
5680
/// mangling had to be generalized without changing the existing
5681
/// manglings.
5682
///
5683
/// I is the zero-based index of the parameter within its parameter
5684
/// declaration clause.  Note that the original ABI document describes
5685
/// this using 1-based ordinals.
5686
0
void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
5687
0
  unsigned parmDepth = parm->getFunctionScopeDepth();
5688
0
  unsigned parmIndex = parm->getFunctionScopeIndex();
5689
5690
  // Compute 'L'.
5691
  // parmDepth does not include the declaring function prototype.
5692
  // FunctionTypeDepth does account for that.
5693
0
  assert(parmDepth < FunctionTypeDepth.getDepth());
5694
0
  unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
5695
0
  if (FunctionTypeDepth.isInResultType())
5696
0
    nestingDepth--;
5697
5698
0
  if (nestingDepth == 0) {
5699
0
    Out << "fp";
5700
0
  } else {
5701
0
    Out << "fL" << (nestingDepth - 1) << 'p';
5702
0
  }
5703
5704
  // Top-level qualifiers.  We don't have to worry about arrays here,
5705
  // because parameters declared as arrays should already have been
5706
  // transformed to have pointer type. FIXME: apparently these don't
5707
  // get mangled if used as an rvalue of a known non-class type?
5708
0
  assert(!parm->getType()->isArrayType()
5709
0
         && "parameter's type is still an array type?");
5710
5711
0
  if (const DependentAddressSpaceType *DAST =
5712
0
      dyn_cast<DependentAddressSpaceType>(parm->getType())) {
5713
0
    mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
5714
0
  } else {
5715
0
    mangleQualifiers(parm->getType().getQualifiers());
5716
0
  }
5717
5718
  // Parameter index.
5719
0
  if (parmIndex != 0) {
5720
0
    Out << (parmIndex - 1);
5721
0
  }
5722
0
  Out << '_';
5723
0
}
5724
5725
void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
5726
0
                                       const CXXRecordDecl *InheritedFrom) {
5727
  // <ctor-dtor-name> ::= C1  # complete object constructor
5728
  //                  ::= C2  # base object constructor
5729
  //                  ::= CI1 <type> # complete inheriting constructor
5730
  //                  ::= CI2 <type> # base inheriting constructor
5731
  //
5732
  // In addition, C5 is a comdat name with C1 and C2 in it.
5733
0
  Out << 'C';
5734
0
  if (InheritedFrom)
5735
0
    Out << 'I';
5736
0
  switch (T) {
5737
0
  case Ctor_Complete:
5738
0
    Out << '1';
5739
0
    break;
5740
0
  case Ctor_Base:
5741
0
    Out << '2';
5742
0
    break;
5743
0
  case Ctor_Comdat:
5744
0
    Out << '5';
5745
0
    break;
5746
0
  case Ctor_DefaultClosure:
5747
0
  case Ctor_CopyingClosure:
5748
0
    llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
5749
0
  }
5750
0
  if (InheritedFrom)
5751
0
    mangleName(InheritedFrom);
5752
0
}
5753
5754
0
void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
5755
  // <ctor-dtor-name> ::= D0  # deleting destructor
5756
  //                  ::= D1  # complete object destructor
5757
  //                  ::= D2  # base object destructor
5758
  //
5759
  // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
5760
0
  switch (T) {
5761
0
  case Dtor_Deleting:
5762
0
    Out << "D0";
5763
0
    break;
5764
0
  case Dtor_Complete:
5765
0
    Out << "D1";
5766
0
    break;
5767
0
  case Dtor_Base:
5768
0
    Out << "D2";
5769
0
    break;
5770
0
  case Dtor_Comdat:
5771
0
    Out << "D5";
5772
0
    break;
5773
0
  }
5774
0
}
5775
5776
// Helper to provide ancillary information on a template used to mangle its
5777
// arguments.
5778
struct CXXNameMangler::TemplateArgManglingInfo {
5779
  const CXXNameMangler &Mangler;
5780
  TemplateDecl *ResolvedTemplate = nullptr;
5781
  bool SeenPackExpansionIntoNonPack = false;
5782
  const NamedDecl *UnresolvedExpandedPack = nullptr;
5783
5784
  TemplateArgManglingInfo(const CXXNameMangler &Mangler, TemplateName TN)
5785
0
      : Mangler(Mangler) {
5786
0
    if (TemplateDecl *TD = TN.getAsTemplateDecl())
5787
0
      ResolvedTemplate = TD;
5788
0
  }
5789
5790
  /// Information about how to mangle a template argument.
5791
  struct Info {
5792
    /// Do we need to mangle the template argument with an exactly correct type?
5793
    bool NeedExactType;
5794
    /// If we need to prefix the mangling with a mangling of the template
5795
    /// parameter, the corresponding parameter.
5796
    const NamedDecl *TemplateParameterToMangle;
5797
  };
5798
5799
  /// Determine whether the resolved template might be overloaded on its
5800
  /// template parameter list. If so, the mangling needs to include enough
5801
  /// information to reconstruct the template parameter list.
5802
0
  bool isOverloadable() {
5803
    // Function templates are generally overloadable. As a special case, a
5804
    // member function template of a generic lambda is not overloadable.
5805
0
    if (auto *FTD = dyn_cast_or_null<FunctionTemplateDecl>(ResolvedTemplate)) {
5806
0
      auto *RD = dyn_cast<CXXRecordDecl>(FTD->getDeclContext());
5807
0
      if (!RD || !RD->isGenericLambda())
5808
0
        return true;
5809
0
    }
5810
5811
    // All other templates are not overloadable. Partial specializations would
5812
    // be, but we never mangle them.
5813
0
    return false;
5814
0
  }
5815
5816
  /// Determine whether we need to prefix this <template-arg> mangling with a
5817
  /// <template-param-decl>. This happens if the natural template parameter for
5818
  /// the argument mangling is not the same as the actual template parameter.
5819
  bool needToMangleTemplateParam(const NamedDecl *Param,
5820
0
                                 const TemplateArgument &Arg) {
5821
    // For a template type parameter, the natural parameter is 'typename T'.
5822
    // The actual parameter might be constrained.
5823
0
    if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5824
0
      return TTP->hasTypeConstraint();
5825
5826
0
    if (Arg.getKind() == TemplateArgument::Pack) {
5827
      // For an empty pack, the natural parameter is `typename...`.
5828
0
      if (Arg.pack_size() == 0)
5829
0
        return true;
5830
5831
      // For any other pack, we use the first argument to determine the natural
5832
      // template parameter.
5833
0
      return needToMangleTemplateParam(Param, *Arg.pack_begin());
5834
0
    }
5835
5836
    // For a non-type template parameter, the natural parameter is `T V` (for a
5837
    // prvalue argument) or `T &V` (for a glvalue argument), where `T` is the
5838
    // type of the argument, which we require to exactly match. If the actual
5839
    // parameter has a deduced or instantiation-dependent type, it is not
5840
    // equivalent to the natural parameter.
5841
0
    if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
5842
0
      return NTTP->getType()->isInstantiationDependentType() ||
5843
0
             NTTP->getType()->getContainedDeducedType();
5844
5845
    // For a template template parameter, the template-head might differ from
5846
    // that of the template.
5847
0
    auto *TTP = cast<TemplateTemplateParmDecl>(Param);
5848
0
    TemplateName ArgTemplateName = Arg.getAsTemplateOrTemplatePattern();
5849
0
    const TemplateDecl *ArgTemplate = ArgTemplateName.getAsTemplateDecl();
5850
0
    if (!ArgTemplate)
5851
0
      return true;
5852
5853
    // Mangle the template parameter list of the parameter and argument to see
5854
    // if they are the same. We can't use Profile for this, because it can't
5855
    // model the depth difference between parameter and argument and might not
5856
    // necessarily have the same definition of "identical" that we use here --
5857
    // that is, same mangling.
5858
0
    auto MangleTemplateParamListToString =
5859
0
        [&](SmallVectorImpl<char> &Buffer, const TemplateParameterList *Params,
5860
0
            unsigned DepthOffset) {
5861
0
          llvm::raw_svector_ostream Stream(Buffer);
5862
0
          CXXNameMangler(Mangler.Context, Stream,
5863
0
                         WithTemplateDepthOffset{DepthOffset})
5864
0
              .mangleTemplateParameterList(Params);
5865
0
        };
5866
0
    llvm::SmallString<128> ParamTemplateHead, ArgTemplateHead;
5867
0
    MangleTemplateParamListToString(ParamTemplateHead,
5868
0
                                    TTP->getTemplateParameters(), 0);
5869
    // Add the depth of the parameter's template parameter list to all
5870
    // parameters appearing in the argument to make the indexes line up
5871
    // properly.
5872
0
    MangleTemplateParamListToString(ArgTemplateHead,
5873
0
                                    ArgTemplate->getTemplateParameters(),
5874
0
                                    TTP->getTemplateParameters()->getDepth());
5875
0
    return ParamTemplateHead != ArgTemplateHead;
5876
0
  }
5877
5878
  /// Determine information about how this template argument should be mangled.
5879
  /// This should be called exactly once for each parameter / argument pair, in
5880
  /// order.
5881
0
  Info getArgInfo(unsigned ParamIdx, const TemplateArgument &Arg) {
5882
    // We need correct types when the template-name is unresolved or when it
5883
    // names a template that is able to be overloaded.
5884
0
    if (!ResolvedTemplate || SeenPackExpansionIntoNonPack)
5885
0
      return {true, nullptr};
5886
5887
    // Move to the next parameter.
5888
0
    const NamedDecl *Param = UnresolvedExpandedPack;
5889
0
    if (!Param) {
5890
0
      assert(ParamIdx < ResolvedTemplate->getTemplateParameters()->size() &&
5891
0
             "no parameter for argument");
5892
0
      Param = ResolvedTemplate->getTemplateParameters()->getParam(ParamIdx);
5893
5894
      // If we reach a parameter pack whose argument isn't in pack form, that
5895
      // means Sema couldn't or didn't figure out which arguments belonged to
5896
      // it, because it contains a pack expansion or because Sema bailed out of
5897
      // computing parameter / argument correspondence before this point. Track
5898
      // the pack as the corresponding parameter for all further template
5899
      // arguments until we hit a pack expansion, at which point we don't know
5900
      // the correspondence between parameters and arguments at all.
5901
0
      if (Param->isParameterPack() && Arg.getKind() != TemplateArgument::Pack) {
5902
0
        UnresolvedExpandedPack = Param;
5903
0
      }
5904
0
    }
5905
5906
    // If we encounter a pack argument that is expanded into a non-pack
5907
    // parameter, we can no longer track parameter / argument correspondence,
5908
    // and need to use exact types from this point onwards.
5909
0
    if (Arg.isPackExpansion() &&
5910
0
        (!Param->isParameterPack() || UnresolvedExpandedPack)) {
5911
0
      SeenPackExpansionIntoNonPack = true;
5912
0
      return {true, nullptr};
5913
0
    }
5914
5915
    // We need exact types for arguments of a template that might be overloaded
5916
    // on template parameter type.
5917
0
    if (isOverloadable())
5918
0
      return {true, needToMangleTemplateParam(Param, Arg) ? Param : nullptr};
5919
5920
    // Otherwise, we only need a correct type if the parameter has a deduced
5921
    // type.
5922
    //
5923
    // Note: for an expanded parameter pack, getType() returns the type prior
5924
    // to expansion. We could ask for the expanded type with getExpansionType(),
5925
    // but it doesn't matter because substitution and expansion don't affect
5926
    // whether a deduced type appears in the type.
5927
0
    auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param);
5928
0
    bool NeedExactType = NTTP && NTTP->getType()->getContainedDeducedType();
5929
0
    return {NeedExactType, nullptr};
5930
0
  }
5931
5932
  /// Determine if we should mangle a requires-clause after the template
5933
  /// argument list. If so, returns the expression to mangle.
5934
0
  const Expr *getTrailingRequiresClauseToMangle() {
5935
0
    if (!isOverloadable())
5936
0
      return nullptr;
5937
0
    return ResolvedTemplate->getTemplateParameters()->getRequiresClause();
5938
0
  }
5939
};
5940
5941
void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
5942
                                        const TemplateArgumentLoc *TemplateArgs,
5943
0
                                        unsigned NumTemplateArgs) {
5944
  // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
5945
0
  Out << 'I';
5946
0
  TemplateArgManglingInfo Info(*this, TN);
5947
0
  for (unsigned i = 0; i != NumTemplateArgs; ++i) {
5948
0
    mangleTemplateArg(Info, i, TemplateArgs[i].getArgument());
5949
0
  }
5950
0
  mangleRequiresClause(Info.getTrailingRequiresClauseToMangle());
5951
0
  Out << 'E';
5952
0
}
5953
5954
void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
5955
0
                                        const TemplateArgumentList &AL) {
5956
  // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
5957
0
  Out << 'I';
5958
0
  TemplateArgManglingInfo Info(*this, TN);
5959
0
  for (unsigned i = 0, e = AL.size(); i != e; ++i) {
5960
0
    mangleTemplateArg(Info, i, AL[i]);
5961
0
  }
5962
0
  mangleRequiresClause(Info.getTrailingRequiresClauseToMangle());
5963
0
  Out << 'E';
5964
0
}
5965
5966
void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
5967
0
                                        ArrayRef<TemplateArgument> Args) {
5968
  // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E
5969
0
  Out << 'I';
5970
0
  TemplateArgManglingInfo Info(*this, TN);
5971
0
  for (unsigned i = 0; i != Args.size(); ++i) {
5972
0
    mangleTemplateArg(Info, i, Args[i]);
5973
0
  }
5974
0
  mangleRequiresClause(Info.getTrailingRequiresClauseToMangle());
5975
0
  Out << 'E';
5976
0
}
5977
5978
void CXXNameMangler::mangleTemplateArg(TemplateArgManglingInfo &Info,
5979
0
                                       unsigned Index, TemplateArgument A) {
5980
0
  TemplateArgManglingInfo::Info ArgInfo = Info.getArgInfo(Index, A);
5981
5982
  // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
5983
0
  if (ArgInfo.TemplateParameterToMangle &&
5984
0
      !isCompatibleWith(LangOptions::ClangABI::Ver17)) {
5985
    // The template parameter is mangled if the mangling would otherwise be
5986
    // ambiguous.
5987
    //
5988
    // <template-arg> ::= <template-param-decl> <template-arg>
5989
    //
5990
    // Clang 17 and before did not do this.
5991
0
    mangleTemplateParamDecl(ArgInfo.TemplateParameterToMangle);
5992
0
  }
5993
5994
0
  mangleTemplateArg(A, ArgInfo.NeedExactType);
5995
0
}
5996
5997
0
void CXXNameMangler::mangleTemplateArg(TemplateArgument A, bool NeedExactType) {
5998
  // <template-arg> ::= <type>              # type or template
5999
  //                ::= X <expression> E    # expression
6000
  //                ::= <expr-primary>      # simple expressions
6001
  //                ::= J <template-arg>* E # argument pack
6002
0
  if (!A.isInstantiationDependent() || A.isDependent())
6003
0
    A = Context.getASTContext().getCanonicalTemplateArgument(A);
6004
6005
0
  switch (A.getKind()) {
6006
0
  case TemplateArgument::Null:
6007
0
    llvm_unreachable("Cannot mangle NULL template argument");
6008
6009
0
  case TemplateArgument::Type:
6010
0
    mangleType(A.getAsType());
6011
0
    break;
6012
0
  case TemplateArgument::Template:
6013
    // This is mangled as <type>.
6014
0
    mangleType(A.getAsTemplate());
6015
0
    break;
6016
0
  case TemplateArgument::TemplateExpansion:
6017
    // <type>  ::= Dp <type>          # pack expansion (C++0x)
6018
0
    Out << "Dp";
6019
0
    mangleType(A.getAsTemplateOrTemplatePattern());
6020
0
    break;
6021
0
  case TemplateArgument::Expression:
6022
0
    mangleTemplateArgExpr(A.getAsExpr());
6023
0
    break;
6024
0
  case TemplateArgument::Integral:
6025
0
    mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
6026
0
    break;
6027
0
  case TemplateArgument::Declaration: {
6028
    //  <expr-primary> ::= L <mangled-name> E # external name
6029
0
    ValueDecl *D = A.getAsDecl();
6030
6031
    // Template parameter objects are modeled by reproducing a source form
6032
    // produced as if by aggregate initialization.
6033
0
    if (A.getParamTypeForDecl()->isRecordType()) {
6034
0
      auto *TPO = cast<TemplateParamObjectDecl>(D);
6035
0
      mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
6036
0
                               TPO->getValue(), /*TopLevel=*/true,
6037
0
                               NeedExactType);
6038
0
      break;
6039
0
    }
6040
6041
0
    ASTContext &Ctx = Context.getASTContext();
6042
0
    APValue Value;
6043
0
    if (D->isCXXInstanceMember())
6044
      // Simple pointer-to-member with no conversion.
6045
0
      Value = APValue(D, /*IsDerivedMember=*/false, /*Path=*/{});
6046
0
    else if (D->getType()->isArrayType() &&
6047
0
             Ctx.hasSimilarType(Ctx.getDecayedType(D->getType()),
6048
0
                                A.getParamTypeForDecl()) &&
6049
0
             !isCompatibleWith(LangOptions::ClangABI::Ver11))
6050
      // Build a value corresponding to this implicit array-to-pointer decay.
6051
0
      Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),
6052
0
                      {APValue::LValuePathEntry::ArrayIndex(0)},
6053
0
                      /*OnePastTheEnd=*/false);
6054
0
    else
6055
      // Regular pointer or reference to a declaration.
6056
0
      Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),
6057
0
                      ArrayRef<APValue::LValuePathEntry>(),
6058
0
                      /*OnePastTheEnd=*/false);
6059
0
    mangleValueInTemplateArg(A.getParamTypeForDecl(), Value, /*TopLevel=*/true,
6060
0
                             NeedExactType);
6061
0
    break;
6062
0
  }
6063
0
  case TemplateArgument::NullPtr: {
6064
0
    mangleNullPointer(A.getNullPtrType());
6065
0
    break;
6066
0
  }
6067
0
  case TemplateArgument::Pack: {
6068
    //  <template-arg> ::= J <template-arg>* E
6069
0
    Out << 'J';
6070
0
    for (const auto &P : A.pack_elements())
6071
0
      mangleTemplateArg(P, NeedExactType);
6072
0
    Out << 'E';
6073
0
  }
6074
0
  }
6075
0
}
6076
6077
0
void CXXNameMangler::mangleTemplateArgExpr(const Expr *E) {
6078
0
  if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) {
6079
0
    mangleExpression(E, UnknownArity, /*AsTemplateArg=*/true);
6080
0
    return;
6081
0
  }
6082
6083
  // Prior to Clang 12, we didn't omit the X .. E around <expr-primary>
6084
  // correctly in cases where the template argument was
6085
  // constructed from an expression rather than an already-evaluated
6086
  // literal. In such a case, we would then e.g. emit 'XLi0EE' instead of
6087
  // 'Li0E'.
6088
  //
6089
  // We did special-case DeclRefExpr to attempt to DTRT for that one
6090
  // expression-kind, but while doing so, unfortunately handled ParmVarDecl
6091
  // (subtype of VarDecl) _incorrectly_, and emitted 'L_Z .. E' instead of
6092
  // the proper 'Xfp_E'.
6093
0
  E = E->IgnoreParenImpCasts();
6094
0
  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6095
0
    const ValueDecl *D = DRE->getDecl();
6096
0
    if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
6097
0
      Out << 'L';
6098
0
      mangle(D);
6099
0
      Out << 'E';
6100
0
      return;
6101
0
    }
6102
0
  }
6103
0
  Out << 'X';
6104
0
  mangleExpression(E);
6105
0
  Out << 'E';
6106
0
}
6107
6108
/// Determine whether a given value is equivalent to zero-initialization for
6109
/// the purpose of discarding a trailing portion of a 'tl' mangling.
6110
///
6111
/// Note that this is not in general equivalent to determining whether the
6112
/// value has an all-zeroes bit pattern.
6113
0
static bool isZeroInitialized(QualType T, const APValue &V) {
6114
  // FIXME: mangleValueInTemplateArg has quadratic time complexity in
6115
  // pathological cases due to using this, but it's a little awkward
6116
  // to do this in linear time in general.
6117
0
  switch (V.getKind()) {
6118
0
  case APValue::None:
6119
0
  case APValue::Indeterminate:
6120
0
  case APValue::AddrLabelDiff:
6121
0
    return false;
6122
6123
0
  case APValue::Struct: {
6124
0
    const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6125
0
    assert(RD && "unexpected type for record value");
6126
0
    unsigned I = 0;
6127
0
    for (const CXXBaseSpecifier &BS : RD->bases()) {
6128
0
      if (!isZeroInitialized(BS.getType(), V.getStructBase(I)))
6129
0
        return false;
6130
0
      ++I;
6131
0
    }
6132
0
    I = 0;
6133
0
    for (const FieldDecl *FD : RD->fields()) {
6134
0
      if (!FD->isUnnamedBitfield() &&
6135
0
          !isZeroInitialized(FD->getType(), V.getStructField(I)))
6136
0
        return false;
6137
0
      ++I;
6138
0
    }
6139
0
    return true;
6140
0
  }
6141
6142
0
  case APValue::Union: {
6143
0
    const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6144
0
    assert(RD && "unexpected type for union value");
6145
    // Zero-initialization zeroes the first non-unnamed-bitfield field, if any.
6146
0
    for (const FieldDecl *FD : RD->fields()) {
6147
0
      if (!FD->isUnnamedBitfield())
6148
0
        return V.getUnionField() && declaresSameEntity(FD, V.getUnionField()) &&
6149
0
               isZeroInitialized(FD->getType(), V.getUnionValue());
6150
0
    }
6151
    // If there are no fields (other than unnamed bitfields), the value is
6152
    // necessarily zero-initialized.
6153
0
    return true;
6154
0
  }
6155
6156
0
  case APValue::Array: {
6157
0
    QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);
6158
0
    for (unsigned I = 0, N = V.getArrayInitializedElts(); I != N; ++I)
6159
0
      if (!isZeroInitialized(ElemT, V.getArrayInitializedElt(I)))
6160
0
        return false;
6161
0
    return !V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller());
6162
0
  }
6163
6164
0
  case APValue::Vector: {
6165
0
    const VectorType *VT = T->castAs<VectorType>();
6166
0
    for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I)
6167
0
      if (!isZeroInitialized(VT->getElementType(), V.getVectorElt(I)))
6168
0
        return false;
6169
0
    return true;
6170
0
  }
6171
6172
0
  case APValue::Int:
6173
0
    return !V.getInt();
6174
6175
0
  case APValue::Float:
6176
0
    return V.getFloat().isPosZero();
6177
6178
0
  case APValue::FixedPoint:
6179
0
    return !V.getFixedPoint().getValue();
6180
6181
0
  case APValue::ComplexFloat:
6182
0
    return V.getComplexFloatReal().isPosZero() &&
6183
0
           V.getComplexFloatImag().isPosZero();
6184
6185
0
  case APValue::ComplexInt:
6186
0
    return !V.getComplexIntReal() && !V.getComplexIntImag();
6187
6188
0
  case APValue::LValue:
6189
0
    return V.isNullPointer();
6190
6191
0
  case APValue::MemberPointer:
6192
0
    return !V.getMemberPointerDecl();
6193
0
  }
6194
6195
0
  llvm_unreachable("Unhandled APValue::ValueKind enum");
6196
0
}
6197
6198
0
static QualType getLValueType(ASTContext &Ctx, const APValue &LV) {
6199
0
  QualType T = LV.getLValueBase().getType();
6200
0
  for (APValue::LValuePathEntry E : LV.getLValuePath()) {
6201
0
    if (const ArrayType *AT = Ctx.getAsArrayType(T))
6202
0
      T = AT->getElementType();
6203
0
    else if (const FieldDecl *FD =
6204
0
                 dyn_cast<FieldDecl>(E.getAsBaseOrMember().getPointer()))
6205
0
      T = FD->getType();
6206
0
    else
6207
0
      T = Ctx.getRecordType(
6208
0
          cast<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()));
6209
0
  }
6210
0
  return T;
6211
0
}
6212
6213
static IdentifierInfo *getUnionInitName(SourceLocation UnionLoc,
6214
                                        DiagnosticsEngine &Diags,
6215
0
                                        const FieldDecl *FD) {
6216
  // According to:
6217
  // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling.anonymous
6218
  // For the purposes of mangling, the name of an anonymous union is considered
6219
  // to be the name of the first named data member found by a pre-order,
6220
  // depth-first, declaration-order walk of the data members of the anonymous
6221
  // union.
6222
6223
0
  if (FD->getIdentifier())
6224
0
    return FD->getIdentifier();
6225
6226
  // The only cases where the identifer of a FieldDecl would be blank is if the
6227
  // field represents an anonymous record type or if it is an unnamed bitfield.
6228
  // There is no type to descend into in the case of a bitfield, so we can just
6229
  // return nullptr in that case.
6230
0
  if (FD->isBitField())
6231
0
    return nullptr;
6232
0
  const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl();
6233
6234
  // Consider only the fields in declaration order, searched depth-first.  We
6235
  // don't care about the active member of the union, as all we are doing is
6236
  // looking for a valid name. We also don't check bases, due to guidance from
6237
  // the Itanium ABI folks.
6238
0
  for (const FieldDecl *RDField : RD->fields()) {
6239
0
    if (IdentifierInfo *II = getUnionInitName(UnionLoc, Diags, RDField))
6240
0
      return II;
6241
0
  }
6242
6243
  // According to the Itanium ABI: If there is no such data member (i.e., if all
6244
  // of the data members in the union are unnamed), then there is no way for a
6245
  // program to refer to the anonymous union, and there is therefore no need to
6246
  // mangle its name. However, we should diagnose this anyway.
6247
0
  unsigned DiagID = Diags.getCustomDiagID(
6248
0
      DiagnosticsEngine::Error, "cannot mangle this unnamed union NTTP yet");
6249
0
  Diags.Report(UnionLoc, DiagID);
6250
6251
0
  return nullptr;
6252
0
}
6253
6254
void CXXNameMangler::mangleValueInTemplateArg(QualType T, const APValue &V,
6255
                                              bool TopLevel,
6256
0
                                              bool NeedExactType) {
6257
  // Ignore all top-level cv-qualifiers, to match GCC.
6258
0
  Qualifiers Quals;
6259
0
  T = getASTContext().getUnqualifiedArrayType(T, Quals);
6260
6261
  // A top-level expression that's not a primary expression is wrapped in X...E.
6262
0
  bool IsPrimaryExpr = true;
6263
0
  auto NotPrimaryExpr = [&] {
6264
0
    if (TopLevel && IsPrimaryExpr)
6265
0
      Out << 'X';
6266
0
    IsPrimaryExpr = false;
6267
0
  };
6268
6269
  // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
6270
0
  switch (V.getKind()) {
6271
0
  case APValue::None:
6272
0
  case APValue::Indeterminate:
6273
0
    Out << 'L';
6274
0
    mangleType(T);
6275
0
    Out << 'E';
6276
0
    break;
6277
6278
0
  case APValue::AddrLabelDiff:
6279
0
    llvm_unreachable("unexpected value kind in template argument");
6280
6281
0
  case APValue::Struct: {
6282
0
    const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6283
0
    assert(RD && "unexpected type for record value");
6284
6285
    // Drop trailing zero-initialized elements.
6286
0
    llvm::SmallVector<const FieldDecl *, 16> Fields(RD->fields());
6287
0
    while (
6288
0
        !Fields.empty() &&
6289
0
        (Fields.back()->isUnnamedBitfield() ||
6290
0
         isZeroInitialized(Fields.back()->getType(),
6291
0
                           V.getStructField(Fields.back()->getFieldIndex())))) {
6292
0
      Fields.pop_back();
6293
0
    }
6294
0
    llvm::ArrayRef<CXXBaseSpecifier> Bases(RD->bases_begin(), RD->bases_end());
6295
0
    if (Fields.empty()) {
6296
0
      while (!Bases.empty() &&
6297
0
             isZeroInitialized(Bases.back().getType(),
6298
0
                               V.getStructBase(Bases.size() - 1)))
6299
0
        Bases = Bases.drop_back();
6300
0
    }
6301
6302
    // <expression> ::= tl <type> <braced-expression>* E
6303
0
    NotPrimaryExpr();
6304
0
    Out << "tl";
6305
0
    mangleType(T);
6306
0
    for (unsigned I = 0, N = Bases.size(); I != N; ++I)
6307
0
      mangleValueInTemplateArg(Bases[I].getType(), V.getStructBase(I), false);
6308
0
    for (unsigned I = 0, N = Fields.size(); I != N; ++I) {
6309
0
      if (Fields[I]->isUnnamedBitfield())
6310
0
        continue;
6311
0
      mangleValueInTemplateArg(Fields[I]->getType(),
6312
0
                               V.getStructField(Fields[I]->getFieldIndex()),
6313
0
                               false);
6314
0
    }
6315
0
    Out << 'E';
6316
0
    break;
6317
0
  }
6318
6319
0
  case APValue::Union: {
6320
0
    assert(T->getAsCXXRecordDecl() && "unexpected type for union value");
6321
0
    const FieldDecl *FD = V.getUnionField();
6322
6323
0
    if (!FD) {
6324
0
      Out << 'L';
6325
0
      mangleType(T);
6326
0
      Out << 'E';
6327
0
      break;
6328
0
    }
6329
6330
    // <braced-expression> ::= di <field source-name> <braced-expression>
6331
0
    NotPrimaryExpr();
6332
0
    Out << "tl";
6333
0
    mangleType(T);
6334
0
    if (!isZeroInitialized(T, V)) {
6335
0
      Out << "di";
6336
0
      IdentifierInfo *II = (getUnionInitName(
6337
0
          T->getAsCXXRecordDecl()->getLocation(), Context.getDiags(), FD));
6338
0
      if (II)
6339
0
        mangleSourceName(II);
6340
0
      mangleValueInTemplateArg(FD->getType(), V.getUnionValue(), false);
6341
0
    }
6342
0
    Out << 'E';
6343
0
    break;
6344
0
  }
6345
6346
0
  case APValue::Array: {
6347
0
    QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);
6348
6349
0
    NotPrimaryExpr();
6350
0
    Out << "tl";
6351
0
    mangleType(T);
6352
6353
    // Drop trailing zero-initialized elements.
6354
0
    unsigned N = V.getArraySize();
6355
0
    if (!V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller())) {
6356
0
      N = V.getArrayInitializedElts();
6357
0
      while (N && isZeroInitialized(ElemT, V.getArrayInitializedElt(N - 1)))
6358
0
        --N;
6359
0
    }
6360
6361
0
    for (unsigned I = 0; I != N; ++I) {
6362
0
      const APValue &Elem = I < V.getArrayInitializedElts()
6363
0
                                ? V.getArrayInitializedElt(I)
6364
0
                                : V.getArrayFiller();
6365
0
      mangleValueInTemplateArg(ElemT, Elem, false);
6366
0
    }
6367
0
    Out << 'E';
6368
0
    break;
6369
0
  }
6370
6371
0
  case APValue::Vector: {
6372
0
    const VectorType *VT = T->castAs<VectorType>();
6373
6374
0
    NotPrimaryExpr();
6375
0
    Out << "tl";
6376
0
    mangleType(T);
6377
0
    unsigned N = V.getVectorLength();
6378
0
    while (N && isZeroInitialized(VT->getElementType(), V.getVectorElt(N - 1)))
6379
0
      --N;
6380
0
    for (unsigned I = 0; I != N; ++I)
6381
0
      mangleValueInTemplateArg(VT->getElementType(), V.getVectorElt(I), false);
6382
0
    Out << 'E';
6383
0
    break;
6384
0
  }
6385
6386
0
  case APValue::Int:
6387
0
    mangleIntegerLiteral(T, V.getInt());
6388
0
    break;
6389
6390
0
  case APValue::Float:
6391
0
    mangleFloatLiteral(T, V.getFloat());
6392
0
    break;
6393
6394
0
  case APValue::FixedPoint:
6395
0
    mangleFixedPointLiteral();
6396
0
    break;
6397
6398
0
  case APValue::ComplexFloat: {
6399
0
    const ComplexType *CT = T->castAs<ComplexType>();
6400
0
    NotPrimaryExpr();
6401
0
    Out << "tl";
6402
0
    mangleType(T);
6403
0
    if (!V.getComplexFloatReal().isPosZero() ||
6404
0
        !V.getComplexFloatImag().isPosZero())
6405
0
      mangleFloatLiteral(CT->getElementType(), V.getComplexFloatReal());
6406
0
    if (!V.getComplexFloatImag().isPosZero())
6407
0
      mangleFloatLiteral(CT->getElementType(), V.getComplexFloatImag());
6408
0
    Out << 'E';
6409
0
    break;
6410
0
  }
6411
6412
0
  case APValue::ComplexInt: {
6413
0
    const ComplexType *CT = T->castAs<ComplexType>();
6414
0
    NotPrimaryExpr();
6415
0
    Out << "tl";
6416
0
    mangleType(T);
6417
0
    if (V.getComplexIntReal().getBoolValue() ||
6418
0
        V.getComplexIntImag().getBoolValue())
6419
0
      mangleIntegerLiteral(CT->getElementType(), V.getComplexIntReal());
6420
0
    if (V.getComplexIntImag().getBoolValue())
6421
0
      mangleIntegerLiteral(CT->getElementType(), V.getComplexIntImag());
6422
0
    Out << 'E';
6423
0
    break;
6424
0
  }
6425
6426
0
  case APValue::LValue: {
6427
    // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
6428
0
    assert((T->isPointerType() || T->isReferenceType()) &&
6429
0
           "unexpected type for LValue template arg");
6430
6431
0
    if (V.isNullPointer()) {
6432
0
      mangleNullPointer(T);
6433
0
      break;
6434
0
    }
6435
6436
0
    APValue::LValueBase B = V.getLValueBase();
6437
0
    if (!B) {
6438
      // Non-standard mangling for integer cast to a pointer; this can only
6439
      // occur as an extension.
6440
0
      CharUnits Offset = V.getLValueOffset();
6441
0
      if (Offset.isZero()) {
6442
        // This is reinterpret_cast<T*>(0), not a null pointer. Mangle this as
6443
        // a cast, because L <type> 0 E means something else.
6444
0
        NotPrimaryExpr();
6445
0
        Out << "rc";
6446
0
        mangleType(T);
6447
0
        Out << "Li0E";
6448
0
        if (TopLevel)
6449
0
          Out << 'E';
6450
0
      } else {
6451
0
        Out << "L";
6452
0
        mangleType(T);
6453
0
        Out << Offset.getQuantity() << 'E';
6454
0
      }
6455
0
      break;
6456
0
    }
6457
6458
0
    ASTContext &Ctx = Context.getASTContext();
6459
6460
0
    enum { Base, Offset, Path } Kind;
6461
0
    if (!V.hasLValuePath()) {
6462
      // Mangle as (T*)((char*)&base + N).
6463
0
      if (T->isReferenceType()) {
6464
0
        NotPrimaryExpr();
6465
0
        Out << "decvP";
6466
0
        mangleType(T->getPointeeType());
6467
0
      } else {
6468
0
        NotPrimaryExpr();
6469
0
        Out << "cv";
6470
0
        mangleType(T);
6471
0
      }
6472
0
      Out << "plcvPcad";
6473
0
      Kind = Offset;
6474
0
    } else {
6475
0
      if (!V.getLValuePath().empty() || V.isLValueOnePastTheEnd()) {
6476
0
        NotPrimaryExpr();
6477
        // A final conversion to the template parameter's type is usually
6478
        // folded into the 'so' mangling, but we can't do that for 'void*'
6479
        // parameters without introducing collisions.
6480
0
        if (NeedExactType && T->isVoidPointerType()) {
6481
0
          Out << "cv";
6482
0
          mangleType(T);
6483
0
        }
6484
0
        if (T->isPointerType())
6485
0
          Out << "ad";
6486
0
        Out << "so";
6487
0
        mangleType(T->isVoidPointerType()
6488
0
                       ? getLValueType(Ctx, V).getUnqualifiedType()
6489
0
                       : T->getPointeeType());
6490
0
        Kind = Path;
6491
0
      } else {
6492
0
        if (NeedExactType &&
6493
0
            !Ctx.hasSameType(T->getPointeeType(), getLValueType(Ctx, V)) &&
6494
0
            !isCompatibleWith(LangOptions::ClangABI::Ver11)) {
6495
0
          NotPrimaryExpr();
6496
0
          Out << "cv";
6497
0
          mangleType(T);
6498
0
        }
6499
0
        if (T->isPointerType()) {
6500
0
          NotPrimaryExpr();
6501
0
          Out << "ad";
6502
0
        }
6503
0
        Kind = Base;
6504
0
      }
6505
0
    }
6506
6507
0
    QualType TypeSoFar = B.getType();
6508
0
    if (auto *VD = B.dyn_cast<const ValueDecl*>()) {
6509
0
      Out << 'L';
6510
0
      mangle(VD);
6511
0
      Out << 'E';
6512
0
    } else if (auto *E = B.dyn_cast<const Expr*>()) {
6513
0
      NotPrimaryExpr();
6514
0
      mangleExpression(E);
6515
0
    } else if (auto TI = B.dyn_cast<TypeInfoLValue>()) {
6516
0
      NotPrimaryExpr();
6517
0
      Out << "ti";
6518
0
      mangleType(QualType(TI.getType(), 0));
6519
0
    } else {
6520
      // We should never see dynamic allocations here.
6521
0
      llvm_unreachable("unexpected lvalue base kind in template argument");
6522
0
    }
6523
6524
0
    switch (Kind) {
6525
0
    case Base:
6526
0
      break;
6527
6528
0
    case Offset:
6529
0
      Out << 'L';
6530
0
      mangleType(Ctx.getPointerDiffType());
6531
0
      mangleNumber(V.getLValueOffset().getQuantity());
6532
0
      Out << 'E';
6533
0
      break;
6534
6535
0
    case Path:
6536
      // <expression> ::= so <referent type> <expr> [<offset number>]
6537
      //                  <union-selector>* [p] E
6538
0
      if (!V.getLValueOffset().isZero())
6539
0
        mangleNumber(V.getLValueOffset().getQuantity());
6540
6541
      // We model a past-the-end array pointer as array indexing with index N,
6542
      // not with the "past the end" flag. Compensate for that.
6543
0
      bool OnePastTheEnd = V.isLValueOnePastTheEnd();
6544
6545
0
      for (APValue::LValuePathEntry E : V.getLValuePath()) {
6546
0
        if (auto *AT = TypeSoFar->getAsArrayTypeUnsafe()) {
6547
0
          if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
6548
0
            OnePastTheEnd |= CAT->getSize() == E.getAsArrayIndex();
6549
0
          TypeSoFar = AT->getElementType();
6550
0
        } else {
6551
0
          const Decl *D = E.getAsBaseOrMember().getPointer();
6552
0
          if (auto *FD = dyn_cast<FieldDecl>(D)) {
6553
            // <union-selector> ::= _ <number>
6554
0
            if (FD->getParent()->isUnion()) {
6555
0
              Out << '_';
6556
0
              if (FD->getFieldIndex())
6557
0
                Out << (FD->getFieldIndex() - 1);
6558
0
            }
6559
0
            TypeSoFar = FD->getType();
6560
0
          } else {
6561
0
            TypeSoFar = Ctx.getRecordType(cast<CXXRecordDecl>(D));
6562
0
          }
6563
0
        }
6564
0
      }
6565
6566
0
      if (OnePastTheEnd)
6567
0
        Out << 'p';
6568
0
      Out << 'E';
6569
0
      break;
6570
0
    }
6571
6572
0
    break;
6573
0
  }
6574
6575
0
  case APValue::MemberPointer:
6576
    // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
6577
0
    if (!V.getMemberPointerDecl()) {
6578
0
      mangleNullPointer(T);
6579
0
      break;
6580
0
    }
6581
6582
0
    ASTContext &Ctx = Context.getASTContext();
6583
6584
0
    NotPrimaryExpr();
6585
0
    if (!V.getMemberPointerPath().empty()) {
6586
0
      Out << "mc";
6587
0
      mangleType(T);
6588
0
    } else if (NeedExactType &&
6589
0
               !Ctx.hasSameType(
6590
0
                   T->castAs<MemberPointerType>()->getPointeeType(),
6591
0
                   V.getMemberPointerDecl()->getType()) &&
6592
0
               !isCompatibleWith(LangOptions::ClangABI::Ver11)) {
6593
0
      Out << "cv";
6594
0
      mangleType(T);
6595
0
    }
6596
0
    Out << "adL";
6597
0
    mangle(V.getMemberPointerDecl());
6598
0
    Out << 'E';
6599
0
    if (!V.getMemberPointerPath().empty()) {
6600
0
      CharUnits Offset =
6601
0
          Context.getASTContext().getMemberPointerPathAdjustment(V);
6602
0
      if (!Offset.isZero())
6603
0
        mangleNumber(Offset.getQuantity());
6604
0
      Out << 'E';
6605
0
    }
6606
0
    break;
6607
0
  }
6608
6609
0
  if (TopLevel && !IsPrimaryExpr)
6610
0
    Out << 'E';
6611
0
}
6612
6613
0
void CXXNameMangler::mangleTemplateParameter(unsigned Depth, unsigned Index) {
6614
  // <template-param> ::= T_    # first template parameter
6615
  //                  ::= T <parameter-2 non-negative number> _
6616
  //                  ::= TL <L-1 non-negative number> __
6617
  //                  ::= TL <L-1 non-negative number> _
6618
  //                         <parameter-2 non-negative number> _
6619
  //
6620
  // The latter two manglings are from a proposal here:
6621
  // https://github.com/itanium-cxx-abi/cxx-abi/issues/31#issuecomment-528122117
6622
0
  Out << 'T';
6623
0
  Depth += TemplateDepthOffset;
6624
0
  if (Depth != 0)
6625
0
    Out << 'L' << (Depth - 1) << '_';
6626
0
  if (Index != 0)
6627
0
    Out << (Index - 1);
6628
0
  Out << '_';
6629
0
}
6630
6631
0
void CXXNameMangler::mangleSeqID(unsigned SeqID) {
6632
0
  if (SeqID == 0) {
6633
    // Nothing.
6634
0
  } else if (SeqID == 1) {
6635
0
    Out << '0';
6636
0
  } else {
6637
0
    SeqID--;
6638
6639
    // <seq-id> is encoded in base-36, using digits and upper case letters.
6640
0
    char Buffer[7]; // log(2**32) / log(36) ~= 7
6641
0
    MutableArrayRef<char> BufferRef(Buffer);
6642
0
    MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
6643
6644
0
    for (; SeqID != 0; SeqID /= 36) {
6645
0
      unsigned C = SeqID % 36;
6646
0
      *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
6647
0
    }
6648
6649
0
    Out.write(I.base(), I - BufferRef.rbegin());
6650
0
  }
6651
0
  Out << '_';
6652
0
}
6653
6654
0
void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
6655
0
  bool result = mangleSubstitution(tname);
6656
0
  assert(result && "no existing substitution for template name");
6657
0
  (void) result;
6658
0
}
6659
6660
// <substitution> ::= S <seq-id> _
6661
//                ::= S_
6662
0
bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
6663
  // Try one of the standard substitutions first.
6664
0
  if (mangleStandardSubstitution(ND))
6665
0
    return true;
6666
6667
0
  ND = cast<NamedDecl>(ND->getCanonicalDecl());
6668
0
  return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
6669
0
}
6670
6671
0
bool CXXNameMangler::mangleSubstitution(NestedNameSpecifier *NNS) {
6672
0
  assert(NNS->getKind() == NestedNameSpecifier::Identifier &&
6673
0
         "mangleSubstitution(NestedNameSpecifier *) is only used for "
6674
0
         "identifier nested name specifiers.");
6675
0
  NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS);
6676
0
  return mangleSubstitution(reinterpret_cast<uintptr_t>(NNS));
6677
0
}
6678
6679
/// Determine whether the given type has any qualifiers that are relevant for
6680
/// substitutions.
6681
0
static bool hasMangledSubstitutionQualifiers(QualType T) {
6682
0
  Qualifiers Qs = T.getQualifiers();
6683
0
  return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
6684
0
}
6685
6686
0
bool CXXNameMangler::mangleSubstitution(QualType T) {
6687
0
  if (!hasMangledSubstitutionQualifiers(T)) {
6688
0
    if (const RecordType *RT = T->getAs<RecordType>())
6689
0
      return mangleSubstitution(RT->getDecl());
6690
0
  }
6691
6692
0
  uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
6693
6694
0
  return mangleSubstitution(TypePtr);
6695
0
}
6696
6697
0
bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
6698
0
  if (TemplateDecl *TD = Template.getAsTemplateDecl())
6699
0
    return mangleSubstitution(TD);
6700
6701
0
  Template = Context.getASTContext().getCanonicalTemplateName(Template);
6702
0
  return mangleSubstitution(
6703
0
                      reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
6704
0
}
6705
6706
0
bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
6707
0
  llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
6708
0
  if (I == Substitutions.end())
6709
0
    return false;
6710
6711
0
  unsigned SeqID = I->second;
6712
0
  Out << 'S';
6713
0
  mangleSeqID(SeqID);
6714
6715
0
  return true;
6716
0
}
6717
6718
/// Returns whether S is a template specialization of std::Name with a single
6719
/// argument of type A.
6720
bool CXXNameMangler::isSpecializedAs(QualType S, llvm::StringRef Name,
6721
0
                                     QualType A) {
6722
0
  if (S.isNull())
6723
0
    return false;
6724
6725
0
  const RecordType *RT = S->getAs<RecordType>();
6726
0
  if (!RT)
6727
0
    return false;
6728
6729
0
  const ClassTemplateSpecializationDecl *SD =
6730
0
    dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6731
0
  if (!SD || !SD->getIdentifier()->isStr(Name))
6732
0
    return false;
6733
6734
0
  if (!isStdNamespace(Context.getEffectiveDeclContext(SD)))
6735
0
    return false;
6736
6737
0
  const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
6738
0
  if (TemplateArgs.size() != 1)
6739
0
    return false;
6740
6741
0
  if (TemplateArgs[0].getAsType() != A)
6742
0
    return false;
6743
6744
0
  if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
6745
0
    return false;
6746
6747
0
  return true;
6748
0
}
6749
6750
/// Returns whether SD is a template specialization std::Name<char,
6751
/// std::char_traits<char> [, std::allocator<char>]>
6752
/// HasAllocator controls whether the 3rd template argument is needed.
6753
bool CXXNameMangler::isStdCharSpecialization(
6754
    const ClassTemplateSpecializationDecl *SD, llvm::StringRef Name,
6755
0
    bool HasAllocator) {
6756
0
  if (!SD->getIdentifier()->isStr(Name))
6757
0
    return false;
6758
6759
0
  const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
6760
0
  if (TemplateArgs.size() != (HasAllocator ? 3 : 2))
6761
0
    return false;
6762
6763
0
  QualType A = TemplateArgs[0].getAsType();
6764
0
  if (A.isNull())
6765
0
    return false;
6766
  // Plain 'char' is named Char_S or Char_U depending on the target ABI.
6767
0
  if (!A->isSpecificBuiltinType(BuiltinType::Char_S) &&
6768
0
      !A->isSpecificBuiltinType(BuiltinType::Char_U))
6769
0
    return false;
6770
6771
0
  if (!isSpecializedAs(TemplateArgs[1].getAsType(), "char_traits", A))
6772
0
    return false;
6773
6774
0
  if (HasAllocator &&
6775
0
      !isSpecializedAs(TemplateArgs[2].getAsType(), "allocator", A))
6776
0
    return false;
6777
6778
0
  if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
6779
0
    return false;
6780
6781
0
  return true;
6782
0
}
6783
6784
0
bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
6785
  // <substitution> ::= St # ::std::
6786
0
  if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
6787
0
    if (isStd(NS)) {
6788
0
      Out << "St";
6789
0
      return true;
6790
0
    }
6791
0
    return false;
6792
0
  }
6793
6794
0
  if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
6795
0
    if (!isStdNamespace(Context.getEffectiveDeclContext(TD)))
6796
0
      return false;
6797
6798
0
    if (TD->getOwningModuleForLinkage())
6799
0
      return false;
6800
6801
    // <substitution> ::= Sa # ::std::allocator
6802
0
    if (TD->getIdentifier()->isStr("allocator")) {
6803
0
      Out << "Sa";
6804
0
      return true;
6805
0
    }
6806
6807
    // <<substitution> ::= Sb # ::std::basic_string
6808
0
    if (TD->getIdentifier()->isStr("basic_string")) {
6809
0
      Out << "Sb";
6810
0
      return true;
6811
0
    }
6812
0
    return false;
6813
0
  }
6814
6815
0
  if (const ClassTemplateSpecializationDecl *SD =
6816
0
        dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
6817
0
    if (!isStdNamespace(Context.getEffectiveDeclContext(SD)))
6818
0
      return false;
6819
6820
0
    if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
6821
0
      return false;
6822
6823
    //    <substitution> ::= Ss # ::std::basic_string<char,
6824
    //                            ::std::char_traits<char>,
6825
    //                            ::std::allocator<char> >
6826
0
    if (isStdCharSpecialization(SD, "basic_string", /*HasAllocator=*/true)) {
6827
0
      Out << "Ss";
6828
0
      return true;
6829
0
    }
6830
6831
    //    <substitution> ::= Si # ::std::basic_istream<char,
6832
    //                            ::std::char_traits<char> >
6833
0
    if (isStdCharSpecialization(SD, "basic_istream", /*HasAllocator=*/false)) {
6834
0
      Out << "Si";
6835
0
      return true;
6836
0
    }
6837
6838
    //    <substitution> ::= So # ::std::basic_ostream<char,
6839
    //                            ::std::char_traits<char> >
6840
0
    if (isStdCharSpecialization(SD, "basic_ostream", /*HasAllocator=*/false)) {
6841
0
      Out << "So";
6842
0
      return true;
6843
0
    }
6844
6845
    //    <substitution> ::= Sd # ::std::basic_iostream<char,
6846
    //                            ::std::char_traits<char> >
6847
0
    if (isStdCharSpecialization(SD, "basic_iostream", /*HasAllocator=*/false)) {
6848
0
      Out << "Sd";
6849
0
      return true;
6850
0
    }
6851
0
    return false;
6852
0
  }
6853
6854
0
  return false;
6855
0
}
6856
6857
0
void CXXNameMangler::addSubstitution(QualType T) {
6858
0
  if (!hasMangledSubstitutionQualifiers(T)) {
6859
0
    if (const RecordType *RT = T->getAs<RecordType>()) {
6860
0
      addSubstitution(RT->getDecl());
6861
0
      return;
6862
0
    }
6863
0
  }
6864
6865
0
  uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
6866
0
  addSubstitution(TypePtr);
6867
0
}
6868
6869
0
void CXXNameMangler::addSubstitution(TemplateName Template) {
6870
0
  if (TemplateDecl *TD = Template.getAsTemplateDecl())
6871
0
    return addSubstitution(TD);
6872
6873
0
  Template = Context.getASTContext().getCanonicalTemplateName(Template);
6874
0
  addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
6875
0
}
6876
6877
0
void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
6878
0
  assert(!Substitutions.count(Ptr) && "Substitution already exists!");
6879
0
  Substitutions[Ptr] = SeqID++;
6880
0
}
6881
6882
0
void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
6883
0
  assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
6884
0
  if (Other->SeqID > SeqID) {
6885
0
    Substitutions.swap(Other->Substitutions);
6886
0
    SeqID = Other->SeqID;
6887
0
  }
6888
0
}
6889
6890
CXXNameMangler::AbiTagList
6891
0
CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
6892
  // When derived abi tags are disabled there is no need to make any list.
6893
0
  if (DisableDerivedAbiTags)
6894
0
    return AbiTagList();
6895
6896
0
  llvm::raw_null_ostream NullOutStream;
6897
0
  CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
6898
0
  TrackReturnTypeTags.disableDerivedAbiTags();
6899
6900
0
  const FunctionProtoType *Proto =
6901
0
      cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
6902
0
  FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
6903
0
  TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
6904
0
  TrackReturnTypeTags.mangleType(Proto->getReturnType());
6905
0
  TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
6906
0
  TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
6907
6908
0
  return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
6909
0
}
6910
6911
CXXNameMangler::AbiTagList
6912
0
CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
6913
  // When derived abi tags are disabled there is no need to make any list.
6914
0
  if (DisableDerivedAbiTags)
6915
0
    return AbiTagList();
6916
6917
0
  llvm::raw_null_ostream NullOutStream;
6918
0
  CXXNameMangler TrackVariableType(*this, NullOutStream);
6919
0
  TrackVariableType.disableDerivedAbiTags();
6920
6921
0
  TrackVariableType.mangleType(VD->getType());
6922
6923
0
  return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
6924
0
}
6925
6926
bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
6927
0
                                       const VarDecl *VD) {
6928
0
  llvm::raw_null_ostream NullOutStream;
6929
0
  CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
6930
0
  TrackAbiTags.mangle(VD);
6931
0
  return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
6932
0
}
6933
6934
//
6935
6936
/// Mangles the name of the declaration D and emits that name to the given
6937
/// output stream.
6938
///
6939
/// If the declaration D requires a mangled name, this routine will emit that
6940
/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
6941
/// and this routine will return false. In this case, the caller should just
6942
/// emit the identifier of the declaration (\c D->getIdentifier()) as its
6943
/// name.
6944
void ItaniumMangleContextImpl::mangleCXXName(GlobalDecl GD,
6945
0
                                             raw_ostream &Out) {
6946
0
  const NamedDecl *D = cast<NamedDecl>(GD.getDecl());
6947
0
  assert((isa<FunctionDecl, VarDecl, TemplateParamObjectDecl>(D)) &&
6948
0
         "Invalid mangleName() call, argument is not a variable or function!");
6949
6950
0
  PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
6951
0
                                 getASTContext().getSourceManager(),
6952
0
                                 "Mangling declaration");
6953
6954
0
  if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) {
6955
0
    auto Type = GD.getCtorType();
6956
0
    CXXNameMangler Mangler(*this, Out, CD, Type);
6957
0
    return Mangler.mangle(GlobalDecl(CD, Type));
6958
0
  }
6959
6960
0
  if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) {
6961
0
    auto Type = GD.getDtorType();
6962
0
    CXXNameMangler Mangler(*this, Out, DD, Type);
6963
0
    return Mangler.mangle(GlobalDecl(DD, Type));
6964
0
  }
6965
6966
0
  CXXNameMangler Mangler(*this, Out, D);
6967
0
  Mangler.mangle(GD);
6968
0
}
6969
6970
void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
6971
0
                                                   raw_ostream &Out) {
6972
0
  CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
6973
0
  Mangler.mangle(GlobalDecl(D, Ctor_Comdat));
6974
0
}
6975
6976
void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
6977
0
                                                   raw_ostream &Out) {
6978
0
  CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
6979
0
  Mangler.mangle(GlobalDecl(D, Dtor_Comdat));
6980
0
}
6981
6982
void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
6983
                                           const ThunkInfo &Thunk,
6984
0
                                           raw_ostream &Out) {
6985
  //  <special-name> ::= T <call-offset> <base encoding>
6986
  //                      # base is the nominal target function of thunk
6987
  //  <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
6988
  //                      # base is the nominal target function of thunk
6989
  //                      # first call-offset is 'this' adjustment
6990
  //                      # second call-offset is result adjustment
6991
6992
0
  assert(!isa<CXXDestructorDecl>(MD) &&
6993
0
         "Use mangleCXXDtor for destructor decls!");
6994
0
  CXXNameMangler Mangler(*this, Out);
6995
0
  Mangler.getStream() << "_ZT";
6996
0
  if (!Thunk.Return.isEmpty())
6997
0
    Mangler.getStream() << 'c';
6998
6999
  // Mangle the 'this' pointer adjustment.
7000
0
  Mangler.mangleCallOffset(Thunk.This.NonVirtual,
7001
0
                           Thunk.This.Virtual.Itanium.VCallOffsetOffset);
7002
7003
  // Mangle the return pointer adjustment if there is one.
7004
0
  if (!Thunk.Return.isEmpty())
7005
0
    Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
7006
0
                             Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
7007
7008
0
  Mangler.mangleFunctionEncoding(MD);
7009
0
}
7010
7011
void ItaniumMangleContextImpl::mangleCXXDtorThunk(
7012
    const CXXDestructorDecl *DD, CXXDtorType Type,
7013
0
    const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
7014
  //  <special-name> ::= T <call-offset> <base encoding>
7015
  //                      # base is the nominal target function of thunk
7016
0
  CXXNameMangler Mangler(*this, Out, DD, Type);
7017
0
  Mangler.getStream() << "_ZT";
7018
7019
  // Mangle the 'this' pointer adjustment.
7020
0
  Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
7021
0
                           ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
7022
7023
0
  Mangler.mangleFunctionEncoding(GlobalDecl(DD, Type));
7024
0
}
7025
7026
/// Returns the mangled name for a guard variable for the passed in VarDecl.
7027
void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
7028
0
                                                         raw_ostream &Out) {
7029
  //  <special-name> ::= GV <object name>       # Guard variable for one-time
7030
  //                                            # initialization
7031
0
  CXXNameMangler Mangler(*this, Out);
7032
  // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
7033
  // be a bug that is fixed in trunk.
7034
0
  Mangler.getStream() << "_ZGV";
7035
0
  Mangler.mangleName(D);
7036
0
}
7037
7038
void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
7039
0
                                                        raw_ostream &Out) {
7040
  // These symbols are internal in the Itanium ABI, so the names don't matter.
7041
  // Clang has traditionally used this symbol and allowed LLVM to adjust it to
7042
  // avoid duplicate symbols.
7043
0
  Out << "__cxx_global_var_init";
7044
0
}
7045
7046
void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
7047
0
                                                             raw_ostream &Out) {
7048
  // Prefix the mangling of D with __dtor_.
7049
0
  CXXNameMangler Mangler(*this, Out);
7050
0
  Mangler.getStream() << "__dtor_";
7051
0
  if (shouldMangleDeclName(D))
7052
0
    Mangler.mangle(D);
7053
0
  else
7054
0
    Mangler.getStream() << D->getName();
7055
0
}
7056
7057
void ItaniumMangleContextImpl::mangleDynamicStermFinalizer(const VarDecl *D,
7058
0
                                                           raw_ostream &Out) {
7059
  // Clang generates these internal-linkage functions as part of its
7060
  // implementation of the XL ABI.
7061
0
  CXXNameMangler Mangler(*this, Out);
7062
0
  Mangler.getStream() << "__finalize_";
7063
0
  if (shouldMangleDeclName(D))
7064
0
    Mangler.mangle(D);
7065
0
  else
7066
0
    Mangler.getStream() << D->getName();
7067
0
}
7068
7069
void ItaniumMangleContextImpl::mangleSEHFilterExpression(
7070
0
    GlobalDecl EnclosingDecl, raw_ostream &Out) {
7071
0
  CXXNameMangler Mangler(*this, Out);
7072
0
  Mangler.getStream() << "__filt_";
7073
0
  auto *EnclosingFD = cast<FunctionDecl>(EnclosingDecl.getDecl());
7074
0
  if (shouldMangleDeclName(EnclosingFD))
7075
0
    Mangler.mangle(EnclosingDecl);
7076
0
  else
7077
0
    Mangler.getStream() << EnclosingFD->getName();
7078
0
}
7079
7080
void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
7081
0
    GlobalDecl EnclosingDecl, raw_ostream &Out) {
7082
0
  CXXNameMangler Mangler(*this, Out);
7083
0
  Mangler.getStream() << "__fin_";
7084
0
  auto *EnclosingFD = cast<FunctionDecl>(EnclosingDecl.getDecl());
7085
0
  if (shouldMangleDeclName(EnclosingFD))
7086
0
    Mangler.mangle(EnclosingDecl);
7087
0
  else
7088
0
    Mangler.getStream() << EnclosingFD->getName();
7089
0
}
7090
7091
void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
7092
0
                                                            raw_ostream &Out) {
7093
  //  <special-name> ::= TH <object name>
7094
0
  CXXNameMangler Mangler(*this, Out);
7095
0
  Mangler.getStream() << "_ZTH";
7096
0
  Mangler.mangleName(D);
7097
0
}
7098
7099
void
7100
ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
7101
0
                                                          raw_ostream &Out) {
7102
  //  <special-name> ::= TW <object name>
7103
0
  CXXNameMangler Mangler(*this, Out);
7104
0
  Mangler.getStream() << "_ZTW";
7105
0
  Mangler.mangleName(D);
7106
0
}
7107
7108
void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
7109
                                                        unsigned ManglingNumber,
7110
0
                                                        raw_ostream &Out) {
7111
  // We match the GCC mangling here.
7112
  //  <special-name> ::= GR <object name>
7113
0
  CXXNameMangler Mangler(*this, Out);
7114
0
  Mangler.getStream() << "_ZGR";
7115
0
  Mangler.mangleName(D);
7116
0
  assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
7117
0
  Mangler.mangleSeqID(ManglingNumber - 1);
7118
0
}
7119
7120
void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
7121
0
                                               raw_ostream &Out) {
7122
  // <special-name> ::= TV <type>  # virtual table
7123
0
  CXXNameMangler Mangler(*this, Out);
7124
0
  Mangler.getStream() << "_ZTV";
7125
0
  Mangler.mangleNameOrStandardSubstitution(RD);
7126
0
}
7127
7128
void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
7129
0
                                            raw_ostream &Out) {
7130
  // <special-name> ::= TT <type>  # VTT structure
7131
0
  CXXNameMangler Mangler(*this, Out);
7132
0
  Mangler.getStream() << "_ZTT";
7133
0
  Mangler.mangleNameOrStandardSubstitution(RD);
7134
0
}
7135
7136
void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
7137
                                                   int64_t Offset,
7138
                                                   const CXXRecordDecl *Type,
7139
0
                                                   raw_ostream &Out) {
7140
  // <special-name> ::= TC <type> <offset number> _ <base type>
7141
0
  CXXNameMangler Mangler(*this, Out);
7142
0
  Mangler.getStream() << "_ZTC";
7143
0
  Mangler.mangleNameOrStandardSubstitution(RD);
7144
0
  Mangler.getStream() << Offset;
7145
0
  Mangler.getStream() << '_';
7146
0
  Mangler.mangleNameOrStandardSubstitution(Type);
7147
0
}
7148
7149
0
void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
7150
  // <special-name> ::= TI <type>  # typeinfo structure
7151
0
  assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
7152
0
  CXXNameMangler Mangler(*this, Out);
7153
0
  Mangler.getStream() << "_ZTI";
7154
0
  Mangler.mangleType(Ty);
7155
0
}
7156
7157
void ItaniumMangleContextImpl::mangleCXXRTTIName(
7158
0
    QualType Ty, raw_ostream &Out, bool NormalizeIntegers = false) {
7159
  // <special-name> ::= TS <type>  # typeinfo name (null terminated byte string)
7160
0
  CXXNameMangler Mangler(*this, Out, NormalizeIntegers);
7161
0
  Mangler.getStream() << "_ZTS";
7162
0
  Mangler.mangleType(Ty);
7163
0
}
7164
7165
void ItaniumMangleContextImpl::mangleCanonicalTypeName(
7166
0
    QualType Ty, raw_ostream &Out, bool NormalizeIntegers = false) {
7167
0
  mangleCXXRTTIName(Ty, Out, NormalizeIntegers);
7168
0
}
7169
7170
0
void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
7171
0
  llvm_unreachable("Can't mangle string literals");
7172
0
}
7173
7174
void ItaniumMangleContextImpl::mangleLambdaSig(const CXXRecordDecl *Lambda,
7175
0
                                               raw_ostream &Out) {
7176
0
  CXXNameMangler Mangler(*this, Out);
7177
0
  Mangler.mangleLambdaSig(Lambda);
7178
0
}
7179
7180
void ItaniumMangleContextImpl::mangleModuleInitializer(const Module *M,
7181
0
                                                       raw_ostream &Out) {
7182
  // <special-name> ::= GI <module-name>  # module initializer function
7183
0
  CXXNameMangler Mangler(*this, Out);
7184
0
  Mangler.getStream() << "_ZGI";
7185
0
  Mangler.mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());
7186
0
  if (M->isModulePartition()) {
7187
    // The partition needs including, as partitions can have them too.
7188
0
    auto Partition = M->Name.find(':');
7189
0
    Mangler.mangleModuleNamePrefix(
7190
0
        StringRef(&M->Name[Partition + 1], M->Name.size() - Partition - 1),
7191
0
        /*IsPartition*/ true);
7192
0
  }
7193
0
}
7194
7195
ItaniumMangleContext *ItaniumMangleContext::create(ASTContext &Context,
7196
                                                   DiagnosticsEngine &Diags,
7197
69
                                                   bool IsAux) {
7198
69
  return new ItaniumMangleContextImpl(
7199
69
      Context, Diags,
7200
69
      [](ASTContext &, const NamedDecl *) -> std::optional<unsigned> {
7201
0
        return std::nullopt;
7202
0
      },
7203
69
      IsAux);
7204
69
}
7205
7206
ItaniumMangleContext *
7207
ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags,
7208
                             DiscriminatorOverrideTy DiscriminatorOverride,
7209
0
                             bool IsAux) {
7210
0
  return new ItaniumMangleContextImpl(Context, Diags, DiscriminatorOverride,
7211
0
                                      IsAux);
7212
0
}