Coverage Report

Created: 2022-07-16 07:03

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