Coverage Report

Created: 2020-09-22 08:39

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