Coverage Report

Created: 2019-07-24 05:18

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