Coverage Report

Created: 2021-09-21 08:58

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