Coverage Report

Created: 2021-09-21 08:58

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