Coverage Report

Created: 2022-05-17 06:19

/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.8k
      OS << str();
68
31.8k
      return;
69
31.8k
    }
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
69.8k
getLambdaDefaultArgumentDeclContext(const Decl *D) {
87
69.8k
  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.8k
  return nullptr;
93
69.8k
}
94
95
/// Retrieve the declaration context that should be used when mangling
96
/// the given declaration.
97
55.2k
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.2k
  if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(D))
105
34
    return LDADC;
106
107
  // Perform the same check for block literals.
108
55.2k
  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.2k
  const DeclContext *DC = D->getDeclContext();
115
55.2k
  if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
116
55.2k
      isa<OMPDeclareMapperDecl>(DC)) {
117
0
    return getEffectiveDeclContext(cast<Decl>(DC));
118
0
  }
119
120
55.2k
  return DC->getRedeclContext();
121
55.2k
}
122
123
0
static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
124
0
  return getEffectiveDeclContext(cast<Decl>(DC));
125
0
}
126
127
2.91k
static const FunctionDecl *getStructor(const NamedDecl *ND) {
128
2.91k
  if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(ND))
129
8
    return FTD->getTemplatedDecl()->getCanonicalDecl();
130
131
2.90k
  const auto *FD = cast<FunctionDecl>(ND);
132
2.90k
  if (const auto *FTD = FD->getPrimaryTemplate())
133
11
    return FTD->getTemplatedDecl()->getCanonicalDecl();
134
135
2.89k
  return FD->getCanonicalDecl();
136
2.90k
}
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.53k
  bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
210
8.53k
    const DeclContext *DC = getEffectiveDeclContext(ND);
211
8.53k
    if (!DC->isFunctionOrMethod())
212
7.93k
      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.2k
                         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.00k
                         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.35k
  bool isStructorDecl(const NamedDecl *ND) const {
391
4.35k
    return ND == Structor || 
getStructor(ND) == Structor280
;
392
4.35k
  }
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.0k
  void mangleUnqualifiedName(GlobalDecl GD) {
402
60.0k
    mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName());
403
60.0k
  }
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
868
    : 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
868
  SourceManager &SM = Context.getSourceManager();
481
868
  if (const FileEntry *FE = SM.getFileEntryForID(SM.getMainFileID())) {
482
    // Truncate the hash so we get 8 characters of hexadecimal.
483
866
    uint32_t TruncatedHash = uint32_t(xxHash64(FE->getName()));
484
866
    AnonymousNamespaceHash = llvm::utohexstr(TruncatedHash);
485
866
  } 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
868
}
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.1k
      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.0k
  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.82k
) {
526
    // C variables are not mangled.
527
4.80k
    if (VD->isExternC())
528
26
      return false;
529
530
    // Variables at global scope with internal linkage are not mangled.
531
4.78k
    const DeclContext *DC = getEffectiveDeclContext(D);
532
    // Check for extern variable declared locally.
533
4.78k
    if (DC->isFunctionOrMethod() && 
D->hasLinkage()334
)
534
0
      while (!DC->isNamespace() && !DC->isTranslationUnit())
535
0
        DC = getEffectiveParentContext(DC);
536
537
4.78k
    if (DC->isTranslationUnit() && 
D->getFormalLinkage() == InternalLinkage3.10k
&&
538
4.78k
        
!isa<VarTemplateSpecializationDecl>(D)23
&&
539
4.78k
        
D->getIdentifier() != nullptr23
)
540
19
      return false;
541
4.78k
  }
542
543
47.2k
  return true;
544
47.3k
}
545
546
bool
547
794
MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
548
794
  return true;
549
794
}
550
551
26.6k
void MicrosoftCXXNameMangler::mangle(GlobalDecl GD, StringRef Prefix) {
552
26.6k
  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.6k
  Out << Prefix;
561
26.6k
  mangleName(GD);
562
26.6k
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
563
24.2k
    mangleFunctionEncoding(GD, Context.shouldMangleDeclName(FD));
564
2.42k
  else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
565
2.40k
    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.6k
}
576
577
void MicrosoftCXXNameMangler::mangleFunctionEncoding(GlobalDecl GD,
578
24.2k
                                                     bool ShouldMangle) {
579
24.2k
  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.2k
  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.2k
  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.2k
  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.2k
}
609
610
2.45k
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.45k
  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.11k
  else if (!VD->isStaticLocal())
629
1.95k
    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.45k
  SourceRange SR = VD->getSourceRange();
638
2.45k
  QualType Ty = VD->getType();
639
2.45k
  if (Ty->isPointerType() || 
Ty->isReferenceType()1.64k
||
640
2.45k
      
Ty->isMemberPointerType()1.61k
) {
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.49k
  } 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.38k
  } else {
659
1.38k
    mangleType(Ty, SR, QMM_Drop);
660
1.38k
    mangleQualifiers(Ty.getQualifiers(), false);
661
1.38k
  }
662
2.45k
}
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.8k
void MicrosoftCXXNameMangler::mangleName(GlobalDecl GD) {
791
  // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
792
793
  // Always start with the unqualified name.
794
41.8k
  mangleUnqualifiedName(GD);
795
796
41.8k
  mangleNestedName(GD);
797
798
  // Terminate the whole name with an '@'.
799
41.8k
  Out << '@';
800
41.8k
}
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.82k
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.82k
  llvm::APInt Value =
812
5.82k
      Number.isSigned() ? 
Number.sextOrSelf(64)5.47k
:
Number.zextOrSelf(64)347
;
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.82k
  if (Value.isNegative()) {
821
472
    Value = -Value;
822
472
    Out << '?';
823
472
  }
824
5.82k
  mangleBits(Value);
825
5.82k
}
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.85k
void MicrosoftCXXNameMangler::mangleBits(llvm::APInt Value) {
847
5.85k
  if (Value == 0)
848
1.27k
    Out << "A@";
849
4.58k
  else if (Value.uge(1) && Value.ule(10))
850
2.47k
    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.85k
}
863
864
static GlobalDecl isTemplate(GlobalDecl GD,
865
60.0k
                             const TemplateArgumentList *&TemplateArgs) {
866
60.0k
  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
867
  // Check if we have a function template.
868
60.0k
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
869
24.5k
    if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
870
896
      TemplateArgs = FD->getTemplateSpecializationArgs();
871
896
      return GD.getWithDecl(TD);
872
896
    }
873
24.5k
  }
874
875
  // Check if we have a class template.
876
59.1k
  if (const ClassTemplateSpecializationDecl *Spec =
877
59.1k
          dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
878
4.85k
    TemplateArgs = &Spec->getTemplateArgs();
879
4.85k
    return GD.getWithDecl(Spec->getSpecializedTemplate());
880
4.85k
  }
881
882
  // Check if we have a variable template.
883
54.3k
  if (const VarTemplateSpecializationDecl *Spec =
884
54.3k
          dyn_cast<VarTemplateSpecializationDecl>(ND)) {
885
218
    TemplateArgs = &Spec->getTemplateArgs();
886
218
    return GD.getWithDecl(Spec->getSpecializedTemplate());
887
218
  }
888
889
54.1k
  return GlobalDecl();
890
54.3k
}
891
892
void MicrosoftCXXNameMangler::mangleUnqualifiedName(GlobalDecl GD,
893
60.0k
                                                    DeclarationName Name) {
894
60.0k
  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.0k
  const TemplateArgumentList *TemplateArgs = nullptr;
902
60.0k
  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.96k
    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.06k
    ArgBackRefMap::iterator Found = TemplateArgBackReferences.find(ND);
931
5.06k
    if (Found == TemplateArgBackReferences.end()) {
932
933
2.68k
      TemplateArgStringMap::iterator Found = TemplateArgStrings.find(ND);
934
2.68k
      if (Found == TemplateArgStrings.end()) {
935
        // Mangle full template name into temporary buffer.
936
2.68k
        llvm::SmallString<64> TemplateMangling;
937
2.68k
        llvm::raw_svector_ostream Stream(TemplateMangling);
938
2.68k
        MicrosoftCXXNameMangler Extra(Context, Stream);
939
2.68k
        Extra.mangleTemplateInstantiationName(TD, *TemplateArgs);
940
941
        // Use the string backref vector to possibly get a back reference.
942
2.68k
        mangleSourceName(TemplateMangling);
943
944
        // Memoize back reference for this type if one exist, else memoize
945
        // the mangling itself.
946
2.68k
        BackRefVec::iterator StringFound =
947
2.68k
            llvm::find(NameBackReferences, TemplateMangling);
948
2.68k
        if (StringFound != NameBackReferences.end()) {
949
2.68k
          TemplateArgBackReferences[ND] =
950
2.68k
              StringFound - NameBackReferences.begin();
951
2.68k
        } else {
952
1
          TemplateArgStrings[ND] =
953
1
              TemplateArgStringStorage.save(TemplateMangling.str());
954
1
        }
955
2.68k
      } else {
956
1
        Out << Found->second << '@'; // Outputs a StringRef.
957
1
      }
958
2.68k
    } else {
959
2.38k
      Out << Found->second; // Outputs a back reference (an int).
960
2.38k
    }
961
5.06k
    return;
962
5.96k
  }
963
964
54.1k
  switch (Name.getNameKind()) {
965
50.5k
    case DeclarationName::Identifier: {
966
50.5k
      if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
967
49.9k
        bool IsDeviceStub =
968
49.9k
            ND &&
969
49.9k
            ((isa<FunctionDecl>(ND) && 
ND->hasAttr<CUDAGlobalAttr>()20.1k
) ||
970
49.9k
             
(49.9k
isa<FunctionTemplateDecl>(ND)49.9k
&&
971
49.9k
              cast<FunctionTemplateDecl>(ND)
972
872
                  ->getTemplatedDecl()
973
872
                  ->hasAttr<CUDAGlobalAttr>())) &&
974
49.9k
            
GD.getKernelReferenceKind() == KernelReferenceKind::Stub24
;
975
49.9k
        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
49.9k
        break;
981
49.9k
      }
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
836
    case DeclarationName::CXXDestructorName:
1144
836
      if (isStructorDecl(ND))
1145
        // If the named decl is the C++ destructor we're mangling,
1146
        // use the type we were given.
1147
832
        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
836
      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.1k
  }
1176
54.1k
}
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.5k
  while (!DC->isTranslationUnit()) {
1184
15.1k
    if (isa<TagDecl>(ND) || 
isa<VarDecl>(ND)7.92k
) {
1185
8.52k
      unsigned Disc;
1186
8.52k
      if (Context.getNextDiscriminator(ND, Disc)) {
1187
596
        Out << '?';
1188
596
        mangleNumber(Disc);
1189
596
        Out << '?';
1190
596
      }
1191
8.52k
    }
1192
1193
15.1k
    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.5k
      } else {
1267
14.5k
        mangleUnqualifiedName(ND);
1268
        // Lambdas in default arguments conceptually belong to the function the
1269
        // parameter corresponds to.
1270
14.5k
        if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(ND)) {
1271
26
          DC = LDADC;
1272
26
          continue;
1273
26
        }
1274
14.5k
      }
1275
15.1k
    }
1276
14.5k
    DC = DC->getParent();
1277
14.5k
  }
1278
41.9k
}
1279
1280
836
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
836
  switch (T) {
1285
  // <operator-name> ::= ?1  # destructor
1286
525
  case Dtor_Base: Out << "?1"; return;
1287
  // <operator-name> ::= ?_D # vbase destructor
1288
95
  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
836
  }
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.4k
void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) {
1437
  // <source name> ::= <identifier> @
1438
79.4k
  BackRefVec::iterator Found = llvm::find(NameBackReferences, Name);
1439
79.4k
  if (Found == NameBackReferences.end()) {
1440
66.5k
    if (NameBackReferences.size() < 10)
1441
66.5k
      NameBackReferences.push_back(std::string(Name));
1442
66.5k
    Out << Name << '@';
1443
66.5k
  } else {
1444
12.8k
    Out << (Found - NameBackReferences.begin());
1445
12.8k
  }
1446
79.4k
}
1447
1448
0
void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1449
0
  Context.mangleObjCMethodNameAsSourceName(MD, Out);
1450
0
}
1451
1452
void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
1453
3.58k
    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.58k
  ArgBackRefMap OuterFunArgsContext;
1460
3.58k
  ArgBackRefMap OuterTemplateArgsContext;
1461
3.58k
  BackRefVec OuterTemplateContext;
1462
3.58k
  PassObjectSizeArgsSet OuterPassObjectSizeArgs;
1463
3.58k
  NameBackReferences.swap(OuterTemplateContext);
1464
3.58k
  FunArgBackReferences.swap(OuterFunArgsContext);
1465
3.58k
  TemplateArgBackReferences.swap(OuterTemplateArgsContext);
1466
3.58k
  PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
1467
1468
3.58k
  mangleUnscopedTemplateName(GD);
1469
3.58k
  mangleTemplateArgs(cast<TemplateDecl>(GD.getDecl()), TemplateArgs);
1470
1471
  // Restore the previous back reference contexts.
1472
3.58k
  NameBackReferences.swap(OuterTemplateContext);
1473
3.58k
  FunArgBackReferences.swap(OuterFunArgsContext);
1474
3.58k
  TemplateArgBackReferences.swap(OuterTemplateArgsContext);
1475
3.58k
  PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
1476
3.58k
}
1477
1478
3.58k
void MicrosoftCXXNameMangler::mangleUnscopedTemplateName(GlobalDecl GD) {
1479
  // <unscoped-template-name> ::= ?$ <unqualified-name>
1480
3.58k
  Out << "?$";
1481
3.58k
  mangleUnqualifiedName(GD);
1482
3.58k
}
1483
1484
void MicrosoftCXXNameMangler::mangleIntegerLiteral(
1485
    const llvm::APSInt &Value, const NonTypeTemplateParmDecl *PD,
1486
629
    QualType TemplateArgType) {
1487
  // <integer-literal> ::= $0 <number>
1488
629
  Out << "$";
1489
1490
  // Since MSVC 2019, add 'M[<type>]' after '$' for auto template parameter when
1491
  // argument is integer.
1492
629
  if (getASTContext().getLangOpts().isCompatibleWithMSVC(
1493
629
          LangOptions::MSVC2019) &&
1494
629
      
PD27
&&
PD->getType()->getTypeClass() == Type::Auto27
&&
1495
629
      
!TemplateArgType.isNull()11
) {
1496
11
    Out << "M";
1497
11
    mangleType(TemplateArgType, SourceRange(), QMM_Drop);
1498
11
  }
1499
1500
629
  Out << "0";
1501
1502
629
  mangleNumber(Value);
1503
629
}
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.58k
    const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1524
  // <template-args> ::= <template-arg>+
1525
3.58k
  const TemplateParameterList *TPL = TD->getTemplateParameters();
1526
3.58k
  assert(TPL->size() == TemplateArgs.size() &&
1527
3.58k
         "size mismatch between args and parms!");
1528
1529
11.2k
  for (size_t i = 0; i < TemplateArgs.size(); 
++i7.66k
) {
1530
7.66k
    const TemplateArgument &TA = TemplateArgs[i];
1531
1532
    // Separate consecutive packs by $$Z.
1533
7.66k
    if (i > 0 && 
TA.getKind() == TemplateArgument::Pack4.08k
&&
1534
7.66k
        
TemplateArgs[i - 1].getKind() == TemplateArgument::Pack17
)
1535
8
      Out << "$$Z";
1536
1537
7.66k
    mangleTemplateArg(TD, TA, TPL->getParam(i));
1538
7.66k
  }
1539
3.58k
}
1540
1541
void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
1542
                                                const TemplateArgument &TA,
1543
7.80k
                                                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.80k
  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
315
  case TemplateArgument::Integral: {
1614
315
    QualType T = TA.getIntegralType();
1615
315
    mangleIntegerLiteral(TA.getAsIntegral(),
1616
315
                         cast<NonTypeTemplateParmDecl>(Parm), T);
1617
315
    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.80k
  }
1688
7.80k
}
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.0k
                                               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.0k
  bool HasConst = Quals.hasConst(),
2009
28.0k
       HasVolatile = Quals.hasVolatile();
2010
2011
28.0k
  if (!IsMember) {
2012
27.8k
    if (HasConst && 
HasVolatile3.47k
) {
2013
29
      Out << 'D';
2014
27.7k
    } else if (HasVolatile) {
2015
90
      Out << 'C';
2016
27.6k
    } else if (HasConst) {
2017
3.45k
      Out << 'B';
2018
24.2k
    } else {
2019
24.2k
      Out << 'A';
2020
24.2k
    }
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.0k
}
2035
2036
void
2037
5.87k
MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2038
  // <ref-qualifier> ::= G                # lvalue reference
2039
  //                 ::= H                # rvalue-reference
2040
5.87k
  switch (RefQualifier) {
2041
5.84k
  case RQ_None:
2042
5.84k
    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.87k
  }
2052
5.87k
}
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.83k
:
2058
13.2k
      
is64BitPointer(PointeeType.getQualifiers())6.40k
;
2059
13.2k
  if (is64Bit && 
(5.79k
PointeeType.isNull()5.79k
||
!PointeeType->isFunctionType()2.65k
))
2060
5.58k
    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.3k
    size_t OutSizeBefore = Out.tell();
2124
2125
28.3k
    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.3k
    bool LongerThanOneChar = (Out.tell() - OutSizeBefore > 1);
2131
28.3k
    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.3k
  } 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.0k
  bool IsPointer = T->isAnyPointerType() || 
T->isMemberPointerType()64.9k
||
2255
69.0k
                   
T->isReferenceType()64.4k
||
T->isBlockPointerType()62.6k
;
2256
2257
69.0k
  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.35k
  case QMM_Mangle:
2263
6.35k
    if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
2264
190
      Out << '6';
2265
190
      mangleFunctionType(FT);
2266
190
      return;
2267
190
    }
2268
6.16k
    mangleQualifiers(Quals, false);
2269
6.16k
    break;
2270
7.75k
  case QMM_Escape:
2271
7.75k
    if (!IsPointer && 
Quals7.62k
) {
2272
64
      Out << "$$C";
2273
64
      mangleQualifiers(Quals, false);
2274
64
    }
2275
7.75k
    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.0k
  }
2287
2288
68.8k
  const Type *ty = T.getTypePtr();
2289
2290
68.8k
  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.8k
  case Type::CLASS: \
2298
68.8k
    mangleType(cast<CLASS##Type>(ty), Quals, Range); \
2299
68.8k
    break;
2300
68.8k
#include 
"clang/AST/TypeNodes.inc"0
2301
68.8k
#undef ABSTRACT_TYPE
2302
68.8k
#undef NON_CANONICAL_TYPE
2303
68.8k
#undef TYPE
2304
68.8k
  }
2305
68.8k
}
2306
2307
void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers,
2308
28.3k
                                         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.3k
  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.53k
  case BuiltinType::UInt:
2360
1.53k
    Out << 'I';
2361
1.53k
    break;
2362
81
  case BuiltinType::Long:
2363
81
    Out << 'J';
2364
81
    break;
2365
29
  case BuiltinType::ULong:
2366
29
    Out << 'K';
2367
29
    break;
2368
531
  case BuiltinType::Float:
2369
531
    Out << 'M';
2370
531
    break;
2371
476
  case BuiltinType::Double:
2372
476
    Out << 'N';
2373
476
    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
595
  case BuiltinType::ULongLong:
2382
595
    Out << "_K";
2383
595
    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
2
  case BuiltinType::Half:
2464
2
    mangleArtificialTagType(TTK_Struct, "_Half", {"__clang"});
2465
2
    break;
2466
2467
0
#define SVE_TYPE(Name, Id, SingletonId) \
2468
49
  case BuiltinType::Id:
2469
49
#include 
"clang/Basic/AArch64SVEACLETypes.def"2
2470
49
#define PPC_VECTOR_TYPE(Name, Id, Size) \
2471
49
  
case BuiltinType::Id:2
2472
49
#include 
"clang/Basic/PPCTypes.def"1
2473
66
#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2474
66
#include 
"clang/Basic/RISCVVTypes.def"1
2475
66
  case BuiltinType::ShortAccum:
2476
1
  case BuiltinType::Accum:
2477
1
  case BuiltinType::LongAccum:
2478
1
  case BuiltinType::UShortAccum:
2479
1
  case BuiltinType::UAccum:
2480
1
  case BuiltinType::ULongAccum:
2481
1
  case BuiltinType::ShortFract:
2482
1
  case BuiltinType::Fract:
2483
1
  case BuiltinType::LongFract:
2484
1
  case BuiltinType::UShortFract:
2485
1
  case BuiltinType::UFract:
2486
1
  case BuiltinType::ULongFract:
2487
1
  case BuiltinType::SatShortAccum:
2488
1
  case BuiltinType::SatAccum:
2489
1
  case BuiltinType::SatLongAccum:
2490
1
  case BuiltinType::SatUShortAccum:
2491
1
  case BuiltinType::SatUAccum:
2492
1
  case BuiltinType::SatULongAccum:
2493
1
  case BuiltinType::SatShortFract:
2494
1
  case BuiltinType::SatFract:
2495
1
  case BuiltinType::SatLongFract:
2496
1
  case BuiltinType::SatUShortFract:
2497
1
  case BuiltinType::SatUFract:
2498
1
  case BuiltinType::SatULongFract:
2499
1
  case BuiltinType::BFloat16:
2500
1
  case BuiltinType::Ibm128:
2501
1
  case BuiltinType::Float128: {
2502
1
    DiagnosticsEngine &Diags = Context.getDiags();
2503
1
    unsigned DiagID = Diags.getCustomDiagID(
2504
1
        DiagnosticsEngine::Error, "cannot mangle this built-in %0 type yet");
2505
1
    Diags.Report(Range.getBegin(), DiagID)
2506
1
        << T->getName(Context.getASTContext().getPrintingPolicy()) << Range;
2507
1
    break;
2508
1
  }
2509
28.3k
  }
2510
28.3k
}
2511
2512
// <type>          ::= <function-type>
2513
void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers,
2514
138
                                         SourceRange) {
2515
  // Structors only appear in decls, so at this point we know it's not a
2516
  // structor type.
2517
  // FIXME: This may not be lambda-friendly.
2518
138
  if (T->getMethodQuals() || 
T->getRefQualifier() != RQ_None102
) {
2519
44
    Out << "$$A8@@";
2520
44
    mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true);
2521
94
  } else {
2522
94
    Out << "$$A6";
2523
94
    mangleFunctionType(T);
2524
94
  }
2525
138
}
2526
void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
2527
0
                                         Qualifiers, SourceRange) {
2528
0
  Out << "$$A6";
2529
0
  mangleFunctionType(T);
2530
0
}
2531
2532
void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
2533
                                                 const FunctionDecl *D,
2534
                                                 bool ForceThisQuals,
2535
25.3k
                                                 bool MangleExceptionSpec) {
2536
  // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
2537
  //                     <return-type> <argument-list> <throw-spec>
2538
25.3k
  const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(T);
2539
2540
25.3k
  SourceRange Range;
2541
25.3k
  if (D) 
Range = D->getSourceRange()24.6k
;
2542
2543
25.3k
  bool IsInLambda = false;
2544
25.3k
  bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false;
2545
25.3k
  CallingConv CC = T->getCallConv();
2546
25.3k
  if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
2547
5.85k
    if (MD->getParent()->isLambda())
2548
117
      IsInLambda = true;
2549
5.85k
    if (MD->isInstance())
2550
5.48k
      HasThisQuals = true;
2551
5.85k
    if (isa<CXXDestructorDecl>(MD)) {
2552
1.00k
      IsStructor = true;
2553
4.84k
    } else if (isa<CXXConstructorDecl>(MD)) {
2554
1.63k
      IsStructor = true;
2555
1.63k
      IsCtorClosure = (StructorType == Ctor_CopyingClosure ||
2556
1.63k
                       
StructorType == Ctor_DefaultClosure1.62k
) &&
2557
1.63k
                      
isStructorDecl(MD)41
;
2558
1.63k
      if (IsCtorClosure)
2559
41
        CC = getASTContext().getDefaultCallingConvention(
2560
41
            /*IsVariadic=*/false, /*IsCXXMethod=*/true);
2561
1.63k
    }
2562
5.85k
  }
2563
2564
  // If this is a C++ instance method, mangle the CVR qualifiers for the
2565
  // this pointer.
2566
25.3k
  if (HasThisQuals) {
2567
5.87k
    Qualifiers Quals = Proto->getMethodQuals();
2568
5.87k
    manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType());
2569
5.87k
    mangleRefQualifier(Proto->getRefQualifier());
2570
5.87k
    mangleQualifiers(Quals, /*IsMember=*/false);
2571
5.87k
  }
2572
2573
25.3k
  mangleCallingConvention(CC);
2574
2575
  // <return-type> ::= <type>
2576
  //               ::= @ # structors (they have no declared return type)
2577
25.3k
  if (IsStructor) {
2578
2.63k
    if (isa<CXXDestructorDecl>(D) && 
isStructorDecl(D)1.00k
) {
2579
      // The scalar deleting destructor takes an extra int argument which is not
2580
      // reflected in the AST.
2581
1.00k
      if (StructorType == Dtor_Deleting) {
2582
386
        Out << (PointersAre64Bit ? 
"PEAXI@Z"165
:
"PAXI@Z"221
);
2583
386
        return;
2584
386
      }
2585
      // The vbase destructor returns void which is not reflected in the AST.
2586
616
      if (StructorType == Dtor_Complete) {
2587
95
        Out << "XXZ";
2588
95
        return;
2589
95
      }
2590
616
    }
2591
2.15k
    if (IsCtorClosure) {
2592
      // Default constructor closure and copy constructor closure both return
2593
      // void.
2594
41
      Out << 'X';
2595
2596
41
      if (StructorType == Ctor_DefaultClosure) {
2597
        // Default constructor closure always has no arguments.
2598
32
        Out << 'X';
2599
32
      } else 
if (9
StructorType == Ctor_CopyingClosure9
) {
2600
        // Copy constructor closure always takes an unqualified reference.
2601
9
        mangleFunctionArgumentType(getASTContext().getLValueReferenceType(
2602
9
                                       Proto->getParamType(0)
2603
9
                                           ->getAs<LValueReferenceType>()
2604
9
                                           ->getPointeeType(),
2605
9
                                       /*SpelledAsLValue=*/true),
2606
9
                                   Range);
2607
9
        Out << '@';
2608
9
      } else {
2609
0
        llvm_unreachable("unexpected constructor closure!");
2610
0
      }
2611
41
      Out << 'Z';
2612
41
      return;
2613
41
    }
2614
2.11k
    Out << '@';
2615
22.6k
  } else if (IsInLambda && 
D117
&&
isa<CXXConversionDecl>(D)117
) {
2616
    // The only lambda conversion operators are to function pointers, which
2617
    // can differ by their calling convention and are typically deduced.  So
2618
    // we make sure that this type gets mangled properly.
2619
13
    mangleType(T->getReturnType(), Range, QMM_Result);
2620
22.6k
  } else {
2621
22.6k
    QualType ResultType = T->getReturnType();
2622
22.6k
    if (IsInLambda && 
isa<CXXConversionDecl>(D)104
) {
2623
      // The only lambda conversion operators are to function pointers, which
2624
      // can differ by their calling convention and are typically deduced.  So
2625
      // we make sure that this type gets mangled properly.
2626
0
      mangleType(ResultType, Range, QMM_Result);
2627
22.6k
    } else if (const auto *AT = dyn_cast_or_null<AutoType>(
2628
22.6k
                   ResultType->getContainedAutoType())) {
2629
76
      Out << '?';
2630
76
      mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
2631
76
      Out << '?';
2632
76
      assert(AT->getKeyword() != AutoTypeKeyword::GNUAutoType &&
2633
76
             "shouldn't need to mangle __auto_type!");
2634
76
      mangleSourceName(AT->isDecltypeAuto() ? 
"<decltype-auto>"0
: "<auto>");
2635
76
      Out << '@';
2636
22.5k
    } else if (IsInLambda) {
2637
60
      Out << '@';
2638
22.5k
    } else {
2639
22.5k
      if (ResultType->isVoidType())
2640
6.26k
        ResultType = ResultType.getUnqualifiedType();
2641
22.5k
      mangleType(ResultType, Range, QMM_Result);
2642
22.5k
    }
2643
22.6k
  }
2644
2645
  // <argument-list> ::= X # void
2646
  //                 ::= <type>+ @
2647
  //                 ::= <type>* Z # varargs
2648
24.7k
  if (!Proto) {
2649
    // Function types without prototypes can arise when mangling a function type
2650
    // within an overloadable function in C. We mangle these as the absence of
2651
    // any parameter types (not even an empty parameter list).
2652
14
    Out << '@';
2653
24.7k
  } else if (Proto->getNumParams() == 0 && 
!Proto->isVariadic()7.65k
) {
2654
7.64k
    Out << 'X';
2655
17.1k
  } else {
2656
    // Happens for function pointer type arguments for example.
2657
55.6k
    for (unsigned I = 0, E = Proto->getNumParams(); I != E; 
++I38.5k
) {
2658
38.5k
      mangleFunctionArgumentType(Proto->getParamType(I), Range);
2659
      // Mangle each pass_object_size parameter as if it's a parameter of enum
2660
      // type passed directly after the parameter with the pass_object_size
2661
      // attribute. The aforementioned enum's name is __pass_object_size, and we
2662
      // pretend it resides in a top-level namespace called __clang.
2663
      //
2664
      // FIXME: Is there a defined extension notation for the MS ABI, or is it
2665
      // necessary to just cross our fingers and hope this type+namespace
2666
      // combination doesn't conflict with anything?
2667
38.5k
      if (D)
2668
38.3k
        if (const auto *P = D->getParamDecl(I)->getAttr<PassObjectSizeAttr>())
2669
34
          manglePassObjectSizeArg(P);
2670
38.5k
    }
2671
    // <builtin-type>      ::= Z  # ellipsis
2672
17.1k
    if (Proto->isVariadic())
2673
46
      Out << 'Z';
2674
17.0k
    else
2675
17.0k
      Out << '@';
2676
17.1k
  }
2677
2678
24.7k
  if (MangleExceptionSpec && 
getASTContext().getLangOpts().CPlusPlus17907
&&
2679
24.7k
      getASTContext().getLangOpts().isCompatibleWithMSVC(
2680
65
          LangOptions::MSVC2017_5))
2681
28
    mangleThrowSpecification(Proto);
2682
24.7k
  else
2683
24.7k
    Out << 'Z';
2684
24.7k
}
2685
2686
24.2k
void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
2687
  // <function-class>  ::= <member-function> E? # E designates a 64-bit 'this'
2688
  //                                            # pointer. in 64-bit mode *all*
2689
  //                                            # 'this' pointers are 64-bit.
2690
  //                   ::= <global-function>
2691
  // <member-function> ::= A # private: near
2692
  //                   ::= B # private: far
2693
  //                   ::= C # private: static near
2694
  //                   ::= D # private: static far
2695
  //                   ::= E # private: virtual near
2696
  //                   ::= F # private: virtual far
2697
  //                   ::= I # protected: near
2698
  //                   ::= J # protected: far
2699
  //                   ::= K # protected: static near
2700
  //                   ::= L # protected: static far
2701
  //                   ::= M # protected: virtual near
2702
  //                   ::= N # protected: virtual far
2703
  //                   ::= Q # public: near
2704
  //                   ::= R # public: far
2705
  //                   ::= S # public: static near
2706
  //                   ::= T # public: static far
2707
  //                   ::= U # public: virtual near
2708
  //                   ::= V # public: virtual far
2709
  // <global-function> ::= Y # global near
2710
  //                   ::= Z # global far
2711
24.2k
  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
2712
5.46k
    bool IsVirtual = MD->isVirtual();
2713
    // When mangling vbase destructor variants, ignore whether or not the
2714
    // underlying destructor was defined to be virtual.
2715
5.46k
    if (isa<CXXDestructorDecl>(MD) && 
isStructorDecl(MD)836
&&
2716
5.46k
        
StructorType == Dtor_Complete832
) {
2717
95
      IsVirtual = false;
2718
95
    }
2719
5.46k
    switch (MD->getAccess()) {
2720
0
      case AS_none:
2721
0
        llvm_unreachable("Unsupported access specifier");
2722
113
      case AS_private:
2723
113
        if (MD->isStatic())
2724
27
          Out << 'C';
2725
86
        else if (IsVirtual)
2726
51
          Out << 'E';
2727
35
        else
2728
35
          Out << 'A';
2729
113
        break;
2730
42
      case AS_protected:
2731
42
        if (MD->isStatic())
2732
14
          Out << 'K';
2733
28
        else if (IsVirtual)
2734
14
          Out << 'M';
2735
14
        else
2736
14
          Out << 'I';
2737
42
        break;
2738
5.31k
      case AS_public:
2739
5.31k
        if (MD->isStatic())
2740
323
          Out << 'S';
2741
4.98k
        else if (IsVirtual)
2742
1.06k
          Out << 'U';
2743
3.92k
        else
2744
3.92k
          Out << 'Q';
2745
5.46k
    }
2746
18.7k
  } else {
2747
18.7k
    Out << 'Y';
2748
18.7k
  }
2749
24.2k
}
2750
25.3k
void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) {
2751
  // <calling-convention> ::= A # __cdecl
2752
  //                      ::= B # __export __cdecl
2753
  //                      ::= C # __pascal
2754
  //                      ::= D # __export __pascal
2755
  //                      ::= E # __thiscall
2756
  //                      ::= F # __export __thiscall
2757
  //                      ::= G # __stdcall
2758
  //                      ::= H # __export __stdcall
2759
  //                      ::= I # __fastcall
2760
  //                      ::= J # __export __fastcall
2761
  //                      ::= Q # __vectorcall
2762
  //                      ::= S # __attribute__((__swiftcall__)) // Clang-only
2763
  //                      ::= T # __attribute__((__swiftasynccall__))
2764
  //                            // Clang-only
2765
  //                      ::= w # __regcall
2766
  // The 'export' calling conventions are from a bygone era
2767
  // (*cough*Win16*cough*) when functions were declared for export with
2768
  // that keyword. (It didn't actually export them, it just made them so
2769
  // that they could be in a DLL and somebody from another module could call
2770
  // them.)
2771
2772
25.3k
  switch (CC) {
2773
0
    default:
2774
0
      llvm_unreachable("Unsupported CC for mangling");
2775
0
    case CC_Win64:
2776
0
    case CC_X86_64SysV:
2777
22.1k
    case CC_C: Out << 'A'; break;
2778
1
    case CC_X86Pascal: Out << 'C'; break;
2779
3.13k
    case CC_X86ThisCall: Out << 'E'; break;
2780
20
    case CC_X86StdCall: Out << 'G'; break;
2781
12
    case CC_X86FastCall: Out << 'I'; break;
2782
13
    case CC_X86VectorCall: Out << 'Q'; break;
2783
13
    case CC_Swift: Out << 'S'; break;
2784
0
    case CC_SwiftAsync: Out << 'W'; break;
2785
12
    case CC_PreserveMost: Out << 'U'; break;
2786
23
    case CC_X86RegCall: Out << 'w'; break;
2787
25.3k
  }
2788
25.3k
}
2789
64
void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
2790
64
  mangleCallingConvention(T->getCallConv());
2791
64
}
2792
2793
void MicrosoftCXXNameMangler::mangleThrowSpecification(
2794
28
                                                const FunctionProtoType *FT) {
2795
  // <throw-spec> ::= Z # (default)
2796
  //              ::= _E # noexcept
2797
28
  if (FT->canThrow())
2798
14
    Out << 'Z';
2799
14
  else
2800
14
    Out << "_E";
2801
28
}
2802
2803
void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
2804
0
                                         Qualifiers, SourceRange Range) {
2805
  // Probably should be mangled as a template instantiation; need to see what
2806
  // VC does first.
2807
0
  DiagnosticsEngine &Diags = Context.getDiags();
2808
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2809
0
    "cannot mangle this unresolved dependent type yet");
2810
0
  Diags.Report(Range.getBegin(), DiagID)
2811
0
    << Range;
2812
0
}
2813
2814
// <type>        ::= <union-type> | <struct-type> | <class-type> | <enum-type>
2815
// <union-type>  ::= T <name>
2816
// <struct-type> ::= U <name>
2817
// <class-type>  ::= V <name>
2818
// <enum-type>   ::= W4 <name>
2819
34.1k
void MicrosoftCXXNameMangler::mangleTagTypeKind(TagTypeKind TTK) {
2820
34.1k
  switch (TTK) {
2821
20.9k
    case TTK_Union:
2822
20.9k
      Out << 'T';
2823
20.9k
      break;
2824
12.0k
    case TTK_Struct:
2825
12.0k
    case TTK_Interface:
2826
12.0k
      Out << 'U';
2827
12.0k
      break;
2828
772
    case TTK_Class:
2829
772
      Out << 'V';
2830
772
      break;
2831
338
    case TTK_Enum:
2832
338
      Out << "W4";
2833
338
      break;
2834
34.1k
  }
2835
34.1k
}
2836
void MicrosoftCXXNameMangler::mangleType(const EnumType *T, Qualifiers,
2837
307
                                         SourceRange) {
2838
307
  mangleType(cast<TagType>(T)->getDecl());
2839
307
}
2840
void MicrosoftCXXNameMangler::mangleType(const RecordType *T, Qualifiers,
2841
8.24k
                                         SourceRange) {
2842
8.24k
  mangleType(cast<TagType>(T)->getDecl());
2843
8.24k
}
2844
8.57k
void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
2845
8.57k
  mangleTagTypeKind(TD->getTagKind());
2846
8.57k
  mangleName(TD);
2847
8.57k
}
2848
2849
// If you add a call to this, consider updating isArtificialTagType() too.
2850
void MicrosoftCXXNameMangler::mangleArtificialTagType(
2851
    TagTypeKind TK, StringRef UnqualifiedName,
2852
25.5k
    ArrayRef<StringRef> NestedNames) {
2853
  // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
2854
25.5k
  mangleTagTypeKind(TK);
2855
2856
  // Always start with the unqualified name.
2857
25.5k
  mangleSourceName(UnqualifiedName);
2858
2859
25.5k
  for (StringRef N : llvm::reverse(NestedNames))
2860
421
    mangleSourceName(N);
2861
2862
  // Terminate the whole name with an '@'.
2863
25.5k
  Out << '@';
2864
25.5k
}
2865
2866
// <type>       ::= <array-type>
2867
// <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2868
//                  [Y <dimension-count> <dimension>+]
2869
//                  <element-type> # as global, E is never required
2870
// It's supposed to be the other way around, but for some strange reason, it
2871
// isn't. Today this behavior is retained for the sole purpose of backwards
2872
// compatibility.
2873
110
void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
2874
  // This isn't a recursive mangling, so now we have to do it all in this
2875
  // one call.
2876
110
  manglePointerCVQualifiers(T->getElementType().getQualifiers());
2877
110
  mangleType(T->getElementType(), SourceRange());
2878
110
}
2879
void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T, Qualifiers,
2880
0
                                         SourceRange) {
2881
0
  llvm_unreachable("Should have been special cased");
2882
0
}
2883
void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T, Qualifiers,
2884
0
                                         SourceRange) {
2885
0
  llvm_unreachable("Should have been special cased");
2886
0
}
2887
void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
2888
0
                                         Qualifiers, SourceRange) {
2889
0
  llvm_unreachable("Should have been special cased");
2890
0
}
2891
void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
2892
0
                                         Qualifiers, SourceRange) {
2893
0
  llvm_unreachable("Should have been special cased");
2894
0
}
2895
62
void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
2896
62
  QualType ElementTy(T, 0);
2897
62
  SmallVector<llvm::APInt, 3> Dimensions;
2898
135
  for (;;) {
2899
135
    if (ElementTy->isConstantArrayType()) {
2900
67
      const ConstantArrayType *CAT =
2901
67
          getASTContext().getAsConstantArrayType(ElementTy);
2902
67
      Dimensions.push_back(CAT->getSize());
2903
67
      ElementTy = CAT->getElementType();
2904
68
    } else if (ElementTy->isIncompleteArrayType()) {
2905
4
      const IncompleteArrayType *IAT =
2906
4
          getASTContext().getAsIncompleteArrayType(ElementTy);
2907
4
      Dimensions.push_back(llvm::APInt(32, 0));
2908
4
      ElementTy = IAT->getElementType();
2909
64
    } else if (ElementTy->isVariableArrayType()) {
2910
2
      const VariableArrayType *VAT =
2911
2
        getASTContext().getAsVariableArrayType(ElementTy);
2912
2
      Dimensions.push_back(llvm::APInt(32, 0));
2913
2
      ElementTy = VAT->getElementType();
2914
62
    } else if (ElementTy->isDependentSizedArrayType()) {
2915
      // The dependent expression has to be folded into a constant (TODO).
2916
0
      const DependentSizedArrayType *DSAT =
2917
0
        getASTContext().getAsDependentSizedArrayType(ElementTy);
2918
0
      DiagnosticsEngine &Diags = Context.getDiags();
2919
0
      unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2920
0
        "cannot mangle this dependent-length array yet");
2921
0
      Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
2922
0
        << DSAT->getBracketsRange();
2923
0
      return;
2924
62
    } else {
2925
62
      break;
2926
62
    }
2927
135
  }
2928
62
  Out << 'Y';
2929
  // <dimension-count> ::= <number> # number of extra dimensions
2930
62
  mangleNumber(Dimensions.size());
2931
62
  for (const llvm::APInt &Dimension : Dimensions)
2932
73
    mangleNumber(Dimension.getLimitedValue());
2933
62
  mangleType(ElementTy, SourceRange(), QMM_Escape);
2934
62
}
2935
2936
// <type>                   ::= <pointer-to-member-type>
2937
// <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2938
//                                                          <class name> <type>
2939
void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T,
2940
464
                                         Qualifiers Quals, SourceRange Range) {
2941
464
  QualType PointeeType = T->getPointeeType();
2942
464
  manglePointerCVQualifiers(Quals);
2943
464
  manglePointerExtQualifiers(Quals, PointeeType);
2944
464
  if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
2945
348
    Out << '8';
2946
348
    mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2947
348
    mangleFunctionType(FPT, nullptr, true);
2948
348
  } else {
2949
116
    mangleQualifiers(PointeeType.getQualifiers(), true);
2950
116
    mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2951
116
    mangleType(PointeeType, Range, QMM_Drop);
2952
116
  }
2953
464
}
2954
2955
void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
2956
0
                                         Qualifiers, SourceRange Range) {
2957
0
  DiagnosticsEngine &Diags = Context.getDiags();
2958
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2959
0
    "cannot mangle this template type parameter type yet");
2960
0
  Diags.Report(Range.getBegin(), DiagID)
2961
0
    << Range;
2962
0
}
2963
2964
void MicrosoftCXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T,
2965
0
                                         Qualifiers, SourceRange Range) {
2966
0
  DiagnosticsEngine &Diags = Context.getDiags();
2967
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2968
0
    "cannot mangle this substituted parameter pack yet");
2969
0
  Diags.Report(Range.getBegin(), DiagID)
2970
0
    << Range;
2971
0
}
2972
2973
// <type> ::= <pointer-type>
2974
// <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
2975
//                       # the E is required for 64-bit non-static pointers
2976
void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals,
2977
4.05k
                                         SourceRange Range) {
2978
4.05k
  QualType PointeeType = T->getPointeeType();
2979
4.05k
  manglePointerCVQualifiers(Quals);
2980
4.05k
  manglePointerExtQualifiers(Quals, PointeeType);
2981
2982
  // For pointer size address spaces, go down the same type mangling path as
2983
  // non address space types.
2984
4.05k
  LangAS AddrSpace = PointeeType.getQualifiers().getAddressSpace();
2985
4.05k
  if (isPtrSizeAddressSpace(AddrSpace) || 
AddrSpace == LangAS::Default4.05k
)
2986
4.03k
    mangleType(PointeeType, Range);
2987
25
  else
2988
25
    mangleAddressSpaceType(PointeeType, PointeeType.getQualifiers(), Range);
2989
4.05k
}
2990
2991
void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
2992
75
                                         Qualifiers Quals, SourceRange Range) {
2993
75
  QualType PointeeType = T->getPointeeType();
2994
75
  switch (Quals.getObjCLifetime()) {
2995
65
  case Qualifiers::OCL_None:
2996
66
  case Qualifiers::OCL_ExplicitNone:
2997
66
    break;
2998
2
  case Qualifiers::OCL_Autoreleasing:
2999
6
  case Qualifiers::OCL_Strong:
3000
9
  case Qualifiers::OCL_Weak:
3001
9
    return mangleObjCLifetime(PointeeType, Quals, Range);
3002
75
  }
3003
66
  manglePointerCVQualifiers(Quals);
3004
66
  manglePointerExtQualifiers(Quals, PointeeType);
3005
66
  mangleType(PointeeType, Range);
3006
66
}
3007
3008
// <type> ::= <reference-type>
3009
// <reference-type> ::= A E? <cvr-qualifiers> <type>
3010
//                 # the E is required for 64-bit non-static lvalue references
3011
void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
3012
1.51k
                                         Qualifiers Quals, SourceRange Range) {
3013
1.51k
  QualType PointeeType = T->getPointeeType();
3014
1.51k
  assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
3015
0
  Out << 'A';
3016
1.51k
  manglePointerExtQualifiers(Quals, PointeeType);
3017
1.51k
  mangleType(PointeeType, Range);
3018
1.51k
}
3019
3020
// <type> ::= <r-value-reference-type>
3021
// <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
3022
//                 # the E is required for 64-bit non-static rvalue references
3023
void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
3024
271
                                         Qualifiers Quals, SourceRange Range) {
3025
271
  QualType PointeeType = T->getPointeeType();
3026
271
  assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
3027
0
  Out << "$$Q";
3028
271
  manglePointerExtQualifiers(Quals, PointeeType);
3029
271
  mangleType(PointeeType, Range);
3030
271
}
3031
3032
void MicrosoftCXXNameMangler::mangleType(const ComplexType *T, Qualifiers,
3033
38
                                         SourceRange Range) {
3034
38
  QualType ElementType = T->getElementType();
3035
3036
38
  llvm::SmallString<64> TemplateMangling;
3037
38
  llvm::raw_svector_ostream Stream(TemplateMangling);
3038
38
  MicrosoftCXXNameMangler Extra(Context, Stream);
3039
38
  Stream << "?$";
3040
38
  Extra.mangleSourceName("_Complex");
3041
38
  Extra.mangleType(ElementType, Range, QMM_Escape);
3042
3043
38
  mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
3044
38
}
3045
3046
// Returns true for types that mangleArtificialTagType() gets called for with
3047
// TTK_Union, TTK_Struct, TTK_Class and where compatibility with MSVC's
3048
// mangling matters.
3049
// (It doesn't matter for Objective-C types and the like that cl.exe doesn't
3050
// support.)
3051
22.4k
bool MicrosoftCXXNameMangler::isArtificialTagType(QualType T) const {
3052
22.4k
  const Type *ty = T.getTypePtr();
3053
22.4k
  switch (ty->getTypeClass()) {
3054
10.7k
  default:
3055
10.7k
    return false;
3056
3057
11.7k
  case Type::Vector: {
3058
    // For ABI compatibility only __m64, __m128(id), and __m256(id) matter,
3059
    // but since mangleType(VectorType*) always calls mangleArtificialTagType()
3060
    // just always return true (the other vector types are clang-only).
3061
11.7k
    return true;
3062
0
  }
3063
22.4k
  }
3064
22.4k
}
3065
3066
void MicrosoftCXXNameMangler::mangleType(const VectorType *T, Qualifiers Quals,
3067
25.1k
                                         SourceRange Range) {
3068
25.1k
  const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>();
3069
25.1k
  assert(ET && "vectors with non-builtin elements are unsupported");
3070
0
  uint64_t Width = getASTContext().getTypeSize(T);
3071
  // Pattern match exactly the typedefs in our intrinsic headers.  Anything that
3072
  // doesn't match the Intel types uses a custom mangling below.
3073
25.1k
  size_t OutSizeBefore = Out.tell();
3074
25.1k
  if (!isa<ExtVectorType>(T)) {
3075
25.1k
    if (getASTContext().getTargetInfo().getTriple().isX86()) {
3076
25.1k
      if (Width == 64 && 
ET->getKind() == BuiltinType::LongLong1.41k
) {
3077
1.41k
        mangleArtificialTagType(TTK_Union, "__m64");
3078
23.7k
      } else if (Width >= 128) {
3079
23.7k
        if (ET->getKind() == BuiltinType::Float)
3080
4.67k
          mangleArtificialTagType(TTK_Union, "__m" + llvm::utostr(Width));
3081
19.0k
        else if (ET->getKind() == BuiltinType::LongLong)
3082
14.7k
          mangleArtificialTagType(TTK_Union, "__m" + llvm::utostr(Width) + 'i');
3083
4.31k
        else if (ET->getKind() == BuiltinType::Double)
3084
4.17k
          mangleArtificialTagType(TTK_Struct, "__m" + llvm::utostr(Width) + 'd');
3085
23.7k
      }
3086
25.1k
    }
3087
25.1k
  }
3088
3089
25.1k
  bool IsBuiltin = Out.tell() != OutSizeBefore;
3090
25.1k
  if (!IsBuiltin) {
3091
    // The MS ABI doesn't have a special mangling for vector types, so we define
3092
    // our own mangling to handle uses of __vector_size__ on user-specified
3093
    // types, and for extensions like __v4sf.
3094
3095
158
    llvm::SmallString<64> TemplateMangling;
3096
158
    llvm::raw_svector_ostream Stream(TemplateMangling);
3097
158
    MicrosoftCXXNameMangler Extra(Context, Stream);
3098
158
    Stream << "?$";
3099
158
    Extra.mangleSourceName("__vector");
3100
158
    Extra.mangleType(QualType(ET, 0), Range, QMM_Escape);
3101
158
    Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(T->getNumElements()));
3102
3103
158
    mangleArtificialTagType(TTK_Union, TemplateMangling, {"__clang"});
3104
158
  }
3105
25.1k
}
3106
3107
void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
3108
18
                                         Qualifiers Quals, SourceRange Range) {
3109
18
  mangleType(static_cast<const VectorType *>(T), Quals, Range);
3110
18
}
3111
3112
void MicrosoftCXXNameMangler::mangleType(const DependentVectorType *T,
3113
0
                                         Qualifiers, SourceRange Range) {
3114
0
  DiagnosticsEngine &Diags = Context.getDiags();
3115
0
  unsigned DiagID = Diags.getCustomDiagID(
3116
0
      DiagnosticsEngine::Error,
3117
0
      "cannot mangle this dependent-sized vector type yet");
3118
0
  Diags.Report(Range.getBegin(), DiagID) << Range;
3119
0
}
3120
3121
void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
3122
0
                                         Qualifiers, SourceRange Range) {
3123
0
  DiagnosticsEngine &Diags = Context.getDiags();
3124
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3125
0
    "cannot mangle this dependent-sized extended vector type yet");
3126
0
  Diags.Report(Range.getBegin(), DiagID)
3127
0
    << Range;
3128
0
}
3129
3130
void MicrosoftCXXNameMangler::mangleType(const ConstantMatrixType *T,
3131
0
                                         Qualifiers quals, SourceRange Range) {
3132
0
  DiagnosticsEngine &Diags = Context.getDiags();
3133
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3134
0
                                          "Cannot mangle this matrix type yet");
3135
0
  Diags.Report(Range.getBegin(), DiagID) << Range;
3136
0
}
3137
3138
void MicrosoftCXXNameMangler::mangleType(const DependentSizedMatrixType *T,
3139
0
                                         Qualifiers quals, SourceRange Range) {
3140
0
  DiagnosticsEngine &Diags = Context.getDiags();
3141
0
  unsigned DiagID = Diags.getCustomDiagID(
3142
0
      DiagnosticsEngine::Error,
3143
0
      "Cannot mangle this dependent-sized matrix type yet");
3144
0
  Diags.Report(Range.getBegin(), DiagID) << Range;
3145
0
}
3146
3147
void MicrosoftCXXNameMangler::mangleType(const DependentAddressSpaceType *T,
3148
0
                                         Qualifiers, SourceRange Range) {
3149
0
  DiagnosticsEngine &Diags = Context.getDiags();
3150
0
  unsigned DiagID = Diags.getCustomDiagID(
3151
0
      DiagnosticsEngine::Error,
3152
0
      "cannot mangle this dependent address space type yet");
3153
0
  Diags.Report(Range.getBegin(), DiagID) << Range;
3154
0
}
3155
3156
void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T, Qualifiers,
3157
24
                                         SourceRange) {
3158
  // ObjC interfaces have structs underlying them.
3159
24
  mangleTagTypeKind(TTK_Struct);
3160
24
  mangleName(T->getDecl());
3161
24
}
3162
3163
void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T,
3164
72
                                         Qualifiers Quals, SourceRange Range) {
3165
72
  if (T->isKindOfType())
3166
7
    return mangleObjCKindOfType(T, Quals, Range);
3167
3168
65
  if (T->qual_empty() && 
!T->isSpecialized()53
)
3169
51
    return mangleType(T->getBaseType(), Range, QMM_Drop);
3170
3171
14
  ArgBackRefMap OuterFunArgsContext;
3172
14
  ArgBackRefMap OuterTemplateArgsContext;
3173
14
  BackRefVec OuterTemplateContext;
3174
3175
14
  FunArgBackReferences.swap(OuterFunArgsContext);
3176
14
  TemplateArgBackReferences.swap(OuterTemplateArgsContext);
3177
14
  NameBackReferences.swap(OuterTemplateContext);
3178
3179
14
  mangleTagTypeKind(TTK_Struct);
3180
3181
14
  Out << "?$";
3182
14
  if (T->isObjCId())
3183
5
    mangleSourceName("objc_object");
3184
9
  else if (T->isObjCClass())
3185
2
    mangleSourceName("objc_class");
3186
7
  else
3187
7
    mangleSourceName(T->getInterface()->getName());
3188
3189
14
  for (const auto &Q : T->quals())
3190
15
    mangleObjCProtocol(Q);
3191
3192
14
  if (T->isSpecialized())
3193
2
    for (const auto &TA : T->getTypeArgs())
3194
2
      mangleType(TA, Range, QMM_Drop);
3195
3196
14
  Out << '@';
3197
3198
14
  Out << '@';
3199
3200
14
  FunArgBackReferences.swap(OuterFunArgsContext);
3201
14
  TemplateArgBackReferences.swap(OuterTemplateArgsContext);
3202
14
  NameBackReferences.swap(OuterTemplateContext);
3203
14
}
3204
3205
void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
3206
16
                                         Qualifiers Quals, SourceRange Range) {
3207
16
  QualType PointeeType = T->getPointeeType();
3208
16
  manglePointerCVQualifiers(Quals);
3209
16
  manglePointerExtQualifiers(Quals, PointeeType);
3210
3211
16
  Out << "_E";
3212
3213
16
  mangleFunctionType(PointeeType->castAs<FunctionProtoType>());
3214
16
}
3215
3216
void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
3217
0
                                         Qualifiers, SourceRange) {
3218
0
  llvm_unreachable("Cannot mangle injected class name type.");
3219
0
}
3220
3221
void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
3222
0
                                         Qualifiers, SourceRange Range) {
3223
0
  DiagnosticsEngine &Diags = Context.getDiags();
3224
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3225
0
    "cannot mangle this template specialization type yet");
3226
0
  Diags.Report(Range.getBegin(), DiagID)
3227
0
    << Range;
3228
0
}
3229
3230
void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T, Qualifiers,
3231
0
                                         SourceRange Range) {
3232
0
  DiagnosticsEngine &Diags = Context.getDiags();
3233
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3234
0
    "cannot mangle this dependent name type yet");
3235
0
  Diags.Report(Range.getBegin(), DiagID)
3236
0
    << Range;
3237
0
}
3238
3239
void MicrosoftCXXNameMangler::mangleType(
3240
    const DependentTemplateSpecializationType *T, Qualifiers,
3241
0
    SourceRange Range) {
3242
0
  DiagnosticsEngine &Diags = Context.getDiags();
3243
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3244
0
    "cannot mangle this dependent template specialization type yet");
3245
0
  Diags.Report(Range.getBegin(), DiagID)
3246
0
    << Range;
3247
0
}
3248
3249
void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T, Qualifiers,
3250
0
                                         SourceRange Range) {
3251
0
  DiagnosticsEngine &Diags = Context.getDiags();
3252
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3253
0
    "cannot mangle this pack expansion yet");
3254
0
  Diags.Report(Range.getBegin(), DiagID)
3255
0
    << Range;
3256
0
}
3257
3258
void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T, Qualifiers,
3259
0
                                         SourceRange Range) {
3260
0
  DiagnosticsEngine &Diags = Context.getDiags();
3261
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3262
0
    "cannot mangle this typeof(type) yet");
3263
0
  Diags.Report(Range.getBegin(), DiagID)
3264
0
    << Range;
3265
0
}
3266
3267
void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T, Qualifiers,
3268
0
                                         SourceRange Range) {
3269
0
  DiagnosticsEngine &Diags = Context.getDiags();
3270
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3271
0
    "cannot mangle this typeof(expression) yet");
3272
0
  Diags.Report(Range.getBegin(), DiagID)
3273
0
    << Range;
3274
0
}
3275
3276
void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T, Qualifiers,
3277
0
                                         SourceRange Range) {
3278
0
  DiagnosticsEngine &Diags = Context.getDiags();
3279
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3280
0
    "cannot mangle this decltype() yet");
3281
0
  Diags.Report(Range.getBegin(), DiagID)
3282
0
    << Range;
3283
0
}
3284
3285
void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
3286
0
                                         Qualifiers, SourceRange Range) {
3287
0
  DiagnosticsEngine &Diags = Context.getDiags();
3288
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3289
0
    "cannot mangle this unary transform type yet");
3290
0
  Diags.Report(Range.getBegin(), DiagID)
3291
0
    << Range;
3292
0
}
3293
3294
void MicrosoftCXXNameMangler::mangleType(const AutoType *T, Qualifiers,
3295
0
                                         SourceRange Range) {
3296
0
  assert(T->getDeducedType().isNull() && "expecting a dependent type!");
3297
3298
0
  DiagnosticsEngine &Diags = Context.getDiags();
3299
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3300
0
    "cannot mangle this 'auto' type yet");
3301
0
  Diags.Report(Range.getBegin(), DiagID)
3302
0
    << Range;
3303
0
}
3304
3305
void MicrosoftCXXNameMangler::mangleType(
3306
0
    const DeducedTemplateSpecializationType *T, Qualifiers, SourceRange Range) {
3307
0
  assert(T->getDeducedType().isNull() && "expecting a dependent type!");
3308
3309
0
  DiagnosticsEngine &Diags = Context.getDiags();
3310
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3311
0
    "cannot mangle this deduced class template specialization type yet");
3312
0
  Diags.Report(Range.getBegin(), DiagID)
3313
0
    << Range;
3314
0
}
3315
3316
void MicrosoftCXXNameMangler::mangleType(const AtomicType *T, Qualifiers,
3317
3
                                         SourceRange Range) {
3318
3
  QualType ValueType = T->getValueType();
3319
3320
3
  llvm::SmallString<64> TemplateMangling;
3321
3
  llvm::raw_svector_ostream Stream(TemplateMangling);
3322
3
  MicrosoftCXXNameMangler Extra(Context, Stream);
3323
3
  Stream << "?$";
3324
3
  Extra.mangleSourceName("_Atomic");
3325
3
  Extra.mangleType(ValueType, Range, QMM_Escape);
3326
3327
3
  mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
3328
3
}
3329
3330
void MicrosoftCXXNameMangler::mangleType(const PipeType *T, Qualifiers,
3331
28
                                         SourceRange Range) {
3332
28
  QualType ElementType = T->getElementType();
3333
3334
28
  llvm::SmallString<64> TemplateMangling;
3335
28
  llvm::raw_svector_ostream Stream(TemplateMangling);
3336
28
  MicrosoftCXXNameMangler Extra(Context, Stream);
3337
28
  Stream << "?$";
3338
28
  Extra.mangleSourceName("ocl_pipe");
3339
28
  Extra.mangleType(ElementType, Range, QMM_Escape);
3340
28
  Extra.mangleIntegerLiteral(llvm::APSInt::get(T->isReadOnly()));
3341
3342
28
  mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
3343
28
}
3344
3345
void MicrosoftMangleContextImpl::mangleCXXName(GlobalDecl GD,
3346
26.0k
                                               raw_ostream &Out) {
3347
26.0k
  const NamedDecl *D = cast<NamedDecl>(GD.getDecl());
3348
26.0k
  PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
3349
26.0k
                                 getASTContext().getSourceManager(),
3350
26.0k
                                 "Mangling declaration");
3351
3352
26.0k
  msvc_hashing_ostream MHO(Out);
3353
3354
26.0k
  if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) {
3355
1.62k
    auto Type = GD.getCtorType();
3356
1.62k
    MicrosoftCXXNameMangler mangler(*this, MHO, CD, Type);
3357
1.62k
    return mangler.mangle(GD);
3358
1.62k
  }
3359
3360
24.4k
  if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) {
3361
832
    auto Type = GD.getDtorType();
3362
832
    MicrosoftCXXNameMangler mangler(*this, MHO, DD, Type);
3363
832
    return mangler.mangle(GD);
3364
832
  }
3365
3366
23.6k
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3367
23.6k
  return Mangler.mangle(GD);
3368
24.4k
}
3369
3370
void MicrosoftCXXNameMangler::mangleType(const BitIntType *T, Qualifiers,
3371
104
                                         SourceRange Range) {
3372
104
  llvm::SmallString<64> TemplateMangling;
3373
104
  llvm::raw_svector_ostream Stream(TemplateMangling);
3374
104
  MicrosoftCXXNameMangler Extra(Context, Stream);
3375
104
  Stream << "?$";
3376
104
  if (T->isUnsigned())
3377
24
    Extra.mangleSourceName("_UBitInt");
3378
80
  else
3379
80
    Extra.mangleSourceName("_BitInt");
3380
104
  Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(T->getNumBits()));
3381
3382
104
  mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
3383
104
}
3384
3385
void MicrosoftCXXNameMangler::mangleType(const DependentBitIntType *T,
3386
0
                                         Qualifiers, SourceRange Range) {
3387
0
  DiagnosticsEngine &Diags = Context.getDiags();
3388
0
  unsigned DiagID = Diags.getCustomDiagID(
3389
0
      DiagnosticsEngine::Error, "cannot mangle this DependentBitInt type yet");
3390
0
  Diags.Report(Range.getBegin(), DiagID) << Range;
3391
0
}
3392
3393
// <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
3394
//                       <virtual-adjustment>
3395
// <no-adjustment>      ::= A # private near
3396
//                      ::= B # private far
3397
//                      ::= I # protected near
3398
//                      ::= J # protected far
3399
//                      ::= Q # public near
3400
//                      ::= R # public far
3401
// <static-adjustment>  ::= G <static-offset> # private near
3402
//                      ::= H <static-offset> # private far
3403
//                      ::= O <static-offset> # protected near
3404
//                      ::= P <static-offset> # protected far
3405
//                      ::= W <static-offset> # public near
3406
//                      ::= X <static-offset> # public far
3407
// <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
3408
//                      ::= $1 <virtual-shift> <static-offset> # private far
3409
//                      ::= $2 <virtual-shift> <static-offset> # protected near
3410
//                      ::= $3 <virtual-shift> <static-offset> # protected far
3411
//                      ::= $4 <virtual-shift> <static-offset> # public near
3412
//                      ::= $5 <virtual-shift> <static-offset> # public far
3413
// <virtual-shift>      ::= <vtordisp-shift> | <vtordispex-shift>
3414
// <vtordisp-shift>     ::= <offset-to-vtordisp>
3415
// <vtordispex-shift>   ::= <offset-to-vbptr> <vbase-offset-offset>
3416
//                          <offset-to-vtordisp>
3417
static void mangleThunkThisAdjustment(AccessSpecifier AS,
3418
                                      const ThisAdjustment &Adjustment,
3419
                                      MicrosoftCXXNameMangler &Mangler,
3420
385
                                      raw_ostream &Out) {
3421
385
  if (!Adjustment.Virtual.isEmpty()) {
3422
194
    Out << '$';
3423
194
    char AccessSpec;
3424
194
    switch (AS) {
3425
0
    case AS_none:
3426
0
      llvm_unreachable("Unsupported access specifier");
3427
4
    case AS_private:
3428
4
      AccessSpec = '0';
3429
4
      break;
3430
4
    case AS_protected:
3431
4
      AccessSpec = '2';
3432
4
      break;
3433
186
    case AS_public:
3434
186
      AccessSpec = '4';
3435
194
    }
3436
194
    if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
3437
22
      Out << 'R' << AccessSpec;
3438
22
      Mangler.mangleNumber(
3439
22
          static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
3440
22
      Mangler.mangleNumber(
3441
22
          static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
3442
22
      Mangler.mangleNumber(
3443
22
          static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
3444
22
      Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
3445
172
    } else {
3446
172
      Out << AccessSpec;
3447
172
      Mangler.mangleNumber(
3448
172
          static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
3449
172
      Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
3450
172
    }
3451
194
  } else 
if (191
Adjustment.NonVirtual != 0191
) {
3452
153
    switch (AS) {
3453
0
    case AS_none:
3454
0
      llvm_unreachable("Unsupported access specifier");
3455
10
    case AS_private:
3456
10
      Out << 'G';
3457
10
      break;
3458
3
    case AS_protected:
3459
3
      Out << 'O';
3460
3
      break;
3461
140
    case AS_public:
3462
140
      Out << 'W';
3463
153
    }
3464
153
    Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
3465
153
  } else {
3466
38
    switch (AS) {
3467
0
    case AS_none:
3468
0
      llvm_unreachable("Unsupported access specifier");
3469
0
    case AS_private:
3470
0
      Out << 'A';
3471
0
      break;
3472
0
    case AS_protected:
3473
0
      Out << 'I';
3474
0
      break;
3475
38
    case AS_public:
3476
38
      Out << 'Q';
3477
38
    }
3478
38
  }
3479
385
}
3480
3481
void MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(
3482
    const CXXMethodDecl *MD, const MethodVFTableLocation &ML,
3483
55
    raw_ostream &Out) {
3484
55
  msvc_hashing_ostream MHO(Out);
3485
55
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3486
55
  Mangler.getStream() << '?';
3487
55
  Mangler.mangleVirtualMemPtrThunk(MD, ML);
3488
55
}
3489
3490
void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
3491
                                             const ThunkInfo &Thunk,
3492
215
                                             raw_ostream &Out) {
3493
215
  msvc_hashing_ostream MHO(Out);
3494
215
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3495
215
  Mangler.getStream() << '?';
3496
215
  Mangler.mangleName(MD);
3497
3498
  // Usually the thunk uses the access specifier of the new method, but if this
3499
  // is a covariant return thunk, then MSVC always uses the public access
3500
  // specifier, and we do the same.
3501
215
  AccessSpecifier AS = Thunk.Return.isEmpty() ? 
MD->getAccess()170
:
AS_public45
;
3502
215
  mangleThunkThisAdjustment(AS, Thunk.This, Mangler, MHO);
3503
3504
215
  if (!Thunk.Return.isEmpty())
3505
45
    assert(Thunk.Method != nullptr &&
3506
215
           "Thunk info should hold the overridee decl");
3507
3508
215
  const CXXMethodDecl *DeclForFPT = Thunk.Method ? 
Thunk.Method63
:
MD152
;
3509
215
  Mangler.mangleFunctionType(
3510
215
      DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
3511
215
}
3512
3513
void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
3514
    const CXXDestructorDecl *DD, CXXDtorType Type,
3515
170
    const ThisAdjustment &Adjustment, raw_ostream &Out) {
3516
  // FIXME: Actually, the dtor thunk should be emitted for vector deleting
3517
  // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
3518
  // mangling manually until we support both deleting dtor types.
3519
170
  assert(Type == Dtor_Deleting);
3520
0
  msvc_hashing_ostream MHO(Out);
3521
170
  MicrosoftCXXNameMangler Mangler(*this, MHO, DD, Type);
3522
170
  Mangler.getStream() << "??_E";
3523
170
  Mangler.mangleName(DD->getParent());
3524
170
  mangleThunkThisAdjustment(DD->getAccess(), Adjustment, Mangler, MHO);
3525
170
  Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
3526
170
}
3527
3528
void MicrosoftMangleContextImpl::mangleCXXVFTable(
3529
    const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3530
1.88k
    raw_ostream &Out) {
3531
  // <mangled-name> ::= ?_7 <class-name> <storage-class>
3532
  //                    <cvr-qualifiers> [<name>] @
3533
  // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3534
  // is always '6' for vftables.
3535
1.88k
  msvc_hashing_ostream MHO(Out);
3536
1.88k
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3537
1.88k
  if (Derived->hasAttr<DLLImportAttr>())
3538
51
    Mangler.getStream() << "??_S";
3539
1.83k
  else
3540
1.83k
    Mangler.getStream() << "??_7";
3541
1.88k
  Mangler.mangleName(Derived);
3542
1.88k
  Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
3543
1.88k
  for (const CXXRecordDecl *RD : BasePath)
3544
692
    Mangler.mangleName(RD);
3545
1.88k
  Mangler.getStream() << '@';
3546
1.88k
}
3547
3548
void MicrosoftMangleContextImpl::mangleCXXVBTable(
3549
    const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3550
584
    raw_ostream &Out) {
3551
  // <mangled-name> ::= ?_8 <class-name> <storage-class>
3552
  //                    <cvr-qualifiers> [<name>] @
3553
  // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3554
  // is always '7' for vbtables.
3555
584
  msvc_hashing_ostream MHO(Out);
3556
584
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3557
584
  Mangler.getStream() << "??_8";
3558
584
  Mangler.mangleName(Derived);
3559
584
  Mangler.getStream() << "7B";  // '7' for vbtable, 'B' for const.
3560
584
  for (const CXXRecordDecl *RD : BasePath)
3561
345
    Mangler.mangleName(RD);
3562
584
  Mangler.getStream() << '@';
3563
584
}
3564
3565
805
void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) {
3566
805
  msvc_hashing_ostream MHO(Out);
3567
805
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3568
805
  Mangler.getStream() << "??_R0";
3569
805
  Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3570
805
  Mangler.getStream() << "@8";
3571
805
}
3572
3573
void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T,
3574
603
                                                   raw_ostream &Out) {
3575
603
  MicrosoftCXXNameMangler Mangler(*this, Out);
3576
603
  Mangler.getStream() << '.';
3577
603
  Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3578
603
}
3579
3580
void MicrosoftMangleContextImpl::mangleCXXVirtualDisplacementMap(
3581
4
    const CXXRecordDecl *SrcRD, const CXXRecordDecl *DstRD, raw_ostream &Out) {
3582
4
  msvc_hashing_ostream MHO(Out);
3583
4
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3584
4
  Mangler.getStream() << "??_K";
3585
4
  Mangler.mangleName(SrcRD);
3586
4
  Mangler.getStream() << "$C";
3587
4
  Mangler.mangleName(DstRD);
3588
4
}
3589
3590
void MicrosoftMangleContextImpl::mangleCXXThrowInfo(QualType T, bool IsConst,
3591
                                                    bool IsVolatile,
3592
                                                    bool IsUnaligned,
3593
                                                    uint32_t NumEntries,
3594
35
                                                    raw_ostream &Out) {
3595
35
  msvc_hashing_ostream MHO(Out);
3596
35
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3597
35
  Mangler.getStream() << "_TI";
3598
35
  if (IsConst)
3599
3
    Mangler.getStream() << 'C';
3600
35
  if (IsVolatile)
3601
0
    Mangler.getStream() << 'V';
3602
35
  if (IsUnaligned)
3603
1
    Mangler.getStream() << 'U';
3604
35
  Mangler.getStream() << NumEntries;
3605
35
  Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3606
35
}
3607
3608
void MicrosoftMangleContextImpl::mangleCXXCatchableTypeArray(
3609
33
    QualType T, uint32_t NumEntries, raw_ostream &Out) {
3610
33
  msvc_hashing_ostream MHO(Out);
3611
33
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3612
33
  Mangler.getStream() << "_CTA";
3613
33
  Mangler.getStream() << NumEntries;
3614
33
  Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3615
33
}
3616
3617
void MicrosoftMangleContextImpl::mangleCXXCatchableType(
3618
    QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size,
3619
    uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex,
3620
56
    raw_ostream &Out) {
3621
56
  MicrosoftCXXNameMangler Mangler(*this, Out);
3622
56
  Mangler.getStream() << "_CT";
3623
3624
56
  llvm::SmallString<64> RTTIMangling;
3625
56
  {
3626
56
    llvm::raw_svector_ostream Stream(RTTIMangling);
3627
56
    msvc_hashing_ostream MHO(Stream);
3628
56
    mangleCXXRTTI(T, MHO);
3629
56
  }
3630
56
  Mangler.getStream() << RTTIMangling;
3631
3632
  // VS2015 and VS2017.1 omit the copy-constructor in the mangled name but
3633
  // both older and newer versions include it.
3634
  // FIXME: It is known that the Ctor is present in 2013, and in 2017.7
3635
  // (_MSC_VER 1914) and newer, and that it's omitted in 2015 and 2017.4
3636
  // (_MSC_VER 1911), but it's unknown when exactly it reappeared (1914?
3637
  // Or 1912, 1913 already?).
3638
56
  bool OmitCopyCtor = getASTContext().getLangOpts().isCompatibleWithMSVC(
3639
56
                          LangOptions::MSVC2015) &&
3640
56
                      !getASTContext().getLangOpts().isCompatibleWithMSVC(
3641
12
                          LangOptions::MSVC2017_7);
3642
56
  llvm::SmallString<64> CopyCtorMangling;
3643
56
  if (!OmitCopyCtor && 
CD50
) {
3644
15
    llvm::raw_svector_ostream Stream(CopyCtorMangling);
3645
15
    msvc_hashing_ostream MHO(Stream);
3646
15
    mangleCXXName(GlobalDecl(CD, CT), MHO);
3647
15
  }
3648
56
  Mangler.getStream() << CopyCtorMangling;
3649
3650
56
  Mangler.getStream() << Size;
3651
56
  if (VBPtrOffset == -1) {
3652
54
    if (NVOffset) {
3653
2
      Mangler.getStream() << NVOffset;
3654
2
    }
3655
54
  } else {
3656
2
    Mangler.getStream() << NVOffset;
3657
2
    Mangler.getStream() << VBPtrOffset;
3658
2
    Mangler.getStream() << VBIndex;
3659
2
  }
3660
56
}
3661
3662
void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor(
3663
    const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset,
3664
484
    uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) {
3665
484
  msvc_hashing_ostream MHO(Out);
3666
484
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3667
484
  Mangler.getStream() << "??_R1";
3668
484
  Mangler.mangleNumber(NVOffset);
3669
484
  Mangler.mangleNumber(VBPtrOffset);
3670
484
  Mangler.mangleNumber(VBTableOffset);
3671
484
  Mangler.mangleNumber(Flags);
3672
484
  Mangler.mangleName(Derived);
3673
484
  Mangler.getStream() << "8";
3674
484
}
3675
3676
void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray(
3677
270
    const CXXRecordDecl *Derived, raw_ostream &Out) {
3678
270
  msvc_hashing_ostream MHO(Out);
3679
270
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3680
270
  Mangler.getStream() << "??_R2";
3681
270
  Mangler.mangleName(Derived);
3682
270
  Mangler.getStream() << "8";
3683
270
}
3684
3685
void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor(
3686
630
    const CXXRecordDecl *Derived, raw_ostream &Out) {
3687
630
  msvc_hashing_ostream MHO(Out);
3688
630
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3689
630
  Mangler.getStream() << "??_R3";
3690
630
  Mangler.mangleName(Derived);
3691
630
  Mangler.getStream() << "8";
3692
630
}
3693
3694
void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator(
3695
    const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3696
256
    raw_ostream &Out) {
3697
  // <mangled-name> ::= ?_R4 <class-name> <storage-class>
3698
  //                    <cvr-qualifiers> [<name>] @
3699
  // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3700
  // is always '6' for vftables.
3701
256
  llvm::SmallString<64> VFTableMangling;
3702
256
  llvm::raw_svector_ostream Stream(VFTableMangling);
3703
256
  mangleCXXVFTable(Derived, BasePath, Stream);
3704
3705
256
  if (VFTableMangling.startswith("??@")) {
3706
7
    assert(VFTableMangling.endswith("@"));
3707
0
    Out << VFTableMangling << "??_R4@";
3708
7
    return;
3709
7
  }
3710
3711
249
  assert(VFTableMangling.startswith("??_7") ||
3712
249
         VFTableMangling.startswith("??_S"));
3713
3714
0
  Out << "??_R4" << VFTableMangling.str().drop_front(4);
3715
249
}
3716
3717
void MicrosoftMangleContextImpl::mangleSEHFilterExpression(
3718
22
    const NamedDecl *EnclosingDecl, raw_ostream &Out) {
3719
22
  msvc_hashing_ostream MHO(Out);
3720
22
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3721
  // The function body is in the same comdat as the function with the handler,
3722
  // so the numbering here doesn't have to be the same across TUs.
3723
  //
3724
  // <mangled-name> ::= ?filt$ <filter-number> @0
3725
22
  Mangler.getStream() << "?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@";
3726
22
  Mangler.mangleName(EnclosingDecl);
3727
22
}
3728
3729
void MicrosoftMangleContextImpl::mangleSEHFinallyBlock(
3730
78
    const NamedDecl *EnclosingDecl, raw_ostream &Out) {
3731
78
  msvc_hashing_ostream MHO(Out);
3732
78
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3733
  // The function body is in the same comdat as the function with the handler,
3734
  // so the numbering here doesn't have to be the same across TUs.
3735
  //
3736
  // <mangled-name> ::= ?fin$ <filter-number> @0
3737
78
  Mangler.getStream() << "?fin$" << SEHFinallyIds[EnclosingDecl]++ << "@0@";
3738
78
  Mangler.mangleName(EnclosingDecl);
3739
78
}
3740
3741
393
void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
3742
  // This is just a made up unique string for the purposes of tbaa.  undname
3743
  // does *not* know how to demangle it.
3744
393
  MicrosoftCXXNameMangler Mangler(*this, Out);
3745
393
  Mangler.getStream() << '?';
3746
393
  Mangler.mangleType(T, SourceRange());
3747
393
}
3748
3749
void MicrosoftMangleContextImpl::mangleReferenceTemporary(
3750
5
    const VarDecl *VD, unsigned ManglingNumber, raw_ostream &Out) {
3751
5
  msvc_hashing_ostream MHO(Out);
3752
5
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3753
3754
5
  Mangler.getStream() << "?$RT" << ManglingNumber << '@';
3755
5
  Mangler.mangle(VD, "");
3756
5
}
3757
3758
void MicrosoftMangleContextImpl::mangleThreadSafeStaticGuardVariable(
3759
37
    const VarDecl *VD, unsigned GuardNum, raw_ostream &Out) {
3760
37
  msvc_hashing_ostream MHO(Out);
3761
37
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3762
3763
37
  Mangler.getStream() << "?$TSS" << GuardNum << '@';
3764
37
  Mangler.mangleNestedName(VD);
3765
37
  Mangler.getStream() << "@4HA";
3766
37
}
3767
3768
void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
3769
27
                                                           raw_ostream &Out) {
3770
  // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
3771
  //              ::= ?__J <postfix> @5 <scope-depth>
3772
  //              ::= ?$S <guard-num> @ <postfix> @4IA
3773
3774
  // The first mangling is what MSVC uses to guard static locals in inline
3775
  // functions.  It uses a different mangling in external functions to support
3776
  // guarding more than 32 variables.  MSVC rejects inline functions with more
3777
  // than 32 static locals.  We don't fully implement the second mangling
3778
  // because those guards are not externally visible, and instead use LLVM's
3779
  // default renaming when creating a new guard variable.
3780
27
  msvc_hashing_ostream MHO(Out);
3781
27
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3782
3783
27
  bool Visible = VD->isExternallyVisible();
3784
27
  if (Visible) {
3785
11
    Mangler.getStream() << (VD->getTLSKind() ? 
"??__J"2
:
"??_B"9
);
3786
16
  } else {
3787
16
    Mangler.getStream() << "?$S1@";
3788
16
  }
3789
27
  unsigned ScopeDepth = 0;
3790
27
  if (Visible && 
!getNextDiscriminator(VD, ScopeDepth)11
)
3791
    // If we do not have a discriminator and are emitting a guard variable for
3792
    // use at global scope, then mangling the nested name will not be enough to
3793
    // remove ambiguities.
3794
0
    Mangler.mangle(VD, "");
3795
27
  else
3796
27
    Mangler.mangleNestedName(VD);
3797
27
  Mangler.getStream() << (Visible ? 
"@5"11
:
"@4IA"16
);
3798
27
  if (ScopeDepth)
3799
11
    Mangler.mangleNumber(ScopeDepth);
3800
27
}
3801
3802
void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
3803
                                                    char CharCode,
3804
498
                                                    raw_ostream &Out) {
3805
498
  msvc_hashing_ostream MHO(Out);
3806
498
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3807
498
  Mangler.getStream() << "??__" << CharCode;
3808
498
  if (D->isStaticDataMember()) {
3809
46
    Mangler.getStream() << '?';
3810
46
    Mangler.mangleName(D);
3811
46
    Mangler.mangleVariableEncoding(D);
3812
46
    Mangler.getStream() << "@@";
3813
452
  } else {
3814
452
    Mangler.mangleName(D);
3815
452
  }
3816
  // This is the function class mangling.  These stubs are global, non-variadic,
3817
  // cdecl functions that return void and take no args.
3818
498
  Mangler.getStream() << "YAXXZ";
3819
498
}
3820
3821
void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
3822
326
                                                          raw_ostream &Out) {
3823
  // <initializer-name> ::= ?__E <name> YAXXZ
3824
326
  mangleInitFiniStub(D, 'E', Out);
3825
326
}
3826
3827
void
3828
MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
3829
172
                                                          raw_ostream &Out) {
3830
  // <destructor-name> ::= ?__F <name> YAXXZ
3831
172
  mangleInitFiniStub(D, 'F', Out);
3832
172
}
3833
3834
void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
3835
793
                                                     raw_ostream &Out) {
3836
  // <char-type> ::= 0   # char, char16_t, char32_t
3837
  //                     # (little endian char data in mangling)
3838
  //             ::= 1   # wchar_t (big endian char data in mangling)
3839
  //
3840
  // <literal-length> ::= <non-negative integer>  # the length of the literal
3841
  //
3842
  // <encoded-crc>    ::= <hex digit>+ @          # crc of the literal including
3843
  //                                              # trailing null bytes
3844
  //
3845
  // <encoded-string> ::= <simple character>           # uninteresting character
3846
  //                  ::= '?$' <hex digit> <hex digit> # these two nibbles
3847
  //                                                   # encode the byte for the
3848
  //                                                   # character
3849
  //                  ::= '?' [a-z]                    # \xe1 - \xfa
3850
  //                  ::= '?' [A-Z]                    # \xc1 - \xda
3851
  //                  ::= '?' [0-9]                    # [,/\:. \n\t'-]
3852
  //
3853
  // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
3854
  //               <encoded-string> '@'
3855
793
  MicrosoftCXXNameMangler Mangler(*this, Out);
3856
793
  Mangler.getStream() << "??_C@_";
3857
3858
  // The actual string length might be different from that of the string literal
3859
  // in cases like:
3860
  // char foo[3] = "foobar";
3861
  // char bar[42] = "foobar";
3862
  // Where it is truncated or zero-padded to fit the array. This is the length
3863
  // used for mangling, and any trailing null-bytes also need to be mangled.
3864
793
  unsigned StringLength = getASTContext()
3865
793
                              .getAsConstantArrayType(SL->getType())
3866
793
                              ->getSize()
3867
793
                              .getZExtValue();
3868
793
  unsigned StringByteLength = StringLength * SL->getCharByteWidth();
3869
3870
  // <char-type>: The "kind" of string literal is encoded into the mangled name.
3871
793
  if (SL->isWide())
3872
206
    Mangler.getStream() << '1';
3873
587
  else
3874
587
    Mangler.getStream() << '0';
3875
3876
  // <literal-length>: The next part of the mangled name consists of the length
3877
  // of the string in bytes.
3878
793
  Mangler.mangleNumber(StringByteLength);
3879
3880
6.30k
  auto GetLittleEndianByte = [&SL](unsigned Index) {
3881
6.30k
    unsigned CharByteWidth = SL->getCharByteWidth();
3882
6.30k
    if (Index / CharByteWidth >= SL->getLength())
3883
1.64k
      return static_cast<char>(0);
3884
4.65k
    uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
3885
4.65k
    unsigned OffsetInCodeUnit = Index % CharByteWidth;
3886
4.65k
    return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
3887
6.30k
  };
3888
3889
1.11k
  auto GetBigEndianByte = [&SL](unsigned Index) {
3890
1.11k
    unsigned CharByteWidth = SL->getCharByteWidth();
3891
1.11k
    if (Index / CharByteWidth >= SL->getLength())
3892
408
      return static_cast<char>(0);
3893
702
    uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
3894
702
    unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
3895
702
    return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
3896
1.11k
  };
3897
3898
  // CRC all the bytes of the StringLiteral.
3899
793
  llvm::JamCRC JC;
3900
4.72k
  for (unsigned I = 0, E = StringByteLength; I != E; 
++I3.93k
)
3901
3.93k
    JC.update(GetLittleEndianByte(I));
3902
3903
  // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
3904
  // scheme.
3905
793
  Mangler.mangleNumber(JC.getCRC());
3906
3907
  // <encoded-string>: The mangled name also contains the first 32 bytes
3908
  // (including null-terminator bytes) of the encoded StringLiteral.
3909
  // Each character is encoded by splitting them into bytes and then encoding
3910
  // the constituent bytes.
3911
3.48k
  auto MangleByte = [&Mangler](char Byte) {
3912
    // There are five different manglings for characters:
3913
    // - [a-zA-Z0-9_$]: A one-to-one mapping.
3914
    // - ?[a-z]: The range from \xe1 to \xfa.
3915
    // - ?[A-Z]: The range from \xc1 to \xda.
3916
    // - ?[0-9]: The set of [,/\:. \n\t'-].
3917
    // - ?$XX: A fallback which maps nibbles.
3918
3.48k
    if (isAsciiIdentifierContinue(Byte, /*AllowDollar=*/true)) {
3919
1.27k
      Mangler.getStream() << Byte;
3920
2.20k
    } else if (isLetter(Byte & 0x7f)) {
3921
107
      Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
3922
2.10k
    } else {
3923
2.10k
      const char SpecialChars[] = {',', '/',  '\\', ':',  '.',
3924
2.10k
                                   ' ', '\n', '\t', '\'', '-'};
3925
2.10k
      const char *Pos = llvm::find(SpecialChars, Byte);
3926
2.10k
      if (Pos != std::end(SpecialChars)) {
3927
216
        Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars));
3928
1.88k
      } else {
3929
1.88k
        Mangler.getStream() << "?$";
3930
1.88k
        Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
3931
1.88k
        Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
3932
1.88k
      }
3933
2.10k
    }
3934
3.48k
  };
3935
3936
  // Enforce our 32 bytes max, except wchar_t which gets 32 chars instead.
3937
793
  unsigned MaxBytesToMangle = SL->isWide() ? 
64U206
:
32U587
;
3938
793
  unsigned NumBytesToMangle = std::min(MaxBytesToMangle, StringByteLength);
3939
4.27k
  for (unsigned I = 0; I != NumBytesToMangle; 
++I3.48k
) {
3940
3.48k
    if (SL->isWide())
3941
1.11k
      MangleByte(GetBigEndianByte(I));
3942
2.37k
    else
3943
2.37k
      MangleByte(GetLittleEndianByte(I));
3944
3.48k
  }
3945
3946
793
  Mangler.getStream() << '@';
3947
793
}
3948
3949
MicrosoftMangleContext *MicrosoftMangleContext::create(ASTContext &Context,
3950
                                                       DiagnosticsEngine &Diags,
3951
868
                                                       bool IsAux) {
3952
868
  return new MicrosoftMangleContextImpl(Context, Diags, IsAux);
3953
868
}