Coverage Report

Created: 2020-02-15 09:57

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