Coverage Report

Created: 2020-02-15 09:57

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