Coverage Report

Created: 2022-07-16 07:03

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/AST/MicrosoftMangle.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- MicrosoftMangle.cpp - Microsoft Visual C++ Name Mangling ---------===//
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
// This provides C++ name mangling targeting the Microsoft Visual C++ ABI.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/AST/ASTContext.h"
14
#include "clang/AST/Attr.h"
15
#include "clang/AST/CXXInheritance.h"
16
#include "clang/AST/CharUnits.h"
17
#include "clang/AST/Decl.h"
18
#include "clang/AST/DeclCXX.h"
19
#include "clang/AST/DeclObjC.h"
20
#include "clang/AST/DeclOpenMP.h"
21
#include "clang/AST/DeclTemplate.h"
22
#include "clang/AST/Expr.h"
23
#include "clang/AST/ExprCXX.h"
24
#include "clang/AST/GlobalDecl.h"
25
#include "clang/AST/Mangle.h"
26
#include "clang/AST/VTableBuilder.h"
27
#include "clang/Basic/ABI.h"
28
#include "clang/Basic/DiagnosticOptions.h"
29
#include "clang/Basic/FileManager.h"
30
#include "clang/Basic/SourceManager.h"
31
#include "clang/Basic/TargetInfo.h"
32
#include "llvm/ADT/StringExtras.h"
33
#include "llvm/Support/CRC.h"
34
#include "llvm/Support/MD5.h"
35
#include "llvm/Support/MathExtras.h"
36
#include "llvm/Support/StringSaver.h"
37
#include "llvm/Support/xxhash.h"
38
39
using namespace clang;
40
41
namespace {
42
43
// Get GlobalDecl of DeclContext of local entities.
44
538
static GlobalDecl getGlobalDeclAsDeclContext(const DeclContext *DC) {
45
538
  GlobalDecl GD;
46
538
  if (auto *CD = dyn_cast<CXXConstructorDecl>(DC))
47
4
    GD = GlobalDecl(CD, Ctor_Complete);
48
534
  else if (auto *DD = dyn_cast<CXXDestructorDecl>(DC))
49
4
    GD = GlobalDecl(DD, Dtor_Complete);
50
530
  else
51
530
    GD = GlobalDecl(cast<FunctionDecl>(DC));
52
538
  return GD;
53
538
}
54
55
struct msvc_hashing_ostream : public llvm::raw_svector_ostream {
56
  raw_ostream &OS;
57
  llvm::SmallString<64> Buffer;
58
59
  msvc_hashing_ostream(raw_ostream &OS)
60
32.0k
      : llvm::raw_svector_ostream(Buffer), OS(OS) {}
61
32.0k
  ~msvc_hashing_ostream() override {
62
32.0k
    StringRef MangledName = str();
63
32.0k
    bool StartsWithEscape = MangledName.startswith("\01");
64
32.0k
    if (StartsWithEscape)
65
0
      MangledName = MangledName.drop_front(1);
66
32.0k
    if (MangledName.size() < 4096) {
67
31.9k
      OS << str();
68
31.9k
      return;
69
31.9k
    }
70
71
134
    llvm::MD5 Hasher;
72
134
    llvm::MD5::MD5Result Hash;
73
134
    Hasher.update(MangledName);
74
134
    Hasher.final(Hash);
75
76
134
    SmallString<32> HexString;
77
134
    llvm::MD5::stringifyResult(Hash, HexString);
78
79
134
    if (StartsWithEscape)
80
0
      OS << '\01';
81
134
    OS << "??@" << HexString << '@';
82
134
  }
83
};
84
85
static const DeclContext *
86
70.0k
getLambdaDefaultArgumentDeclContext(const Decl *D) {
87
70.0k
  if (const auto *RD = dyn_cast<CXXRecordDecl>(D))
88
27.5k
    if (RD->isLambda())
89
352
      if (const auto *Parm =
90
352
              dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
91
60
        return Parm->getDeclContext();
92
69.9k
  return nullptr;
93
70.0k
}
94
95
/// Retrieve the declaration context that should be used when mangling
96
/// the given declaration.
97
55.4k
static const DeclContext *getEffectiveDeclContext(const Decl *D) {
98
  // The ABI assumes that lambda closure types that occur within
99
  // default arguments live in the context of the function. However, due to
100
  // the way in which Clang parses and creates function declarations, this is
101
  // not the case: the lambda closure type ends up living in the context
102
  // where the function itself resides, because the function declaration itself
103
  // had not yet been created. Fix the context here.
104
55.4k
  if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(D))
105
34
    return LDADC;
106
107
  // Perform the same check for block literals.
108
55.3k
  if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
109
58
    if (ParmVarDecl *ContextParam =
110
58
            dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
111
16
      return ContextParam->getDeclContext();
112
58
  }
113
114
55.3k
  const DeclContext *DC = D->getDeclContext();
115
55.3k
  if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
116
55.3k
      isa<OMPDeclareMapperDecl>(DC)) {
117
0
    return getEffectiveDeclContext(cast<Decl>(DC));
118
0
  }
119
120
55.3k
  return DC->getRedeclContext();
121
55.3k
}
122
123
0
static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
124
0
  return getEffectiveDeclContext(cast<Decl>(DC));
125
0
}
126
127
2.93k
static const FunctionDecl *getStructor(const NamedDecl *ND) {
128
2.93k
  if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(ND))
129
8
    return FTD->getTemplatedDecl()->getCanonicalDecl();
130
131
2.92k
  const auto *FD = cast<FunctionDecl>(ND);
132
2.92k
  if (const auto *FTD = FD->getPrimaryTemplate())
133
11
    return FTD->getTemplatedDecl()->getCanonicalDecl();
134
135
2.91k
  return FD->getCanonicalDecl();
136
2.92k
}
137
138
/// MicrosoftMangleContextImpl - Overrides the default MangleContext for the
139
/// Microsoft Visual C++ ABI.
140
class MicrosoftMangleContextImpl : public MicrosoftMangleContext {
141
  typedef std::pair<const DeclContext *, IdentifierInfo *> DiscriminatorKeyTy;
142
  llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
143
  llvm::DenseMap<const NamedDecl *, unsigned> Uniquifier;
144
  llvm::DenseMap<const CXXRecordDecl *, unsigned> LambdaIds;
145
  llvm::DenseMap<const NamedDecl *, unsigned> SEHFilterIds;
146
  llvm::DenseMap<const NamedDecl *, unsigned> SEHFinallyIds;
147
  SmallString<16> AnonymousNamespaceHash;
148
149
public:
150
  MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags,
151
                             bool IsAux = false);
152
  bool shouldMangleCXXName(const NamedDecl *D) override;
153
  bool shouldMangleStringLiteral(const StringLiteral *SL) override;
154
  void mangleCXXName(GlobalDecl GD, raw_ostream &Out) override;
155
  void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
156
                                const MethodVFTableLocation &ML,
157
                                raw_ostream &Out) override;
158
  void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
159
                   raw_ostream &) override;
160
  void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
161
                          const ThisAdjustment &ThisAdjustment,
162
                          raw_ostream &) override;
163
  void mangleCXXVFTable(const CXXRecordDecl *Derived,
164
                        ArrayRef<const CXXRecordDecl *> BasePath,
165
                        raw_ostream &Out) override;
166
  void mangleCXXVBTable(const CXXRecordDecl *Derived,
167
                        ArrayRef<const CXXRecordDecl *> BasePath,
168
                        raw_ostream &Out) override;
169
  void mangleCXXVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
170
                                       const CXXRecordDecl *DstRD,
171
                                       raw_ostream &Out) override;
172
  void mangleCXXThrowInfo(QualType T, bool IsConst, bool IsVolatile,
173
                          bool IsUnaligned, uint32_t NumEntries,
174
                          raw_ostream &Out) override;
175
  void mangleCXXCatchableTypeArray(QualType T, uint32_t NumEntries,
176
                                   raw_ostream &Out) override;
177
  void mangleCXXCatchableType(QualType T, const CXXConstructorDecl *CD,
178
                              CXXCtorType CT, uint32_t Size, uint32_t NVOffset,
179
                              int32_t VBPtrOffset, uint32_t VBIndex,
180
                              raw_ostream &Out) override;
181
  void mangleCXXRTTI(QualType T, raw_ostream &Out) override;
182
  void mangleCXXRTTIName(QualType T, raw_ostream &Out) override;
183
  void mangleCXXRTTIBaseClassDescriptor(const CXXRecordDecl *Derived,
184
                                        uint32_t NVOffset, int32_t VBPtrOffset,
185
                                        uint32_t VBTableOffset, uint32_t Flags,
186
                                        raw_ostream &Out) override;
187
  void mangleCXXRTTIBaseClassArray(const CXXRecordDecl *Derived,
188
                                   raw_ostream &Out) override;
189
  void mangleCXXRTTIClassHierarchyDescriptor(const CXXRecordDecl *Derived,
190
                                             raw_ostream &Out) override;
191
  void
192
  mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl *Derived,
193
                                     ArrayRef<const CXXRecordDecl *> BasePath,
194
                                     raw_ostream &Out) override;
195
  void mangleTypeName(QualType T, raw_ostream &) override;
196
  void mangleReferenceTemporary(const VarDecl *, unsigned ManglingNumber,
197
                                raw_ostream &) override;
198
  void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override;
199
  void mangleThreadSafeStaticGuardVariable(const VarDecl *D, unsigned GuardNum,
200
                                           raw_ostream &Out) override;
201
  void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
202
  void mangleDynamicAtExitDestructor(const VarDecl *D,
203
                                     raw_ostream &Out) override;
204
  void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
205
                                 raw_ostream &Out) override;
206
  void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
207
                             raw_ostream &Out) override;
208
  void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override;
209
8.54k
  bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
210
8.54k
    const DeclContext *DC = getEffectiveDeclContext(ND);
211
8.54k
    if (!DC->isFunctionOrMethod())
212
7.94k
      return false;
213
214
    // Lambda closure types are already numbered, give out a phony number so
215
    // that they demangle nicely.
216
607
    if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
217
258
      if (RD->isLambda()) {
218
153
        disc = 1;
219
153
        return true;
220
153
      }
221
258
    }
222
223
    // Use the canonical number for externally visible decls.
224
454
    if (ND->isExternallyVisible()) {
225
234
      disc = getASTContext().getManglingNumber(ND, isAux());
226
234
      return true;
227
234
    }
228
229
    // Anonymous tags are already numbered.
230
220
    if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
231
73
      if (!Tag->hasNameForLinkage() &&
232
73
          
!getASTContext().getDeclaratorForUnnamedTagDecl(Tag)19
&&
233
73
          
!getASTContext().getTypedefNameForUnnamedTagDecl(Tag)0
)
234
0
        return false;
235
73
    }
236
237
    // Make up a reasonable number for internal decls.
238
220
    unsigned &discriminator = Uniquifier[ND];
239
220
    if (!discriminator)
240
91
      discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
241
220
    disc = discriminator + 1;
242
220
    return true;
243
220
  }
244
245
16
  std::string getLambdaString(const CXXRecordDecl *Lambda) override {
246
16
    assert(Lambda->isLambda() && "RD must be a lambda!");
247
0
    std::string Name("<lambda_");
248
249
16
    Decl *LambdaContextDecl = Lambda->getLambdaContextDecl();
250
16
    unsigned LambdaManglingNumber = Lambda->getLambdaManglingNumber();
251
16
    unsigned LambdaId;
252
16
    const ParmVarDecl *Parm = dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
253
16
    const FunctionDecl *Func =
254
16
        Parm ? 
dyn_cast<FunctionDecl>(Parm->getDeclContext())6
:
nullptr10
;
255
256
16
    if (Func) {
257
6
      unsigned DefaultArgNo =
258
6
          Func->getNumParams() - Parm->getFunctionScopeIndex();
259
6
      Name += llvm::utostr(DefaultArgNo);
260
6
      Name += "_";
261
6
    }
262
263
16
    if (LambdaManglingNumber)
264
13
      LambdaId = LambdaManglingNumber;
265
3
    else
266
3
      LambdaId = getLambdaIdForDebugInfo(Lambda);
267
268
16
    Name += llvm::utostr(LambdaId);
269
16
    Name += ">";
270
16
    return Name;
271
16
  }
272
273
53
  unsigned getLambdaId(const CXXRecordDecl *RD) {
274
53
    assert(RD->isLambda() && "RD must be a lambda!");
275
0
    assert(!RD->isExternallyVisible() && "RD must not be visible!");
276
0
    assert(RD->getLambdaManglingNumber() == 0 &&
277
53
           "RD must not have a mangling number!");
278
0
    std::pair<llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator, bool>
279
53
        Result = LambdaIds.insert(std::make_pair(RD, LambdaIds.size()));
280
53
    return Result.first->second;
281
53
  }
282
283
3
  unsigned getLambdaIdForDebugInfo(const CXXRecordDecl *RD) {
284
3
    assert(RD->isLambda() && "RD must be a lambda!");
285
0
    assert(!RD->isExternallyVisible() && "RD must not be visible!");
286
0
    assert(RD->getLambdaManglingNumber() == 0 &&
287
3
           "RD must not have a mangling number!");
288
0
    llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator Result =
289
3
        LambdaIds.find(RD);
290
    // The lambda should exist, but return 0 in case it doesn't.
291
3
    if (Result == LambdaIds.end())
292
2
      return 0;
293
1
    return Result->second;
294
3
  }
295
296
  /// Return a character sequence that is (somewhat) unique to the TU suitable
297
  /// for mangling anonymous namespaces.
298
299
  StringRef getAnonymousNamespaceHash() const {
299
299
    return AnonymousNamespaceHash;
300
299
  }
301
302
private:
303
  void mangleInitFiniStub(const VarDecl *D, char CharCode, raw_ostream &Out);
304
};
305
306
/// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
307
/// Microsoft Visual C++ ABI.
308
class MicrosoftCXXNameMangler {
309
  MicrosoftMangleContextImpl &Context;
310
  raw_ostream &Out;
311
312
  /// The "structor" is the top-level declaration being mangled, if
313
  /// that's not a template specialization; otherwise it's the pattern
314
  /// for that specialization.
315
  const NamedDecl *Structor;
316
  unsigned StructorType;
317
318
  typedef llvm::SmallVector<std::string, 10> BackRefVec;
319
  BackRefVec NameBackReferences;
320
321
  typedef llvm::DenseMap<const void *, unsigned> ArgBackRefMap;
322
  ArgBackRefMap FunArgBackReferences;
323
  ArgBackRefMap TemplateArgBackReferences;
324
325
  typedef llvm::DenseMap<const void *, StringRef> TemplateArgStringMap;
326
  TemplateArgStringMap TemplateArgStrings;
327
  llvm::StringSaver TemplateArgStringStorage;
328
  llvm::BumpPtrAllocator TemplateArgStringStorageAlloc;
329
330
  typedef std::set<std::pair<int, bool>> PassObjectSizeArgsSet;
331
  PassObjectSizeArgsSet PassObjectSizeArgs;
332
333
193k
  ASTContext &getASTContext() const { return Context.getASTContext(); }
334
335
  const bool PointersAre64Bit;
336
337
public:
338
  enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
339
340
  MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_)
341
      : Context(C), Out(Out_), Structor(nullptr), StructorType(-1),
342
        TemplateArgStringStorage(TemplateArgStringStorageAlloc),
343
        PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
344
34.3k
                         64) {}
345
346
  MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
347
                          const CXXConstructorDecl *D, CXXCtorType Type)
348
      : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
349
        TemplateArgStringStorage(TemplateArgStringStorageAlloc),
350
        PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
351
1.62k
                         64) {}
352
353
  MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
354
                          const CXXDestructorDecl *D, CXXDtorType Type)
355
      : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
356
        TemplateArgStringStorage(TemplateArgStringStorageAlloc),
357
        PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
358
1.02k
                         64) {}
359
360
24.5k
  raw_ostream &getStream() const { return Out; }
361
362
  void mangle(GlobalDecl GD, StringRef Prefix = "?");
363
  void mangleName(GlobalDecl GD);
364
  void mangleFunctionEncoding(GlobalDecl GD, bool ShouldMangle);
365
  void mangleVariableEncoding(const VarDecl *VD);
366
  void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD,
367
                               StringRef Prefix = "$");
368
  void mangleMemberFunctionPointer(const CXXRecordDecl *RD,
369
                                   const CXXMethodDecl *MD,
370
                                   StringRef Prefix = "$");
371
  void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
372
                                const MethodVFTableLocation &ML);
373
  void mangleNumber(int64_t Number);
374
  void mangleNumber(llvm::APSInt Number);
375
  void mangleFloat(llvm::APFloat Number);
376
  void mangleBits(llvm::APInt Number);
377
  void mangleTagTypeKind(TagTypeKind TK);
378
  void mangleArtificialTagType(TagTypeKind TK, StringRef UnqualifiedName,
379
                              ArrayRef<StringRef> NestedNames = None);
380
  void mangleAddressSpaceType(QualType T, Qualifiers Quals, SourceRange Range);
381
  void mangleType(QualType T, SourceRange Range,
382
                  QualifierMangleMode QMM = QMM_Mangle);
383
  void mangleFunctionType(const FunctionType *T,
384
                          const FunctionDecl *D = nullptr,
385
                          bool ForceThisQuals = false,
386
                          bool MangleExceptionSpec = true);
387
  void mangleNestedName(GlobalDecl GD);
388
389
private:
390
4.42k
  bool isStructorDecl(const NamedDecl *ND) const {
391
4.42k
    return ND == Structor || 
getStructor(ND) == Structor280
;
392
4.42k
  }
393
394
6.40k
  bool is64BitPointer(Qualifiers Quals) const {
395
6.40k
    LangAS AddrSpace = Quals.getAddressSpace();
396
6.40k
    return AddrSpace == LangAS::ptr64 ||
397
6.40k
           (PointersAre64Bit && 
!(2.66k
AddrSpace == LangAS::ptr32_sptr2.66k
||
398
2.66k
                                  
AddrSpace == LangAS::ptr32_uptr2.65k
));
399
6.40k
  }
400
401
60.1k
  void mangleUnqualifiedName(GlobalDecl GD) {
402
60.1k
    mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName());
403
60.1k
  }
404
  void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name);
405
  void mangleSourceName(StringRef Name);
406
  void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
407
  void mangleCXXDtorType(CXXDtorType T);
408
  void mangleQualifiers(Qualifiers Quals, bool IsMember);
409
  void mangleRefQualifier(RefQualifierKind RefQualifier);
410
  void manglePointerCVQualifiers(Qualifiers Quals);
411
  void manglePointerExtQualifiers(Qualifiers Quals, QualType PointeeType);
412
413
  void mangleUnscopedTemplateName(GlobalDecl GD);
414
  void
415
  mangleTemplateInstantiationName(GlobalDecl GD,
416
                                  const TemplateArgumentList &TemplateArgs);
417
  void mangleObjCMethodName(const ObjCMethodDecl *MD);
418
419
  void mangleFunctionArgumentType(QualType T, SourceRange Range);
420
  void manglePassObjectSizeArg(const PassObjectSizeAttr *POSA);
421
422
  bool isArtificialTagType(QualType T) const;
423
424
  // Declare manglers for every type class.
425
#define ABSTRACT_TYPE(CLASS, PARENT)
426
#define NON_CANONICAL_TYPE(CLASS, PARENT)
427
#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
428
                                            Qualifiers Quals, \
429
                                            SourceRange Range);
430
#include "clang/AST/TypeNodes.inc"
431
#undef ABSTRACT_TYPE
432
#undef NON_CANONICAL_TYPE
433
#undef TYPE
434
435
  void mangleType(const TagDecl *TD);
436
  void mangleDecayedArrayType(const ArrayType *T);
437
  void mangleArrayType(const ArrayType *T);
438
  void mangleFunctionClass(const FunctionDecl *FD);
439
  void mangleCallingConvention(CallingConv CC);
440
  void mangleCallingConvention(const FunctionType *T);
441
  void mangleIntegerLiteral(const llvm::APSInt &Number,
442
                            const NonTypeTemplateParmDecl *PD = nullptr,
443
                            QualType TemplateArgType = QualType());
444
  void mangleExpression(const Expr *E, const NonTypeTemplateParmDecl *PD);
445
  void mangleThrowSpecification(const FunctionProtoType *T);
446
447
  void mangleTemplateArgs(const TemplateDecl *TD,
448
                          const TemplateArgumentList &TemplateArgs);
449
  void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA,
450
                         const NamedDecl *Parm);
451
  void mangleTemplateArgValue(QualType T, const APValue &V,
452
                              bool WithScalarType = false);
453
454
  void mangleObjCProtocol(const ObjCProtocolDecl *PD);
455
  void mangleObjCLifetime(const QualType T, Qualifiers Quals,
456
                          SourceRange Range);
457
  void mangleObjCKindOfType(const ObjCObjectType *T, Qualifiers Quals,
458
                            SourceRange Range);
459
};
460
}
461
462
MicrosoftMangleContextImpl::MicrosoftMangleContextImpl(ASTContext &Context,
463
                                                       DiagnosticsEngine &Diags,
464
                                                       bool IsAux)
465
882
    : MicrosoftMangleContext(Context, Diags, IsAux) {
466
  // To mangle anonymous namespaces, hash the path to the main source file. The
467
  // path should be whatever (probably relative) path was passed on the command
468
  // line. The goal is for the compiler to produce the same output regardless of
469
  // working directory, so use the uncanonicalized relative path.
470
  //
471
  // It's important to make the mangled names unique because, when CodeView
472
  // debug info is in use, the debugger uses mangled type names to distinguish
473
  // between otherwise identically named types in anonymous namespaces.
474
  //
475
  // These symbols are always internal, so there is no need for the hash to
476
  // match what MSVC produces. For the same reason, clang is free to change the
477
  // hash at any time without breaking compatibility with old versions of clang.
478
  // The generated names are intended to look similar to what MSVC generates,
479
  // which are something like "?A0x01234567@".
480
882
  SourceManager &SM = Context.getSourceManager();
481
882
  if (const FileEntry *FE = SM.getFileEntryForID(SM.getMainFileID())) {
482
    // Truncate the hash so we get 8 characters of hexadecimal.
483
880
    uint32_t TruncatedHash = uint32_t(xxHash64(FE->getName()));
484
880
    AnonymousNamespaceHash = llvm::utohexstr(TruncatedHash);
485
880
  } else {
486
    // If we don't have a path to the main file, we'll just use 0.
487
2
    AnonymousNamespaceHash = "0";
488
2
  }
489
882
}
490
491
129k
bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
492
129k
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
493
124k
    LanguageLinkage L = FD->getLanguageLinkage();
494
    // Overloadable functions need mangling.
495
124k
    if (FD->hasAttr<OverloadableAttr>())
496
105
      return true;
497
498
    // The ABI expects that we would never mangle "typical" user-defined entry
499
    // points regardless of visibility or freestanding-ness.
500
    //
501
    // N.B. This is distinct from asking about "main".  "main" has a lot of
502
    // special rules associated with it in the standard while these
503
    // user-defined entry points are outside of the purview of the standard.
504
    // For example, there can be only one definition for "main" in a standards
505
    // compliant program; however nothing forbids the existence of wmain and
506
    // WinMain in the same translation unit.
507
124k
    if (FD->isMSVCRTEntryPoint())
508
106
      return false;
509
510
    // C++ functions and those whose names are not a simple identifier need
511
    // mangling.
512
124k
    if (!FD->getDeclName().isIdentifier() || 
L == CXXLanguageLinkage113k
)
513
29.2k
      return true;
514
515
    // C functions are not mangled.
516
95.1k
    if (L == CLanguageLinkage)
517
994
      return false;
518
95.1k
  }
519
520
  // Otherwise, no mangling is done outside C++ mode.
521
99.1k
  if (!getASTContext().getLangOpts().CPlusPlus)
522
51.7k
    return false;
523
524
47.3k
  const VarDecl *VD = dyn_cast<VarDecl>(D);
525
47.3k
  if (VD && 
!isa<DecompositionDecl>(D)4.86k
) {
526
    // C variables are not mangled.
527
4.85k
    if (VD->isExternC())
528
26
      return false;
529
530
    // Variables at global scope with internal linkage are not mangled.
531
4.82k
    const DeclContext *DC = getEffectiveDeclContext(D);
532
    // Check for extern variable declared locally.
533
4.82k
    if (DC->isFunctionOrMethod() && 
D->hasLinkage()334
)
534
0
      while (!DC->isNamespace() && !DC->isTranslationUnit())
535
0
        DC = getEffectiveParentContext(DC);
536
537
4.82k
    if (DC->isTranslationUnit() && 
D->getFormalLinkage() == InternalLinkage3.14k
&&
538
4.82k
        
!isa<VarTemplateSpecializationDecl>(D)24
&&
539
4.82k
        
D->getIdentifier() != nullptr24
)
540
20
      return false;
541
4.82k
  }
542
543
47.3k
  return true;
544
47.3k
}
545
546
bool
547
794
MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
548
794
  return true;
549
794
}
550
551
26.7k
void MicrosoftCXXNameMangler::mangle(GlobalDecl GD, StringRef Prefix) {
552
26.7k
  const NamedDecl *D = cast<NamedDecl>(GD.getDecl());
553
  // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
554
  // Therefore it's really important that we don't decorate the
555
  // name with leading underscores or leading/trailing at signs. So, by
556
  // default, we emit an asm marker at the start so we get the name right.
557
  // Callers can override this with a custom prefix.
558
559
  // <mangled-name> ::= ? <name> <type-encoding>
560
26.7k
  Out << Prefix;
561
26.7k
  mangleName(GD);
562
26.7k
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
563
24.2k
    mangleFunctionEncoding(GD, Context.shouldMangleDeclName(FD));
564
2.44k
  else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
565
2.42k
    mangleVariableEncoding(VD);
566
23
  else if (isa<MSGuidDecl>(D))
567
    // MSVC appears to mangle GUIDs as if they were variables of type
568
    // 'const struct __s_GUID'.
569
20
    Out << "3U__s_GUID@@B";
570
3
  else if (isa<TemplateParamObjectDecl>(D)) {
571
    // Template parameter objects don't get a <type-encoding>; their type is
572
    // specified as part of their value.
573
3
  } else
574
0
    llvm_unreachable("Tried to mangle unexpected NamedDecl!");
575
26.7k
}
576
577
void MicrosoftCXXNameMangler::mangleFunctionEncoding(GlobalDecl GD,
578
24.3k
                                                     bool ShouldMangle) {
579
24.3k
  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
580
  // <type-encoding> ::= <function-class> <function-type>
581
582
  // Since MSVC operates on the type as written and not the canonical type, it
583
  // actually matters which decl we have here.  MSVC appears to choose the
584
  // first, since it is most likely to be the declaration in a header file.
585
24.3k
  FD = FD->getFirstDecl();
586
587
  // We should never ever see a FunctionNoProtoType at this point.
588
  // We don't even know how to mangle their types anyway :).
589
24.3k
  const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
590
591
  // extern "C" functions can hold entities that must be mangled.
592
  // As it stands, these functions still need to get expressed in the full
593
  // external name.  They have their class and type omitted, replaced with '9'.
594
24.3k
  if (ShouldMangle) {
595
    // We would like to mangle all extern "C" functions using this additional
596
    // component but this would break compatibility with MSVC's behavior.
597
    // Instead, do this when we know that compatibility isn't important (in
598
    // other words, when it is an overloaded extern "C" function).
599
24.2k
    if (FD->isExternC() && 
FD->hasAttr<OverloadableAttr>()32
)
600
28
      Out << "$$J0";
601
602
24.2k
    mangleFunctionClass(FD);
603
604
24.2k
    mangleFunctionType(FT, FD, false, false);
605
24.2k
  } else {
606
25
    Out << '9';
607
25
  }
608
24.3k
}
609
610
2.47k
void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
611
  // <type-encoding> ::= <storage-class> <variable-type>
612
  // <storage-class> ::= 0  # private static member
613
  //                 ::= 1  # protected static member
614
  //                 ::= 2  # public static member
615
  //                 ::= 3  # global
616
  //                 ::= 4  # static local
617
618
  // The first character in the encoding (after the name) is the storage class.
619
2.47k
  if (VD->isStaticDataMember()) {
620
    // If it's a static member, it also encodes the access level.
621
332
    switch (VD->getAccess()) {
622
0
      default:
623
13
      case AS_private: Out << '0'; break;
624
5
      case AS_protected: Out << '1'; break;
625
314
      case AS_public: Out << '2'; break;
626
332
    }
627
332
  }
628
2.14k
  else if (!VD->isStaticLocal())
629
1.97k
    Out << '3';
630
167
  else
631
167
    Out << '4';
632
  // Now mangle the type.
633
  // <variable-type> ::= <type> <cvr-qualifiers>
634
  //                 ::= <type> <pointee-cvr-qualifiers> # pointers, references
635
  // Pointers and references are odd. The type of 'int * const foo;' gets
636
  // mangled as 'QAHA' instead of 'PAHB', for example.
637
2.47k
  SourceRange SR = VD->getSourceRange();
638
2.47k
  QualType Ty = VD->getType();
639
2.47k
  if (Ty->isPointerType() || 
Ty->isReferenceType()1.66k
||
640
2.47k
      
Ty->isMemberPointerType()1.64k
) {
641
958
    mangleType(Ty, SR, QMM_Drop);
642
958
    manglePointerExtQualifiers(
643
958
        Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), QualType());
644
958
    if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) {
645
126
      mangleQualifiers(MPT->getPointeeType().getQualifiers(), true);
646
      // Member pointers are suffixed with a back reference to the member
647
      // pointer's class name.
648
126
      mangleName(MPT->getClass()->getAsCXXRecordDecl());
649
126
    } else
650
832
      mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
651
1.51k
  } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
652
    // Global arrays are funny, too.
653
110
    mangleDecayedArrayType(AT);
654
110
    if (AT->getElementType()->isArrayType())
655
12
      Out << 'A';
656
98
    else
657
98
      mangleQualifiers(Ty.getQualifiers(), false);
658
1.40k
  } else {
659
1.40k
    mangleType(Ty, SR, QMM_Drop);
660
1.40k
    mangleQualifiers(Ty.getQualifiers(), false);
661
1.40k
  }
662
2.47k
}
663
664
void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD,
665
                                                      const ValueDecl *VD,
666
20
                                                      StringRef Prefix) {
667
  // <member-data-pointer> ::= <integer-literal>
668
  //                       ::= $F <number> <number>
669
  //                       ::= $G <number> <number> <number>
670
671
20
  int64_t FieldOffset;
672
20
  int64_t VBTableOffset;
673
20
  MSInheritanceModel IM = RD->getMSInheritanceModel();
674
20
  if (VD) {
675
12
    FieldOffset = getASTContext().getFieldOffset(VD);
676
12
    assert(FieldOffset % getASTContext().getCharWidth() == 0 &&
677
12
           "cannot take address of bitfield");
678
0
    FieldOffset /= getASTContext().getCharWidth();
679
680
12
    VBTableOffset = 0;
681
682
12
    if (IM == MSInheritanceModel::Virtual)
683
2
      FieldOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
684
12
  } else {
685
8
    FieldOffset = RD->nullFieldOffsetIsZero() ? 
04
:
-14
;
686
687
8
    VBTableOffset = -1;
688
8
  }
689
690
0
  char Code = '\0';
691
20
  switch (IM) {
692
6
  case MSInheritanceModel::Single:      Code = '0'; break;
693
6
  case MSInheritanceModel::Multiple:    Code = '0'; break;
694
3
  case MSInheritanceModel::Virtual:     Code = 'F'; break;
695
5
  case MSInheritanceModel::Unspecified: Code = 'G'; break;
696
20
  }
697
698
20
  Out << Prefix << Code;
699
700
20
  mangleNumber(FieldOffset);
701
702
  // The C++ standard doesn't allow base-to-derived member pointer conversions
703
  // in template parameter contexts, so the vbptr offset of data member pointers
704
  // is always zero.
705
20
  if (inheritanceModelHasVBPtrOffsetField(IM))
706
5
    mangleNumber(0);
707
20
  if (inheritanceModelHasVBTableOffsetField(IM))
708
8
    mangleNumber(VBTableOffset);
709
20
}
710
711
void
712
MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD,
713
                                                     const CXXMethodDecl *MD,
714
19
                                                     StringRef Prefix) {
715
  // <member-function-pointer> ::= $1? <name>
716
  //                           ::= $H? <name> <number>
717
  //                           ::= $I? <name> <number> <number>
718
  //                           ::= $J? <name> <number> <number> <number>
719
720
19
  MSInheritanceModel IM = RD->getMSInheritanceModel();
721
722
19
  char Code = '\0';
723
19
  switch (IM) {
724
7
  case MSInheritanceModel::Single:      Code = '1'; break;
725
4
  case MSInheritanceModel::Multiple:    Code = 'H'; break;
726
4
  case MSInheritanceModel::Virtual:     Code = 'I'; break;
727
4
  case MSInheritanceModel::Unspecified: Code = 'J'; break;
728
19
  }
729
730
  // If non-virtual, mangle the name.  If virtual, mangle as a virtual memptr
731
  // thunk.
732
19
  uint64_t NVOffset = 0;
733
19
  uint64_t VBTableOffset = 0;
734
19
  uint64_t VBPtrOffset = 0;
735
19
  if (MD) {
736
15
    Out << Prefix << Code << '?';
737
15
    if (MD->isVirtual()) {
738
9
      MicrosoftVTableContext *VTContext =
739
9
          cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
740
9
      MethodVFTableLocation ML =
741
9
          VTContext->getMethodVFTableLocation(GlobalDecl(MD));
742
9
      mangleVirtualMemPtrThunk(MD, ML);
743
9
      NVOffset = ML.VFPtrOffset.getQuantity();
744
9
      VBTableOffset = ML.VBTableIndex * 4;
745
9
      if (ML.VBase) {
746
1
        const ASTRecordLayout &Layout = getASTContext().getASTRecordLayout(RD);
747
1
        VBPtrOffset = Layout.getVBPtrOffset().getQuantity();
748
1
      }
749
9
    } else {
750
6
      mangleName(MD);
751
6
      mangleFunctionEncoding(MD, /*ShouldMangle=*/true);
752
6
    }
753
754
15
    if (VBTableOffset == 0 && 
IM == MSInheritanceModel::Virtual14
)
755
3
      NVOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
756
15
  } else {
757
    // Null single inheritance member functions are encoded as a simple nullptr.
758
4
    if (IM == MSInheritanceModel::Single) {
759
1
      Out << Prefix << "0A@";
760
1
      return;
761
1
    }
762
3
    if (IM == MSInheritanceModel::Unspecified)
763
1
      VBTableOffset = -1;
764
3
    Out << Prefix << Code;
765
3
  }
766
767
18
  if (inheritanceModelHasNVOffsetField(/*IsMemberFunction=*/true, IM))
768
12
    mangleNumber(static_cast<uint32_t>(NVOffset));
769
18
  if (inheritanceModelHasVBPtrOffsetField(IM))
770
4
    mangleNumber(VBPtrOffset);
771
18
  if (inheritanceModelHasVBTableOffsetField(IM))
772
8
    mangleNumber(VBTableOffset);
773
18
}
774
775
void MicrosoftCXXNameMangler::mangleVirtualMemPtrThunk(
776
64
    const CXXMethodDecl *MD, const MethodVFTableLocation &ML) {
777
  // Get the vftable offset.
778
64
  CharUnits PointerWidth = getASTContext().toCharUnitsFromBits(
779
64
      getASTContext().getTargetInfo().getPointerWidth(0));
780
64
  uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
781
782
64
  Out << "?_9";
783
64
  mangleName(MD->getParent());
784
64
  Out << "$B";
785
64
  mangleNumber(OffsetInVFTable);
786
64
  Out << 'A';
787
64
  mangleCallingConvention(MD->getType()->castAs<FunctionProtoType>());
788
64
}
789
790
41.9k
void MicrosoftCXXNameMangler::mangleName(GlobalDecl GD) {
791
  // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
792
793
  // Always start with the unqualified name.
794
41.9k
  mangleUnqualifiedName(GD);
795
796
41.9k
  mangleNestedName(GD);
797
798
  // Terminate the whole name with an '@'.
799
41.9k
  Out << '@';
800
41.9k
}
801
802
4.97k
void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
803
4.97k
  mangleNumber(llvm::APSInt(llvm::APInt(64, Number), /*IsUnsigned*/false));
804
4.97k
}
805
806
5.86k
void MicrosoftCXXNameMangler::mangleNumber(llvm::APSInt Number) {
807
  // MSVC never mangles any integer wider than 64 bits. In general it appears
808
  // to convert every integer to signed 64 bit before mangling (including
809
  // unsigned 64 bit values). Do the same, but preserve bits beyond the bottom
810
  // 64.
811
5.86k
  unsigned Width = std::max(Number.getBitWidth(), 64U);
812
5.86k
  llvm::APInt Value = Number.extend(Width);
813
814
  // <non-negative integer> ::= A@              # when Number == 0
815
  //                        ::= <decimal digit> # when 1 <= Number <= 10
816
  //                        ::= <hex digit>+ @  # when Number >= 10
817
  //
818
  // <number>               ::= [?] <non-negative integer>
819
820
5.86k
  if (Value.isNegative()) {
821
472
    Value = -Value;
822
472
    Out << '?';
823
472
  }
824
5.86k
  mangleBits(Value);
825
5.86k
}
826
827
38
void MicrosoftCXXNameMangler::mangleFloat(llvm::APFloat Number) {
828
38
  using llvm::APFloat;
829
830
38
  switch (APFloat::SemanticsToEnum(Number.getSemantics())) {
831
26
  case APFloat::S_IEEEsingle: Out << 'A'; break;
832
12
  case APFloat::S_IEEEdouble: Out << 'B'; break;
833
834
  // The following are all Clang extensions. We try to pick manglings that are
835
  // unlikely to conflict with MSVC's scheme.
836
0
  case APFloat::S_IEEEhalf: Out << 'V'; break;
837
0
  case APFloat::S_BFloat: Out << 'W'; break;
838
0
  case APFloat::S_x87DoubleExtended: Out << 'X'; break;
839
0
  case APFloat::S_IEEEquad: Out << 'Y'; break;
840
0
  case APFloat::S_PPCDoubleDouble: Out << 'Z'; break;
841
38
  }
842
843
38
  mangleBits(Number.bitcastToAPInt());
844
38
}
845
846
5.90k
void MicrosoftCXXNameMangler::mangleBits(llvm::APInt Value) {
847
5.90k
  if (Value == 0)
848
1.27k
    Out << "A@";
849
4.63k
  else if (Value.uge(1) && Value.ule(10))
850
2.51k
    Out << (Value - 1);
851
2.11k
  else {
852
    // Numbers that are not encoded as decimal digits are represented as nibbles
853
    // in the range of ASCII characters 'A' to 'P'.
854
    // The number 0x123450 would be encoded as 'BCDEFA'
855
2.11k
    llvm::SmallString<32> EncodedNumberBuffer;
856
12.8k
    for (; Value != 0; 
Value.lshrInPlace(4)10.7k
)
857
10.7k
      EncodedNumberBuffer.push_back('A' + (Value & 0xf).getZExtValue());
858
2.11k
    std::reverse(EncodedNumberBuffer.begin(), EncodedNumberBuffer.end());
859
2.11k
    Out.write(EncodedNumberBuffer.data(), EncodedNumberBuffer.size());
860
2.11k
    Out << '@';
861
2.11k
  }
862
5.90k
}
863
864
static GlobalDecl isTemplate(GlobalDecl GD,
865
60.1k
                             const TemplateArgumentList *&TemplateArgs) {
866
60.1k
  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
867
  // Check if we have a function template.
868
60.1k
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
869
24.6k
    if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
870
896
      TemplateArgs = FD->getTemplateSpecializationArgs();
871
896
      return GD.getWithDecl(TD);
872
896
    }
873
24.6k
  }
874
875
  // Check if we have a class template.
876
59.2k
  if (const ClassTemplateSpecializationDecl *Spec =
877
59.2k
          dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
878
4.87k
    TemplateArgs = &Spec->getTemplateArgs();
879
4.87k
    return GD.getWithDecl(Spec->getSpecializedTemplate());
880
4.87k
  }
881
882
  // Check if we have a variable template.
883
54.4k
  if (const VarTemplateSpecializationDecl *Spec =
884
54.4k
          dyn_cast<VarTemplateSpecializationDecl>(ND)) {
885
218
    TemplateArgs = &Spec->getTemplateArgs();
886
218
    return GD.getWithDecl(Spec->getSpecializedTemplate());
887
218
  }
888
889
54.2k
  return GlobalDecl();
890
54.4k
}
891
892
void MicrosoftCXXNameMangler::mangleUnqualifiedName(GlobalDecl GD,
893
60.1k
                                                    DeclarationName Name) {
894
60.1k
  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
895
  //  <unqualified-name> ::= <operator-name>
896
  //                     ::= <ctor-dtor-name>
897
  //                     ::= <source-name>
898
  //                     ::= <template-name>
899
900
  // Check if we have a template.
901
60.1k
  const TemplateArgumentList *TemplateArgs = nullptr;
902
60.1k
  if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
903
    // Function templates aren't considered for name back referencing.  This
904
    // makes sense since function templates aren't likely to occur multiple
905
    // times in a symbol.
906
5.98k
    if (isa<FunctionTemplateDecl>(TD.getDecl())) {
907
896
      mangleTemplateInstantiationName(TD, *TemplateArgs);
908
896
      Out << '@';
909
896
      return;
910
896
    }
911
912
    // Here comes the tricky thing: if we need to mangle something like
913
    //   void foo(A::X<Y>, B::X<Y>),
914
    // the X<Y> part is aliased. However, if you need to mangle
915
    //   void foo(A::X<A::Y>, A::X<B::Y>),
916
    // the A::X<> part is not aliased.
917
    // That is, from the mangler's perspective we have a structure like this:
918
    //   namespace[s] -> type[ -> template-parameters]
919
    // but from the Clang perspective we have
920
    //   type [ -> template-parameters]
921
    //      \-> namespace[s]
922
    // What we do is we create a new mangler, mangle the same type (without
923
    // a namespace suffix) to a string using the extra mangler and then use
924
    // the mangled type name as a key to check the mangling of different types
925
    // for aliasing.
926
927
    // It's important to key cache reads off ND, not TD -- the same TD can
928
    // be used with different TemplateArgs, but ND uniquely identifies
929
    // TD / TemplateArg pairs.
930
5.09k
    ArgBackRefMap::iterator Found = TemplateArgBackReferences.find(ND);
931
5.09k
    if (Found == TemplateArgBackReferences.end()) {
932
933
2.71k
      TemplateArgStringMap::iterator Found = TemplateArgStrings.find(ND);
934
2.71k
      if (Found == TemplateArgStrings.end()) {
935
        // Mangle full template name into temporary buffer.
936
2.70k
        llvm::SmallString<64> TemplateMangling;
937
2.70k
        llvm::raw_svector_ostream Stream(TemplateMangling);
938
2.70k
        MicrosoftCXXNameMangler Extra(Context, Stream);
939
2.70k
        Extra.mangleTemplateInstantiationName(TD, *TemplateArgs);
940
941
        // Use the string backref vector to possibly get a back reference.
942
2.70k
        mangleSourceName(TemplateMangling);
943
944
        // Memoize back reference for this type if one exist, else memoize
945
        // the mangling itself.
946
2.70k
        BackRefVec::iterator StringFound =
947
2.70k
            llvm::find(NameBackReferences, TemplateMangling);
948
2.70k
        if (StringFound != NameBackReferences.end()) {
949
2.70k
          TemplateArgBackReferences[ND] =
950
2.70k
              StringFound - NameBackReferences.begin();
951
2.70k
        } else {
952
1
          TemplateArgStrings[ND] =
953
1
              TemplateArgStringStorage.save(TemplateMangling.str());
954
1
        }
955
2.70k
      } else {
956
1
        Out << Found->second << '@'; // Outputs a StringRef.
957
1
      }
958
2.71k
    } else {
959
2.38k
      Out << Found->second; // Outputs a back reference (an int).
960
2.38k
    }
961
5.09k
    return;
962
5.98k
  }
963
964
54.2k
  switch (Name.getNameKind()) {
965
50.6k
    case DeclarationName::Identifier: {
966
50.6k
      if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
967
50.0k
        bool IsDeviceStub =
968
50.0k
            ND &&
969
50.0k
            ((isa<FunctionDecl>(ND) && 
ND->hasAttr<CUDAGlobalAttr>()20.1k
) ||
970
50.0k
             
(49.9k
isa<FunctionTemplateDecl>(ND)49.9k
&&
971
49.9k
              cast<FunctionTemplateDecl>(ND)
972
872
                  ->getTemplatedDecl()
973
872
                  ->hasAttr<CUDAGlobalAttr>())) &&
974
50.0k
            
GD.getKernelReferenceKind() == KernelReferenceKind::Stub24
;
975
50.0k
        if (IsDeviceStub)
976
12
          mangleSourceName(
977
12
              (llvm::Twine("__device_stub__") + II->getName()).str());
978
49.9k
        else
979
49.9k
          mangleSourceName(II->getName());
980
50.0k
        break;
981
50.0k
      }
982
983
      // Otherwise, an anonymous entity.  We must have a declaration.
984
637
      assert(ND && "mangling empty name without declaration");
985
986
637
      if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
987
299
        if (NS->isAnonymousNamespace()) {
988
299
          Out << "?A0x" << Context.getAnonymousNamespaceHash() << '@';
989
299
          break;
990
299
        }
991
299
      }
992
993
338
      if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(ND)) {
994
        // Decomposition declarations are considered anonymous, and get
995
        // numbered with a $S prefix.
996
12
        llvm::SmallString<64> Name("$S");
997
        // Get a unique id for the anonymous struct.
998
12
        Name += llvm::utostr(Context.getAnonymousStructId(DD) + 1);
999
12
        mangleSourceName(Name);
1000
12
        break;
1001
12
      }
1002
1003
326
      if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1004
        // We must have an anonymous union or struct declaration.
1005
8
        const CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl();
1006
8
        assert(RD && "expected variable decl to have a record type");
1007
        // Anonymous types with no tag or typedef get the name of their
1008
        // declarator mangled in.  If they have no declarator, number them with
1009
        // a $S prefix.
1010
0
        llvm::SmallString<64> Name("$S");
1011
        // Get a unique id for the anonymous struct.
1012
8
        Name += llvm::utostr(Context.getAnonymousStructId(RD) + 1);
1013
8
        mangleSourceName(Name.str());
1014
8
        break;
1015
8
      }
1016
1017
318
      if (const MSGuidDecl *GD = dyn_cast<MSGuidDecl>(ND)) {
1018
        // Mangle a GUID object as if it were a variable with the corresponding
1019
        // mangled name.
1020
20
        SmallString<sizeof("_GUID_12345678_1234_1234_1234_1234567890ab")> GUID;
1021
20
        llvm::raw_svector_ostream GUIDOS(GUID);
1022
20
        Context.mangleMSGuidDecl(GD, GUIDOS);
1023
20
        mangleSourceName(GUID);
1024
20
        break;
1025
20
      }
1026
1027
298
      if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
1028
3
        Out << "?__N";
1029
3
        mangleTemplateArgValue(TPO->getType().getUnqualifiedType(),
1030
3
                               TPO->getValue());
1031
3
        break;
1032
3
      }
1033
1034
      // We must have an anonymous struct.
1035
295
      const TagDecl *TD = cast<TagDecl>(ND);
1036
295
      if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1037
19
        assert(TD->getDeclContext() == D->getDeclContext() &&
1038
19
               "Typedef should not be in another decl context!");
1039
0
        assert(D->getDeclName().getAsIdentifierInfo() &&
1040
19
               "Typedef was not named!");
1041
0
        mangleSourceName(D->getDeclName().getAsIdentifierInfo()->getName());
1042
19
        break;
1043
19
      }
1044
1045
276
      if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1046
242
        if (Record->isLambda()) {
1047
184
          llvm::SmallString<10> Name("<lambda_");
1048
1049
184
          Decl *LambdaContextDecl = Record->getLambdaContextDecl();
1050
184
          unsigned LambdaManglingNumber = Record->getLambdaManglingNumber();
1051
184
          unsigned LambdaId;
1052
184
          const ParmVarDecl *Parm =
1053
184
              dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
1054
184
          const FunctionDecl *Func =
1055
184
              Parm ? 
dyn_cast<FunctionDecl>(Parm->getDeclContext())30
:
nullptr154
;
1056
1057
184
          if (Func) {
1058
30
            unsigned DefaultArgNo =
1059
30
                Func->getNumParams() - Parm->getFunctionScopeIndex();
1060
30
            Name += llvm::utostr(DefaultArgNo);
1061
30
            Name += "_";
1062
30
          }
1063
1064
184
          if (LambdaManglingNumber)
1065
131
            LambdaId = LambdaManglingNumber;
1066
53
          else
1067
53
            LambdaId = Context.getLambdaId(Record);
1068
1069
184
          Name += llvm::utostr(LambdaId);
1070
184
          Name += ">";
1071
1072
184
          mangleSourceName(Name);
1073
1074
          // If the context is a variable or a class member and not a parameter,
1075
          // it is encoded in a qualified name.
1076
184
          if (LambdaManglingNumber && 
LambdaContextDecl131
) {
1077
52
            if ((isa<VarDecl>(LambdaContextDecl) ||
1078
52
                 
isa<FieldDecl>(LambdaContextDecl)14
) &&
1079
52
                !isa<ParmVarDecl>(LambdaContextDecl)) {
1080
22
              mangleUnqualifiedName(cast<NamedDecl>(LambdaContextDecl));
1081
22
            }
1082
52
          }
1083
184
          break;
1084
184
        }
1085
242
      }
1086
1087
92
      llvm::SmallString<64> Name;
1088
92
      if (DeclaratorDecl *DD =
1089
92
              Context.getASTContext().getDeclaratorForUnnamedTagDecl(TD)) {
1090
        // Anonymous types without a name for linkage purposes have their
1091
        // declarator mangled in if they have one.
1092
58
        Name += "<unnamed-type-";
1093
58
        Name += DD->getName();
1094
58
      } else 
if (TypedefNameDecl *34
TND34
=
1095
34
                     Context.getASTContext().getTypedefNameForUnnamedTagDecl(
1096
34
                         TD)) {
1097
        // Anonymous types without a name for linkage purposes have their
1098
        // associate typedef mangled in if they have one.
1099
8
        Name += "<unnamed-type-";
1100
8
        Name += TND->getName();
1101
26
      } else if (isa<EnumDecl>(TD) &&
1102
26
                 cast<EnumDecl>(TD)->enumerator_begin() !=
1103
11
                     cast<EnumDecl>(TD)->enumerator_end()) {
1104
        // Anonymous non-empty enums mangle in the first enumerator.
1105
7
        auto *ED = cast<EnumDecl>(TD);
1106
7
        Name += "<unnamed-enum-";
1107
7
        Name += ED->enumerator_begin()->getName();
1108
19
      } else {
1109
        // Otherwise, number the types using a $S prefix.
1110
19
        Name += "<unnamed-type-$S";
1111
19
        Name += llvm::utostr(Context.getAnonymousStructId(TD) + 1);
1112
19
      }
1113
92
      Name += ">";
1114
92
      mangleSourceName(Name.str());
1115
92
      break;
1116
276
    }
1117
1118
0
    case DeclarationName::ObjCZeroArgSelector:
1119
0
    case DeclarationName::ObjCOneArgSelector:
1120
0
    case DeclarationName::ObjCMultiArgSelector: {
1121
      // This is reachable only when constructing an outlined SEH finally
1122
      // block.  Nothing depends on this mangling and it's used only with
1123
      // functinos with internal linkage.
1124
0
      llvm::SmallString<64> Name;
1125
0
      mangleSourceName(Name.str());
1126
0
      break;
1127
0
    }
1128
1129
1.63k
    case DeclarationName::CXXConstructorName:
1130
1.63k
      if (isStructorDecl(ND)) {
1131
1.62k
        if (StructorType == Ctor_CopyingClosure) {
1132
9
          Out << "?_O";
1133
9
          return;
1134
9
        }
1135
1.61k
        if (StructorType == Ctor_DefaultClosure) {
1136
32
          Out << "?_F";
1137
32
          return;
1138
32
        }
1139
1.61k
      }
1140
1.59k
      Out << "?0";
1141
1.59k
      return;
1142
1143
861
    case DeclarationName::CXXDestructorName:
1144
861
      if (isStructorDecl(ND))
1145
        // If the named decl is the C++ destructor we're mangling,
1146
        // use the type we were given.
1147
857
        mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1148
4
      else
1149
        // Otherwise, use the base destructor name. This is relevant if a
1150
        // class with a destructor is declared within a destructor.
1151
4
        mangleCXXDtorType(Dtor_Base);
1152
861
      break;
1153
1154
34
    case DeclarationName::CXXConversionFunctionName:
1155
      // <operator-name> ::= ?B # (cast)
1156
      // The target type is encoded as the return type.
1157
34
      Out << "?B";
1158
34
      break;
1159
1160
1.03k
    case DeclarationName::CXXOperatorName:
1161
1.03k
      mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation());
1162
1.03k
      break;
1163
1164
6
    case DeclarationName::CXXLiteralOperatorName: {
1165
6
      Out << "?__K";
1166
6
      mangleSourceName(Name.getCXXLiteralIdentifier()->getName());
1167
6
      break;
1168
1.63k
    }
1169
1170
0
    case DeclarationName::CXXDeductionGuideName:
1171
0
      llvm_unreachable("Can't mangle a deduction guide name!");
1172
1173
0
    case DeclarationName::CXXUsingDirective:
1174
0
      llvm_unreachable("Can't mangle a using directive name!");
1175
54.2k
  }
1176
54.2k
}
1177
1178
// <postfix> ::= <unqualified-name> [<postfix>]
1179
//           ::= <substitution> [<postfix>]
1180
41.9k
void MicrosoftCXXNameMangler::mangleNestedName(GlobalDecl GD) {
1181
41.9k
  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1182
41.9k
  const DeclContext *DC = getEffectiveDeclContext(ND);
1183
56.6k
  while (!DC->isTranslationUnit()) {
1184
15.2k
    if (isa<TagDecl>(ND) || 
isa<VarDecl>(ND)7.95k
) {
1185
8.53k
      unsigned Disc;
1186
8.53k
      if (Context.getNextDiscriminator(ND, Disc)) {
1187
596
        Out << '?';
1188
596
        mangleNumber(Disc);
1189
596
        Out << '?';
1190
596
      }
1191
8.53k
    }
1192
1193
15.2k
    if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
1194
58
      auto Discriminate =
1195
58
          [](StringRef Name, const unsigned Discriminator,
1196
116
             const unsigned ParameterDiscriminator) -> std::string {
1197
116
        std::string Buffer;
1198
116
        llvm::raw_string_ostream Stream(Buffer);
1199
116
        Stream << Name;
1200
116
        if (Discriminator)
1201
112
          Stream << '_' << Discriminator;
1202
116
        if (ParameterDiscriminator)
1203
32
          Stream << '_' << ParameterDiscriminator;
1204
116
        return Stream.str();
1205
116
      };
1206
1207
58
      unsigned Discriminator = BD->getBlockManglingNumber();
1208
58
      if (!Discriminator)
1209
18
        Discriminator = Context.getBlockId(BD, /*Local=*/false);
1210
1211
      // Mangle the parameter position as a discriminator to deal with unnamed
1212
      // parameters.  Rather than mangling the unqualified parameter name,
1213
      // always use the position to give a uniform mangling.
1214
58
      unsigned ParameterDiscriminator = 0;
1215
58
      if (const auto *MC = BD->getBlockManglingContextDecl())
1216
28
        if (const auto *P = dyn_cast<ParmVarDecl>(MC))
1217
16
          if (const auto *F = dyn_cast<FunctionDecl>(P->getDeclContext()))
1218
16
            ParameterDiscriminator =
1219
16
                F->getNumParams() - P->getFunctionScopeIndex();
1220
1221
58
      DC = getEffectiveDeclContext(BD);
1222
1223
58
      Out << '?';
1224
58
      mangleSourceName(Discriminate("_block_invoke", Discriminator,
1225
58
                                    ParameterDiscriminator));
1226
      // If we have a block mangling context, encode that now.  This allows us
1227
      // to discriminate between named static data initializers in the same
1228
      // scope.  This is handled differently from parameters, which use
1229
      // positions to discriminate between multiple instances.
1230
58
      if (const auto *MC = BD->getBlockManglingContextDecl())
1231
28
        if (!isa<ParmVarDecl>(MC))
1232
12
          if (const auto *ND = dyn_cast<NamedDecl>(MC))
1233
12
            mangleUnqualifiedName(ND);
1234
      // MS ABI and Itanium manglings are in inverted scopes.  In the case of a
1235
      // RecordDecl, mangle the entire scope hierarchy at this point rather than
1236
      // just the unqualified name to get the ordering correct.
1237
58
      if (const auto *RD = dyn_cast<RecordDecl>(DC))
1238
12
        mangleName(RD);
1239
46
      else
1240
46
        Out << '@';
1241
      // void __cdecl
1242
58
      Out << "YAX";
1243
      // struct __block_literal *
1244
58
      Out << 'P';
1245
      // __ptr64
1246
58
      if (PointersAre64Bit)
1247
29
        Out << 'E';
1248
58
      Out << 'A';
1249
58
      mangleArtificialTagType(TTK_Struct,
1250
58
                             Discriminate("__block_literal", Discriminator,
1251
58
                                          ParameterDiscriminator));
1252
58
      Out << "@Z";
1253
1254
      // If the effective context was a Record, we have fully mangled the
1255
      // qualified name and do not need to continue.
1256
58
      if (isa<RecordDecl>(DC))
1257
12
        break;
1258
46
      continue;
1259
15.1k
    } else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
1260
0
      mangleObjCMethodName(Method);
1261
15.1k
    } else if (isa<NamedDecl>(DC)) {
1262
15.1k
      ND = cast<NamedDecl>(DC);
1263
15.1k
      if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1264
538
        mangle(getGlobalDeclAsDeclContext(FD), "?");
1265
538
        break;
1266
14.6k
      } else {
1267
14.6k
        mangleUnqualifiedName(ND);
1268
        // Lambdas in default arguments conceptually belong to the function the
1269
        // parameter corresponds to.
1270
14.6k
        if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(ND)) {
1271
26
          DC = LDADC;
1272
26
          continue;
1273
26
        }
1274
14.6k
      }
1275
15.1k
    }
1276
14.6k
    DC = DC->getParent();
1277
14.6k
  }
1278
41.9k
}
1279
1280
861
void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
1281
  // Microsoft uses the names on the case labels for these dtor variants.  Clang
1282
  // uses the Itanium terminology internally.  Everything in this ABI delegates
1283
  // towards the base dtor.
1284
861
  switch (T) {
1285
  // <operator-name> ::= ?1  # destructor
1286
525
  case Dtor_Base: Out << "?1"; return;
1287
  // <operator-name> ::= ?_D # vbase destructor
1288
120
  case Dtor_Complete: Out << "?_D"; return;
1289
  // <operator-name> ::= ?_G # scalar deleting destructor
1290
216
  case Dtor_Deleting: Out << "?_G"; return;
1291
  // <operator-name> ::= ?_E # vector deleting destructor
1292
  // FIXME: Add a vector deleting dtor type.  It goes in the vtable, so we need
1293
  // it.
1294
0
  case Dtor_Comdat:
1295
0
    llvm_unreachable("not expecting a COMDAT");
1296
861
  }
1297
0
  llvm_unreachable("Unsupported dtor type?");
1298
0
}
1299
1300
void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
1301
1.03k
                                                 SourceLocation Loc) {
1302
1.03k
  switch (OO) {
1303
  //                     ?0 # constructor
1304
  //                     ?1 # destructor
1305
  // <operator-name> ::= ?2 # new
1306
67
  case OO_New: Out << "?2"; break;
1307
  // <operator-name> ::= ?3 # delete
1308
114
  case OO_Delete: Out << "?3"; break;
1309
  // <operator-name> ::= ?4 # =
1310
629
  case OO_Equal: Out << "?4"; break;
1311
  // <operator-name> ::= ?5 # >>
1312
4
  case OO_GreaterGreater: Out << "?5"; break;
1313
  // <operator-name> ::= ?6 # <<
1314
4
  case OO_LessLess: Out << "?6"; break;
1315
  // <operator-name> ::= ?7 # !
1316
0
  case OO_Exclaim: Out << "?7"; break;
1317
  // <operator-name> ::= ?8 # ==
1318
5
  case OO_EqualEqual: Out << "?8"; break;
1319
  // <operator-name> ::= ?9 # !=
1320
0
  case OO_ExclaimEqual: Out << "?9"; break;
1321
  // <operator-name> ::= ?A # []
1322
2
  case OO_Subscript: Out << "?A"; break;
1323
  //                     ?B # conversion
1324
  // <operator-name> ::= ?C # ->
1325
3
  case OO_Arrow: Out << "?C"; break;
1326
  // <operator-name> ::= ?D # *
1327
3
  case OO_Star: Out << "?D"; break;
1328
  // <operator-name> ::= ?E # ++
1329
1
  case OO_PlusPlus: Out << "?E"; break;
1330
  // <operator-name> ::= ?F # --
1331
0
  case OO_MinusMinus: Out << "?F"; break;
1332
  // <operator-name> ::= ?G # -
1333
0
  case OO_Minus: Out << "?G"; break;
1334
  // <operator-name> ::= ?H # +
1335
16
  case OO_Plus: Out << "?H"; break;
1336
  // <operator-name> ::= ?I # &
1337
1
  case OO_Amp: Out << "?I"; break;
1338
  // <operator-name> ::= ?J # ->*
1339
4
  case OO_ArrowStar: Out << "?J"; break;
1340
  // <operator-name> ::= ?K # /
1341
0
  case OO_Slash: Out << "?K"; break;
1342
  // <operator-name> ::= ?L # %
1343
0
  case OO_Percent: Out << "?L"; break;
1344
  // <operator-name> ::= ?M # <
1345
0
  case OO_Less: Out << "?M"; break;
1346
  // <operator-name> ::= ?N # <=
1347
0
  case OO_LessEqual: Out << "?N"; break;
1348
  // <operator-name> ::= ?O # >
1349
0
  case OO_Greater: Out << "?O"; break;
1350
  // <operator-name> ::= ?P # >=
1351
0
  case OO_GreaterEqual: Out << "?P"; break;
1352
  // <operator-name> ::= ?Q # ,
1353
4
  case OO_Comma: Out << "?Q"; break;
1354
  // <operator-name> ::= ?R # ()
1355
100
  case OO_Call: Out << "?R"; break;
1356
  // <operator-name> ::= ?S # ~
1357
0
  case OO_Tilde: Out << "?S"; break;
1358
  // <operator-name> ::= ?T # ^
1359
0
  case OO_Caret: Out << "?T"; break;
1360
  // <operator-name> ::= ?U # |
1361
0
  case OO_Pipe: Out << "?U"; break;
1362
  // <operator-name> ::= ?V # &&
1363
4
  case OO_AmpAmp: Out << "?V"; break;
1364
  // <operator-name> ::= ?W # ||
1365
4
  case OO_PipePipe: Out << "?W"; break;
1366
  // <operator-name> ::= ?X # *=
1367
0
  case OO_StarEqual: Out << "?X"; break;
1368
  // <operator-name> ::= ?Y # +=
1369
6
  case OO_PlusEqual: Out << "?Y"; break;
1370
  // <operator-name> ::= ?Z # -=
1371
0
  case OO_MinusEqual: Out << "?Z"; break;
1372
  // <operator-name> ::= ?_0 # /=
1373
0
  case OO_SlashEqual: Out << "?_0"; break;
1374
  // <operator-name> ::= ?_1 # %=
1375
0
  case OO_PercentEqual: Out << "?_1"; break;
1376
  // <operator-name> ::= ?_2 # >>=
1377
0
  case OO_GreaterGreaterEqual: Out << "?_2"; break;
1378
  // <operator-name> ::= ?_3 # <<=
1379
0
  case OO_LessLessEqual: Out << "?_3"; break;
1380
  // <operator-name> ::= ?_4 # &=
1381
0
  case OO_AmpEqual: Out << "?_4"; break;
1382
  // <operator-name> ::= ?_5 # |=
1383
0
  case OO_PipeEqual: Out << "?_5"; break;
1384
  // <operator-name> ::= ?_6 # ^=
1385
0
  case OO_CaretEqual: Out << "?_6"; break;
1386
  //                     ?_7 # vftable
1387
  //                     ?_8 # vbtable
1388
  //                     ?_9 # vcall
1389
  //                     ?_A # typeof
1390
  //                     ?_B # local static guard
1391
  //                     ?_C # string
1392
  //                     ?_D # vbase destructor
1393
  //                     ?_E # vector deleting destructor
1394
  //                     ?_F # default constructor closure
1395
  //                     ?_G # scalar deleting destructor
1396
  //                     ?_H # vector constructor iterator
1397
  //                     ?_I # vector destructor iterator
1398
  //                     ?_J # vector vbase constructor iterator
1399
  //                     ?_K # virtual displacement map
1400
  //                     ?_L # eh vector constructor iterator
1401
  //                     ?_M # eh vector destructor iterator
1402
  //                     ?_N # eh vector vbase constructor iterator
1403
  //                     ?_O # copy constructor closure
1404
  //                     ?_P<name> # udt returning <name>
1405
  //                     ?_Q # <unknown>
1406
  //                     ?_R0 # RTTI Type Descriptor
1407
  //                     ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
1408
  //                     ?_R2 # RTTI Base Class Array
1409
  //                     ?_R3 # RTTI Class Hierarchy Descriptor
1410
  //                     ?_R4 # RTTI Complete Object Locator
1411
  //                     ?_S # local vftable
1412
  //                     ?_T # local vftable constructor closure
1413
  // <operator-name> ::= ?_U # new[]
1414
27
  case OO_Array_New: Out << "?_U"; break;
1415
  // <operator-name> ::= ?_V # delete[]
1416
26
  case OO_Array_Delete: Out << "?_V"; break;
1417
  // <operator-name> ::= ?__L # co_await
1418
4
  case OO_Coawait: Out << "?__L"; break;
1419
  // <operator-name> ::= ?__M # <=>
1420
6
  case OO_Spaceship: Out << "?__M"; break;
1421
1422
0
  case OO_Conditional: {
1423
0
    DiagnosticsEngine &Diags = Context.getDiags();
1424
0
    unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1425
0
      "cannot mangle this conditional operator yet");
1426
0
    Diags.Report(Loc, DiagID);
1427
0
    break;
1428
0
  }
1429
1430
0
  case OO_None:
1431
0
  case NUM_OVERLOADED_OPERATORS:
1432
0
    llvm_unreachable("Not an overloaded operator");
1433
1.03k
  }
1434
1.03k
}
1435
1436
79.5k
void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) {
1437
  // <source name> ::= <identifier> @
1438
79.5k
  BackRefVec::iterator Found = llvm::find(NameBackReferences, Name);
1439
79.5k
  if (Found == NameBackReferences.end()) {
1440
66.7k
    if (NameBackReferences.size() < 10)
1441
66.7k
      NameBackReferences.push_back(std::string(Name));
1442
66.7k
    Out << Name << '@';
1443
66.7k
  } else {
1444
12.8k
    Out << (Found - NameBackReferences.begin());
1445
12.8k
  }
1446
79.5k
}
1447
1448
0
void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1449
0
  Context.mangleObjCMethodNameAsSourceName(MD, Out);
1450
0
}
1451
1452
void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
1453
3.60k
    GlobalDecl GD, const TemplateArgumentList &TemplateArgs) {
1454
  // <template-name> ::= <unscoped-template-name> <template-args>
1455
  //                 ::= <substitution>
1456
  // Always start with the unqualified name.
1457
1458
  // Templates have their own context for back references.
1459
3.60k
  ArgBackRefMap OuterFunArgsContext;
1460
3.60k
  ArgBackRefMap OuterTemplateArgsContext;
1461
3.60k
  BackRefVec OuterTemplateContext;
1462
3.60k
  PassObjectSizeArgsSet OuterPassObjectSizeArgs;
1463
3.60k
  NameBackReferences.swap(OuterTemplateContext);
1464
3.60k
  FunArgBackReferences.swap(OuterFunArgsContext);
1465
3.60k
  TemplateArgBackReferences.swap(OuterTemplateArgsContext);
1466
3.60k
  PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
1467
1468
3.60k
  mangleUnscopedTemplateName(GD);
1469
3.60k
  mangleTemplateArgs(cast<TemplateDecl>(GD.getDecl()), TemplateArgs);
1470
1471
  // Restore the previous back reference contexts.
1472
3.60k
  NameBackReferences.swap(OuterTemplateContext);
1473
3.60k
  FunArgBackReferences.swap(OuterFunArgsContext);
1474
3.60k
  TemplateArgBackReferences.swap(OuterTemplateArgsContext);
1475
3.60k
  PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
1476
3.60k
}
1477
1478
3.60k
void MicrosoftCXXNameMangler::mangleUnscopedTemplateName(GlobalDecl GD) {
1479
  // <unscoped-template-name> ::= ?$ <unqualified-name>
1480
3.60k
  Out << "?$";
1481
3.60k
  mangleUnqualifiedName(GD);
1482
3.60k
}
1483
1484
void MicrosoftCXXNameMangler::mangleIntegerLiteral(
1485
    const llvm::APSInt &Value, const NonTypeTemplateParmDecl *PD,
1486
672
    QualType TemplateArgType) {
1487
  // <integer-literal> ::= $0 <number>
1488
672
  Out << "$";
1489
1490
  // Since MSVC 2019, add 'M[<type>]' after '$' for auto template parameter when
1491
  // argument is integer.
1492
672
  if (getASTContext().getLangOpts().isCompatibleWithMSVC(
1493
672
          LangOptions::MSVC2019) &&
1494
672
      
PD27
&&
PD->getType()->getTypeClass() == Type::Auto27
&&
1495
672
      
!TemplateArgType.isNull()11
) {
1496
11
    Out << "M";
1497
11
    mangleType(TemplateArgType, SourceRange(), QMM_Drop);
1498
11
  }
1499
1500
672
  Out << "0";
1501
1502
672
  mangleNumber(Value);
1503
672
}
1504
1505
void MicrosoftCXXNameMangler::mangleExpression(
1506
0
    const Expr *E, const NonTypeTemplateParmDecl *PD) {
1507
  // See if this is a constant expression.
1508
0
  if (Optional<llvm::APSInt> Value =
1509
0
          E->getIntegerConstantExpr(Context.getASTContext())) {
1510
0
    mangleIntegerLiteral(*Value, PD, E->getType());
1511
0
    return;
1512
0
  }
1513
1514
  // As bad as this diagnostic is, it's better than crashing.
1515
0
  DiagnosticsEngine &Diags = Context.getDiags();
1516
0
  unsigned DiagID = Diags.getCustomDiagID(
1517
0
      DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
1518
0
  Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
1519
0
                                        << E->getSourceRange();
1520
0
}
1521
1522
void MicrosoftCXXNameMangler::mangleTemplateArgs(
1523
3.60k
    const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1524
  // <template-args> ::= <template-arg>+
1525
3.60k
  const TemplateParameterList *TPL = TD->getTemplateParameters();
1526
3.60k
  assert(TPL->size() == TemplateArgs.size() &&
1527
3.60k
         "size mismatch between args and parms!");
1528
1529
11.2k
  for (size_t i = 0; i < TemplateArgs.size(); 
++i7.69k
) {
1530
7.69k
    const TemplateArgument &TA = TemplateArgs[i];
1531
1532
    // Separate consecutive packs by $$Z.
1533
7.69k
    if (i > 0 && 
TA.getKind() == TemplateArgument::Pack4.08k
&&
1534
7.69k
        
TemplateArgs[i - 1].getKind() == TemplateArgument::Pack17
)
1535
8
      Out << "$$Z";
1536
1537
7.69k
    mangleTemplateArg(TD, TA, TPL->getParam(i));
1538
7.69k
  }
1539
3.60k
}
1540
1541
void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
1542
                                                const TemplateArgument &TA,
1543
7.83k
                                                const NamedDecl *Parm) {
1544
  // <template-arg> ::= <type>
1545
  //                ::= <integer-literal>
1546
  //                ::= <member-data-pointer>
1547
  //                ::= <member-function-pointer>
1548
  //                ::= $ <constant-value>
1549
  //                ::= <template-args>
1550
  //
1551
  // <constant-value> ::= 0 <number>                   # integer
1552
  //                  ::= 1 <mangled-name>             # address of D
1553
  //                  ::= 2 <type> <typed-constant-value>* @ # struct
1554
  //                  ::= 3 <type> <constant-value>* @ # array
1555
  //                  ::= 4 ???                        # string
1556
  //                  ::= 5 <constant-value> @         # address of subobject
1557
  //                  ::= 6 <constant-value> <unqualified-name> @ # a.b
1558
  //                  ::= 7 <type> [<unqualified-name> <constant-value>] @
1559
  //                      # union, with or without an active member
1560
  //                  # pointer to member, symbolically
1561
  //                  ::= 8 <class> <unqualified-name> @
1562
  //                  ::= A <type> <non-negative integer>  # float
1563
  //                  ::= B <type> <non-negative integer>  # double
1564
  //                  ::= E <mangled-name>             # reference to D
1565
  //                  # pointer to member, by component value
1566
  //                  ::= F <number> <number>
1567
  //                  ::= G <number> <number> <number>
1568
  //                  ::= H <mangled-name> <number>
1569
  //                  ::= I <mangled-name> <number> <number>
1570
  //                  ::= J <mangled-name> <number> <number> <number>
1571
  //
1572
  // <typed-constant-value> ::= [<type>] <constant-value>
1573
  //
1574
  // The <type> appears to be included in a <typed-constant-value> only in the
1575
  // '0', '1', '8', 'A', 'B', and 'E' cases.
1576
1577
7.83k
  switch (TA.getKind()) {
1578
0
  case TemplateArgument::Null:
1579
0
    llvm_unreachable("Can't mangle null template arguments!");
1580
0
  case TemplateArgument::TemplateExpansion:
1581
0
    llvm_unreachable("Can't mangle template expansion arguments!");
1582
7.25k
  case TemplateArgument::Type: {
1583
7.25k
    QualType T = TA.getAsType();
1584
7.25k
    mangleType(T, SourceRange(), QMM_Escape);
1585
7.25k
    break;
1586
0
  }
1587
132
  case TemplateArgument::Declaration: {
1588
132
    const NamedDecl *ND = TA.getAsDecl();
1589
132
    if (isa<FieldDecl>(ND) || 
isa<IndirectFieldDecl>(ND)123
) {
1590
11
      mangleMemberDataPointer(cast<CXXRecordDecl>(ND->getDeclContext())
1591
11
                                  ->getMostRecentNonInjectedDecl(),
1592
11
                              cast<ValueDecl>(ND));
1593
121
    } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1594
37
      const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1595
37
      if (MD && 
MD->isInstance()17
) {
1596
15
        mangleMemberFunctionPointer(
1597
15
            MD->getParent()->getMostRecentNonInjectedDecl(), MD);
1598
22
      } else {
1599
22
        Out << "$1?";
1600
22
        mangleName(FD);
1601
22
        mangleFunctionEncoding(FD, /*ShouldMangle=*/true);
1602
22
      }
1603
84
    } else if (TA.getParamTypeForDecl()->isRecordType()) {
1604
55
      Out << "$";
1605
55
      auto *TPO = cast<TemplateParamObjectDecl>(ND);
1606
55
      mangleTemplateArgValue(TPO->getType().getUnqualifiedType(),
1607
55
                             TPO->getValue());
1608
55
    } else {
1609
29
      mangle(ND, TA.getParamTypeForDecl()->isReferenceType() ? 
"$E?"10
:
"$1?"19
);
1610
29
    }
1611
132
    break;
1612
0
  }
1613
340
  case TemplateArgument::Integral: {
1614
340
    QualType T = TA.getIntegralType();
1615
340
    mangleIntegerLiteral(TA.getAsIntegral(),
1616
340
                         cast<NonTypeTemplateParmDecl>(Parm), T);
1617
340
    break;
1618
0
  }
1619
23
  case TemplateArgument::NullPtr: {
1620
23
    QualType T = TA.getNullPtrType();
1621
23
    if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
1622
19
      const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1623
19
      if (MPT->isMemberFunctionPointerType() &&
1624
19
          
!isa<FunctionTemplateDecl>(TD)8
) {
1625
4
        mangleMemberFunctionPointer(RD, nullptr);
1626
4
        return;
1627
4
      }
1628
15
      if (MPT->isMemberDataPointer()) {
1629
11
        if (!isa<FunctionTemplateDecl>(TD)) {
1630
6
          mangleMemberDataPointer(RD, nullptr);
1631
6
          return;
1632
6
        }
1633
        // nullptr data pointers are always represented with a single field
1634
        // which is initialized with either 0 or -1.  Why -1?  Well, we need to
1635
        // distinguish the case where the data member is at offset zero in the
1636
        // record.
1637
        // However, we are free to use 0 *if* we would use multiple fields for
1638
        // non-nullptr member pointers.
1639
5
        if (!RD->nullFieldOffsetIsZero()) {
1640
1
          mangleIntegerLiteral(llvm::APSInt::get(-1),
1641
1
                               cast<NonTypeTemplateParmDecl>(Parm), T);
1642
1
          return;
1643
1
        }
1644
5
      }
1645
15
    }
1646
12
    mangleIntegerLiteral(llvm::APSInt::getUnsigned(0),
1647
12
                         cast<NonTypeTemplateParmDecl>(Parm), T);
1648
12
    break;
1649
23
  }
1650
0
  case TemplateArgument::Expression:
1651
0
    mangleExpression(TA.getAsExpr(), cast<NonTypeTemplateParmDecl>(Parm));
1652
0
    break;
1653
62
  case TemplateArgument::Pack: {
1654
62
    ArrayRef<TemplateArgument> TemplateArgs = TA.getPackAsArray();
1655
62
    if (TemplateArgs.empty()) {
1656
13
      if (isa<TemplateTypeParmDecl>(Parm) ||
1657
13
          
isa<TemplateTemplateParmDecl>(Parm)6
)
1658
        // MSVC 2015 changed the mangling for empty expanded template packs,
1659
        // use the old mangling for link compatibility for old versions.
1660
10
        Out << (Context.getASTContext().getLangOpts().isCompatibleWithMSVC(
1661
10
                    LangOptions::MSVC2015)
1662
10
                    ? 
"$$V"6
1663
10
                    : 
"$$$V"4
);
1664
3
      else if (isa<NonTypeTemplateParmDecl>(Parm))
1665
3
        Out << "$S";
1666
0
      else
1667
0
        llvm_unreachable("unexpected template parameter decl!");
1668
49
    } else {
1669
49
      for (const TemplateArgument &PA : TemplateArgs)
1670
140
        mangleTemplateArg(TD, PA, Parm);
1671
49
    }
1672
62
    break;
1673
23
  }
1674
19
  case TemplateArgument::Template: {
1675
19
    const NamedDecl *ND =
1676
19
        TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl();
1677
19
    if (const auto *TD = dyn_cast<TagDecl>(ND)) {
1678
16
      mangleType(TD);
1679
16
    } else 
if (3
isa<TypeAliasDecl>(ND)3
) {
1680
3
      Out << "$$Y";
1681
3
      mangleName(ND);
1682
3
    } else {
1683
0
      llvm_unreachable("unexpected template template NamedDecl!");
1684
0
    }
1685
19
    break;
1686
23
  }
1687
7.83k
  }
1688
7.83k
}
1689
1690
void MicrosoftCXXNameMangler::mangleTemplateArgValue(QualType T,
1691
                                                     const APValue &V,
1692
348
                                                     bool WithScalarType) {
1693
348
  switch (V.getKind()) {
1694
0
  case APValue::None:
1695
0
  case APValue::Indeterminate:
1696
    // FIXME: MSVC doesn't allow this, so we can't be sure how it should be
1697
    // mangled.
1698
0
    if (WithScalarType)
1699
0
      mangleType(T, SourceRange(), QMM_Escape);
1700
0
    Out << '@';
1701
0
    return;
1702
1703
202
  case APValue::Int:
1704
202
    if (WithScalarType)
1705
58
      mangleType(T, SourceRange(), QMM_Escape);
1706
202
    Out << '0';
1707
202
    mangleNumber(V.getInt());
1708
202
    return;
1709
1710
22
  case APValue::Float:
1711
22
    if (WithScalarType)
1712
15
      mangleType(T, SourceRange(), QMM_Escape);
1713
22
    mangleFloat(V.getFloat());
1714
22
    return;
1715
1716
8
  case APValue::LValue: {
1717
8
    if (WithScalarType)
1718
8
      mangleType(T, SourceRange(), QMM_Escape);
1719
1720
    // We don't know how to mangle past-the-end pointers yet.
1721
8
    if (V.isLValueOnePastTheEnd())
1722
0
      break;
1723
1724
8
    APValue::LValueBase Base = V.getLValueBase();
1725
8
    if (!V.hasLValuePath() || 
V.getLValuePath().empty()7
) {
1726
      // Taking the address of a complete object has a special-case mangling.
1727
5
      if (Base.isNull()) {
1728
        // MSVC emits 0A@ for null pointers. Generalize this for arbitrary
1729
        // integers cast to pointers.
1730
        // FIXME: This mangles 0 cast to a pointer the same as a null pointer,
1731
        // even in cases where the two are different values.
1732
4
        Out << "0";
1733
4
        mangleNumber(V.getLValueOffset().getQuantity());
1734
4
      } else 
if (1
!V.hasLValuePath()1
) {
1735
        // FIXME: This can only happen as an extension. Invent a mangling.
1736
0
        break;
1737
1
      } else if (auto *VD = Base.dyn_cast<const ValueDecl*>()) {
1738
1
        Out << (T->isReferenceType() ? 
"E"0
: "1");
1739
1
        mangle(VD);
1740
1
      } else {
1741
0
        break;
1742
0
      }
1743
5
    } else {
1744
3
      unsigned NumAts = 0;
1745
3
      if (T->isPointerType()) {
1746
2
        Out << "5";
1747
2
        ++NumAts;
1748
2
      }
1749
1750
3
      QualType T = Base.getType();
1751
3
      for (APValue::LValuePathEntry E : V.getLValuePath()) {
1752
        // We don't know how to mangle array subscripting yet.
1753
3
        if (T->isArrayType())
1754
0
          goto mangling_unknown;
1755
1756
3
        const Decl *D = E.getAsBaseOrMember().getPointer();
1757
3
        auto *FD = dyn_cast<FieldDecl>(D);
1758
        // We don't know how to mangle derived-to-base conversions yet.
1759
3
        if (!FD)
1760
0
          goto mangling_unknown;
1761
1762
3
        Out << "6";
1763
3
        ++NumAts;
1764
3
        T = FD->getType();
1765
3
      }
1766
1767
3
      auto *VD = Base.dyn_cast<const ValueDecl*>();
1768
3
      if (!VD)
1769
0
        break;
1770
3
      Out << "E";
1771
3
      mangle(VD);
1772
1773
3
      for (APValue::LValuePathEntry E : V.getLValuePath()) {
1774
3
        const Decl *D = E.getAsBaseOrMember().getPointer();
1775
3
        mangleUnqualifiedName(cast<FieldDecl>(D));
1776
3
      }
1777
8
      for (unsigned I = 0; I != NumAts; 
++I5
)
1778
5
        Out << '@';
1779
3
    }
1780
1781
8
    return;
1782
8
  }
1783
1784
8
  case APValue::MemberPointer: {
1785
3
    if (WithScalarType)
1786
3
      mangleType(T, SourceRange(), QMM_Escape);
1787
1788
    // FIXME: The below manglings don't include a conversion, so bail if there
1789
    // would be one. MSVC mangles the (possibly converted) value of the
1790
    // pointer-to-member object as if it were a struct, leading to collisions
1791
    // in some cases.
1792
3
    if (!V.getMemberPointerPath().empty())
1793
0
      break;
1794
1795
3
    const CXXRecordDecl *RD =
1796
3
        T->castAs<MemberPointerType>()->getMostRecentCXXRecordDecl();
1797
3
    const ValueDecl *D = V.getMemberPointerDecl();
1798
3
    if (T->isMemberDataPointerType())
1799
3
      mangleMemberDataPointer(RD, D, "");
1800
0
    else
1801
0
      mangleMemberFunctionPointer(RD, cast_or_null<CXXMethodDecl>(D), "");
1802
3
    return;
1803
3
  }
1804
1805
64
  case APValue::Struct: {
1806
64
    Out << '2';
1807
64
    mangleType(T, SourceRange(), QMM_Escape);
1808
64
    const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
1809
64
    assert(RD && "unexpected type for record value");
1810
1811
0
    unsigned BaseIndex = 0;
1812
64
    for (const CXXBaseSpecifier &B : RD->bases())
1813
10
      mangleTemplateArgValue(B.getType(), V.getStructBase(BaseIndex++));
1814
64
    for (const FieldDecl *FD : RD->fields())
1815
133
      if (!FD->isUnnamedBitfield())
1816
121
        mangleTemplateArgValue(FD->getType(),
1817
121
                               V.getStructField(FD->getFieldIndex()),
1818
121
                               /*WithScalarType*/ true);
1819
64
    Out << '@';
1820
64
    return;
1821
3
  }
1822
1823
10
  case APValue::Union:
1824
10
    Out << '7';
1825
10
    mangleType(T, SourceRange(), QMM_Escape);
1826
10
    if (const FieldDecl *FD = V.getUnionField()) {
1827
6
      mangleUnqualifiedName(FD);
1828
6
      mangleTemplateArgValue(FD->getType(), V.getUnionValue());
1829
6
    }
1830
10
    Out << '@';
1831
10
    return;
1832
1833
8
  case APValue::ComplexInt:
1834
    // We mangle complex types as structs, so mangle the value as a struct too.
1835
8
    Out << '2';
1836
8
    mangleType(T, SourceRange(), QMM_Escape);
1837
8
    Out << '0';
1838
8
    mangleNumber(V.getComplexIntReal());
1839
8
    Out << '0';
1840
8
    mangleNumber(V.getComplexIntImag());
1841
8
    Out << '@';
1842
8
    return;
1843
1844
8
  case APValue::ComplexFloat:
1845
8
    Out << '2';
1846
8
    mangleType(T, SourceRange(), QMM_Escape);
1847
8
    mangleFloat(V.getComplexFloatReal());
1848
8
    mangleFloat(V.getComplexFloatImag());
1849
8
    Out << '@';
1850
8
    return;
1851
1852
12
  case APValue::Array: {
1853
12
    Out << '3';
1854
12
    QualType ElemT = getASTContext().getAsArrayType(T)->getElementType();
1855
12
    mangleType(ElemT, SourceRange(), QMM_Escape);
1856
133
    for (unsigned I = 0, N = V.getArraySize(); I != N; 
++I121
) {
1857
121
      const APValue &ElemV = I < V.getArrayInitializedElts()
1858
121
                                 ? 
V.getArrayInitializedElt(I)52
1859
121
                                 : 
V.getArrayFiller()69
;
1860
121
      mangleTemplateArgValue(ElemT, ElemV);
1861
121
      Out << '@';
1862
121
    }
1863
12
    Out << '@';
1864
12
    return;
1865
3
  }
1866
1867
11
  case APValue::Vector: {
1868
    // __m128 is mangled as a struct containing an array. We follow this
1869
    // approach for all vector types.
1870
11
    Out << '2';
1871
11
    mangleType(T, SourceRange(), QMM_Escape);
1872
11
    Out << '3';
1873
11
    QualType ElemT = T->castAs<VectorType>()->getElementType();
1874
11
    mangleType(ElemT, SourceRange(), QMM_Escape);
1875
43
    for (unsigned I = 0, N = V.getVectorLength(); I != N; 
++I32
) {
1876
32
      const APValue &ElemV = V.getVectorElt(I);
1877
32
      mangleTemplateArgValue(ElemT, ElemV);
1878
32
      Out << '@';
1879
32
    }
1880
11
    Out << "@@";
1881
11
    return;
1882
3
  }
1883
1884
0
  case APValue::AddrLabelDiff:
1885
0
  case APValue::FixedPoint:
1886
0
    break;
1887
348
  }
1888
1889
0
mangling_unknown:
1890
0
  DiagnosticsEngine &Diags = Context.getDiags();
1891
0
  unsigned DiagID = Diags.getCustomDiagID(
1892
0
      DiagnosticsEngine::Error, "cannot mangle this template argument yet");
1893
0
  Diags.Report(DiagID);
1894
0
}
1895
1896
15
void MicrosoftCXXNameMangler::mangleObjCProtocol(const ObjCProtocolDecl *PD) {
1897
15
  llvm::SmallString<64> TemplateMangling;
1898
15
  llvm::raw_svector_ostream Stream(TemplateMangling);
1899
15
  MicrosoftCXXNameMangler Extra(Context, Stream);
1900
1901
15
  Stream << "?$";
1902
15
  Extra.mangleSourceName("Protocol");
1903
15
  Extra.mangleArtificialTagType(TTK_Struct, PD->getName());
1904
1905
15
  mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__ObjC"});
1906
15
}
1907
1908
void MicrosoftCXXNameMangler::mangleObjCLifetime(const QualType Type,
1909
                                                 Qualifiers Quals,
1910
9
                                                 SourceRange Range) {
1911
9
  llvm::SmallString<64> TemplateMangling;
1912
9
  llvm::raw_svector_ostream Stream(TemplateMangling);
1913
9
  MicrosoftCXXNameMangler Extra(Context, Stream);
1914
1915
9
  Stream << "?$";
1916
9
  switch (Quals.getObjCLifetime()) {
1917
0
  case Qualifiers::OCL_None:
1918
0
  case Qualifiers::OCL_ExplicitNone:
1919
0
    break;
1920
2
  case Qualifiers::OCL_Autoreleasing:
1921
2
    Extra.mangleSourceName("Autoreleasing");
1922
2
    break;
1923
4
  case Qualifiers::OCL_Strong:
1924
4
    Extra.mangleSourceName("Strong");
1925
4
    break;
1926
3
  case Qualifiers::OCL_Weak:
1927
3
    Extra.mangleSourceName("Weak");
1928
3
    break;
1929
9
  }
1930
9
  Extra.manglePointerCVQualifiers(Quals);
1931
9
  Extra.manglePointerExtQualifiers(Quals, Type);
1932
9
  Extra.mangleType(Type, Range);
1933
1934
9
  mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__ObjC"});
1935
9
}
1936
1937
void MicrosoftCXXNameMangler::mangleObjCKindOfType(const ObjCObjectType *T,
1938
                                                   Qualifiers Quals,
1939
7
                                                   SourceRange Range) {
1940
7
  llvm::SmallString<64> TemplateMangling;
1941
7
  llvm::raw_svector_ostream Stream(TemplateMangling);
1942
7
  MicrosoftCXXNameMangler Extra(Context, Stream);
1943
1944
7
  Stream << "?$";
1945
7
  Extra.mangleSourceName("KindOf");
1946
7
  Extra.mangleType(QualType(T, 0)
1947
7
                       .stripObjCKindOfType(getASTContext())
1948
7
                       ->castAs<ObjCObjectType>(),
1949
7
                   Quals, Range);
1950
1951
7
  mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__ObjC"});
1952
7
}
1953
1954
void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
1955
28.1k
                                               bool IsMember) {
1956
  // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
1957
  // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
1958
  // 'I' means __restrict (32/64-bit).
1959
  // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
1960
  // keyword!
1961
  // <base-cvr-qualifiers> ::= A  # near
1962
  //                       ::= B  # near const
1963
  //                       ::= C  # near volatile
1964
  //                       ::= D  # near const volatile
1965
  //                       ::= E  # far (16-bit)
1966
  //                       ::= F  # far const (16-bit)
1967
  //                       ::= G  # far volatile (16-bit)
1968
  //                       ::= H  # far const volatile (16-bit)
1969
  //                       ::= I  # huge (16-bit)
1970
  //                       ::= J  # huge const (16-bit)
1971
  //                       ::= K  # huge volatile (16-bit)
1972
  //                       ::= L  # huge const volatile (16-bit)
1973
  //                       ::= M <basis> # based
1974
  //                       ::= N <basis> # based const
1975
  //                       ::= O <basis> # based volatile
1976
  //                       ::= P <basis> # based const volatile
1977
  //                       ::= Q  # near member
1978
  //                       ::= R  # near const member
1979
  //                       ::= S  # near volatile member
1980
  //                       ::= T  # near const volatile member
1981
  //                       ::= U  # far member (16-bit)
1982
  //                       ::= V  # far const member (16-bit)
1983
  //                       ::= W  # far volatile member (16-bit)
1984
  //                       ::= X  # far const volatile member (16-bit)
1985
  //                       ::= Y  # huge member (16-bit)
1986
  //                       ::= Z  # huge const member (16-bit)
1987
  //                       ::= 0  # huge volatile member (16-bit)
1988
  //                       ::= 1  # huge const volatile member (16-bit)
1989
  //                       ::= 2 <basis> # based member
1990
  //                       ::= 3 <basis> # based const member
1991
  //                       ::= 4 <basis> # based volatile member
1992
  //                       ::= 5 <basis> # based const volatile member
1993
  //                       ::= 6  # near function (pointers only)
1994
  //                       ::= 7  # far function (pointers only)
1995
  //                       ::= 8  # near method (pointers only)
1996
  //                       ::= 9  # far method (pointers only)
1997
  //                       ::= _A <basis> # based function (pointers only)
1998
  //                       ::= _B <basis> # based function (far?) (pointers only)
1999
  //                       ::= _C <basis> # based method (pointers only)
2000
  //                       ::= _D <basis> # based method (far?) (pointers only)
2001
  //                       ::= _E # block (Clang)
2002
  // <basis> ::= 0 # __based(void)
2003
  //         ::= 1 # __based(segment)?
2004
  //         ::= 2 <name> # __based(name)
2005
  //         ::= 3 # ?
2006
  //         ::= 4 # ?
2007
  //         ::= 5 # not really based
2008
28.1k
  bool HasConst = Quals.hasConst(),
2009
28.1k
       HasVolatile = Quals.hasVolatile();
2010
2011
28.1k
  if (!IsMember) {
2012
27.8k
    if (HasConst && 
HasVolatile3.47k
) {
2013
29
      Out << 'D';
2014
27.8k
    } else if (HasVolatile) {
2015
90
      Out << 'C';
2016
27.7k
    } else if (HasConst) {
2017
3.45k
      Out << 'B';
2018
24.3k
    } else {
2019
24.3k
      Out << 'A';
2020
24.3k
    }
2021
27.8k
  } else {
2022
242
    if (HasConst && 
HasVolatile15
) {
2023
6
      Out << 'T';
2024
236
    } else if (HasVolatile) {
2025
24
      Out << 'S';
2026
212
    } else if (HasConst) {
2027
9
      Out << 'R';
2028
203
    } else {
2029
203
      Out << 'Q';
2030
203
    }
2031
242
  }
2032
2033
  // FIXME: For now, just drop all extension qualifiers on the floor.
2034
28.1k
}
2035
2036
void
2037
5.90k
MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2038
  // <ref-qualifier> ::= G                # lvalue reference
2039
  //                 ::= H                # rvalue-reference
2040
5.90k
  switch (RefQualifier) {
2041
5.86k
  case RQ_None:
2042
5.86k
    break;
2043
2044
19
  case RQ_LValue:
2045
19
    Out << 'G';
2046
19
    break;
2047
2048
19
  case RQ_RValue:
2049
19
    Out << 'H';
2050
19
    break;
2051
5.90k
  }
2052
5.90k
}
2053
2054
void MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals,
2055
13.2k
                                                         QualType PointeeType) {
2056
  // Check if this is a default 64-bit pointer or has __ptr64 qualifier.
2057
13.2k
  bool is64Bit = PointeeType.isNull() ? 
PointersAre64Bit6.86k
:
2058
13.2k
      
is64BitPointer(PointeeType.getQualifiers())6.40k
;
2059
13.2k
  if (is64Bit && 
(5.81k
PointeeType.isNull()5.81k
||
!PointeeType->isFunctionType()2.65k
))
2060
5.60k
    Out << 'E';
2061
2062
13.2k
  if (Quals.hasRestrict())
2063
40
    Out << 'I';
2064
2065
13.2k
  if (Quals.hasUnaligned() ||
2066
13.2k
      
(13.2k
!PointeeType.isNull()13.2k
&&
PointeeType.getLocalQualifiers().hasUnaligned()6.39k
))
2067
40
    Out << 'F';
2068
13.2k
}
2069
2070
4.72k
void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
2071
  // <pointer-cv-qualifiers> ::= P  # no qualifiers
2072
  //                         ::= Q  # const
2073
  //                         ::= R  # volatile
2074
  //                         ::= S  # const volatile
2075
4.72k
  bool HasConst = Quals.hasConst(),
2076
4.72k
       HasVolatile = Quals.hasVolatile();
2077
2078
4.72k
  if (HasConst && 
HasVolatile219
) {
2079
7
    Out << 'S';
2080
4.71k
  } else if (HasVolatile) {
2081
45
    Out << 'R';
2082
4.67k
  } else if (HasConst) {
2083
212
    Out << 'Q';
2084
4.45k
  } else {
2085
4.45k
    Out << 'P';
2086
4.45k
  }
2087
4.72k
}
2088
2089
void MicrosoftCXXNameMangler::mangleFunctionArgumentType(QualType T,
2090
38.5k
                                                         SourceRange Range) {
2091
  // MSVC will backreference two canonically equivalent types that have slightly
2092
  // different manglings when mangled alone.
2093
2094
  // Decayed types do not match up with non-decayed versions of the same type.
2095
  //
2096
  // e.g.
2097
  // void (*x)(void) will not form a backreference with void x(void)
2098
38.5k
  void *TypePtr;
2099
38.5k
  if (const auto *DT = T->getAs<DecayedType>()) {
2100
165
    QualType OriginalType = DT->getOriginalType();
2101
    // All decayed ArrayTypes should be treated identically; as-if they were
2102
    // a decayed IncompleteArrayType.
2103
165
    if (const auto *AT = getASTContext().getAsArrayType(OriginalType))
2104
83
      OriginalType = getASTContext().getIncompleteArrayType(
2105
83
          AT->getElementType(), AT->getSizeModifier(),
2106
83
          AT->getIndexTypeCVRQualifiers());
2107
2108
165
    TypePtr = OriginalType.getCanonicalType().getAsOpaquePtr();
2109
    // If the original parameter was textually written as an array,
2110
    // instead treat the decayed parameter like it's const.
2111
    //
2112
    // e.g.
2113
    // int [] -> int * const
2114
165
    if (OriginalType->isArrayType())
2115
83
      T = T.withConst();
2116
38.3k
  } else {
2117
38.3k
    TypePtr = T.getCanonicalType().getAsOpaquePtr();
2118
38.3k
  }
2119
2120
38.5k
  ArgBackRefMap::iterator Found = FunArgBackReferences.find(TypePtr);
2121
2122
38.5k
  if (Found == FunArgBackReferences.end()) {
2123
28.4k
    size_t OutSizeBefore = Out.tell();
2124
2125
28.4k
    mangleType(T, Range, QMM_Drop);
2126
2127
    // See if it's worth creating a back reference.
2128
    // Only types longer than 1 character are considered
2129
    // and only 10 back references slots are available:
2130
28.4k
    bool LongerThanOneChar = (Out.tell() - OutSizeBefore > 1);
2131
28.4k
    if (LongerThanOneChar && 
FunArgBackReferences.size() < 1018.1k
) {
2132
18.1k
      size_t Size = FunArgBackReferences.size();
2133
18.1k
      FunArgBackReferences[TypePtr] = Size;
2134
18.1k
    }
2135
28.4k
  } else {
2136
10.1k
    Out << Found->second;
2137
10.1k
  }
2138
38.5k
}
2139
2140
void MicrosoftCXXNameMangler::manglePassObjectSizeArg(
2141
34
    const PassObjectSizeAttr *POSA) {
2142
34
  int Type = POSA->getType();
2143
34
  bool Dynamic = POSA->isDynamic();
2144
2145
34
  auto Iter = PassObjectSizeArgs.insert({Type, Dynamic}).first;
2146
34
  auto *TypePtr = (const void *)&*Iter;
2147
34
  ArgBackRefMap::iterator Found = FunArgBackReferences.find(TypePtr);
2148
2149
34
  if (Found == FunArgBackReferences.end()) {
2150
31
    std::string Name =
2151
31
        Dynamic ? 
"__pass_dynamic_object_size"3
:
"__pass_object_size"28
;
2152
31
    mangleArtificialTagType(TTK_Enum, Name + llvm::utostr(Type), {"__clang"});
2153
2154
31
    if (FunArgBackReferences.size() < 10) {
2155
31
      size_t Size = FunArgBackReferences.size();
2156
31
      FunArgBackReferences[TypePtr] = Size;
2157
31
    }
2158
31
  } else {
2159
3
    Out << Found->second;
2160
3
  }
2161
34
}
2162
2163
void MicrosoftCXXNameMangler::mangleAddressSpaceType(QualType T,
2164
                                                     Qualifiers Quals,
2165
25
                                                     SourceRange Range) {
2166
  // Address space is mangled as an unqualified templated type in the __clang
2167
  // namespace. The demangled version of this is:
2168
  // In the case of a language specific address space:
2169
  // __clang::struct _AS[language_addr_space]<Type>
2170
  // where:
2171
  //  <language_addr_space> ::= <OpenCL-addrspace> | <CUDA-addrspace>
2172
  //    <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2173
  //                                "private"| "generic" | "device" | "host" ]
2174
  //    <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2175
  //    Note that the above were chosen to match the Itanium mangling for this.
2176
  //
2177
  // In the case of a non-language specific address space:
2178
  //  __clang::struct _AS<TargetAS, Type>
2179
25
  assert(Quals.hasAddressSpace() && "Not valid without address space");
2180
0
  llvm::SmallString<32> ASMangling;
2181
25
  llvm::raw_svector_ostream Stream(ASMangling);
2182
25
  MicrosoftCXXNameMangler Extra(Context, Stream);
2183
25
  Stream << "?$";
2184
2185
25
  LangAS AS = Quals.getAddressSpace();
2186
25
  if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2187
11
    unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
2188
11
    Extra.mangleSourceName("_AS");
2189
11
    Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(TargetAS));
2190
14
  } else {
2191
14
    switch (AS) {
2192
0
    default:
2193
0
      llvm_unreachable("Not a language specific address space");
2194
5
    case LangAS::opencl_global:
2195
5
      Extra.mangleSourceName("_ASCLglobal");
2196
5
      break;
2197
1
    case LangAS::opencl_global_device:
2198
1
      Extra.mangleSourceName("_ASCLdevice");
2199
1
      break;
2200
1
    case LangAS::opencl_global_host:
2201
1
      Extra.mangleSourceName("_ASCLhost");
2202
1
      break;
2203
0
    case LangAS::opencl_local:
2204
0
      Extra.mangleSourceName("_ASCLlocal");
2205
0
      break;
2206
2
    case LangAS::opencl_constant:
2207
2
      Extra.mangleSourceName("_ASCLconstant");
2208
2
      break;
2209
1
    case LangAS::opencl_private:
2210
1
      Extra.mangleSourceName("_ASCLprivate");
2211
1
      break;
2212
4
    case LangAS::opencl_generic:
2213
4
      Extra.mangleSourceName("_ASCLgeneric");
2214
4
      break;
2215
0
    case LangAS::cuda_device:
2216
0
      Extra.mangleSourceName("_ASCUdevice");
2217
0
      break;
2218
0
    case LangAS::cuda_constant:
2219
0
      Extra.mangleSourceName("_ASCUconstant");
2220
0
      break;
2221
0
    case LangAS::cuda_shared:
2222
0
      Extra.mangleSourceName("_ASCUshared");
2223
0
      break;
2224
0
    case LangAS::ptr32_sptr:
2225
0
    case LangAS::ptr32_uptr:
2226
0
    case LangAS::ptr64:
2227
0
      llvm_unreachable("don't mangle ptr address spaces with _AS");
2228
14
    }
2229
14
  }
2230
2231
25
  Extra.mangleType(T, Range, QMM_Escape);
2232
25
  mangleQualifiers(Qualifiers(), false);
2233
25
  mangleArtificialTagType(TTK_Struct, ASMangling, {"__clang"});
2234
25
}
2235
2236
void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
2237
69.1k
                                         QualifierMangleMode QMM) {
2238
  // Don't use the canonical types.  MSVC includes things like 'const' on
2239
  // pointer arguments to function pointers that canonicalization strips away.
2240
69.1k
  T = T.getDesugaredType(getASTContext());
2241
69.1k
  Qualifiers Quals = T.getLocalQualifiers();
2242
2243
69.1k
  if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
2244
    // If there were any Quals, getAsArrayType() pushed them onto the array
2245
    // element type.
2246
62
    if (QMM == QMM_Mangle)
2247
40
      Out << 'A';
2248
22
    else if (QMM == QMM_Escape || 
QMM == QMM_Result0
)
2249
22
      Out << "$$B";
2250
62
    mangleArrayType(AT);
2251
62
    return;
2252
62
  }
2253
2254
69.1k
  bool IsPointer = T->isAnyPointerType() || 
T->isMemberPointerType()64.9k
||
2255
69.1k
                   
T->isReferenceType()64.5k
||
T->isBlockPointerType()62.7k
;
2256
2257
69.1k
  switch (QMM) {
2258
30.9k
  case QMM_Drop:
2259
30.9k
    if (Quals.hasObjCLifetime())
2260
25
      Quals = Quals.withoutObjCLifetime();
2261
30.9k
    break;
2262
6.37k
  case QMM_Mangle:
2263
6.37k
    if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
2264
190
      Out << '6';
2265
190
      mangleFunctionType(FT);
2266
190
      return;
2267
190
    }
2268
6.18k
    mangleQualifiers(Quals, false);
2269
6.18k
    break;
2270
7.77k
  case QMM_Escape:
2271
7.77k
    if (!IsPointer && 
Quals7.64k
) {
2272
64
      Out << "$$C";
2273
64
      mangleQualifiers(Quals, false);
2274
64
    }
2275
7.77k
    break;
2276
24.0k
  case QMM_Result:
2277
    // Presence of __unaligned qualifier shouldn't affect mangling here.
2278
24.0k
    Quals.removeUnaligned();
2279
24.0k
    if (Quals.hasObjCLifetime())
2280
1
      Quals = Quals.withoutObjCLifetime();
2281
24.0k
    if ((!IsPointer && 
Quals22.4k
) ||
isa<TagType>(T)24.0k
||
isArtificialTagType(T)22.4k
) {
2282
13.2k
      Out << '?';
2283
13.2k
      mangleQualifiers(Quals, false);
2284
13.2k
    }
2285
24.0k
    break;
2286
69.1k
  }
2287
2288
68.9k
  const Type *ty = T.getTypePtr();
2289
2290
68.9k
  switch (ty->getTypeClass()) {
2291
0
#define ABSTRACT_TYPE(CLASS, PARENT)
2292
0
#define NON_CANONICAL_TYPE(CLASS, PARENT) \
2293
0
  case Type::CLASS: \
2294
0
    llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2295
0
    return;
2296
0
#define TYPE(CLASS, PARENT) \
2297
68.9k
  case Type::CLASS: \
2298
68.9k
    mangleType(cast<CLASS##Type>(ty), Quals, Range); \
2299
68.9k
    break;
2300
68.9k
#include 
"clang/AST/TypeNodes.inc"0
2301
68.9k
#undef ABSTRACT_TYPE
2302
68.9k
#undef NON_CANONICAL_TYPE
2303
68.9k
#undef TYPE
2304
68.9k
  }
2305
68.9k
}
2306
2307
void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers,
2308
28.4k
                                         SourceRange Range) {
2309
  //  <type>         ::= <builtin-type>
2310
  //  <builtin-type> ::= X  # void
2311
  //                 ::= C  # signed char
2312
  //                 ::= D  # char
2313
  //                 ::= E  # unsigned char
2314
  //                 ::= F  # short
2315
  //                 ::= G  # unsigned short (or wchar_t if it's not a builtin)
2316
  //                 ::= H  # int
2317
  //                 ::= I  # unsigned int
2318
  //                 ::= J  # long
2319
  //                 ::= K  # unsigned long
2320
  //                     L  # <none>
2321
  //                 ::= M  # float
2322
  //                 ::= N  # double
2323
  //                 ::= O  # long double (__float80 is mangled differently)
2324
  //                 ::= _J # long long, __int64
2325
  //                 ::= _K # unsigned long long, __int64
2326
  //                 ::= _L # __int128
2327
  //                 ::= _M # unsigned __int128
2328
  //                 ::= _N # bool
2329
  //                     _O # <array in parameter>
2330
  //                 ::= _Q # char8_t
2331
  //                 ::= _S # char16_t
2332
  //                 ::= _T # __float80 (Intel)
2333
  //                 ::= _U # char32_t
2334
  //                 ::= _W # wchar_t
2335
  //                 ::= _Z # __float80 (Digital Mars)
2336
28.4k
  switch (T->getKind()) {
2337
7.76k
  case BuiltinType::Void:
2338
7.76k
    Out << 'X';
2339
7.76k
    break;
2340
4
  case BuiltinType::SChar:
2341
4
    Out << 'C';
2342
4
    break;
2343
0
  case BuiltinType::Char_U:
2344
1.71k
  case BuiltinType::Char_S:
2345
1.71k
    Out << 'D';
2346
1.71k
    break;
2347
4.77k
  case BuiltinType::UChar:
2348
4.77k
    Out << 'E';
2349
4.77k
    break;
2350
610
  case BuiltinType::Short:
2351
610
    Out << 'F';
2352
610
    break;
2353
1.60k
  case BuiltinType::UShort:
2354
1.60k
    Out << 'G';
2355
1.60k
    break;
2356
8.00k
  case BuiltinType::Int:
2357
8.00k
    Out << 'H';
2358
8.00k
    break;
2359
1.54k
  case BuiltinType::UInt:
2360
1.54k
    Out << 'I';
2361
1.54k
    break;
2362
85
  case BuiltinType::Long:
2363
85
    Out << 'J';
2364
85
    break;
2365
33
  case BuiltinType::ULong:
2366
33
    Out << 'K';
2367
33
    break;
2368
540
  case BuiltinType::Float:
2369
540
    Out << 'M';
2370
540
    break;
2371
479
  case BuiltinType::Double:
2372
479
    Out << 'N';
2373
479
    break;
2374
  // TODO: Determine size and mangle accordingly
2375
12
  case BuiltinType::LongDouble:
2376
12
    Out << 'O';
2377
12
    break;
2378
215
  case BuiltinType::LongLong:
2379
215
    Out << "_J";
2380
215
    break;
2381
597
  case BuiltinType::ULongLong:
2382
597
    Out << "_K";
2383
597
    break;
2384
0
  case BuiltinType::Int128:
2385
0
    Out << "_L";
2386
0
    break;
2387
0
  case BuiltinType::UInt128:
2388
0
    Out << "_M";
2389
0
    break;
2390
115
  case BuiltinType::Bool:
2391
115
    Out << "_N";
2392
115
    break;
2393
3
  case BuiltinType::Char8:
2394
3
    Out << "_Q";
2395
3
    break;
2396
9
  case BuiltinType::Char16:
2397
9
    Out << "_S";
2398
9
    break;
2399
9
  case BuiltinType::Char32:
2400
9
    Out << "_U";
2401
9
    break;
2402
0
  case BuiltinType::WChar_S:
2403
206
  case BuiltinType::WChar_U:
2404
206
    Out << "_W";
2405
206
    break;
2406
2407
0
#define BUILTIN_TYPE(Id, SingletonId)
2408
0
#define PLACEHOLDER_TYPE(Id, SingletonId) \
2409
0
  case BuiltinType::Id:
2410
206
#include "clang/AST/BuiltinTypes.def"
2411
0
  case BuiltinType::Dependent:
2412
0
    llvm_unreachable("placeholder types shouldn't get to name mangling");
2413
2414
35
  case BuiltinType::ObjCId:
2415
35
    mangleArtificialTagType(TTK_Struct, "objc_object");
2416
35
    break;
2417
12
  case BuiltinType::ObjCClass:
2418
12
    mangleArtificialTagType(TTK_Struct, "objc_class");
2419
12
    break;
2420
15
  case BuiltinType::ObjCSel:
2421
15
    mangleArtificialTagType(TTK_Struct, "objc_selector");
2422
15
    break;
2423
2424
0
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2425
0
  case BuiltinType::Id: \
2426
0
    Out << "PAUocl_" #ImgType "_" #Suffix "@@"; \
2427
0
    break;
2428
15
#include "clang/Basic/OpenCLImageTypes.def"
2429
0
  case BuiltinType::OCLSampler:
2430
0
    Out << "PA";
2431
0
    mangleArtificialTagType(TTK_Struct, "ocl_sampler");
2432
0
    break;
2433
0
  case BuiltinType::OCLEvent:
2434
0
    Out << "PA";
2435
0
    mangleArtificialTagType(TTK_Struct, "ocl_event");
2436
0
    break;
2437
0
  case BuiltinType::OCLClkEvent:
2438
0
    Out << "PA";
2439
0
    mangleArtificialTagType(TTK_Struct, "ocl_clkevent");
2440
0
    break;
2441
0
  case BuiltinType::OCLQueue:
2442
0
    Out << "PA";
2443
0
    mangleArtificialTagType(TTK_Struct, "ocl_queue");
2444
0
    break;
2445
0
  case BuiltinType::OCLReserveID:
2446
0
    Out << "PA";
2447
0
    mangleArtificialTagType(TTK_Struct, "ocl_reserveid");
2448
0
    break;
2449
0
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2450
0
  case BuiltinType::Id: \
2451
0
    mangleArtificialTagType(TTK_Struct, "ocl_" #ExtType); \
2452
0
    break;
2453
0
#include "clang/Basic/OpenCLExtensionTypes.def"
2454
2455
16
  case BuiltinType::NullPtr:
2456
16
    Out << "$$T";
2457
16
    break;
2458
2459
1
  case BuiltinType::Float16:
2460
1
    mangleArtificialTagType(TTK_Struct, "_Float16", {"__clang"});
2461
1
    break;
2462
2463
6
  case BuiltinType::Half:
2464
6
    if (!getASTContext().getLangOpts().HLSL)
2465
2
      mangleArtificialTagType(TTK_Struct, "_Half", {"__clang"});
2466
4
    else if (getASTContext().getLangOpts().NativeHalfType)
2467
2
      Out << "$f16@";
2468
2
    else
2469
2
      Out << "$halff@";
2470
6
    break;
2471
2472
0
#define SVE_TYPE(Name, Id, SingletonId) \
2473
49
  case BuiltinType::Id:
2474
49
#include 
"clang/Basic/AArch64SVEACLETypes.def"6
2475
49
#define PPC_VECTOR_TYPE(Name, Id, Size) \
2476
49
  
case BuiltinType::Id:2
2477
49
#include 
"clang/Basic/PPCTypes.def"1
2478
66
#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2479
66
#include 
"clang/Basic/RISCVVTypes.def"1
2480
66
  case BuiltinType::ShortAccum:
2481
1
  case BuiltinType::Accum:
2482
1
  case BuiltinType::LongAccum:
2483
1
  case BuiltinType::UShortAccum:
2484
1
  case BuiltinType::UAccum:
2485
1
  case BuiltinType::ULongAccum:
2486
1
  case BuiltinType::ShortFract:
2487
1
  case BuiltinType::Fract:
2488
1
  case BuiltinType::LongFract:
2489
1
  case BuiltinType::UShortFract:
2490
1
  case BuiltinType::UFract:
2491
1
  case BuiltinType::ULongFract:
2492
1
  case BuiltinType::SatShortAccum:
2493
1
  case BuiltinType::SatAccum:
2494
1
  case BuiltinType::SatLongAccum:
2495
1
  case BuiltinType::SatUShortAccum:
2496
1
  case BuiltinType::SatUAccum:
2497
1
  case BuiltinType::SatULongAccum:
2498
1
  case BuiltinType::SatShortFract:
2499
1
  case BuiltinType::SatFract:
2500
1
  case BuiltinType::SatLongFract:
2501
1
  case BuiltinType::SatUShortFract:
2502
1
  case BuiltinType::SatUFract:
2503
1
  case BuiltinType::SatULongFract:
2504
1
  case BuiltinType::BFloat16:
2505
1
  case BuiltinType::Ibm128:
2506
1
  case BuiltinType::Float128: {
2507
1
    DiagnosticsEngine &Diags = Context.getDiags();
2508
1
    unsigned DiagID = Diags.getCustomDiagID(
2509
1
        DiagnosticsEngine::Error, "cannot mangle this built-in %0 type yet");
2510
1
    Diags.Report(Range.getBegin(), DiagID)
2511
1
        << T->getName(Context.getASTContext().getPrintingPolicy()) << Range;
2512
1
    break;
2513
1
  }
2514
28.4k
  }
2515
28.4k
}
2516
2517
// <type>          ::= <function-type>
2518
void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers,
2519
138
                                         SourceRange) {
2520
  // Structors only appear in decls, so at this point we know it's not a
2521
  // structor type.
2522
  // FIXME: This may not be lambda-friendly.
2523
138
  if (T->getMethodQuals() || 
T->getRefQualifier() != RQ_None102
) {
2524
44
    Out << "$$A8@@";
2525
44
    mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true);
2526
94
  } else {
2527
94
    Out << "$$A6";
2528
94
    mangleFunctionType(T);
2529
94
  }
2530
138
}
2531
void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
2532
0
                                         Qualifiers, SourceRange) {
2533
0
  Out << "$$A6";
2534
0
  mangleFunctionType(T);
2535
0
}
2536
2537
void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
2538
                                                 const FunctionDecl *D,
2539
                                                 bool ForceThisQuals,
2540
25.3k
                                                 bool MangleExceptionSpec) {
2541
  // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
2542
  //                     <return-type> <argument-list> <throw-spec>
2543
25.3k
  const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(T);
2544
2545
25.3k
  SourceRange Range;
2546
25.3k
  if (D) 
Range = D->getSourceRange()24.6k
;
2547
2548
25.3k
  bool IsInLambda = false;
2549
25.3k
  bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false;
2550
25.3k
  CallingConv CC = T->getCallConv();
2551
25.3k
  if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
2552
5.87k
    if (MD->getParent()->isLambda())
2553
117
      IsInLambda = true;
2554
5.87k
    if (MD->isInstance())
2555
5.51k
      HasThisQuals = true;
2556
5.87k
    if (isa<CXXDestructorDecl>(MD)) {
2557
1.03k
      IsStructor = true;
2558
4.84k
    } else if (isa<CXXConstructorDecl>(MD)) {
2559
1.63k
      IsStructor = true;
2560
1.63k
      IsCtorClosure = (StructorType == Ctor_CopyingClosure ||
2561
1.63k
                       
StructorType == Ctor_DefaultClosure1.62k
) &&
2562
1.63k
                      
isStructorDecl(MD)41
;
2563
1.63k
      if (IsCtorClosure)
2564
41
        CC = getASTContext().getDefaultCallingConvention(
2565
41
            /*IsVariadic=*/false, /*IsCXXMethod=*/true);
2566
1.63k
    }
2567
5.87k
  }
2568
2569
  // If this is a C++ instance method, mangle the CVR qualifiers for the
2570
  // this pointer.
2571
25.3k
  if (HasThisQuals) {
2572
5.90k
    Qualifiers Quals = Proto->getMethodQuals();
2573
5.90k
    manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType());
2574
5.90k
    mangleRefQualifier(Proto->getRefQualifier());
2575
5.90k
    mangleQualifiers(Quals, /*IsMember=*/false);
2576
5.90k
  }
2577
2578
25.3k
  mangleCallingConvention(CC);
2579
2580
  // <return-type> ::= <type>
2581
  //               ::= @ # structors (they have no declared return type)
2582
25.3k
  if (IsStructor) {
2583
2.66k
    if (isa<CXXDestructorDecl>(D) && 
isStructorDecl(D)1.03k
) {
2584
      // The scalar deleting destructor takes an extra int argument which is not
2585
      // reflected in the AST.
2586
1.02k
      if (StructorType == Dtor_Deleting) {
2587
386
        Out << (PointersAre64Bit ? 
"PEAXI@Z"165
:
"PAXI@Z"221
);
2588
386
        return;
2589
386
      }
2590
      // The vbase destructor returns void which is not reflected in the AST.
2591
641
      if (StructorType == Dtor_Complete) {
2592
120
        Out << "XXZ";
2593
120
        return;
2594
120
      }
2595
641
    }
2596
2.15k
    if (IsCtorClosure) {
2597
      // Default constructor closure and copy constructor closure both return
2598
      // void.
2599
41
      Out << 'X';
2600
2601
41
      if (StructorType == Ctor_DefaultClosure) {
2602
        // Default constructor closure always has no arguments.
2603
32
        Out << 'X';
2604
32
      } else 
if (9
StructorType == Ctor_CopyingClosure9
) {
2605
        // Copy constructor closure always takes an unqualified reference.
2606
9
        mangleFunctionArgumentType(getASTContext().getLValueReferenceType(
2607
9
                                       Proto->getParamType(0)
2608
9
                                           ->getAs<LValueReferenceType>()
2609
9
                                           ->getPointeeType(),
2610
9
                                       /*SpelledAsLValue=*/true),
2611
9
                                   Range);
2612
9
        Out << '@';
2613
9
      } else {
2614
0
        llvm_unreachable("unexpected constructor closure!");
2615
0
      }
2616
41
      Out << 'Z';
2617
41
      return;
2618
41
    }
2619
2.11k
    Out << '@';
2620
22.6k
  } else if (IsInLambda && 
D117
&&
isa<CXXConversionDecl>(D)117
) {
2621
    // The only lambda conversion operators are to function pointers, which
2622
    // can differ by their calling convention and are typically deduced.  So
2623
    // we make sure that this type gets mangled properly.
2624
13
    mangleType(T->getReturnType(), Range, QMM_Result);
2625
22.6k
  } else {
2626
22.6k
    QualType ResultType = T->getReturnType();
2627
22.6k
    if (IsInLambda && 
isa<CXXConversionDecl>(D)104
) {
2628
      // The only lambda conversion operators are to function pointers, which
2629
      // can differ by their calling convention and are typically deduced.  So
2630
      // we make sure that this type gets mangled properly.
2631
0
      mangleType(ResultType, Range, QMM_Result);
2632
22.6k
    } else if (const auto *AT = dyn_cast_or_null<AutoType>(
2633
22.6k
                   ResultType->getContainedAutoType())) {
2634
76
      Out << '?';
2635
76
      mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
2636
76
      Out << '?';
2637
76
      assert(AT->getKeyword() != AutoTypeKeyword::GNUAutoType &&
2638
76
             "shouldn't need to mangle __auto_type!");
2639
76
      mangleSourceName(AT->isDecltypeAuto() ? 
"<decltype-auto>"0
: "<auto>");
2640
76
      Out << '@';
2641
22.6k
    } else if (IsInLambda) {
2642
60
      Out << '@';
2643
22.5k
    } else {
2644
22.5k
      if (ResultType->isVoidType())
2645
6.26k
        ResultType = ResultType.getUnqualifiedType();
2646
22.5k
      mangleType(ResultType, Range, QMM_Result);
2647
22.5k
    }
2648
22.6k
  }
2649
2650
  // <argument-list> ::= X # void
2651
  //                 ::= <type>+ @
2652
  //                 ::= <type>* Z # varargs
2653
24.8k
  if (!Proto) {
2654
    // Function types without prototypes can arise when mangling a function type
2655
    // within an overloadable function in C. We mangle these as the absence of
2656
    // any parameter types (not even an empty parameter list).
2657
14
    Out << '@';
2658
24.7k
  } else if (Proto->getNumParams() == 0 && 
!Proto->isVariadic()7.65k
) {
2659
7.64k
    Out << 'X';
2660
17.1k
  } else {
2661
    // Happens for function pointer type arguments for example.
2662
55.6k
    for (unsigned I = 0, E = Proto->getNumParams(); I != E; 
++I38.5k
) {
2663
38.5k
      mangleFunctionArgumentType(Proto->getParamType(I), Range);
2664
      // Mangle each pass_object_size parameter as if it's a parameter of enum
2665
      // type passed directly after the parameter with the pass_object_size
2666
      // attribute. The aforementioned enum's name is __pass_object_size, and we
2667
      // pretend it resides in a top-level namespace called __clang.
2668
      //
2669
      // FIXME: Is there a defined extension notation for the MS ABI, or is it
2670
      // necessary to just cross our fingers and hope this type+namespace
2671
      // combination doesn't conflict with anything?
2672
38.5k
      if (D)
2673
38.3k
        if (const auto *P = D->getParamDecl(I)->getAttr<PassObjectSizeAttr>())
2674
34
          manglePassObjectSizeArg(P);
2675
38.5k
    }
2676
    // <builtin-type>      ::= Z  # ellipsis
2677
17.1k
    if (Proto->isVariadic())
2678
46
      Out << 'Z';
2679
17.1k
    else
2680
17.1k
      Out << '@';
2681
17.1k
  }
2682
2683
24.8k
  if (MangleExceptionSpec && 
getASTContext().getLangOpts().CPlusPlus17907
&&
2684
24.8k
      getASTContext().getLangOpts().isCompatibleWithMSVC(
2685
65
          LangOptions::MSVC2017_5))
2686
28
    mangleThrowSpecification(Proto);
2687
24.7k
  else
2688
24.7k
    Out << 'Z';
2689
24.8k
}
2690
2691
24.2k
void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
2692
  // <function-class>  ::= <member-function> E? # E designates a 64-bit 'this'
2693
  //                                            # pointer. in 64-bit mode *all*
2694
  //                                            # 'this' pointers are 64-bit.
2695
  //                   ::= <global-function>
2696
  // <member-function> ::= A # private: near
2697
  //                   ::= B # private: far
2698
  //                   ::= C # private: static near
2699
  //                   ::= D # private: static far
2700
  //                   ::= E # private: virtual near
2701
  //                   ::= F # private: virtual far
2702
  //                   ::= I # protected: near
2703
  //                   ::= J # protected: far
2704
  //                   ::= K # protected: static near
2705
  //                   ::= L # protected: static far
2706
  //                   ::= M # protected: virtual near
2707
  //                   ::= N # protected: virtual far
2708
  //                   ::= Q # public: near
2709
  //                   ::= R # public: far
2710
  //                   ::= S # public: static near
2711
  //                   ::= T # public: static far
2712
  //                   ::= U # public: virtual near
2713
  //                   ::= V # public: virtual far
2714
  // <global-function> ::= Y # global near
2715
  //                   ::= Z # global far
2716
24.2k
  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
2717
5.49k
    bool IsVirtual = MD->isVirtual();
2718
    // When mangling vbase destructor variants, ignore whether or not the
2719
    // underlying destructor was defined to be virtual.
2720
5.49k
    if (isa<CXXDestructorDecl>(MD) && 
isStructorDecl(MD)861
&&
2721
5.49k
        
StructorType == Dtor_Complete857
) {
2722
120
      IsVirtual = false;
2723
120
    }
2724
5.49k
    switch (MD->getAccess()) {
2725
0
      case AS_none:
2726
0
        llvm_unreachable("Unsupported access specifier");
2727
118
      case AS_private:
2728
118
        if (MD->isStatic())
2729
27
          Out << 'C';
2730
91
        else if (IsVirtual)
2731
51
          Out << 'E';
2732
40
        else
2733
40
          Out << 'A';
2734
118
        break;
2735
42
      case AS_protected:
2736
42
        if (MD->isStatic())
2737
14
          Out << 'K';
2738
28
        else if (IsVirtual)
2739
14
          Out << 'M';
2740
14
        else
2741
14
          Out << 'I';
2742
42
        break;
2743
5.33k
      case AS_public:
2744
5.33k
        if (MD->isStatic())
2745
323
          Out << 'S';
2746
5.00k
        else if (IsVirtual)
2747
1.06k
          Out << 'U';
2748
3.94k
        else
2749
3.94k
          Out << 'Q';
2750
5.49k
    }
2751
18.7k
  } else {
2752
18.7k
    Out << 'Y';
2753
18.7k
  }
2754
24.2k
}
2755
25.4k
void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) {
2756
  // <calling-convention> ::= A # __cdecl
2757
  //                      ::= B # __export __cdecl
2758
  //                      ::= C # __pascal
2759
  //                      ::= D # __export __pascal
2760
  //                      ::= E # __thiscall
2761
  //                      ::= F # __export __thiscall
2762
  //                      ::= G # __stdcall
2763
  //                      ::= H # __export __stdcall
2764
  //                      ::= I # __fastcall
2765
  //                      ::= J # __export __fastcall
2766
  //                      ::= Q # __vectorcall
2767
  //                      ::= S # __attribute__((__swiftcall__)) // Clang-only
2768
  //                      ::= T # __attribute__((__swiftasynccall__))
2769
  //                            // Clang-only
2770
  //                      ::= w # __regcall
2771
  // The 'export' calling conventions are from a bygone era
2772
  // (*cough*Win16*cough*) when functions were declared for export with
2773
  // that keyword. (It didn't actually export them, it just made them so
2774
  // that they could be in a DLL and somebody from another module could call
2775
  // them.)
2776
2777
25.4k
  switch (CC) {
2778
0
    default:
2779
0
      llvm_unreachable("Unsupported CC for mangling");
2780
0
    case CC_Win64:
2781
0
    case CC_X86_64SysV:
2782
22.1k
    case CC_C: Out << 'A'; break;
2783
1
    case CC_X86Pascal: Out << 'C'; break;
2784
3.13k
    case CC_X86ThisCall: Out << 'E'; break;
2785
20
    case CC_X86StdCall: Out << 'G'; break;
2786
12
    case CC_X86FastCall: Out << 'I'; break;
2787
13
    case CC_X86VectorCall: Out << 'Q'; break;
2788
13
    case CC_Swift: Out << 'S'; break;
2789
0
    case CC_SwiftAsync: Out << 'W'; break;
2790
12
    case CC_PreserveMost: Out << 'U'; break;
2791
23
    case CC_X86RegCall: Out << 'w'; break;
2792
25.4k
  }
2793
25.4k
}
2794
64
void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
2795
64
  mangleCallingConvention(T->getCallConv());
2796
64
}
2797
2798
void MicrosoftCXXNameMangler::mangleThrowSpecification(
2799
28
                                                const FunctionProtoType *FT) {
2800
  // <throw-spec> ::= Z # (default)
2801
  //              ::= _E # noexcept
2802
28
  if (FT->canThrow())
2803
14
    Out << 'Z';
2804
14
  else
2805
14
    Out << "_E";
2806
28
}
2807
2808
void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
2809
0
                                         Qualifiers, SourceRange Range) {
2810
  // Probably should be mangled as a template instantiation; need to see what
2811
  // VC does first.
2812
0
  DiagnosticsEngine &Diags = Context.getDiags();
2813
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2814
0
    "cannot mangle this unresolved dependent type yet");
2815
0
  Diags.Report(Range.getBegin(), DiagID)
2816
0
    << Range;
2817
0
}
2818
2819
// <type>        ::= <union-type> | <struct-type> | <class-type> | <enum-type>
2820
// <union-type>  ::= T <name>
2821
// <struct-type> ::= U <name>
2822
// <class-type>  ::= V <name>
2823
// <enum-type>   ::= W4 <name>
2824
34.1k
void MicrosoftCXXNameMangler::mangleTagTypeKind(TagTypeKind TTK) {
2825
34.1k
  switch (TTK) {
2826
21.0k
    case TTK_Union:
2827
21.0k
      Out << 'T';
2828
21.0k
      break;
2829
12.0k
    case TTK_Struct:
2830
12.0k
    case TTK_Interface:
2831
12.0k
      Out << 'U';
2832
12.0k
      break;
2833
775
    case TTK_Class:
2834
775
      Out << 'V';
2835
775
      break;
2836
338
    case TTK_Enum:
2837
338
      Out << "W4";
2838
338
      break;
2839
34.1k
  }
2840
34.1k
}
2841
void MicrosoftCXXNameMangler::mangleType(const EnumType *T, Qualifiers,
2842
307
                                         SourceRange) {
2843
307
  mangleType(cast<TagType>(T)->getDecl());
2844
307
}
2845
void MicrosoftCXXNameMangler::mangleType(const RecordType *T, Qualifiers,
2846
8.26k
                                         SourceRange) {
2847
8.26k
  mangleType(cast<TagType>(T)->getDecl());
2848
8.26k
}
2849
8.58k
void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
2850
8.58k
  mangleTagTypeKind(TD->getTagKind());
2851
8.58k
  mangleName(TD);
2852
8.58k
}
2853
2854
// If you add a call to this, consider updating isArtificialTagType() too.
2855
void MicrosoftCXXNameMangler::mangleArtificialTagType(
2856
    TagTypeKind TK, StringRef UnqualifiedName,
2857
25.5k
    ArrayRef<StringRef> NestedNames) {
2858
  // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
2859
25.5k
  mangleTagTypeKind(TK);
2860
2861
  // Always start with the unqualified name.
2862
25.5k
  mangleSourceName(UnqualifiedName);
2863
2864
25.5k
  for (StringRef N : llvm::reverse(NestedNames))
2865
439
    mangleSourceName(N);
2866
2867
  // Terminate the whole name with an '@'.
2868
25.5k
  Out << '@';
2869
25.5k
}
2870
2871
// <type>       ::= <array-type>
2872
// <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2873
//                  [Y <dimension-count> <dimension>+]
2874
//                  <element-type> # as global, E is never required
2875
// It's supposed to be the other way around, but for some strange reason, it
2876
// isn't. Today this behavior is retained for the sole purpose of backwards
2877
// compatibility.
2878
110
void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
2879
  // This isn't a recursive mangling, so now we have to do it all in this
2880
  // one call.
2881
110
  manglePointerCVQualifiers(T->getElementType().getQualifiers());
2882
110
  mangleType(T->getElementType(), SourceRange());
2883
110
}
2884
void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T, Qualifiers,
2885
0
                                         SourceRange) {
2886
0
  llvm_unreachable("Should have been special cased");
2887
0
}
2888
void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T, Qualifiers,
2889
0
                                         SourceRange) {
2890
0
  llvm_unreachable("Should have been special cased");
2891
0
}
2892
void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
2893
0
                                         Qualifiers, SourceRange) {
2894
0
  llvm_unreachable("Should have been special cased");
2895
0
}
2896
void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
2897
0
                                         Qualifiers, SourceRange) {
2898
0
  llvm_unreachable("Should have been special cased");
2899
0
}
2900
62
void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
2901
62
  QualType ElementTy(T, 0);
2902
62
  SmallVector<llvm::APInt, 3> Dimensions;
2903
135
  for (;;) {
2904
135
    if (ElementTy->isConstantArrayType()) {
2905
67
      const ConstantArrayType *CAT =
2906
67
          getASTContext().getAsConstantArrayType(ElementTy);
2907
67
      Dimensions.push_back(CAT->getSize());
2908
67
      ElementTy = CAT->getElementType();
2909
68
    } else if (ElementTy->isIncompleteArrayType()) {
2910
4
      const IncompleteArrayType *IAT =
2911
4
          getASTContext().getAsIncompleteArrayType(ElementTy);
2912
4
      Dimensions.push_back(llvm::APInt(32, 0));
2913
4
      ElementTy = IAT->getElementType();
2914
64
    } else if (ElementTy->isVariableArrayType()) {
2915
2
      const VariableArrayType *VAT =
2916
2
        getASTContext().getAsVariableArrayType(ElementTy);
2917
2
      Dimensions.push_back(llvm::APInt(32, 0));
2918
2
      ElementTy = VAT->getElementType();
2919
62
    } else if (ElementTy->isDependentSizedArrayType()) {
2920
      // The dependent expression has to be folded into a constant (TODO).
2921
0
      const DependentSizedArrayType *DSAT =
2922
0
        getASTContext().getAsDependentSizedArrayType(ElementTy);
2923
0
      DiagnosticsEngine &Diags = Context.getDiags();
2924
0
      unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2925
0
        "cannot mangle this dependent-length array yet");
2926
0
      Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
2927
0
        << DSAT->getBracketsRange();
2928
0
      return;
2929
62
    } else {
2930
62
      break;
2931
62
    }
2932
135
  }
2933
62
  Out << 'Y';
2934
  // <dimension-count> ::= <number> # number of extra dimensions
2935
62
  mangleNumber(Dimensions.size());
2936
62
  for (const llvm::APInt &Dimension : Dimensions)
2937
73
    mangleNumber(Dimension.getLimitedValue());
2938
62
  mangleType(ElementTy, SourceRange(), QMM_Escape);
2939
62
}
2940
2941
// <type>                   ::= <pointer-to-member-type>
2942
// <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2943
//                                                          <class name> <type>
2944
void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T,
2945
464
                                         Qualifiers Quals, SourceRange Range) {
2946
464
  QualType PointeeType = T->getPointeeType();
2947
464
  manglePointerCVQualifiers(Quals);
2948
464
  manglePointerExtQualifiers(Quals, PointeeType);
2949
464
  if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
2950
348
    Out << '8';
2951
348
    mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2952
348
    mangleFunctionType(FPT, nullptr, true);
2953
348
  } else {
2954
116
    mangleQualifiers(PointeeType.getQualifiers(), true);
2955
116
    mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2956
116
    mangleType(PointeeType, Range, QMM_Drop);
2957
116
  }
2958
464
}
2959
2960
void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
2961
0
                                         Qualifiers, SourceRange Range) {
2962
0
  DiagnosticsEngine &Diags = Context.getDiags();
2963
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2964
0
    "cannot mangle this template type parameter type yet");
2965
0
  Diags.Report(Range.getBegin(), DiagID)
2966
0
    << Range;
2967
0
}
2968
2969
void MicrosoftCXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T,
2970
0
                                         Qualifiers, SourceRange Range) {
2971
0
  DiagnosticsEngine &Diags = Context.getDiags();
2972
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2973
0
    "cannot mangle this substituted parameter pack yet");
2974
0
  Diags.Report(Range.getBegin(), DiagID)
2975
0
    << Range;
2976
0
}
2977
2978
// <type> ::= <pointer-type>
2979
// <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
2980
//                       # the E is required for 64-bit non-static pointers
2981
void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals,
2982
4.05k
                                         SourceRange Range) {
2983
4.05k
  QualType PointeeType = T->getPointeeType();
2984
4.05k
  manglePointerCVQualifiers(Quals);
2985
4.05k
  manglePointerExtQualifiers(Quals, PointeeType);
2986
2987
  // For pointer size address spaces, go down the same type mangling path as
2988
  // non address space types.
2989
4.05k
  LangAS AddrSpace = PointeeType.getQualifiers().getAddressSpace();
2990
4.05k
  if (isPtrSizeAddressSpace(AddrSpace) || 
AddrSpace == LangAS::Default4.05k
)
2991
4.03k
    mangleType(PointeeType, Range);
2992
25
  else
2993
25
    mangleAddressSpaceType(PointeeType, PointeeType.getQualifiers(), Range);
2994
4.05k
}
2995
2996
void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
2997
75
                                         Qualifiers Quals, SourceRange Range) {
2998
75
  QualType PointeeType = T->getPointeeType();
2999
75
  switch (Quals.getObjCLifetime()) {
3000
65
  case Qualifiers::OCL_None:
3001
66
  case Qualifiers::OCL_ExplicitNone:
3002
66
    break;
3003
2
  case Qualifiers::OCL_Autoreleasing:
3004
6
  case Qualifiers::OCL_Strong:
3005
9
  case Qualifiers::OCL_Weak:
3006
9
    return mangleObjCLifetime(PointeeType, Quals, Range);
3007
75
  }
3008
66
  manglePointerCVQualifiers(Quals);
3009
66
  manglePointerExtQualifiers(Quals, PointeeType);
3010
66
  mangleType(PointeeType, Range);
3011
66
}
3012
3013
// <type> ::= <reference-type>
3014
// <reference-type> ::= A E? <cvr-qualifiers> <type>
3015
//                 # the E is required for 64-bit non-static lvalue references
3016
void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
3017
1.51k
                                         Qualifiers Quals, SourceRange Range) {
3018
1.51k
  QualType PointeeType = T->getPointeeType();
3019
1.51k
  assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
3020
0
  Out << 'A';
3021
1.51k
  manglePointerExtQualifiers(Quals, PointeeType);
3022
1.51k
  mangleType(PointeeType, Range);
3023
1.51k
}
3024
3025
// <type> ::= <r-value-reference-type>
3026
// <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
3027
//                 # the E is required for 64-bit non-static rvalue references
3028
void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
3029
271
                                         Qualifiers Quals, SourceRange Range) {
3030
271
  QualType PointeeType = T->getPointeeType();
3031
271
  assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
3032
0
  Out << "$$Q";
3033
271
  manglePointerExtQualifiers(Quals, PointeeType);
3034
271
  mangleType(PointeeType, Range);
3035
271
}
3036
3037
void MicrosoftCXXNameMangler::mangleType(const ComplexType *T, Qualifiers,
3038
38
                                         SourceRange Range) {
3039
38
  QualType ElementType = T->getElementType();
3040
3041
38
  llvm::SmallString<64> TemplateMangling;
3042
38
  llvm::raw_svector_ostream Stream(TemplateMangling);
3043
38
  MicrosoftCXXNameMangler Extra(Context, Stream);
3044
38
  Stream << "?$";
3045
38
  Extra.mangleSourceName("_Complex");
3046
38
  Extra.mangleType(ElementType, Range, QMM_Escape);
3047
3048
38
  mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
3049
38
}
3050
3051
// Returns true for types that mangleArtificialTagType() gets called for with
3052
// TTK_Union, TTK_Struct, TTK_Class and where compatibility with MSVC's
3053
// mangling matters.
3054
// (It doesn't matter for Objective-C types and the like that cl.exe doesn't
3055
// support.)
3056
22.4k
bool MicrosoftCXXNameMangler::isArtificialTagType(QualType T) const {
3057
22.4k
  const Type *ty = T.getTypePtr();
3058
22.4k
  switch (ty->getTypeClass()) {
3059
10.7k
  default:
3060
10.7k
    return false;
3061
3062
11.7k
  case Type::Vector: {
3063
    // For ABI compatibility only __m64, __m128(id), and __m256(id) matter,
3064
    // but since mangleType(VectorType*) always calls mangleArtificialTagType()
3065
    // just always return true (the other vector types are clang-only).
3066
11.7k
    return true;
3067
0
  }
3068
22.4k
  }
3069
22.4k
}
3070
3071
void MicrosoftCXXNameMangler::mangleType(const VectorType *T, Qualifiers Quals,
3072
25.1k
                                         SourceRange Range) {
3073
25.1k
  const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>();
3074
25.1k
  assert(ET && "vectors with non-builtin elements are unsupported");
3075
0
  uint64_t Width = getASTContext().getTypeSize(T);
3076
  // Pattern match exactly the typedefs in our intrinsic headers.  Anything that
3077
  // doesn't match the Intel types uses a custom mangling below.
3078
25.1k
  size_t OutSizeBefore = Out.tell();
3079
25.1k
  if (!isa<ExtVectorType>(T)) {
3080
25.1k
    if (getASTContext().getTargetInfo().getTriple().isX86()) {
3081
25.1k
      if (Width == 64 && 
ET->getKind() == BuiltinType::LongLong1.41k
) {
3082
1.41k
        mangleArtificialTagType(TTK_Union, "__m64");
3083
23.7k
      } else if (Width >= 128) {
3084
23.7k
        if (ET->getKind() == BuiltinType::Float)
3085
4.67k
          mangleArtificialTagType(TTK_Union, "__m" + llvm::utostr(Width));
3086
19.0k
        else if (ET->getKind() == BuiltinType::LongLong)
3087
14.7k
          mangleArtificialTagType(TTK_Union, "__m" + llvm::utostr(Width) + 'i');
3088
4.31k
        else if (ET->getKind() == BuiltinType::Double)
3089
4.17k
          mangleArtificialTagType(TTK_Struct, "__m" + llvm::utostr(Width) + 'd');
3090
23.7k
      }
3091
25.1k
    }
3092
25.1k
  }
3093
3094
25.1k
  bool IsBuiltin = Out.tell() != OutSizeBefore;
3095
25.1k
  if (!IsBuiltin) {
3096
    // The MS ABI doesn't have a special mangling for vector types, so we define
3097
    // our own mangling to handle uses of __vector_size__ on user-specified
3098
    // types, and for extensions like __v4sf.
3099
3100
176
    llvm::SmallString<64> TemplateMangling;
3101
176
    llvm::raw_svector_ostream Stream(TemplateMangling);
3102
176
    MicrosoftCXXNameMangler Extra(Context, Stream);
3103
176
    Stream << "?$";
3104
176
    Extra.mangleSourceName("__vector");
3105
176
    Extra.mangleType(QualType(ET, 0), Range, QMM_Escape);
3106
176
    Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(T->getNumElements()));
3107
3108
176
    mangleArtificialTagType(TTK_Union, TemplateMangling, {"__clang"});
3109
176
  }
3110
25.1k
}
3111
3112
void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
3113
36
                                         Qualifiers Quals, SourceRange Range) {
3114
36
  mangleType(static_cast<const VectorType *>(T), Quals, Range);
3115
36
}
3116
3117
void MicrosoftCXXNameMangler::mangleType(const DependentVectorType *T,
3118
0
                                         Qualifiers, SourceRange Range) {
3119
0
  DiagnosticsEngine &Diags = Context.getDiags();
3120
0
  unsigned DiagID = Diags.getCustomDiagID(
3121
0
      DiagnosticsEngine::Error,
3122
0
      "cannot mangle this dependent-sized vector type yet");
3123
0
  Diags.Report(Range.getBegin(), DiagID) << Range;
3124
0
}
3125
3126
void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
3127
0
                                         Qualifiers, SourceRange Range) {
3128
0
  DiagnosticsEngine &Diags = Context.getDiags();
3129
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3130
0
    "cannot mangle this dependent-sized extended vector type yet");
3131
0
  Diags.Report(Range.getBegin(), DiagID)
3132
0
    << Range;
3133
0
}
3134
3135
void MicrosoftCXXNameMangler::mangleType(const ConstantMatrixType *T,
3136
0
                                         Qualifiers quals, SourceRange Range) {
3137
0
  DiagnosticsEngine &Diags = Context.getDiags();
3138
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3139
0
                                          "Cannot mangle this matrix type yet");
3140
0
  Diags.Report(Range.getBegin(), DiagID) << Range;
3141
0
}
3142
3143
void MicrosoftCXXNameMangler::mangleType(const DependentSizedMatrixType *T,
3144
0
                                         Qualifiers quals, SourceRange Range) {
3145
0
  DiagnosticsEngine &Diags = Context.getDiags();
3146
0
  unsigned DiagID = Diags.getCustomDiagID(
3147
0
      DiagnosticsEngine::Error,
3148
0
      "Cannot mangle this dependent-sized matrix type yet");
3149
0
  Diags.Report(Range.getBegin(), DiagID) << Range;
3150
0
}
3151
3152
void MicrosoftCXXNameMangler::mangleType(const DependentAddressSpaceType *T,
3153
0
                                         Qualifiers, SourceRange Range) {
3154
0
  DiagnosticsEngine &Diags = Context.getDiags();
3155
0
  unsigned DiagID = Diags.getCustomDiagID(
3156
0
      DiagnosticsEngine::Error,
3157
0
      "cannot mangle this dependent address space type yet");
3158
0
  Diags.Report(Range.getBegin(), DiagID) << Range;
3159
0
}
3160
3161
void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T, Qualifiers,
3162
24
                                         SourceRange) {
3163
  // ObjC interfaces have structs underlying them.
3164
24
  mangleTagTypeKind(TTK_Struct);
3165
24
  mangleName(T->getDecl());
3166
24
}
3167
3168
void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T,
3169
72
                                         Qualifiers Quals, SourceRange Range) {
3170
72
  if (T->isKindOfType())
3171
7
    return mangleObjCKindOfType(T, Quals, Range);
3172
3173
65
  if (T->qual_empty() && 
!T->isSpecialized()53
)
3174
51
    return mangleType(T->getBaseType(), Range, QMM_Drop);
3175
3176
14
  ArgBackRefMap OuterFunArgsContext;
3177
14
  ArgBackRefMap OuterTemplateArgsContext;
3178
14
  BackRefVec OuterTemplateContext;
3179
3180
14
  FunArgBackReferences.swap(OuterFunArgsContext);
3181
14
  TemplateArgBackReferences.swap(OuterTemplateArgsContext);
3182
14
  NameBackReferences.swap(OuterTemplateContext);
3183
3184
14
  mangleTagTypeKind(TTK_Struct);
3185
3186
14
  Out << "?$";
3187
14
  if (T->isObjCId())
3188
5
    mangleSourceName("objc_object");
3189
9
  else if (T->isObjCClass())
3190
2
    mangleSourceName("objc_class");
3191
7
  else
3192
7
    mangleSourceName(T->getInterface()->getName());
3193
3194
14
  for (const auto &Q : T->quals())
3195
15
    mangleObjCProtocol(Q);
3196
3197
14
  if (T->isSpecialized())
3198
2
    for (const auto &TA : T->getTypeArgs())
3199
2
      mangleType(TA, Range, QMM_Drop);
3200
3201
14
  Out << '@';
3202
3203
14
  Out << '@';
3204
3205
14
  FunArgBackReferences.swap(OuterFunArgsContext);
3206
14
  TemplateArgBackReferences.swap(OuterTemplateArgsContext);
3207
14
  NameBackReferences.swap(OuterTemplateContext);
3208
14
}
3209
3210
void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
3211
16
                                         Qualifiers Quals, SourceRange Range) {
3212
16
  QualType PointeeType = T->getPointeeType();
3213
16
  manglePointerCVQualifiers(Quals);
3214
16
  manglePointerExtQualifiers(Quals, PointeeType);
3215
3216
16
  Out << "_E";
3217
3218
16
  mangleFunctionType(PointeeType->castAs<FunctionProtoType>());
3219
16
}
3220
3221
void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
3222
0
                                         Qualifiers, SourceRange) {
3223
0
  llvm_unreachable("Cannot mangle injected class name type.");
3224
0
}
3225
3226
void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
3227
0
                                         Qualifiers, SourceRange Range) {
3228
0
  DiagnosticsEngine &Diags = Context.getDiags();
3229
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3230
0
    "cannot mangle this template specialization type yet");
3231
0
  Diags.Report(Range.getBegin(), DiagID)
3232
0
    << Range;
3233
0
}
3234
3235
void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T, Qualifiers,
3236
0
                                         SourceRange Range) {
3237
0
  DiagnosticsEngine &Diags = Context.getDiags();
3238
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3239
0
    "cannot mangle this dependent name type yet");
3240
0
  Diags.Report(Range.getBegin(), DiagID)
3241
0
    << Range;
3242
0
}
3243
3244
void MicrosoftCXXNameMangler::mangleType(
3245
    const DependentTemplateSpecializationType *T, Qualifiers,
3246
0
    SourceRange Range) {
3247
0
  DiagnosticsEngine &Diags = Context.getDiags();
3248
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3249
0
    "cannot mangle this dependent template specialization type yet");
3250
0
  Diags.Report(Range.getBegin(), DiagID)
3251
0
    << Range;
3252
0
}
3253
3254
void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T, Qualifiers,
3255
0
                                         SourceRange Range) {
3256
0
  DiagnosticsEngine &Diags = Context.getDiags();
3257
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3258
0
    "cannot mangle this pack expansion yet");
3259
0
  Diags.Report(Range.getBegin(), DiagID)
3260
0
    << Range;
3261
0
}
3262
3263
void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T, Qualifiers,
3264
0
                                         SourceRange Range) {
3265
0
  DiagnosticsEngine &Diags = Context.getDiags();
3266
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3267
0
    "cannot mangle this typeof(type) yet");
3268
0
  Diags.Report(Range.getBegin(), DiagID)
3269
0
    << Range;
3270
0
}
3271
3272
void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T, Qualifiers,
3273
0
                                         SourceRange Range) {
3274
0
  DiagnosticsEngine &Diags = Context.getDiags();
3275
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3276
0
    "cannot mangle this typeof(expression) yet");
3277
0
  Diags.Report(Range.getBegin(), DiagID)
3278
0
    << Range;
3279
0
}
3280
3281
void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T, Qualifiers,
3282
0
                                         SourceRange Range) {
3283
0
  DiagnosticsEngine &Diags = Context.getDiags();
3284
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3285
0
    "cannot mangle this decltype() yet");
3286
0
  Diags.Report(Range.getBegin(), DiagID)
3287
0
    << Range;
3288
0
}
3289
3290
void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
3291
0
                                         Qualifiers, SourceRange Range) {
3292
0
  DiagnosticsEngine &Diags = Context.getDiags();
3293
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3294
0
    "cannot mangle this unary transform type yet");
3295
0
  Diags.Report(Range.getBegin(), DiagID)
3296
0
    << Range;
3297
0
}
3298
3299
void MicrosoftCXXNameMangler::mangleType(const AutoType *T, Qualifiers,
3300
0
                                         SourceRange Range) {
3301
0
  assert(T->getDeducedType().isNull() && "expecting a dependent type!");
3302
3303
0
  DiagnosticsEngine &Diags = Context.getDiags();
3304
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3305
0
    "cannot mangle this 'auto' type yet");
3306
0
  Diags.Report(Range.getBegin(), DiagID)
3307
0
    << Range;
3308
0
}
3309
3310
void MicrosoftCXXNameMangler::mangleType(
3311
0
    const DeducedTemplateSpecializationType *T, Qualifiers, SourceRange Range) {
3312
0
  assert(T->getDeducedType().isNull() && "expecting a dependent type!");
3313
3314
0
  DiagnosticsEngine &Diags = Context.getDiags();
3315
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3316
0
    "cannot mangle this deduced class template specialization type yet");
3317
0
  Diags.Report(Range.getBegin(), DiagID)
3318
0
    << Range;
3319
0
}
3320
3321
void MicrosoftCXXNameMangler::mangleType(const AtomicType *T, Qualifiers,
3322
3
                                         SourceRange Range) {
3323
3
  QualType ValueType = T->getValueType();
3324
3325
3
  llvm::SmallString<64> TemplateMangling;
3326
3
  llvm::raw_svector_ostream Stream(TemplateMangling);
3327
3
  MicrosoftCXXNameMangler Extra(Context, Stream);
3328
3
  Stream << "?$";
3329
3
  Extra.mangleSourceName("_Atomic");
3330
3
  Extra.mangleType(ValueType, Range, QMM_Escape);
3331
3332
3
  mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
3333
3
}
3334
3335
void MicrosoftCXXNameMangler::mangleType(const PipeType *T, Qualifiers,
3336
28
                                         SourceRange Range) {
3337
28
  QualType ElementType = T->getElementType();
3338
3339
28
  llvm::SmallString<64> TemplateMangling;
3340
28
  llvm::raw_svector_ostream Stream(TemplateMangling);
3341
28
  MicrosoftCXXNameMangler Extra(Context, Stream);
3342
28
  Stream << "?$";
3343
28
  Extra.mangleSourceName("ocl_pipe");
3344
28
  Extra.mangleType(ElementType, Range, QMM_Escape);
3345
28
  Extra.mangleIntegerLiteral(llvm::APSInt::get(T->isReadOnly()));
3346
3347
28
  mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
3348
28
}
3349
3350
void MicrosoftMangleContextImpl::mangleCXXName(GlobalDecl GD,
3351
26.1k
                                               raw_ostream &Out) {
3352
26.1k
  const NamedDecl *D = cast<NamedDecl>(GD.getDecl());
3353
26.1k
  PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
3354
26.1k
                                 getASTContext().getSourceManager(),
3355
26.1k
                                 "Mangling declaration");
3356
3357
26.1k
  msvc_hashing_ostream MHO(Out);
3358
3359
26.1k
  if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) {
3360
1.62k
    auto Type = GD.getCtorType();
3361
1.62k
    MicrosoftCXXNameMangler mangler(*this, MHO, CD, Type);
3362
1.62k
    return mangler.mangle(GD);
3363
1.62k
  }
3364
3365
24.5k
  if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) {
3366
857
    auto Type = GD.getDtorType();
3367
857
    MicrosoftCXXNameMangler mangler(*this, MHO, DD, Type);
3368
857
    return mangler.mangle(GD);
3369
857
  }
3370
3371
23.6k
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3372
23.6k
  return Mangler.mangle(GD);
3373
24.5k
}
3374
3375
void MicrosoftCXXNameMangler::mangleType(const BitIntType *T, Qualifiers,
3376
104
                                         SourceRange Range) {
3377
104
  llvm::SmallString<64> TemplateMangling;
3378
104
  llvm::raw_svector_ostream Stream(TemplateMangling);
3379
104
  MicrosoftCXXNameMangler Extra(Context, Stream);
3380
104
  Stream << "?$";
3381
104
  if (T->isUnsigned())
3382
24
    Extra.mangleSourceName("_UBitInt");
3383
80
  else
3384
80
    Extra.mangleSourceName("_BitInt");
3385
104
  Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(T->getNumBits()));
3386
3387
104
  mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
3388
104
}
3389
3390
void MicrosoftCXXNameMangler::mangleType(const DependentBitIntType *T,
3391
0
                                         Qualifiers, SourceRange Range) {
3392
0
  DiagnosticsEngine &Diags = Context.getDiags();
3393
0
  unsigned DiagID = Diags.getCustomDiagID(
3394
0
      DiagnosticsEngine::Error, "cannot mangle this DependentBitInt type yet");
3395
0
  Diags.Report(Range.getBegin(), DiagID) << Range;
3396
0
}
3397
3398
// <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
3399
//                       <virtual-adjustment>
3400
// <no-adjustment>      ::= A # private near
3401
//                      ::= B # private far
3402
//                      ::= I # protected near
3403
//                      ::= J # protected far
3404
//                      ::= Q # public near
3405
//                      ::= R # public far
3406
// <static-adjustment>  ::= G <static-offset> # private near
3407
//                      ::= H <static-offset> # private far
3408
//                      ::= O <static-offset> # protected near
3409
//                      ::= P <static-offset> # protected far
3410
//                      ::= W <static-offset> # public near
3411
//                      ::= X <static-offset> # public far
3412
// <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
3413
//                      ::= $1 <virtual-shift> <static-offset> # private far
3414
//                      ::= $2 <virtual-shift> <static-offset> # protected near
3415
//                      ::= $3 <virtual-shift> <static-offset> # protected far
3416
//                      ::= $4 <virtual-shift> <static-offset> # public near
3417
//                      ::= $5 <virtual-shift> <static-offset> # public far
3418
// <virtual-shift>      ::= <vtordisp-shift> | <vtordispex-shift>
3419
// <vtordisp-shift>     ::= <offset-to-vtordisp>
3420
// <vtordispex-shift>   ::= <offset-to-vbptr> <vbase-offset-offset>
3421
//                          <offset-to-vtordisp>
3422
static void mangleThunkThisAdjustment(AccessSpecifier AS,
3423
                                      const ThisAdjustment &Adjustment,
3424
                                      MicrosoftCXXNameMangler &Mangler,
3425
385
                                      raw_ostream &Out) {
3426
385
  if (!Adjustment.Virtual.isEmpty()) {
3427
194
    Out << '$';
3428
194
    char AccessSpec;
3429
194
    switch (AS) {
3430
0
    case AS_none:
3431
0
      llvm_unreachable("Unsupported access specifier");
3432
4
    case AS_private:
3433
4
      AccessSpec = '0';
3434
4
      break;
3435
4
    case AS_protected:
3436
4
      AccessSpec = '2';
3437
4
      break;
3438
186
    case AS_public:
3439
186
      AccessSpec = '4';
3440
194
    }
3441
194
    if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
3442
22
      Out << 'R' << AccessSpec;
3443
22
      Mangler.mangleNumber(
3444
22
          static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
3445
22
      Mangler.mangleNumber(
3446
22
          static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
3447
22
      Mangler.mangleNumber(
3448
22
          static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
3449
22
      Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
3450
172
    } else {
3451
172
      Out << AccessSpec;
3452
172
      Mangler.mangleNumber(
3453
172
          static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
3454
172
      Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
3455
172
    }
3456
194
  } else 
if (191
Adjustment.NonVirtual != 0191
) {
3457
153
    switch (AS) {
3458
0
    case AS_none:
3459
0
      llvm_unreachable("Unsupported access specifier");
3460
10
    case AS_private:
3461
10
      Out << 'G';
3462
10
      break;
3463
3
    case AS_protected:
3464
3
      Out << 'O';
3465
3
      break;
3466
140
    case AS_public:
3467
140
      Out << 'W';
3468
153
    }
3469
153
    Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
3470
153
  } else {
3471
38
    switch (AS) {
3472
0
    case AS_none:
3473
0
      llvm_unreachable("Unsupported access specifier");
3474
0
    case AS_private:
3475
0
      Out << 'A';
3476
0
      break;
3477
0
    case AS_protected:
3478
0
      Out << 'I';
3479
0
      break;
3480
38
    case AS_public:
3481
38
      Out << 'Q';
3482
38
    }
3483
38
  }
3484
385
}
3485
3486
void MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(
3487
    const CXXMethodDecl *MD, const MethodVFTableLocation &ML,
3488
55
    raw_ostream &Out) {
3489
55
  msvc_hashing_ostream MHO(Out);
3490
55
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3491
55
  Mangler.getStream() << '?';
3492
55
  Mangler.mangleVirtualMemPtrThunk(MD, ML);
3493
55
}
3494
3495
void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
3496
                                             const ThunkInfo &Thunk,
3497
215
                                             raw_ostream &Out) {
3498
215
  msvc_hashing_ostream MHO(Out);
3499
215
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3500
215
  Mangler.getStream() << '?';
3501
215
  Mangler.mangleName(MD);
3502
3503
  // Usually the thunk uses the access specifier of the new method, but if this
3504
  // is a covariant return thunk, then MSVC always uses the public access
3505
  // specifier, and we do the same.
3506
215
  AccessSpecifier AS = Thunk.Return.isEmpty() ? 
MD->getAccess()170
:
AS_public45
;
3507
215
  mangleThunkThisAdjustment(AS, Thunk.This, Mangler, MHO);
3508
3509
215
  if (!Thunk.Return.isEmpty())
3510
45
    assert(Thunk.Method != nullptr &&
3511
215
           "Thunk info should hold the overridee decl");
3512
3513
215
  const CXXMethodDecl *DeclForFPT = Thunk.Method ? 
Thunk.Method63
:
MD152
;
3514
215
  Mangler.mangleFunctionType(
3515
215
      DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
3516
215
}
3517
3518
void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
3519
    const CXXDestructorDecl *DD, CXXDtorType Type,
3520
170
    const ThisAdjustment &Adjustment, raw_ostream &Out) {
3521
  // FIXME: Actually, the dtor thunk should be emitted for vector deleting
3522
  // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
3523
  // mangling manually until we support both deleting dtor types.
3524
170
  assert(Type == Dtor_Deleting);
3525
0
  msvc_hashing_ostream MHO(Out);
3526
170
  MicrosoftCXXNameMangler Mangler(*this, MHO, DD, Type);
3527
170
  Mangler.getStream() << "??_E";
3528
170
  Mangler.mangleName(DD->getParent());
3529
170
  mangleThunkThisAdjustment(DD->getAccess(), Adjustment, Mangler, MHO);
3530
170
  Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
3531
170
}
3532
3533
void MicrosoftMangleContextImpl::mangleCXXVFTable(
3534
    const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3535
1.88k
    raw_ostream &Out) {
3536
  // <mangled-name> ::= ?_7 <class-name> <storage-class>
3537
  //                    <cvr-qualifiers> [<name>] @
3538
  // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3539
  // is always '6' for vftables.
3540
1.88k
  msvc_hashing_ostream MHO(Out);
3541
1.88k
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3542
1.88k
  if (Derived->hasAttr<DLLImportAttr>())
3543
51
    Mangler.getStream() << "??_S";
3544
1.83k
  else
3545
1.83k
    Mangler.getStream() << "??_7";
3546
1.88k
  Mangler.mangleName(Derived);
3547
1.88k
  Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
3548
1.88k
  for (const CXXRecordDecl *RD : BasePath)
3549
692
    Mangler.mangleName(RD);
3550
1.88k
  Mangler.getStream() << '@';
3551
1.88k
}
3552
3553
void MicrosoftMangleContextImpl::mangleCXXVBTable(
3554
    const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3555
584
    raw_ostream &Out) {
3556
  // <mangled-name> ::= ?_8 <class-name> <storage-class>
3557
  //                    <cvr-qualifiers> [<name>] @
3558
  // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3559
  // is always '7' for vbtables.
3560
584
  msvc_hashing_ostream MHO(Out);
3561
584
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3562
584
  Mangler.getStream() << "??_8";
3563
584
  Mangler.mangleName(Derived);
3564
584
  Mangler.getStream() << "7B";  // '7' for vbtable, 'B' for const.
3565
584
  for (const CXXRecordDecl *RD : BasePath)
3566
345
    Mangler.mangleName(RD);
3567
584
  Mangler.getStream() << '@';
3568
584
}
3569
3570
805
void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) {
3571
805
  msvc_hashing_ostream MHO(Out);
3572
805
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3573
805
  Mangler.getStream() << "??_R0";
3574
805
  Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3575
805
  Mangler.getStream() << "@8";
3576
805
}
3577
3578
void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T,
3579
603
                                                   raw_ostream &Out) {
3580
603
  MicrosoftCXXNameMangler Mangler(*this, Out);
3581
603
  Mangler.getStream() << '.';
3582
603
  Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3583
603
}
3584
3585
void MicrosoftMangleContextImpl::mangleCXXVirtualDisplacementMap(
3586
4
    const CXXRecordDecl *SrcRD, const CXXRecordDecl *DstRD, raw_ostream &Out) {
3587
4
  msvc_hashing_ostream MHO(Out);
3588
4
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3589
4
  Mangler.getStream() << "??_K";
3590
4
  Mangler.mangleName(SrcRD);
3591
4
  Mangler.getStream() << "$C";
3592
4
  Mangler.mangleName(DstRD);
3593
4
}
3594
3595
void MicrosoftMangleContextImpl::mangleCXXThrowInfo(QualType T, bool IsConst,
3596
                                                    bool IsVolatile,
3597
                                                    bool IsUnaligned,
3598
                                                    uint32_t NumEntries,
3599
35
                                                    raw_ostream &Out) {
3600
35
  msvc_hashing_ostream MHO(Out);
3601
35
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3602
35
  Mangler.getStream() << "_TI";
3603
35
  if (IsConst)
3604
3
    Mangler.getStream() << 'C';
3605
35
  if (IsVolatile)
3606
0
    Mangler.getStream() << 'V';
3607
35
  if (IsUnaligned)
3608
1
    Mangler.getStream() << 'U';
3609
35
  Mangler.getStream() << NumEntries;
3610
35
  Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3611
35
}
3612
3613
void MicrosoftMangleContextImpl::mangleCXXCatchableTypeArray(
3614
33
    QualType T, uint32_t NumEntries, raw_ostream &Out) {
3615
33
  msvc_hashing_ostream MHO(Out);
3616
33
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3617
33
  Mangler.getStream() << "_CTA";
3618
33
  Mangler.getStream() << NumEntries;
3619
33
  Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3620
33
}
3621
3622
void MicrosoftMangleContextImpl::mangleCXXCatchableType(
3623
    QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size,
3624
    uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex,
3625
56
    raw_ostream &Out) {
3626
56
  MicrosoftCXXNameMangler Mangler(*this, Out);
3627
56
  Mangler.getStream() << "_CT";
3628
3629
56
  llvm::SmallString<64> RTTIMangling;
3630
56
  {
3631
56
    llvm::raw_svector_ostream Stream(RTTIMangling);
3632
56
    msvc_hashing_ostream MHO(Stream);
3633
56
    mangleCXXRTTI(T, MHO);
3634
56
  }
3635
56
  Mangler.getStream() << RTTIMangling;
3636
3637
  // VS2015 and VS2017.1 omit the copy-constructor in the mangled name but
3638
  // both older and newer versions include it.
3639
  // FIXME: It is known that the Ctor is present in 2013, and in 2017.7
3640
  // (_MSC_VER 1914) and newer, and that it's omitted in 2015 and 2017.4
3641
  // (_MSC_VER 1911), but it's unknown when exactly it reappeared (1914?
3642
  // Or 1912, 1913 already?).
3643
56
  bool OmitCopyCtor = getASTContext().getLangOpts().isCompatibleWithMSVC(
3644
56
                          LangOptions::MSVC2015) &&
3645
56
                      !getASTContext().getLangOpts().isCompatibleWithMSVC(
3646
12
                          LangOptions::MSVC2017_7);
3647
56
  llvm::SmallString<64> CopyCtorMangling;
3648
56
  if (!OmitCopyCtor && 
CD50
) {
3649
15
    llvm::raw_svector_ostream Stream(CopyCtorMangling);
3650
15
    msvc_hashing_ostream MHO(Stream);
3651
15
    mangleCXXName(GlobalDecl(CD, CT), MHO);
3652
15
  }
3653
56
  Mangler.getStream() << CopyCtorMangling;
3654
3655
56
  Mangler.getStream() << Size;
3656
56
  if (VBPtrOffset == -1) {
3657
54
    if (NVOffset) {
3658
2
      Mangler.getStream() << NVOffset;
3659
2
    }
3660
54
  } else {
3661
2
    Mangler.getStream() << NVOffset;
3662
2
    Mangler.getStream() << VBPtrOffset;
3663
2
    Mangler.getStream() << VBIndex;
3664
2
  }
3665
56
}
3666
3667
void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor(
3668
    const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset,
3669
484
    uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) {
3670
484
  msvc_hashing_ostream MHO(Out);
3671
484
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3672
484
  Mangler.getStream() << "??_R1";
3673
484
  Mangler.mangleNumber(NVOffset);
3674
484
  Mangler.mangleNumber(VBPtrOffset);
3675
484
  Mangler.mangleNumber(VBTableOffset);
3676
484
  Mangler.mangleNumber(Flags);
3677
484
  Mangler.mangleName(Derived);
3678
484
  Mangler.getStream() << "8";
3679
484
}
3680
3681
void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray(
3682
270
    const CXXRecordDecl *Derived, raw_ostream &Out) {
3683
270
  msvc_hashing_ostream MHO(Out);
3684
270
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3685
270
  Mangler.getStream() << "??_R2";
3686
270
  Mangler.mangleName(Derived);
3687
270
  Mangler.getStream() << "8";
3688
270
}
3689
3690
void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor(
3691
630
    const CXXRecordDecl *Derived, raw_ostream &Out) {
3692
630
  msvc_hashing_ostream MHO(Out);
3693
630
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3694
630
  Mangler.getStream() << "??_R3";
3695
630
  Mangler.mangleName(Derived);
3696
630
  Mangler.getStream() << "8";
3697
630
}
3698
3699
void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator(
3700
    const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3701
256
    raw_ostream &Out) {
3702
  // <mangled-name> ::= ?_R4 <class-name> <storage-class>
3703
  //                    <cvr-qualifiers> [<name>] @
3704
  // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3705
  // is always '6' for vftables.
3706
256
  llvm::SmallString<64> VFTableMangling;
3707
256
  llvm::raw_svector_ostream Stream(VFTableMangling);
3708
256
  mangleCXXVFTable(Derived, BasePath, Stream);
3709
3710
256
  if (VFTableMangling.startswith("??@")) {
3711
7
    assert(VFTableMangling.endswith("@"));
3712
0
    Out << VFTableMangling << "??_R4@";
3713
7
    return;
3714
7
  }
3715
3716
249
  assert(VFTableMangling.startswith("??_7") ||
3717
249
         VFTableMangling.startswith("??_S"));
3718
3719
0
  Out << "??_R4" << VFTableMangling.str().drop_front(4);
3720
249
}
3721
3722
void MicrosoftMangleContextImpl::mangleSEHFilterExpression(
3723
22
    const NamedDecl *EnclosingDecl, raw_ostream &Out) {
3724
22
  msvc_hashing_ostream MHO(Out);
3725
22
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3726
  // The function body is in the same comdat as the function with the handler,
3727
  // so the numbering here doesn't have to be the same across TUs.
3728
  //
3729
  // <mangled-name> ::= ?filt$ <filter-number> @0
3730
22
  Mangler.getStream() << "?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@";
3731
22
  Mangler.mangleName(EnclosingDecl);
3732
22
}
3733
3734
void MicrosoftMangleContextImpl::mangleSEHFinallyBlock(
3735
78
    const NamedDecl *EnclosingDecl, raw_ostream &Out) {
3736
78
  msvc_hashing_ostream MHO(Out);
3737
78
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3738
  // The function body is in the same comdat as the function with the handler,
3739
  // so the numbering here doesn't have to be the same across TUs.
3740
  //
3741
  // <mangled-name> ::= ?fin$ <filter-number> @0
3742
78
  Mangler.getStream() << "?fin$" << SEHFinallyIds[EnclosingDecl]++ << "@0@";
3743
78
  Mangler.mangleName(EnclosingDecl);
3744
78
}
3745
3746
408
void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
3747
  // This is just a made up unique string for the purposes of tbaa.  undname
3748
  // does *not* know how to demangle it.
3749
408
  MicrosoftCXXNameMangler Mangler(*this, Out);
3750
408
  Mangler.getStream() << '?';
3751
408
  Mangler.mangleType(T, SourceRange());
3752
408
}
3753
3754
void MicrosoftMangleContextImpl::mangleReferenceTemporary(
3755
5
    const VarDecl *VD, unsigned ManglingNumber, raw_ostream &Out) {
3756
5
  msvc_hashing_ostream MHO(Out);
3757
5
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3758
3759
5
  Mangler.getStream() << "?$RT" << ManglingNumber << '@';
3760
5
  Mangler.mangle(VD, "");
3761
5
}
3762
3763
void MicrosoftMangleContextImpl::mangleThreadSafeStaticGuardVariable(
3764
37
    const VarDecl *VD, unsigned GuardNum, raw_ostream &Out) {
3765
37
  msvc_hashing_ostream MHO(Out);
3766
37
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3767
3768
37
  Mangler.getStream() << "?$TSS" << GuardNum << '@';
3769
37
  Mangler.mangleNestedName(VD);
3770
37
  Mangler.getStream() << "@4HA";
3771
37
}
3772
3773
void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
3774
27
                                                           raw_ostream &Out) {
3775
  // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
3776
  //              ::= ?__J <postfix> @5 <scope-depth>
3777
  //              ::= ?$S <guard-num> @ <postfix> @4IA
3778
3779
  // The first mangling is what MSVC uses to guard static locals in inline
3780
  // functions.  It uses a different mangling in external functions to support
3781
  // guarding more than 32 variables.  MSVC rejects inline functions with more
3782
  // than 32 static locals.  We don't fully implement the second mangling
3783
  // because those guards are not externally visible, and instead use LLVM's
3784
  // default renaming when creating a new guard variable.
3785
27
  msvc_hashing_ostream MHO(Out);
3786
27
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3787
3788
27
  bool Visible = VD->isExternallyVisible();
3789
27
  if (Visible) {
3790
11
    Mangler.getStream() << (VD->getTLSKind() ? 
"??__J"2
:
"??_B"9
);
3791
16
  } else {
3792
16
    Mangler.getStream() << "?$S1@";
3793
16
  }
3794
27
  unsigned ScopeDepth = 0;
3795
27
  if (Visible && 
!getNextDiscriminator(VD, ScopeDepth)11
)
3796
    // If we do not have a discriminator and are emitting a guard variable for
3797
    // use at global scope, then mangling the nested name will not be enough to
3798
    // remove ambiguities.
3799
0
    Mangler.mangle(VD, "");
3800
27
  else
3801
27
    Mangler.mangleNestedName(VD);
3802
27
  Mangler.getStream() << (Visible ? 
"@5"11
:
"@4IA"16
);
3803
27
  if (ScopeDepth)
3804
11
    Mangler.mangleNumber(ScopeDepth);
3805
27
}
3806
3807
void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
3808
                                                    char CharCode,
3809
498
                                                    raw_ostream &Out) {
3810
498
  msvc_hashing_ostream MHO(Out);
3811
498
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3812
498
  Mangler.getStream() << "??__" << CharCode;
3813
498
  if (D->isStaticDataMember()) {
3814
46
    Mangler.getStream() << '?';
3815
46
    Mangler.mangleName(D);
3816
46
    Mangler.mangleVariableEncoding(D);
3817
46
    Mangler.getStream() << "@@";
3818
452
  } else {
3819
452
    Mangler.mangleName(D);
3820
452
  }
3821
  // This is the function class mangling.  These stubs are global, non-variadic,
3822
  // cdecl functions that return void and take no args.
3823
498
  Mangler.getStream() << "YAXXZ";
3824
498
}
3825
3826
void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
3827
326
                                                          raw_ostream &Out) {
3828
  // <initializer-name> ::= ?__E <name> YAXXZ
3829
326
  mangleInitFiniStub(D, 'E', Out);
3830
326
}
3831
3832
void
3833
MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
3834
172
                                                          raw_ostream &Out) {
3835
  // <destructor-name> ::= ?__F <name> YAXXZ
3836
172
  mangleInitFiniStub(D, 'F', Out);
3837
172
}
3838
3839
void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
3840
793
                                                     raw_ostream &Out) {
3841
  // <char-type> ::= 0   # char, char16_t, char32_t
3842
  //                     # (little endian char data in mangling)
3843
  //             ::= 1   # wchar_t (big endian char data in mangling)
3844
  //
3845
  // <literal-length> ::= <non-negative integer>  # the length of the literal
3846
  //
3847
  // <encoded-crc>    ::= <hex digit>+ @          # crc of the literal including
3848
  //                                              # trailing null bytes
3849
  //
3850
  // <encoded-string> ::= <simple character>           # uninteresting character
3851
  //                  ::= '?$' <hex digit> <hex digit> # these two nibbles
3852
  //                                                   # encode the byte for the
3853
  //                                                   # character
3854
  //                  ::= '?' [a-z]                    # \xe1 - \xfa
3855
  //                  ::= '?' [A-Z]                    # \xc1 - \xda
3856
  //                  ::= '?' [0-9]                    # [,/\:. \n\t'-]
3857
  //
3858
  // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
3859
  //               <encoded-string> '@'
3860
793
  MicrosoftCXXNameMangler Mangler(*this, Out);
3861
793
  Mangler.getStream() << "??_C@_";
3862
3863
  // The actual string length might be different from that of the string literal
3864
  // in cases like:
3865
  // char foo[3] = "foobar";
3866
  // char bar[42] = "foobar";
3867
  // Where it is truncated or zero-padded to fit the array. This is the length
3868
  // used for mangling, and any trailing null-bytes also need to be mangled.
3869
793
  unsigned StringLength = getASTContext()
3870
793
                              .getAsConstantArrayType(SL->getType())
3871
793
                              ->getSize()
3872
793
                              .getZExtValue();
3873
793
  unsigned StringByteLength = StringLength * SL->getCharByteWidth();
3874
3875
  // <char-type>: The "kind" of string literal is encoded into the mangled name.
3876
793
  if (SL->isWide())
3877
206
    Mangler.getStream() << '1';
3878
587
  else
3879
587
    Mangler.getStream() << '0';
3880
3881
  // <literal-length>: The next part of the mangled name consists of the length
3882
  // of the string in bytes.
3883
793
  Mangler.mangleNumber(StringByteLength);
3884
3885
6.30k
  auto GetLittleEndianByte = [&SL](unsigned Index) {
3886
6.30k
    unsigned CharByteWidth = SL->getCharByteWidth();
3887
6.30k
    if (Index / CharByteWidth >= SL->getLength())
3888
1.64k
      return static_cast<char>(0);
3889
4.65k
    uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
3890
4.65k
    unsigned OffsetInCodeUnit = Index % CharByteWidth;
3891
4.65k
    return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
3892
6.30k
  };
3893
3894
1.11k
  auto GetBigEndianByte = [&SL](unsigned Index) {
3895
1.11k
    unsigned CharByteWidth = SL->getCharByteWidth();
3896
1.11k
    if (Index / CharByteWidth >= SL->getLength())
3897
408
      return static_cast<char>(0);
3898
702
    uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
3899
702
    unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
3900
702
    return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
3901
1.11k
  };
3902
3903
  // CRC all the bytes of the StringLiteral.
3904
793
  llvm::JamCRC JC;
3905
4.72k
  for (unsigned I = 0, E = StringByteLength; I != E; 
++I3.93k
)
3906
3.93k
    JC.update(GetLittleEndianByte(I));
3907
3908
  // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
3909
  // scheme.
3910
793
  Mangler.mangleNumber(JC.getCRC());
3911
3912
  // <encoded-string>: The mangled name also contains the first 32 bytes
3913
  // (including null-terminator bytes) of the encoded StringLiteral.
3914
  // Each character is encoded by splitting them into bytes and then encoding
3915
  // the constituent bytes.
3916
3.48k
  auto MangleByte = [&Mangler](char Byte) {
3917
    // There are five different manglings for characters:
3918
    // - [a-zA-Z0-9_$]: A one-to-one mapping.
3919
    // - ?[a-z]: The range from \xe1 to \xfa.
3920
    // - ?[A-Z]: The range from \xc1 to \xda.
3921
    // - ?[0-9]: The set of [,/\:. \n\t'-].
3922
    // - ?$XX: A fallback which maps nibbles.
3923
3.48k
    if (isAsciiIdentifierContinue(Byte, /*AllowDollar=*/true)) {
3924
1.27k
      Mangler.getStream() << Byte;
3925
2.20k
    } else if (isLetter(Byte & 0x7f)) {
3926
107
      Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
3927
2.10k
    } else {
3928
2.10k
      const char SpecialChars[] = {',', '/',  '\\', ':',  '.',
3929
2.10k
                                   ' ', '\n', '\t', '\'', '-'};
3930
2.10k
      const char *Pos = llvm::find(SpecialChars, Byte);
3931
2.10k
      if (Pos != std::end(SpecialChars)) {
3932
216
        Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars));
3933
1.88k
      } else {
3934
1.88k
        Mangler.getStream() << "?$";
3935
1.88k
        Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
3936
1.88k
        Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
3937
1.88k
      }
3938
2.10k
    }
3939
3.48k
  };
3940
3941
  // Enforce our 32 bytes max, except wchar_t which gets 32 chars instead.
3942
793
  unsigned MaxBytesToMangle = SL->isWide() ? 
64U206
:
32U587
;
3943
793
  unsigned NumBytesToMangle = std::min(MaxBytesToMangle, StringByteLength);
3944
4.27k
  for (unsigned I = 0; I != NumBytesToMangle; 
++I3.48k
) {
3945
3.48k
    if (SL->isWide())
3946
1.11k
      MangleByte(GetBigEndianByte(I));
3947
2.37k
    else
3948
2.37k
      MangleByte(GetLittleEndianByte(I));
3949
3.48k
  }
3950
3951
793
  Mangler.getStream() << '@';
3952
793
}
3953
3954
MicrosoftMangleContext *MicrosoftMangleContext::create(ASTContext &Context,
3955
                                                       DiagnosticsEngine &Diags,
3956
882
                                                       bool IsAux) {
3957
882
  return new MicrosoftMangleContextImpl(Context, Diags, IsAux);
3958
882
}