Coverage Report

Created: 2020-09-22 08:39

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