Coverage Report

Created: 2021-01-23 06:44

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