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