Coverage Report

Created: 2019-07-24 05:18

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