• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- MicrosoftMangle.cpp - Microsoft Visual C++ Name Mangling ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This provides C++ name mangling targeting the Microsoft Visual C++ ABI.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/Mangle.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/VTableBuilder.h"
26 #include "clang/Basic/ABI.h"
27 #include "clang/Basic/DiagnosticOptions.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Support/JamCRC.h"
32 
33 using namespace clang;
34 
35 namespace {
36 
37 /// \brief Retrieve the declaration context that should be used when mangling
38 /// the given declaration.
getEffectiveDeclContext(const Decl * D)39 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
40   // The ABI assumes that lambda closure types that occur within
41   // default arguments live in the context of the function. However, due to
42   // the way in which Clang parses and creates function declarations, this is
43   // not the case: the lambda closure type ends up living in the context
44   // where the function itself resides, because the function declaration itself
45   // had not yet been created. Fix the context here.
46   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
47     if (RD->isLambda())
48       if (ParmVarDecl *ContextParam =
49               dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
50         return ContextParam->getDeclContext();
51   }
52 
53   // Perform the same check for block literals.
54   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
55     if (ParmVarDecl *ContextParam =
56             dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
57       return ContextParam->getDeclContext();
58   }
59 
60   const DeclContext *DC = D->getDeclContext();
61   if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(DC))
62     return getEffectiveDeclContext(CD);
63 
64   return DC;
65 }
66 
getEffectiveParentContext(const DeclContext * DC)67 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
68   return getEffectiveDeclContext(cast<Decl>(DC));
69 }
70 
getStructor(const NamedDecl * ND)71 static const FunctionDecl *getStructor(const NamedDecl *ND) {
72   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(ND))
73     return FTD->getTemplatedDecl();
74 
75   const auto *FD = cast<FunctionDecl>(ND);
76   if (const auto *FTD = FD->getPrimaryTemplate())
77     return FTD->getTemplatedDecl();
78 
79   return FD;
80 }
81 
isLambda(const NamedDecl * ND)82 static bool isLambda(const NamedDecl *ND) {
83   const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
84   if (!Record)
85     return false;
86 
87   return Record->isLambda();
88 }
89 
90 /// MicrosoftMangleContextImpl - Overrides the default MangleContext for the
91 /// Microsoft Visual C++ ABI.
92 class MicrosoftMangleContextImpl : public MicrosoftMangleContext {
93   typedef std::pair<const DeclContext *, IdentifierInfo *> DiscriminatorKeyTy;
94   llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
95   llvm::DenseMap<const NamedDecl *, unsigned> Uniquifier;
96   llvm::DenseMap<const CXXRecordDecl *, unsigned> LambdaIds;
97   llvm::DenseMap<const NamedDecl *, unsigned> SEHFilterIds;
98   llvm::DenseMap<const NamedDecl *, unsigned> SEHFinallyIds;
99 
100 public:
MicrosoftMangleContextImpl(ASTContext & Context,DiagnosticsEngine & Diags)101   MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags)
102       : MicrosoftMangleContext(Context, Diags) {}
103   bool shouldMangleCXXName(const NamedDecl *D) override;
104   bool shouldMangleStringLiteral(const StringLiteral *SL) override;
105   void mangleCXXName(const NamedDecl *D, raw_ostream &Out) override;
106   void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
107                                 raw_ostream &) override;
108   void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
109                    raw_ostream &) override;
110   void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
111                           const ThisAdjustment &ThisAdjustment,
112                           raw_ostream &) override;
113   void mangleCXXVFTable(const CXXRecordDecl *Derived,
114                         ArrayRef<const CXXRecordDecl *> BasePath,
115                         raw_ostream &Out) override;
116   void mangleCXXVBTable(const CXXRecordDecl *Derived,
117                         ArrayRef<const CXXRecordDecl *> BasePath,
118                         raw_ostream &Out) override;
119   void mangleCXXVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
120                                        const CXXRecordDecl *DstRD,
121                                        raw_ostream &Out) override;
122   void mangleCXXThrowInfo(QualType T, bool IsConst, bool IsVolatile,
123                           uint32_t NumEntries, raw_ostream &Out) override;
124   void mangleCXXCatchableTypeArray(QualType T, uint32_t NumEntries,
125                                    raw_ostream &Out) override;
126   void mangleCXXCatchableType(QualType T, const CXXConstructorDecl *CD,
127                               CXXCtorType CT, uint32_t Size, uint32_t NVOffset,
128                               int32_t VBPtrOffset, uint32_t VBIndex,
129                               raw_ostream &Out) override;
130   void mangleCXXCatchHandlerType(QualType T, uint32_t Flags,
131                                  raw_ostream &Out) override;
132   void mangleCXXRTTI(QualType T, raw_ostream &Out) override;
133   void mangleCXXRTTIName(QualType T, raw_ostream &Out) override;
134   void mangleCXXRTTIBaseClassDescriptor(const CXXRecordDecl *Derived,
135                                         uint32_t NVOffset, int32_t VBPtrOffset,
136                                         uint32_t VBTableOffset, uint32_t Flags,
137                                         raw_ostream &Out) override;
138   void mangleCXXRTTIBaseClassArray(const CXXRecordDecl *Derived,
139                                    raw_ostream &Out) override;
140   void mangleCXXRTTIClassHierarchyDescriptor(const CXXRecordDecl *Derived,
141                                              raw_ostream &Out) override;
142   void
143   mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl *Derived,
144                                      ArrayRef<const CXXRecordDecl *> BasePath,
145                                      raw_ostream &Out) override;
146   void mangleTypeName(QualType T, raw_ostream &) override;
147   void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
148                      raw_ostream &) override;
149   void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
150                      raw_ostream &) override;
151   void mangleReferenceTemporary(const VarDecl *, unsigned ManglingNumber,
152                                 raw_ostream &) override;
153   void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override;
154   void mangleThreadSafeStaticGuardVariable(const VarDecl *D, unsigned GuardNum,
155                                            raw_ostream &Out) override;
156   void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
157   void mangleDynamicAtExitDestructor(const VarDecl *D,
158                                      raw_ostream &Out) override;
159   void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
160                                  raw_ostream &Out) override;
161   void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
162                              raw_ostream &Out) override;
163   void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override;
getNextDiscriminator(const NamedDecl * ND,unsigned & disc)164   bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
165     // Lambda closure types are already numbered.
166     if (isLambda(ND))
167       return false;
168 
169     const DeclContext *DC = getEffectiveDeclContext(ND);
170     if (!DC->isFunctionOrMethod())
171       return false;
172 
173     // Use the canonical number for externally visible decls.
174     if (ND->isExternallyVisible()) {
175       disc = getASTContext().getManglingNumber(ND);
176       return true;
177     }
178 
179     // Anonymous tags are already numbered.
180     if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
181       if (!Tag->hasNameForLinkage() &&
182           !getASTContext().getDeclaratorForUnnamedTagDecl(Tag) &&
183           !getASTContext().getTypedefNameForUnnamedTagDecl(Tag))
184         return false;
185     }
186 
187     // Make up a reasonable number for internal decls.
188     unsigned &discriminator = Uniquifier[ND];
189     if (!discriminator)
190       discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
191     disc = discriminator + 1;
192     return true;
193   }
194 
getLambdaId(const CXXRecordDecl * RD)195   unsigned getLambdaId(const CXXRecordDecl *RD) {
196     assert(RD->isLambda() && "RD must be a lambda!");
197     assert(!RD->isExternallyVisible() && "RD must not be visible!");
198     assert(RD->getLambdaManglingNumber() == 0 &&
199            "RD must not have a mangling number!");
200     std::pair<llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator, bool>
201         Result = LambdaIds.insert(std::make_pair(RD, LambdaIds.size()));
202     return Result.first->second;
203   }
204 
205 private:
206   void mangleInitFiniStub(const VarDecl *D, raw_ostream &Out, char CharCode);
207 };
208 
209 /// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
210 /// Microsoft Visual C++ ABI.
211 class MicrosoftCXXNameMangler {
212   MicrosoftMangleContextImpl &Context;
213   raw_ostream &Out;
214 
215   /// The "structor" is the top-level declaration being mangled, if
216   /// that's not a template specialization; otherwise it's the pattern
217   /// for that specialization.
218   const NamedDecl *Structor;
219   unsigned StructorType;
220 
221   typedef llvm::SmallVector<std::string, 10> BackRefVec;
222   BackRefVec NameBackReferences;
223 
224   typedef llvm::DenseMap<void *, unsigned> ArgBackRefMap;
225   ArgBackRefMap TypeBackReferences;
226 
getASTContext() const227   ASTContext &getASTContext() const { return Context.getASTContext(); }
228 
229   // FIXME: If we add support for __ptr32/64 qualifiers, then we should push
230   // this check into mangleQualifiers().
231   const bool PointersAre64Bit;
232 
233 public:
234   enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
235 
MicrosoftCXXNameMangler(MicrosoftMangleContextImpl & C,raw_ostream & Out_)236   MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_)
237       : Context(C), Out(Out_), Structor(nullptr), StructorType(-1),
238         PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
239                          64) {}
240 
MicrosoftCXXNameMangler(MicrosoftMangleContextImpl & C,raw_ostream & Out_,const CXXConstructorDecl * D,CXXCtorType Type)241   MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
242                           const CXXConstructorDecl *D, CXXCtorType Type)
243       : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
244         PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
245                          64) {}
246 
MicrosoftCXXNameMangler(MicrosoftMangleContextImpl & C,raw_ostream & Out_,const CXXDestructorDecl * D,CXXDtorType Type)247   MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
248                           const CXXDestructorDecl *D, CXXDtorType Type)
249       : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
250         PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
251                          64) {}
252 
getStream() const253   raw_ostream &getStream() const { return Out; }
254 
255   void mangle(const NamedDecl *D, StringRef Prefix = "\01?");
256   void mangleName(const NamedDecl *ND);
257   void mangleFunctionEncoding(const FunctionDecl *FD, bool ShouldMangle);
258   void mangleVariableEncoding(const VarDecl *VD);
259   void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD);
260   void mangleMemberFunctionPointer(const CXXRecordDecl *RD,
261                                    const CXXMethodDecl *MD);
262   void mangleVirtualMemPtrThunk(
263       const CXXMethodDecl *MD,
264       const MicrosoftVTableContext::MethodVFTableLocation &ML);
265   void mangleNumber(int64_t Number);
266   void mangleType(QualType T, SourceRange Range,
267                   QualifierMangleMode QMM = QMM_Mangle);
268   void mangleFunctionType(const FunctionType *T,
269                           const FunctionDecl *D = nullptr,
270                           bool ForceThisQuals = false);
271   void mangleNestedName(const NamedDecl *ND);
272 
273 private:
mangleUnqualifiedName(const NamedDecl * ND)274   void mangleUnqualifiedName(const NamedDecl *ND) {
275     mangleUnqualifiedName(ND, ND->getDeclName());
276   }
277   void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
278   void mangleSourceName(StringRef Name);
279   void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
280   void mangleCXXDtorType(CXXDtorType T);
281   void mangleQualifiers(Qualifiers Quals, bool IsMember);
282   void mangleRefQualifier(RefQualifierKind RefQualifier);
283   void manglePointerCVQualifiers(Qualifiers Quals);
284   void manglePointerExtQualifiers(Qualifiers Quals, QualType PointeeType);
285 
286   void mangleUnscopedTemplateName(const TemplateDecl *ND);
287   void
288   mangleTemplateInstantiationName(const TemplateDecl *TD,
289                                   const TemplateArgumentList &TemplateArgs);
290   void mangleObjCMethodName(const ObjCMethodDecl *MD);
291 
292   void mangleArgumentType(QualType T, SourceRange Range);
293 
294   // Declare manglers for every type class.
295 #define ABSTRACT_TYPE(CLASS, PARENT)
296 #define NON_CANONICAL_TYPE(CLASS, PARENT)
297 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
298                                             Qualifiers Quals, \
299                                             SourceRange Range);
300 #include "clang/AST/TypeNodes.def"
301 #undef ABSTRACT_TYPE
302 #undef NON_CANONICAL_TYPE
303 #undef TYPE
304 
305   void mangleType(const TagDecl *TD);
306   void mangleDecayedArrayType(const ArrayType *T);
307   void mangleArrayType(const ArrayType *T);
308   void mangleFunctionClass(const FunctionDecl *FD);
309   void mangleCallingConvention(CallingConv CC);
310   void mangleCallingConvention(const FunctionType *T);
311   void mangleIntegerLiteral(const llvm::APSInt &Number, bool IsBoolean);
312   void mangleExpression(const Expr *E);
313   void mangleThrowSpecification(const FunctionProtoType *T);
314 
315   void mangleTemplateArgs(const TemplateDecl *TD,
316                           const TemplateArgumentList &TemplateArgs);
317   void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA,
318                          const NamedDecl *Parm);
319 };
320 }
321 
shouldMangleCXXName(const NamedDecl * D)322 bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
323   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
324     LanguageLinkage L = FD->getLanguageLinkage();
325     // Overloadable functions need mangling.
326     if (FD->hasAttr<OverloadableAttr>())
327       return true;
328 
329     // The ABI expects that we would never mangle "typical" user-defined entry
330     // points regardless of visibility or freestanding-ness.
331     //
332     // N.B. This is distinct from asking about "main".  "main" has a lot of
333     // special rules associated with it in the standard while these
334     // user-defined entry points are outside of the purview of the standard.
335     // For example, there can be only one definition for "main" in a standards
336     // compliant program; however nothing forbids the existence of wmain and
337     // WinMain in the same translation unit.
338     if (FD->isMSVCRTEntryPoint())
339       return false;
340 
341     // C++ functions and those whose names are not a simple identifier need
342     // mangling.
343     if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
344       return true;
345 
346     // C functions are not mangled.
347     if (L == CLanguageLinkage)
348       return false;
349   }
350 
351   // Otherwise, no mangling is done outside C++ mode.
352   if (!getASTContext().getLangOpts().CPlusPlus)
353     return false;
354 
355   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
356     // C variables are not mangled.
357     if (VD->isExternC())
358       return false;
359 
360     // Variables at global scope with non-internal linkage are not mangled.
361     const DeclContext *DC = getEffectiveDeclContext(D);
362     // Check for extern variable declared locally.
363     if (DC->isFunctionOrMethod() && D->hasLinkage())
364       while (!DC->isNamespace() && !DC->isTranslationUnit())
365         DC = getEffectiveParentContext(DC);
366 
367     if (DC->isTranslationUnit() && D->getFormalLinkage() == InternalLinkage &&
368         !isa<VarTemplateSpecializationDecl>(D) &&
369         D->getIdentifier() != nullptr)
370       return false;
371   }
372 
373   return true;
374 }
375 
376 bool
shouldMangleStringLiteral(const StringLiteral * SL)377 MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
378   return true;
379 }
380 
mangle(const NamedDecl * D,StringRef Prefix)381 void MicrosoftCXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
382   // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
383   // Therefore it's really important that we don't decorate the
384   // name with leading underscores or leading/trailing at signs. So, by
385   // default, we emit an asm marker at the start so we get the name right.
386   // Callers can override this with a custom prefix.
387 
388   // <mangled-name> ::= ? <name> <type-encoding>
389   Out << Prefix;
390   mangleName(D);
391   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
392     mangleFunctionEncoding(FD, Context.shouldMangleDeclName(FD));
393   else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
394     mangleVariableEncoding(VD);
395   else {
396     // TODO: Fields? Can MSVC even mangle them?
397     // Issue a diagnostic for now.
398     DiagnosticsEngine &Diags = Context.getDiags();
399     unsigned DiagID = Diags.getCustomDiagID(
400         DiagnosticsEngine::Error, "cannot mangle this declaration yet");
401     Diags.Report(D->getLocation(), DiagID) << D->getSourceRange();
402   }
403 }
404 
mangleFunctionEncoding(const FunctionDecl * FD,bool ShouldMangle)405 void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD,
406                                                      bool ShouldMangle) {
407   // <type-encoding> ::= <function-class> <function-type>
408 
409   // Since MSVC operates on the type as written and not the canonical type, it
410   // actually matters which decl we have here.  MSVC appears to choose the
411   // first, since it is most likely to be the declaration in a header file.
412   FD = FD->getFirstDecl();
413 
414   // We should never ever see a FunctionNoProtoType at this point.
415   // We don't even know how to mangle their types anyway :).
416   const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
417 
418   // extern "C" functions can hold entities that must be mangled.
419   // As it stands, these functions still need to get expressed in the full
420   // external name.  They have their class and type omitted, replaced with '9'.
421   if (ShouldMangle) {
422     // We would like to mangle all extern "C" functions using this additional
423     // component but this would break compatibility with MSVC's behavior.
424     // Instead, do this when we know that compatibility isn't important (in
425     // other words, when it is an overloaded extern "C" function).
426     if (FD->isExternC() && FD->hasAttr<OverloadableAttr>())
427       Out << "$$J0";
428 
429     mangleFunctionClass(FD);
430 
431     mangleFunctionType(FT, FD);
432   } else {
433     Out << '9';
434   }
435 }
436 
mangleVariableEncoding(const VarDecl * VD)437 void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
438   // <type-encoding> ::= <storage-class> <variable-type>
439   // <storage-class> ::= 0  # private static member
440   //                 ::= 1  # protected static member
441   //                 ::= 2  # public static member
442   //                 ::= 3  # global
443   //                 ::= 4  # static local
444 
445   // The first character in the encoding (after the name) is the storage class.
446   if (VD->isStaticDataMember()) {
447     // If it's a static member, it also encodes the access level.
448     switch (VD->getAccess()) {
449       default:
450       case AS_private: Out << '0'; break;
451       case AS_protected: Out << '1'; break;
452       case AS_public: Out << '2'; break;
453     }
454   }
455   else if (!VD->isStaticLocal())
456     Out << '3';
457   else
458     Out << '4';
459   // Now mangle the type.
460   // <variable-type> ::= <type> <cvr-qualifiers>
461   //                 ::= <type> <pointee-cvr-qualifiers> # pointers, references
462   // Pointers and references are odd. The type of 'int * const foo;' gets
463   // mangled as 'QAHA' instead of 'PAHB', for example.
464   SourceRange SR = VD->getSourceRange();
465   QualType Ty = VD->getType();
466   if (Ty->isPointerType() || Ty->isReferenceType() ||
467       Ty->isMemberPointerType()) {
468     mangleType(Ty, SR, QMM_Drop);
469     manglePointerExtQualifiers(
470         Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), QualType());
471     if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) {
472       mangleQualifiers(MPT->getPointeeType().getQualifiers(), true);
473       // Member pointers are suffixed with a back reference to the member
474       // pointer's class name.
475       mangleName(MPT->getClass()->getAsCXXRecordDecl());
476     } else
477       mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
478   } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
479     // Global arrays are funny, too.
480     mangleDecayedArrayType(AT);
481     if (AT->getElementType()->isArrayType())
482       Out << 'A';
483     else
484       mangleQualifiers(Ty.getQualifiers(), false);
485   } else {
486     mangleType(Ty, SR, QMM_Drop);
487     mangleQualifiers(Ty.getQualifiers(), false);
488   }
489 }
490 
mangleMemberDataPointer(const CXXRecordDecl * RD,const ValueDecl * VD)491 void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD,
492                                                       const ValueDecl *VD) {
493   // <member-data-pointer> ::= <integer-literal>
494   //                       ::= $F <number> <number>
495   //                       ::= $G <number> <number> <number>
496 
497   int64_t FieldOffset;
498   int64_t VBTableOffset;
499   MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
500   if (VD) {
501     FieldOffset = getASTContext().getFieldOffset(VD);
502     assert(FieldOffset % getASTContext().getCharWidth() == 0 &&
503            "cannot take address of bitfield");
504     FieldOffset /= getASTContext().getCharWidth();
505 
506     VBTableOffset = 0;
507 
508     if (IM == MSInheritanceAttr::Keyword_virtual_inheritance)
509       FieldOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
510   } else {
511     FieldOffset = RD->nullFieldOffsetIsZero() ? 0 : -1;
512 
513     VBTableOffset = -1;
514   }
515 
516   char Code = '\0';
517   switch (IM) {
518   case MSInheritanceAttr::Keyword_single_inheritance:      Code = '0'; break;
519   case MSInheritanceAttr::Keyword_multiple_inheritance:    Code = '0'; break;
520   case MSInheritanceAttr::Keyword_virtual_inheritance:     Code = 'F'; break;
521   case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'G'; break;
522   }
523 
524   Out << '$' << Code;
525 
526   mangleNumber(FieldOffset);
527 
528   // The C++ standard doesn't allow base-to-derived member pointer conversions
529   // in template parameter contexts, so the vbptr offset of data member pointers
530   // is always zero.
531   if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
532     mangleNumber(0);
533   if (MSInheritanceAttr::hasVBTableOffsetField(IM))
534     mangleNumber(VBTableOffset);
535 }
536 
537 void
mangleMemberFunctionPointer(const CXXRecordDecl * RD,const CXXMethodDecl * MD)538 MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD,
539                                                      const CXXMethodDecl *MD) {
540   // <member-function-pointer> ::= $1? <name>
541   //                           ::= $H? <name> <number>
542   //                           ::= $I? <name> <number> <number>
543   //                           ::= $J? <name> <number> <number> <number>
544 
545   MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
546 
547   char Code = '\0';
548   switch (IM) {
549   case MSInheritanceAttr::Keyword_single_inheritance:      Code = '1'; break;
550   case MSInheritanceAttr::Keyword_multiple_inheritance:    Code = 'H'; break;
551   case MSInheritanceAttr::Keyword_virtual_inheritance:     Code = 'I'; break;
552   case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'J'; break;
553   }
554 
555   // If non-virtual, mangle the name.  If virtual, mangle as a virtual memptr
556   // thunk.
557   uint64_t NVOffset = 0;
558   uint64_t VBTableOffset = 0;
559   uint64_t VBPtrOffset = 0;
560   if (MD) {
561     Out << '$' << Code << '?';
562     if (MD->isVirtual()) {
563       MicrosoftVTableContext *VTContext =
564           cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
565       const MicrosoftVTableContext::MethodVFTableLocation &ML =
566           VTContext->getMethodVFTableLocation(GlobalDecl(MD));
567       mangleVirtualMemPtrThunk(MD, ML);
568       NVOffset = ML.VFPtrOffset.getQuantity();
569       VBTableOffset = ML.VBTableIndex * 4;
570       if (ML.VBase) {
571         const ASTRecordLayout &Layout = getASTContext().getASTRecordLayout(RD);
572         VBPtrOffset = Layout.getVBPtrOffset().getQuantity();
573       }
574     } else {
575       mangleName(MD);
576       mangleFunctionEncoding(MD, /*ShouldMangle=*/true);
577     }
578 
579     if (VBTableOffset == 0 &&
580         IM == MSInheritanceAttr::Keyword_virtual_inheritance)
581       NVOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
582   } else {
583     // Null single inheritance member functions are encoded as a simple nullptr.
584     if (IM == MSInheritanceAttr::Keyword_single_inheritance) {
585       Out << "$0A@";
586       return;
587     }
588     if (IM == MSInheritanceAttr::Keyword_unspecified_inheritance)
589       VBTableOffset = -1;
590     Out << '$' << Code;
591   }
592 
593   if (MSInheritanceAttr::hasNVOffsetField(/*IsMemberFunction=*/true, IM))
594     mangleNumber(static_cast<uint32_t>(NVOffset));
595   if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
596     mangleNumber(VBPtrOffset);
597   if (MSInheritanceAttr::hasVBTableOffsetField(IM))
598     mangleNumber(VBTableOffset);
599 }
600 
mangleVirtualMemPtrThunk(const CXXMethodDecl * MD,const MicrosoftVTableContext::MethodVFTableLocation & ML)601 void MicrosoftCXXNameMangler::mangleVirtualMemPtrThunk(
602     const CXXMethodDecl *MD,
603     const MicrosoftVTableContext::MethodVFTableLocation &ML) {
604   // Get the vftable offset.
605   CharUnits PointerWidth = getASTContext().toCharUnitsFromBits(
606       getASTContext().getTargetInfo().getPointerWidth(0));
607   uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
608 
609   Out << "?_9";
610   mangleName(MD->getParent());
611   Out << "$B";
612   mangleNumber(OffsetInVFTable);
613   Out << 'A';
614   mangleCallingConvention(MD->getType()->getAs<FunctionProtoType>());
615 }
616 
mangleName(const NamedDecl * ND)617 void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) {
618   // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
619 
620   // Always start with the unqualified name.
621   mangleUnqualifiedName(ND);
622 
623   mangleNestedName(ND);
624 
625   // Terminate the whole name with an '@'.
626   Out << '@';
627 }
628 
mangleNumber(int64_t Number)629 void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
630   // <non-negative integer> ::= A@              # when Number == 0
631   //                        ::= <decimal digit> # when 1 <= Number <= 10
632   //                        ::= <hex digit>+ @  # when Number >= 10
633   //
634   // <number>               ::= [?] <non-negative integer>
635 
636   uint64_t Value = static_cast<uint64_t>(Number);
637   if (Number < 0) {
638     Value = -Value;
639     Out << '?';
640   }
641 
642   if (Value == 0)
643     Out << "A@";
644   else if (Value >= 1 && Value <= 10)
645     Out << (Value - 1);
646   else {
647     // Numbers that are not encoded as decimal digits are represented as nibbles
648     // in the range of ASCII characters 'A' to 'P'.
649     // The number 0x123450 would be encoded as 'BCDEFA'
650     char EncodedNumberBuffer[sizeof(uint64_t) * 2];
651     MutableArrayRef<char> BufferRef(EncodedNumberBuffer);
652     MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
653     for (; Value != 0; Value >>= 4)
654       *I++ = 'A' + (Value & 0xf);
655     Out.write(I.base(), I - BufferRef.rbegin());
656     Out << '@';
657   }
658 }
659 
660 static const TemplateDecl *
isTemplate(const NamedDecl * ND,const TemplateArgumentList * & TemplateArgs)661 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
662   // Check if we have a function template.
663   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
664     if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
665       TemplateArgs = FD->getTemplateSpecializationArgs();
666       return TD;
667     }
668   }
669 
670   // Check if we have a class template.
671   if (const ClassTemplateSpecializationDecl *Spec =
672           dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
673     TemplateArgs = &Spec->getTemplateArgs();
674     return Spec->getSpecializedTemplate();
675   }
676 
677   // Check if we have a variable template.
678   if (const VarTemplateSpecializationDecl *Spec =
679           dyn_cast<VarTemplateSpecializationDecl>(ND)) {
680     TemplateArgs = &Spec->getTemplateArgs();
681     return Spec->getSpecializedTemplate();
682   }
683 
684   return nullptr;
685 }
686 
mangleUnqualifiedName(const NamedDecl * ND,DeclarationName Name)687 void MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
688                                                     DeclarationName Name) {
689   //  <unqualified-name> ::= <operator-name>
690   //                     ::= <ctor-dtor-name>
691   //                     ::= <source-name>
692   //                     ::= <template-name>
693 
694   // Check if we have a template.
695   const TemplateArgumentList *TemplateArgs = nullptr;
696   if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
697     // Function templates aren't considered for name back referencing.  This
698     // makes sense since function templates aren't likely to occur multiple
699     // times in a symbol.
700     if (!isa<ClassTemplateDecl>(TD)) {
701       mangleTemplateInstantiationName(TD, *TemplateArgs);
702       Out << '@';
703       return;
704     }
705 
706     // Here comes the tricky thing: if we need to mangle something like
707     //   void foo(A::X<Y>, B::X<Y>),
708     // the X<Y> part is aliased. However, if you need to mangle
709     //   void foo(A::X<A::Y>, A::X<B::Y>),
710     // the A::X<> part is not aliased.
711     // That said, from the mangler's perspective we have a structure like this:
712     //   namespace[s] -> type[ -> template-parameters]
713     // but from the Clang perspective we have
714     //   type [ -> template-parameters]
715     //      \-> namespace[s]
716     // What we do is we create a new mangler, mangle the same type (without
717     // a namespace suffix) to a string using the extra mangler and then use
718     // the mangled type name as a key to check the mangling of different types
719     // for aliasing.
720 
721     llvm::SmallString<64> TemplateMangling;
722     llvm::raw_svector_ostream Stream(TemplateMangling);
723     MicrosoftCXXNameMangler Extra(Context, Stream);
724     Extra.mangleTemplateInstantiationName(TD, *TemplateArgs);
725 
726     mangleSourceName(TemplateMangling);
727     return;
728   }
729 
730   switch (Name.getNameKind()) {
731     case DeclarationName::Identifier: {
732       if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
733         mangleSourceName(II->getName());
734         break;
735       }
736 
737       // Otherwise, an anonymous entity.  We must have a declaration.
738       assert(ND && "mangling empty name without declaration");
739 
740       if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
741         if (NS->isAnonymousNamespace()) {
742           Out << "?A@";
743           break;
744         }
745       }
746 
747       if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
748         // We must have an anonymous union or struct declaration.
749         const CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl();
750         assert(RD && "expected variable decl to have a record type");
751         // Anonymous types with no tag or typedef get the name of their
752         // declarator mangled in.  If they have no declarator, number them with
753         // a $S prefix.
754         llvm::SmallString<64> Name("$S");
755         // Get a unique id for the anonymous struct.
756         Name += llvm::utostr(Context.getAnonymousStructId(RD) + 1);
757         mangleSourceName(Name.str());
758         break;
759       }
760 
761       // We must have an anonymous struct.
762       const TagDecl *TD = cast<TagDecl>(ND);
763       if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
764         assert(TD->getDeclContext() == D->getDeclContext() &&
765                "Typedef should not be in another decl context!");
766         assert(D->getDeclName().getAsIdentifierInfo() &&
767                "Typedef was not named!");
768         mangleSourceName(D->getDeclName().getAsIdentifierInfo()->getName());
769         break;
770       }
771 
772       if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
773         if (Record->isLambda()) {
774           llvm::SmallString<10> Name("<lambda_");
775           unsigned LambdaId;
776           if (Record->getLambdaManglingNumber())
777             LambdaId = Record->getLambdaManglingNumber();
778           else
779             LambdaId = Context.getLambdaId(Record);
780 
781           Name += llvm::utostr(LambdaId);
782           Name += ">";
783 
784           mangleSourceName(Name);
785           break;
786         }
787       }
788 
789       llvm::SmallString<64> Name("<unnamed-type-");
790       if (DeclaratorDecl *DD =
791               Context.getASTContext().getDeclaratorForUnnamedTagDecl(TD)) {
792         // Anonymous types without a name for linkage purposes have their
793         // declarator mangled in if they have one.
794         Name += DD->getName();
795       } else if (TypedefNameDecl *TND =
796                      Context.getASTContext().getTypedefNameForUnnamedTagDecl(
797                          TD)) {
798         // Anonymous types without a name for linkage purposes have their
799         // associate typedef mangled in if they have one.
800         Name += TND->getName();
801       } else {
802         // Otherwise, number the types using a $S prefix.
803         Name += "$S";
804         Name += llvm::utostr(Context.getAnonymousStructId(TD) + 1);
805       }
806       Name += ">";
807       mangleSourceName(Name.str());
808       break;
809     }
810 
811     case DeclarationName::ObjCZeroArgSelector:
812     case DeclarationName::ObjCOneArgSelector:
813     case DeclarationName::ObjCMultiArgSelector:
814       llvm_unreachable("Can't mangle Objective-C selector names here!");
815 
816     case DeclarationName::CXXConstructorName:
817       if (Structor == getStructor(ND)) {
818         if (StructorType == Ctor_CopyingClosure) {
819           Out << "?_O";
820           return;
821         }
822         if (StructorType == Ctor_DefaultClosure) {
823           Out << "?_F";
824           return;
825         }
826       }
827       Out << "?0";
828       return;
829 
830     case DeclarationName::CXXDestructorName:
831       if (ND == Structor)
832         // If the named decl is the C++ destructor we're mangling,
833         // use the type we were given.
834         mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
835       else
836         // Otherwise, use the base destructor name. This is relevant if a
837         // class with a destructor is declared within a destructor.
838         mangleCXXDtorType(Dtor_Base);
839       break;
840 
841     case DeclarationName::CXXConversionFunctionName:
842       // <operator-name> ::= ?B # (cast)
843       // The target type is encoded as the return type.
844       Out << "?B";
845       break;
846 
847     case DeclarationName::CXXOperatorName:
848       mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation());
849       break;
850 
851     case DeclarationName::CXXLiteralOperatorName: {
852       Out << "?__K";
853       mangleSourceName(Name.getCXXLiteralIdentifier()->getName());
854       break;
855     }
856 
857     case DeclarationName::CXXUsingDirective:
858       llvm_unreachable("Can't mangle a using directive name!");
859   }
860 }
861 
mangleNestedName(const NamedDecl * ND)862 void MicrosoftCXXNameMangler::mangleNestedName(const NamedDecl *ND) {
863   // <postfix> ::= <unqualified-name> [<postfix>]
864   //           ::= <substitution> [<postfix>]
865   const DeclContext *DC = getEffectiveDeclContext(ND);
866 
867   while (!DC->isTranslationUnit()) {
868     if (isa<TagDecl>(ND) || isa<VarDecl>(ND)) {
869       unsigned Disc;
870       if (Context.getNextDiscriminator(ND, Disc)) {
871         Out << '?';
872         mangleNumber(Disc);
873         Out << '?';
874       }
875     }
876 
877     if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
878       DiagnosticsEngine &Diags = Context.getDiags();
879       unsigned DiagID =
880           Diags.getCustomDiagID(DiagnosticsEngine::Error,
881                                 "cannot mangle a local inside this block yet");
882       Diags.Report(BD->getLocation(), DiagID);
883 
884       // FIXME: This is completely, utterly, wrong; see ItaniumMangle
885       // for how this should be done.
886       Out << "__block_invoke" << Context.getBlockId(BD, false);
887       Out << '@';
888       continue;
889     } else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
890       mangleObjCMethodName(Method);
891     } else if (isa<NamedDecl>(DC)) {
892       ND = cast<NamedDecl>(DC);
893       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
894         mangle(FD, "?");
895         break;
896       } else
897         mangleUnqualifiedName(ND);
898     }
899     DC = DC->getParent();
900   }
901 }
902 
mangleCXXDtorType(CXXDtorType T)903 void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
904   // Microsoft uses the names on the case labels for these dtor variants.  Clang
905   // uses the Itanium terminology internally.  Everything in this ABI delegates
906   // towards the base dtor.
907   switch (T) {
908   // <operator-name> ::= ?1  # destructor
909   case Dtor_Base: Out << "?1"; return;
910   // <operator-name> ::= ?_D # vbase destructor
911   case Dtor_Complete: Out << "?_D"; return;
912   // <operator-name> ::= ?_G # scalar deleting destructor
913   case Dtor_Deleting: Out << "?_G"; return;
914   // <operator-name> ::= ?_E # vector deleting destructor
915   // FIXME: Add a vector deleting dtor type.  It goes in the vtable, so we need
916   // it.
917   case Dtor_Comdat:
918     llvm_unreachable("not expecting a COMDAT");
919   }
920   llvm_unreachable("Unsupported dtor type?");
921 }
922 
mangleOperatorName(OverloadedOperatorKind OO,SourceLocation Loc)923 void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
924                                                  SourceLocation Loc) {
925   switch (OO) {
926   //                     ?0 # constructor
927   //                     ?1 # destructor
928   // <operator-name> ::= ?2 # new
929   case OO_New: Out << "?2"; break;
930   // <operator-name> ::= ?3 # delete
931   case OO_Delete: Out << "?3"; break;
932   // <operator-name> ::= ?4 # =
933   case OO_Equal: Out << "?4"; break;
934   // <operator-name> ::= ?5 # >>
935   case OO_GreaterGreater: Out << "?5"; break;
936   // <operator-name> ::= ?6 # <<
937   case OO_LessLess: Out << "?6"; break;
938   // <operator-name> ::= ?7 # !
939   case OO_Exclaim: Out << "?7"; break;
940   // <operator-name> ::= ?8 # ==
941   case OO_EqualEqual: Out << "?8"; break;
942   // <operator-name> ::= ?9 # !=
943   case OO_ExclaimEqual: Out << "?9"; break;
944   // <operator-name> ::= ?A # []
945   case OO_Subscript: Out << "?A"; break;
946   //                     ?B # conversion
947   // <operator-name> ::= ?C # ->
948   case OO_Arrow: Out << "?C"; break;
949   // <operator-name> ::= ?D # *
950   case OO_Star: Out << "?D"; break;
951   // <operator-name> ::= ?E # ++
952   case OO_PlusPlus: Out << "?E"; break;
953   // <operator-name> ::= ?F # --
954   case OO_MinusMinus: Out << "?F"; break;
955   // <operator-name> ::= ?G # -
956   case OO_Minus: Out << "?G"; break;
957   // <operator-name> ::= ?H # +
958   case OO_Plus: Out << "?H"; break;
959   // <operator-name> ::= ?I # &
960   case OO_Amp: Out << "?I"; break;
961   // <operator-name> ::= ?J # ->*
962   case OO_ArrowStar: Out << "?J"; break;
963   // <operator-name> ::= ?K # /
964   case OO_Slash: Out << "?K"; break;
965   // <operator-name> ::= ?L # %
966   case OO_Percent: Out << "?L"; break;
967   // <operator-name> ::= ?M # <
968   case OO_Less: Out << "?M"; break;
969   // <operator-name> ::= ?N # <=
970   case OO_LessEqual: Out << "?N"; break;
971   // <operator-name> ::= ?O # >
972   case OO_Greater: Out << "?O"; break;
973   // <operator-name> ::= ?P # >=
974   case OO_GreaterEqual: Out << "?P"; break;
975   // <operator-name> ::= ?Q # ,
976   case OO_Comma: Out << "?Q"; break;
977   // <operator-name> ::= ?R # ()
978   case OO_Call: Out << "?R"; break;
979   // <operator-name> ::= ?S # ~
980   case OO_Tilde: Out << "?S"; break;
981   // <operator-name> ::= ?T # ^
982   case OO_Caret: Out << "?T"; break;
983   // <operator-name> ::= ?U # |
984   case OO_Pipe: Out << "?U"; break;
985   // <operator-name> ::= ?V # &&
986   case OO_AmpAmp: Out << "?V"; break;
987   // <operator-name> ::= ?W # ||
988   case OO_PipePipe: Out << "?W"; break;
989   // <operator-name> ::= ?X # *=
990   case OO_StarEqual: Out << "?X"; break;
991   // <operator-name> ::= ?Y # +=
992   case OO_PlusEqual: Out << "?Y"; break;
993   // <operator-name> ::= ?Z # -=
994   case OO_MinusEqual: Out << "?Z"; break;
995   // <operator-name> ::= ?_0 # /=
996   case OO_SlashEqual: Out << "?_0"; break;
997   // <operator-name> ::= ?_1 # %=
998   case OO_PercentEqual: Out << "?_1"; break;
999   // <operator-name> ::= ?_2 # >>=
1000   case OO_GreaterGreaterEqual: Out << "?_2"; break;
1001   // <operator-name> ::= ?_3 # <<=
1002   case OO_LessLessEqual: Out << "?_3"; break;
1003   // <operator-name> ::= ?_4 # &=
1004   case OO_AmpEqual: Out << "?_4"; break;
1005   // <operator-name> ::= ?_5 # |=
1006   case OO_PipeEqual: Out << "?_5"; break;
1007   // <operator-name> ::= ?_6 # ^=
1008   case OO_CaretEqual: Out << "?_6"; break;
1009   //                     ?_7 # vftable
1010   //                     ?_8 # vbtable
1011   //                     ?_9 # vcall
1012   //                     ?_A # typeof
1013   //                     ?_B # local static guard
1014   //                     ?_C # string
1015   //                     ?_D # vbase destructor
1016   //                     ?_E # vector deleting destructor
1017   //                     ?_F # default constructor closure
1018   //                     ?_G # scalar deleting destructor
1019   //                     ?_H # vector constructor iterator
1020   //                     ?_I # vector destructor iterator
1021   //                     ?_J # vector vbase constructor iterator
1022   //                     ?_K # virtual displacement map
1023   //                     ?_L # eh vector constructor iterator
1024   //                     ?_M # eh vector destructor iterator
1025   //                     ?_N # eh vector vbase constructor iterator
1026   //                     ?_O # copy constructor closure
1027   //                     ?_P<name> # udt returning <name>
1028   //                     ?_Q # <unknown>
1029   //                     ?_R0 # RTTI Type Descriptor
1030   //                     ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
1031   //                     ?_R2 # RTTI Base Class Array
1032   //                     ?_R3 # RTTI Class Hierarchy Descriptor
1033   //                     ?_R4 # RTTI Complete Object Locator
1034   //                     ?_S # local vftable
1035   //                     ?_T # local vftable constructor closure
1036   // <operator-name> ::= ?_U # new[]
1037   case OO_Array_New: Out << "?_U"; break;
1038   // <operator-name> ::= ?_V # delete[]
1039   case OO_Array_Delete: Out << "?_V"; break;
1040 
1041   case OO_Conditional: {
1042     DiagnosticsEngine &Diags = Context.getDiags();
1043     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1044       "cannot mangle this conditional operator yet");
1045     Diags.Report(Loc, DiagID);
1046     break;
1047   }
1048 
1049   case OO_Coawait: {
1050     DiagnosticsEngine &Diags = Context.getDiags();
1051     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1052       "cannot mangle this operator co_await yet");
1053     Diags.Report(Loc, DiagID);
1054     break;
1055   }
1056 
1057   case OO_None:
1058   case NUM_OVERLOADED_OPERATORS:
1059     llvm_unreachable("Not an overloaded operator");
1060   }
1061 }
1062 
mangleSourceName(StringRef Name)1063 void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) {
1064   // <source name> ::= <identifier> @
1065   BackRefVec::iterator Found =
1066       std::find(NameBackReferences.begin(), NameBackReferences.end(), Name);
1067   if (Found == NameBackReferences.end()) {
1068     if (NameBackReferences.size() < 10)
1069       NameBackReferences.push_back(Name);
1070     Out << Name << '@';
1071   } else {
1072     Out << (Found - NameBackReferences.begin());
1073   }
1074 }
1075 
mangleObjCMethodName(const ObjCMethodDecl * MD)1076 void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1077   Context.mangleObjCMethodName(MD, Out);
1078 }
1079 
mangleTemplateInstantiationName(const TemplateDecl * TD,const TemplateArgumentList & TemplateArgs)1080 void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
1081     const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1082   // <template-name> ::= <unscoped-template-name> <template-args>
1083   //                 ::= <substitution>
1084   // Always start with the unqualified name.
1085 
1086   // Templates have their own context for back references.
1087   ArgBackRefMap OuterArgsContext;
1088   BackRefVec OuterTemplateContext;
1089   NameBackReferences.swap(OuterTemplateContext);
1090   TypeBackReferences.swap(OuterArgsContext);
1091 
1092   mangleUnscopedTemplateName(TD);
1093   mangleTemplateArgs(TD, TemplateArgs);
1094 
1095   // Restore the previous back reference contexts.
1096   NameBackReferences.swap(OuterTemplateContext);
1097   TypeBackReferences.swap(OuterArgsContext);
1098 }
1099 
1100 void
mangleUnscopedTemplateName(const TemplateDecl * TD)1101 MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
1102   // <unscoped-template-name> ::= ?$ <unqualified-name>
1103   Out << "?$";
1104   mangleUnqualifiedName(TD);
1105 }
1106 
mangleIntegerLiteral(const llvm::APSInt & Value,bool IsBoolean)1107 void MicrosoftCXXNameMangler::mangleIntegerLiteral(const llvm::APSInt &Value,
1108                                                    bool IsBoolean) {
1109   // <integer-literal> ::= $0 <number>
1110   Out << "$0";
1111   // Make sure booleans are encoded as 0/1.
1112   if (IsBoolean && Value.getBoolValue())
1113     mangleNumber(1);
1114   else if (Value.isSigned())
1115     mangleNumber(Value.getSExtValue());
1116   else
1117     mangleNumber(Value.getZExtValue());
1118 }
1119 
mangleExpression(const Expr * E)1120 void MicrosoftCXXNameMangler::mangleExpression(const Expr *E) {
1121   // See if this is a constant expression.
1122   llvm::APSInt Value;
1123   if (E->isIntegerConstantExpr(Value, Context.getASTContext())) {
1124     mangleIntegerLiteral(Value, E->getType()->isBooleanType());
1125     return;
1126   }
1127 
1128   // Look through no-op casts like template parameter substitutions.
1129   E = E->IgnoreParenNoopCasts(Context.getASTContext());
1130 
1131   const CXXUuidofExpr *UE = nullptr;
1132   if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1133     if (UO->getOpcode() == UO_AddrOf)
1134       UE = dyn_cast<CXXUuidofExpr>(UO->getSubExpr());
1135   } else
1136     UE = dyn_cast<CXXUuidofExpr>(E);
1137 
1138   if (UE) {
1139     // This CXXUuidofExpr is mangled as-if it were actually a VarDecl from
1140     // const __s_GUID _GUID_{lower case UUID with underscores}
1141     StringRef Uuid = UE->getUuidAsStringRef(Context.getASTContext());
1142     std::string Name = "_GUID_" + Uuid.lower();
1143     std::replace(Name.begin(), Name.end(), '-', '_');
1144 
1145     // If we had to peek through an address-of operator, treat this like we are
1146     // dealing with a pointer type.  Otherwise, treat it like a const reference.
1147     //
1148     // N.B. This matches up with the handling of TemplateArgument::Declaration
1149     // in mangleTemplateArg
1150     if (UE == E)
1151       Out << "$E?";
1152     else
1153       Out << "$1?";
1154     Out << Name << "@@3U__s_GUID@@B";
1155     return;
1156   }
1157 
1158   // As bad as this diagnostic is, it's better than crashing.
1159   DiagnosticsEngine &Diags = Context.getDiags();
1160   unsigned DiagID = Diags.getCustomDiagID(
1161       DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
1162   Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
1163                                         << E->getSourceRange();
1164 }
1165 
mangleTemplateArgs(const TemplateDecl * TD,const TemplateArgumentList & TemplateArgs)1166 void MicrosoftCXXNameMangler::mangleTemplateArgs(
1167     const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1168   // <template-args> ::= <template-arg>+
1169   const TemplateParameterList *TPL = TD->getTemplateParameters();
1170   assert(TPL->size() == TemplateArgs.size() &&
1171          "size mismatch between args and parms!");
1172 
1173   unsigned Idx = 0;
1174   for (const TemplateArgument &TA : TemplateArgs.asArray())
1175     mangleTemplateArg(TD, TA, TPL->getParam(Idx++));
1176 }
1177 
mangleTemplateArg(const TemplateDecl * TD,const TemplateArgument & TA,const NamedDecl * Parm)1178 void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
1179                                                 const TemplateArgument &TA,
1180                                                 const NamedDecl *Parm) {
1181   // <template-arg> ::= <type>
1182   //                ::= <integer-literal>
1183   //                ::= <member-data-pointer>
1184   //                ::= <member-function-pointer>
1185   //                ::= $E? <name> <type-encoding>
1186   //                ::= $1? <name> <type-encoding>
1187   //                ::= $0A@
1188   //                ::= <template-args>
1189 
1190   switch (TA.getKind()) {
1191   case TemplateArgument::Null:
1192     llvm_unreachable("Can't mangle null template arguments!");
1193   case TemplateArgument::TemplateExpansion:
1194     llvm_unreachable("Can't mangle template expansion arguments!");
1195   case TemplateArgument::Type: {
1196     QualType T = TA.getAsType();
1197     mangleType(T, SourceRange(), QMM_Escape);
1198     break;
1199   }
1200   case TemplateArgument::Declaration: {
1201     const NamedDecl *ND = cast<NamedDecl>(TA.getAsDecl());
1202     if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) {
1203       mangleMemberDataPointer(
1204           cast<CXXRecordDecl>(ND->getDeclContext())->getMostRecentDecl(),
1205           cast<ValueDecl>(ND));
1206     } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1207       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1208       if (MD && MD->isInstance()) {
1209         mangleMemberFunctionPointer(MD->getParent()->getMostRecentDecl(), MD);
1210       } else {
1211         Out << "$1?";
1212         mangleName(FD);
1213         mangleFunctionEncoding(FD, /*ShouldMangle=*/true);
1214       }
1215     } else {
1216       mangle(ND, TA.getParamTypeForDecl()->isReferenceType() ? "$E?" : "$1?");
1217     }
1218     break;
1219   }
1220   case TemplateArgument::Integral:
1221     mangleIntegerLiteral(TA.getAsIntegral(),
1222                          TA.getIntegralType()->isBooleanType());
1223     break;
1224   case TemplateArgument::NullPtr: {
1225     QualType T = TA.getNullPtrType();
1226     if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
1227       const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1228       if (MPT->isMemberFunctionPointerType() &&
1229           !isa<FunctionTemplateDecl>(TD)) {
1230         mangleMemberFunctionPointer(RD, nullptr);
1231         return;
1232       }
1233       if (MPT->isMemberDataPointer()) {
1234         if (!isa<FunctionTemplateDecl>(TD)) {
1235           mangleMemberDataPointer(RD, nullptr);
1236           return;
1237         }
1238         // nullptr data pointers are always represented with a single field
1239         // which is initialized with either 0 or -1.  Why -1?  Well, we need to
1240         // distinguish the case where the data member is at offset zero in the
1241         // record.
1242         // However, we are free to use 0 *if* we would use multiple fields for
1243         // non-nullptr member pointers.
1244         if (!RD->nullFieldOffsetIsZero()) {
1245           mangleIntegerLiteral(llvm::APSInt::get(-1), /*IsBoolean=*/false);
1246           return;
1247         }
1248       }
1249     }
1250     mangleIntegerLiteral(llvm::APSInt::getUnsigned(0), /*IsBoolean=*/false);
1251     break;
1252   }
1253   case TemplateArgument::Expression:
1254     mangleExpression(TA.getAsExpr());
1255     break;
1256   case TemplateArgument::Pack: {
1257     ArrayRef<TemplateArgument> TemplateArgs = TA.getPackAsArray();
1258     if (TemplateArgs.empty()) {
1259       if (isa<TemplateTypeParmDecl>(Parm) ||
1260           isa<TemplateTemplateParmDecl>(Parm))
1261         // MSVC 2015 changed the mangling for empty expanded template packs,
1262         // use the old mangling for link compatibility for old versions.
1263         Out << (Context.getASTContext().getLangOpts().isCompatibleWithMSVC(
1264                     LangOptions::MSVC2015)
1265                     ? "$$V"
1266                     : "$$$V");
1267       else if (isa<NonTypeTemplateParmDecl>(Parm))
1268         Out << "$S";
1269       else
1270         llvm_unreachable("unexpected template parameter decl!");
1271     } else {
1272       for (const TemplateArgument &PA : TemplateArgs)
1273         mangleTemplateArg(TD, PA, Parm);
1274     }
1275     break;
1276   }
1277   case TemplateArgument::Template: {
1278     const NamedDecl *ND =
1279         TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl();
1280     if (const auto *TD = dyn_cast<TagDecl>(ND)) {
1281       mangleType(TD);
1282     } else if (isa<TypeAliasDecl>(ND)) {
1283       Out << "$$Y";
1284       mangleName(ND);
1285     } else {
1286       llvm_unreachable("unexpected template template NamedDecl!");
1287     }
1288     break;
1289   }
1290   }
1291 }
1292 
mangleQualifiers(Qualifiers Quals,bool IsMember)1293 void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
1294                                                bool IsMember) {
1295   // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
1296   // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
1297   // 'I' means __restrict (32/64-bit).
1298   // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
1299   // keyword!
1300   // <base-cvr-qualifiers> ::= A  # near
1301   //                       ::= B  # near const
1302   //                       ::= C  # near volatile
1303   //                       ::= D  # near const volatile
1304   //                       ::= E  # far (16-bit)
1305   //                       ::= F  # far const (16-bit)
1306   //                       ::= G  # far volatile (16-bit)
1307   //                       ::= H  # far const volatile (16-bit)
1308   //                       ::= I  # huge (16-bit)
1309   //                       ::= J  # huge const (16-bit)
1310   //                       ::= K  # huge volatile (16-bit)
1311   //                       ::= L  # huge const volatile (16-bit)
1312   //                       ::= M <basis> # based
1313   //                       ::= N <basis> # based const
1314   //                       ::= O <basis> # based volatile
1315   //                       ::= P <basis> # based const volatile
1316   //                       ::= Q  # near member
1317   //                       ::= R  # near const member
1318   //                       ::= S  # near volatile member
1319   //                       ::= T  # near const volatile member
1320   //                       ::= U  # far member (16-bit)
1321   //                       ::= V  # far const member (16-bit)
1322   //                       ::= W  # far volatile member (16-bit)
1323   //                       ::= X  # far const volatile member (16-bit)
1324   //                       ::= Y  # huge member (16-bit)
1325   //                       ::= Z  # huge const member (16-bit)
1326   //                       ::= 0  # huge volatile member (16-bit)
1327   //                       ::= 1  # huge const volatile member (16-bit)
1328   //                       ::= 2 <basis> # based member
1329   //                       ::= 3 <basis> # based const member
1330   //                       ::= 4 <basis> # based volatile member
1331   //                       ::= 5 <basis> # based const volatile member
1332   //                       ::= 6  # near function (pointers only)
1333   //                       ::= 7  # far function (pointers only)
1334   //                       ::= 8  # near method (pointers only)
1335   //                       ::= 9  # far method (pointers only)
1336   //                       ::= _A <basis> # based function (pointers only)
1337   //                       ::= _B <basis> # based function (far?) (pointers only)
1338   //                       ::= _C <basis> # based method (pointers only)
1339   //                       ::= _D <basis> # based method (far?) (pointers only)
1340   //                       ::= _E # block (Clang)
1341   // <basis> ::= 0 # __based(void)
1342   //         ::= 1 # __based(segment)?
1343   //         ::= 2 <name> # __based(name)
1344   //         ::= 3 # ?
1345   //         ::= 4 # ?
1346   //         ::= 5 # not really based
1347   bool HasConst = Quals.hasConst(),
1348        HasVolatile = Quals.hasVolatile();
1349 
1350   if (!IsMember) {
1351     if (HasConst && HasVolatile) {
1352       Out << 'D';
1353     } else if (HasVolatile) {
1354       Out << 'C';
1355     } else if (HasConst) {
1356       Out << 'B';
1357     } else {
1358       Out << 'A';
1359     }
1360   } else {
1361     if (HasConst && HasVolatile) {
1362       Out << 'T';
1363     } else if (HasVolatile) {
1364       Out << 'S';
1365     } else if (HasConst) {
1366       Out << 'R';
1367     } else {
1368       Out << 'Q';
1369     }
1370   }
1371 
1372   // FIXME: For now, just drop all extension qualifiers on the floor.
1373 }
1374 
1375 void
mangleRefQualifier(RefQualifierKind RefQualifier)1376 MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1377   // <ref-qualifier> ::= G                # lvalue reference
1378   //                 ::= H                # rvalue-reference
1379   switch (RefQualifier) {
1380   case RQ_None:
1381     break;
1382 
1383   case RQ_LValue:
1384     Out << 'G';
1385     break;
1386 
1387   case RQ_RValue:
1388     Out << 'H';
1389     break;
1390   }
1391 }
1392 
manglePointerExtQualifiers(Qualifiers Quals,QualType PointeeType)1393 void MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals,
1394                                                          QualType PointeeType) {
1395   bool HasRestrict = Quals.hasRestrict();
1396   if (PointersAre64Bit &&
1397       (PointeeType.isNull() || !PointeeType->isFunctionType()))
1398     Out << 'E';
1399 
1400   if (HasRestrict)
1401     Out << 'I';
1402 }
1403 
manglePointerCVQualifiers(Qualifiers Quals)1404 void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
1405   // <pointer-cv-qualifiers> ::= P  # no qualifiers
1406   //                         ::= Q  # const
1407   //                         ::= R  # volatile
1408   //                         ::= S  # const volatile
1409   bool HasConst = Quals.hasConst(),
1410        HasVolatile = Quals.hasVolatile();
1411 
1412   if (HasConst && HasVolatile) {
1413     Out << 'S';
1414   } else if (HasVolatile) {
1415     Out << 'R';
1416   } else if (HasConst) {
1417     Out << 'Q';
1418   } else {
1419     Out << 'P';
1420   }
1421 }
1422 
mangleArgumentType(QualType T,SourceRange Range)1423 void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
1424                                                  SourceRange Range) {
1425   // MSVC will backreference two canonically equivalent types that have slightly
1426   // different manglings when mangled alone.
1427 
1428   // Decayed types do not match up with non-decayed versions of the same type.
1429   //
1430   // e.g.
1431   // void (*x)(void) will not form a backreference with void x(void)
1432   void *TypePtr;
1433   if (const auto *DT = T->getAs<DecayedType>()) {
1434     QualType OriginalType = DT->getOriginalType();
1435     // All decayed ArrayTypes should be treated identically; as-if they were
1436     // a decayed IncompleteArrayType.
1437     if (const auto *AT = getASTContext().getAsArrayType(OriginalType))
1438       OriginalType = getASTContext().getIncompleteArrayType(
1439           AT->getElementType(), AT->getSizeModifier(),
1440           AT->getIndexTypeCVRQualifiers());
1441 
1442     TypePtr = OriginalType.getCanonicalType().getAsOpaquePtr();
1443     // If the original parameter was textually written as an array,
1444     // instead treat the decayed parameter like it's const.
1445     //
1446     // e.g.
1447     // int [] -> int * const
1448     if (OriginalType->isArrayType())
1449       T = T.withConst();
1450   } else {
1451     TypePtr = T.getCanonicalType().getAsOpaquePtr();
1452   }
1453 
1454   ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1455 
1456   if (Found == TypeBackReferences.end()) {
1457     size_t OutSizeBefore = Out.tell();
1458 
1459     mangleType(T, Range, QMM_Drop);
1460 
1461     // See if it's worth creating a back reference.
1462     // Only types longer than 1 character are considered
1463     // and only 10 back references slots are available:
1464     bool LongerThanOneChar = (Out.tell() - OutSizeBefore > 1);
1465     if (LongerThanOneChar && TypeBackReferences.size() < 10) {
1466       size_t Size = TypeBackReferences.size();
1467       TypeBackReferences[TypePtr] = Size;
1468     }
1469   } else {
1470     Out << Found->second;
1471   }
1472 }
1473 
mangleType(QualType T,SourceRange Range,QualifierMangleMode QMM)1474 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
1475                                          QualifierMangleMode QMM) {
1476   // Don't use the canonical types.  MSVC includes things like 'const' on
1477   // pointer arguments to function pointers that canonicalization strips away.
1478   T = T.getDesugaredType(getASTContext());
1479   Qualifiers Quals = T.getLocalQualifiers();
1480   if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
1481     // If there were any Quals, getAsArrayType() pushed them onto the array
1482     // element type.
1483     if (QMM == QMM_Mangle)
1484       Out << 'A';
1485     else if (QMM == QMM_Escape || QMM == QMM_Result)
1486       Out << "$$B";
1487     mangleArrayType(AT);
1488     return;
1489   }
1490 
1491   bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
1492                    T->isReferenceType() || T->isBlockPointerType();
1493 
1494   switch (QMM) {
1495   case QMM_Drop:
1496     break;
1497   case QMM_Mangle:
1498     if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
1499       Out << '6';
1500       mangleFunctionType(FT);
1501       return;
1502     }
1503     mangleQualifiers(Quals, false);
1504     break;
1505   case QMM_Escape:
1506     if (!IsPointer && Quals) {
1507       Out << "$$C";
1508       mangleQualifiers(Quals, false);
1509     }
1510     break;
1511   case QMM_Result:
1512     if ((!IsPointer && Quals) || isa<TagType>(T)) {
1513       Out << '?';
1514       mangleQualifiers(Quals, false);
1515     }
1516     break;
1517   }
1518 
1519   const Type *ty = T.getTypePtr();
1520 
1521   switch (ty->getTypeClass()) {
1522 #define ABSTRACT_TYPE(CLASS, PARENT)
1523 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1524   case Type::CLASS: \
1525     llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1526     return;
1527 #define TYPE(CLASS, PARENT) \
1528   case Type::CLASS: \
1529     mangleType(cast<CLASS##Type>(ty), Quals, Range); \
1530     break;
1531 #include "clang/AST/TypeNodes.def"
1532 #undef ABSTRACT_TYPE
1533 #undef NON_CANONICAL_TYPE
1534 #undef TYPE
1535   }
1536 }
1537 
mangleType(const BuiltinType * T,Qualifiers,SourceRange Range)1538 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers,
1539                                          SourceRange Range) {
1540   //  <type>         ::= <builtin-type>
1541   //  <builtin-type> ::= X  # void
1542   //                 ::= C  # signed char
1543   //                 ::= D  # char
1544   //                 ::= E  # unsigned char
1545   //                 ::= F  # short
1546   //                 ::= G  # unsigned short (or wchar_t if it's not a builtin)
1547   //                 ::= H  # int
1548   //                 ::= I  # unsigned int
1549   //                 ::= J  # long
1550   //                 ::= K  # unsigned long
1551   //                     L  # <none>
1552   //                 ::= M  # float
1553   //                 ::= N  # double
1554   //                 ::= O  # long double (__float80 is mangled differently)
1555   //                 ::= _J # long long, __int64
1556   //                 ::= _K # unsigned long long, __int64
1557   //                 ::= _L # __int128
1558   //                 ::= _M # unsigned __int128
1559   //                 ::= _N # bool
1560   //                     _O # <array in parameter>
1561   //                 ::= _T # __float80 (Intel)
1562   //                 ::= _W # wchar_t
1563   //                 ::= _Z # __float80 (Digital Mars)
1564   switch (T->getKind()) {
1565   case BuiltinType::Void:
1566     Out << 'X';
1567     break;
1568   case BuiltinType::SChar:
1569     Out << 'C';
1570     break;
1571   case BuiltinType::Char_U:
1572   case BuiltinType::Char_S:
1573     Out << 'D';
1574     break;
1575   case BuiltinType::UChar:
1576     Out << 'E';
1577     break;
1578   case BuiltinType::Short:
1579     Out << 'F';
1580     break;
1581   case BuiltinType::UShort:
1582     Out << 'G';
1583     break;
1584   case BuiltinType::Int:
1585     Out << 'H';
1586     break;
1587   case BuiltinType::UInt:
1588     Out << 'I';
1589     break;
1590   case BuiltinType::Long:
1591     Out << 'J';
1592     break;
1593   case BuiltinType::ULong:
1594     Out << 'K';
1595     break;
1596   case BuiltinType::Float:
1597     Out << 'M';
1598     break;
1599   case BuiltinType::Double:
1600     Out << 'N';
1601     break;
1602   // TODO: Determine size and mangle accordingly
1603   case BuiltinType::LongDouble:
1604     Out << 'O';
1605     break;
1606   case BuiltinType::LongLong:
1607     Out << "_J";
1608     break;
1609   case BuiltinType::ULongLong:
1610     Out << "_K";
1611     break;
1612   case BuiltinType::Int128:
1613     Out << "_L";
1614     break;
1615   case BuiltinType::UInt128:
1616     Out << "_M";
1617     break;
1618   case BuiltinType::Bool:
1619     Out << "_N";
1620     break;
1621   case BuiltinType::Char16:
1622     Out << "_S";
1623     break;
1624   case BuiltinType::Char32:
1625     Out << "_U";
1626     break;
1627   case BuiltinType::WChar_S:
1628   case BuiltinType::WChar_U:
1629     Out << "_W";
1630     break;
1631 
1632 #define BUILTIN_TYPE(Id, SingletonId)
1633 #define PLACEHOLDER_TYPE(Id, SingletonId) \
1634   case BuiltinType::Id:
1635 #include "clang/AST/BuiltinTypes.def"
1636   case BuiltinType::Dependent:
1637     llvm_unreachable("placeholder types shouldn't get to name mangling");
1638 
1639   case BuiltinType::ObjCId:
1640     Out << "PAUobjc_object@@";
1641     break;
1642   case BuiltinType::ObjCClass:
1643     Out << "PAUobjc_class@@";
1644     break;
1645   case BuiltinType::ObjCSel:
1646     Out << "PAUobjc_selector@@";
1647     break;
1648 
1649   case BuiltinType::OCLImage1d:
1650     Out << "PAUocl_image1d@@";
1651     break;
1652   case BuiltinType::OCLImage1dArray:
1653     Out << "PAUocl_image1darray@@";
1654     break;
1655   case BuiltinType::OCLImage1dBuffer:
1656     Out << "PAUocl_image1dbuffer@@";
1657     break;
1658   case BuiltinType::OCLImage2d:
1659     Out << "PAUocl_image2d@@";
1660     break;
1661   case BuiltinType::OCLImage2dArray:
1662     Out << "PAUocl_image2darray@@";
1663     break;
1664   case BuiltinType::OCLImage2dDepth:
1665     Out << "PAUocl_image2ddepth@@";
1666     break;
1667   case BuiltinType::OCLImage2dArrayDepth:
1668     Out << "PAUocl_image2darraydepth@@";
1669     break;
1670   case BuiltinType::OCLImage2dMSAA:
1671     Out << "PAUocl_image2dmsaa@@";
1672     break;
1673   case BuiltinType::OCLImage2dArrayMSAA:
1674     Out << "PAUocl_image2darraymsaa@@";
1675     break;
1676   case BuiltinType::OCLImage2dMSAADepth:
1677     Out << "PAUocl_image2dmsaadepth@@";
1678     break;
1679   case BuiltinType::OCLImage2dArrayMSAADepth:
1680     Out << "PAUocl_image2darraymsaadepth@@";
1681     break;
1682   case BuiltinType::OCLImage3d:
1683     Out << "PAUocl_image3d@@";
1684     break;
1685   case BuiltinType::OCLSampler:
1686     Out << "PAUocl_sampler@@";
1687     break;
1688   case BuiltinType::OCLEvent:
1689     Out << "PAUocl_event@@";
1690     break;
1691   case BuiltinType::OCLClkEvent:
1692     Out << "PAUocl_clkevent@@";
1693     break;
1694   case BuiltinType::OCLQueue:
1695     Out << "PAUocl_queue@@";
1696     break;
1697   case BuiltinType::OCLNDRange:
1698     Out << "PAUocl_ndrange@@";
1699     break;
1700   case BuiltinType::OCLReserveID:
1701     Out << "PAUocl_reserveid@@";
1702     break;
1703 
1704   case BuiltinType::NullPtr:
1705     Out << "$$T";
1706     break;
1707 
1708   case BuiltinType::Half: {
1709     DiagnosticsEngine &Diags = Context.getDiags();
1710     unsigned DiagID = Diags.getCustomDiagID(
1711         DiagnosticsEngine::Error, "cannot mangle this built-in %0 type yet");
1712     Diags.Report(Range.getBegin(), DiagID)
1713         << T->getName(Context.getASTContext().getPrintingPolicy()) << Range;
1714     break;
1715   }
1716   }
1717 }
1718 
1719 // <type>          ::= <function-type>
mangleType(const FunctionProtoType * T,Qualifiers,SourceRange)1720 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers,
1721                                          SourceRange) {
1722   // Structors only appear in decls, so at this point we know it's not a
1723   // structor type.
1724   // FIXME: This may not be lambda-friendly.
1725   if (T->getTypeQuals() || T->getRefQualifier() != RQ_None) {
1726     Out << "$$A8@@";
1727     mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true);
1728   } else {
1729     Out << "$$A6";
1730     mangleFunctionType(T);
1731   }
1732 }
mangleType(const FunctionNoProtoType * T,Qualifiers,SourceRange)1733 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
1734                                          Qualifiers, SourceRange) {
1735   Out << "$$A6";
1736   mangleFunctionType(T);
1737 }
1738 
mangleFunctionType(const FunctionType * T,const FunctionDecl * D,bool ForceThisQuals)1739 void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
1740                                                  const FunctionDecl *D,
1741                                                  bool ForceThisQuals) {
1742   // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
1743   //                     <return-type> <argument-list> <throw-spec>
1744   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(T);
1745 
1746   SourceRange Range;
1747   if (D) Range = D->getSourceRange();
1748 
1749   bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false;
1750   CallingConv CC = T->getCallConv();
1751   if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
1752     if (MD->isInstance())
1753       HasThisQuals = true;
1754     if (isa<CXXDestructorDecl>(MD)) {
1755       IsStructor = true;
1756     } else if (isa<CXXConstructorDecl>(MD)) {
1757       IsStructor = true;
1758       IsCtorClosure = (StructorType == Ctor_CopyingClosure ||
1759                        StructorType == Ctor_DefaultClosure) &&
1760                       getStructor(MD) == Structor;
1761       if (IsCtorClosure)
1762         CC = getASTContext().getDefaultCallingConvention(
1763             /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1764     }
1765   }
1766 
1767   // If this is a C++ instance method, mangle the CVR qualifiers for the
1768   // this pointer.
1769   if (HasThisQuals) {
1770     Qualifiers Quals = Qualifiers::fromCVRMask(Proto->getTypeQuals());
1771     manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType());
1772     mangleRefQualifier(Proto->getRefQualifier());
1773     mangleQualifiers(Quals, /*IsMember=*/false);
1774   }
1775 
1776   mangleCallingConvention(CC);
1777 
1778   // <return-type> ::= <type>
1779   //               ::= @ # structors (they have no declared return type)
1780   if (IsStructor) {
1781     if (isa<CXXDestructorDecl>(D) && D == Structor &&
1782         StructorType == Dtor_Deleting) {
1783       // The scalar deleting destructor takes an extra int argument.
1784       // However, the FunctionType generated has 0 arguments.
1785       // FIXME: This is a temporary hack.
1786       // Maybe should fix the FunctionType creation instead?
1787       Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
1788       return;
1789     }
1790     if (IsCtorClosure) {
1791       // Default constructor closure and copy constructor closure both return
1792       // void.
1793       Out << 'X';
1794 
1795       if (StructorType == Ctor_DefaultClosure) {
1796         // Default constructor closure always has no arguments.
1797         Out << 'X';
1798       } else if (StructorType == Ctor_CopyingClosure) {
1799         // Copy constructor closure always takes an unqualified reference.
1800         mangleArgumentType(getASTContext().getLValueReferenceType(
1801                                Proto->getParamType(0)
1802                                    ->getAs<LValueReferenceType>()
1803                                    ->getPointeeType(),
1804                                /*SpelledAsLValue=*/true),
1805                            Range);
1806         Out << '@';
1807       } else {
1808         llvm_unreachable("unexpected constructor closure!");
1809       }
1810       Out << 'Z';
1811       return;
1812     }
1813     Out << '@';
1814   } else {
1815     QualType ResultType = T->getReturnType();
1816     if (const auto *AT =
1817             dyn_cast_or_null<AutoType>(ResultType->getContainedAutoType())) {
1818       Out << '?';
1819       mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
1820       Out << '?';
1821       assert(AT->getKeyword() != AutoTypeKeyword::GNUAutoType &&
1822              "shouldn't need to mangle __auto_type!");
1823       mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>");
1824       Out << '@';
1825     } else {
1826       if (ResultType->isVoidType())
1827         ResultType = ResultType.getUnqualifiedType();
1828       mangleType(ResultType, Range, QMM_Result);
1829     }
1830   }
1831 
1832   // <argument-list> ::= X # void
1833   //                 ::= <type>+ @
1834   //                 ::= <type>* Z # varargs
1835   if (!Proto) {
1836     // Function types without prototypes can arise when mangling a function type
1837     // within an overloadable function in C. We mangle these as the absence of
1838     // any parameter types (not even an empty parameter list).
1839     Out << '@';
1840   } else if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
1841     Out << 'X';
1842   } else {
1843     // Happens for function pointer type arguments for example.
1844     for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
1845       mangleArgumentType(Proto->getParamType(I), Range);
1846       // Mangle each pass_object_size parameter as if it's a paramater of enum
1847       // type passed directly after the parameter with the pass_object_size
1848       // attribute. The aforementioned enum's name is __pass_object_size, and we
1849       // pretend it resides in a top-level namespace called __clang.
1850       //
1851       // FIXME: Is there a defined extension notation for the MS ABI, or is it
1852       // necessary to just cross our fingers and hope this type+namespace
1853       // combination doesn't conflict with anything?
1854       if (D)
1855         if (auto *P = D->getParamDecl(I)->getAttr<PassObjectSizeAttr>())
1856           Out << "W4__pass_object_size" << P->getType() << "@__clang@@";
1857     }
1858     // <builtin-type>      ::= Z  # ellipsis
1859     if (Proto->isVariadic())
1860       Out << 'Z';
1861     else
1862       Out << '@';
1863   }
1864 
1865   mangleThrowSpecification(Proto);
1866 }
1867 
mangleFunctionClass(const FunctionDecl * FD)1868 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
1869   // <function-class>  ::= <member-function> E? # E designates a 64-bit 'this'
1870   //                                            # pointer. in 64-bit mode *all*
1871   //                                            # 'this' pointers are 64-bit.
1872   //                   ::= <global-function>
1873   // <member-function> ::= A # private: near
1874   //                   ::= B # private: far
1875   //                   ::= C # private: static near
1876   //                   ::= D # private: static far
1877   //                   ::= E # private: virtual near
1878   //                   ::= F # private: virtual far
1879   //                   ::= I # protected: near
1880   //                   ::= J # protected: far
1881   //                   ::= K # protected: static near
1882   //                   ::= L # protected: static far
1883   //                   ::= M # protected: virtual near
1884   //                   ::= N # protected: virtual far
1885   //                   ::= Q # public: near
1886   //                   ::= R # public: far
1887   //                   ::= S # public: static near
1888   //                   ::= T # public: static far
1889   //                   ::= U # public: virtual near
1890   //                   ::= V # public: virtual far
1891   // <global-function> ::= Y # global near
1892   //                   ::= Z # global far
1893   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1894     switch (MD->getAccess()) {
1895       case AS_none:
1896         llvm_unreachable("Unsupported access specifier");
1897       case AS_private:
1898         if (MD->isStatic())
1899           Out << 'C';
1900         else if (MD->isVirtual())
1901           Out << 'E';
1902         else
1903           Out << 'A';
1904         break;
1905       case AS_protected:
1906         if (MD->isStatic())
1907           Out << 'K';
1908         else if (MD->isVirtual())
1909           Out << 'M';
1910         else
1911           Out << 'I';
1912         break;
1913       case AS_public:
1914         if (MD->isStatic())
1915           Out << 'S';
1916         else if (MD->isVirtual())
1917           Out << 'U';
1918         else
1919           Out << 'Q';
1920     }
1921   } else {
1922     Out << 'Y';
1923   }
1924 }
mangleCallingConvention(CallingConv CC)1925 void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) {
1926   // <calling-convention> ::= A # __cdecl
1927   //                      ::= B # __export __cdecl
1928   //                      ::= C # __pascal
1929   //                      ::= D # __export __pascal
1930   //                      ::= E # __thiscall
1931   //                      ::= F # __export __thiscall
1932   //                      ::= G # __stdcall
1933   //                      ::= H # __export __stdcall
1934   //                      ::= I # __fastcall
1935   //                      ::= J # __export __fastcall
1936   //                      ::= Q # __vectorcall
1937   // The 'export' calling conventions are from a bygone era
1938   // (*cough*Win16*cough*) when functions were declared for export with
1939   // that keyword. (It didn't actually export them, it just made them so
1940   // that they could be in a DLL and somebody from another module could call
1941   // them.)
1942 
1943   switch (CC) {
1944     default:
1945       llvm_unreachable("Unsupported CC for mangling");
1946     case CC_X86_64Win64:
1947     case CC_X86_64SysV:
1948     case CC_C: Out << 'A'; break;
1949     case CC_X86Pascal: Out << 'C'; break;
1950     case CC_X86ThisCall: Out << 'E'; break;
1951     case CC_X86StdCall: Out << 'G'; break;
1952     case CC_X86FastCall: Out << 'I'; break;
1953     case CC_X86VectorCall: Out << 'Q'; break;
1954   }
1955 }
mangleCallingConvention(const FunctionType * T)1956 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
1957   mangleCallingConvention(T->getCallConv());
1958 }
mangleThrowSpecification(const FunctionProtoType * FT)1959 void MicrosoftCXXNameMangler::mangleThrowSpecification(
1960                                                 const FunctionProtoType *FT) {
1961   // <throw-spec> ::= Z # throw(...) (default)
1962   //              ::= @ # throw() or __declspec/__attribute__((nothrow))
1963   //              ::= <type>+
1964   // NOTE: Since the Microsoft compiler ignores throw specifications, they are
1965   // all actually mangled as 'Z'. (They're ignored because their associated
1966   // functionality isn't implemented, and probably never will be.)
1967   Out << 'Z';
1968 }
1969 
mangleType(const UnresolvedUsingType * T,Qualifiers,SourceRange Range)1970 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
1971                                          Qualifiers, SourceRange Range) {
1972   // Probably should be mangled as a template instantiation; need to see what
1973   // VC does first.
1974   DiagnosticsEngine &Diags = Context.getDiags();
1975   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1976     "cannot mangle this unresolved dependent type yet");
1977   Diags.Report(Range.getBegin(), DiagID)
1978     << Range;
1979 }
1980 
1981 // <type>        ::= <union-type> | <struct-type> | <class-type> | <enum-type>
1982 // <union-type>  ::= T <name>
1983 // <struct-type> ::= U <name>
1984 // <class-type>  ::= V <name>
1985 // <enum-type>   ::= W4 <name>
mangleType(const EnumType * T,Qualifiers,SourceRange)1986 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, Qualifiers,
1987                                          SourceRange) {
1988   mangleType(cast<TagType>(T)->getDecl());
1989 }
mangleType(const RecordType * T,Qualifiers,SourceRange)1990 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, Qualifiers,
1991                                          SourceRange) {
1992   mangleType(cast<TagType>(T)->getDecl());
1993 }
mangleType(const TagDecl * TD)1994 void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
1995   switch (TD->getTagKind()) {
1996     case TTK_Union:
1997       Out << 'T';
1998       break;
1999     case TTK_Struct:
2000     case TTK_Interface:
2001       Out << 'U';
2002       break;
2003     case TTK_Class:
2004       Out << 'V';
2005       break;
2006     case TTK_Enum:
2007       Out << "W4";
2008       break;
2009   }
2010   mangleName(TD);
2011 }
2012 
2013 // <type>       ::= <array-type>
2014 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2015 //                  [Y <dimension-count> <dimension>+]
2016 //                  <element-type> # as global, E is never required
2017 // It's supposed to be the other way around, but for some strange reason, it
2018 // isn't. Today this behavior is retained for the sole purpose of backwards
2019 // compatibility.
mangleDecayedArrayType(const ArrayType * T)2020 void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
2021   // This isn't a recursive mangling, so now we have to do it all in this
2022   // one call.
2023   manglePointerCVQualifiers(T->getElementType().getQualifiers());
2024   mangleType(T->getElementType(), SourceRange());
2025 }
mangleType(const ConstantArrayType * T,Qualifiers,SourceRange)2026 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T, Qualifiers,
2027                                          SourceRange) {
2028   llvm_unreachable("Should have been special cased");
2029 }
mangleType(const VariableArrayType * T,Qualifiers,SourceRange)2030 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T, Qualifiers,
2031                                          SourceRange) {
2032   llvm_unreachable("Should have been special cased");
2033 }
mangleType(const DependentSizedArrayType * T,Qualifiers,SourceRange)2034 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
2035                                          Qualifiers, SourceRange) {
2036   llvm_unreachable("Should have been special cased");
2037 }
mangleType(const IncompleteArrayType * T,Qualifiers,SourceRange)2038 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
2039                                          Qualifiers, SourceRange) {
2040   llvm_unreachable("Should have been special cased");
2041 }
mangleArrayType(const ArrayType * T)2042 void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
2043   QualType ElementTy(T, 0);
2044   SmallVector<llvm::APInt, 3> Dimensions;
2045   for (;;) {
2046     if (ElementTy->isConstantArrayType()) {
2047       const ConstantArrayType *CAT =
2048           getASTContext().getAsConstantArrayType(ElementTy);
2049       Dimensions.push_back(CAT->getSize());
2050       ElementTy = CAT->getElementType();
2051     } else if (ElementTy->isIncompleteArrayType()) {
2052       const IncompleteArrayType *IAT =
2053           getASTContext().getAsIncompleteArrayType(ElementTy);
2054       Dimensions.push_back(llvm::APInt(32, 0));
2055       ElementTy = IAT->getElementType();
2056     } else if (ElementTy->isVariableArrayType()) {
2057       const VariableArrayType *VAT =
2058         getASTContext().getAsVariableArrayType(ElementTy);
2059       Dimensions.push_back(llvm::APInt(32, 0));
2060       ElementTy = VAT->getElementType();
2061     } else if (ElementTy->isDependentSizedArrayType()) {
2062       // The dependent expression has to be folded into a constant (TODO).
2063       const DependentSizedArrayType *DSAT =
2064         getASTContext().getAsDependentSizedArrayType(ElementTy);
2065       DiagnosticsEngine &Diags = Context.getDiags();
2066       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2067         "cannot mangle this dependent-length array yet");
2068       Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
2069         << DSAT->getBracketsRange();
2070       return;
2071     } else {
2072       break;
2073     }
2074   }
2075   Out << 'Y';
2076   // <dimension-count> ::= <number> # number of extra dimensions
2077   mangleNumber(Dimensions.size());
2078   for (const llvm::APInt &Dimension : Dimensions)
2079     mangleNumber(Dimension.getLimitedValue());
2080   mangleType(ElementTy, SourceRange(), QMM_Escape);
2081 }
2082 
2083 // <type>                   ::= <pointer-to-member-type>
2084 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2085 //                                                          <class name> <type>
mangleType(const MemberPointerType * T,Qualifiers Quals,SourceRange Range)2086 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T, Qualifiers Quals,
2087                                          SourceRange Range) {
2088   QualType PointeeType = T->getPointeeType();
2089   manglePointerCVQualifiers(Quals);
2090   manglePointerExtQualifiers(Quals, PointeeType);
2091   if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
2092     Out << '8';
2093     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2094     mangleFunctionType(FPT, nullptr, true);
2095   } else {
2096     mangleQualifiers(PointeeType.getQualifiers(), true);
2097     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2098     mangleType(PointeeType, Range, QMM_Drop);
2099   }
2100 }
2101 
mangleType(const TemplateTypeParmType * T,Qualifiers,SourceRange Range)2102 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
2103                                          Qualifiers, SourceRange Range) {
2104   DiagnosticsEngine &Diags = Context.getDiags();
2105   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2106     "cannot mangle this template type parameter type yet");
2107   Diags.Report(Range.getBegin(), DiagID)
2108     << Range;
2109 }
2110 
mangleType(const SubstTemplateTypeParmPackType * T,Qualifiers,SourceRange Range)2111 void MicrosoftCXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T,
2112                                          Qualifiers, SourceRange Range) {
2113   DiagnosticsEngine &Diags = Context.getDiags();
2114   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2115     "cannot mangle this substituted parameter pack yet");
2116   Diags.Report(Range.getBegin(), DiagID)
2117     << Range;
2118 }
2119 
2120 // <type> ::= <pointer-type>
2121 // <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
2122 //                       # the E is required for 64-bit non-static pointers
mangleType(const PointerType * T,Qualifiers Quals,SourceRange Range)2123 void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals,
2124                                          SourceRange Range) {
2125   QualType PointeeType = T->getPointeeType();
2126   manglePointerCVQualifiers(Quals);
2127   manglePointerExtQualifiers(Quals, PointeeType);
2128   mangleType(PointeeType, Range);
2129 }
mangleType(const ObjCObjectPointerType * T,Qualifiers Quals,SourceRange Range)2130 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
2131                                          Qualifiers Quals, SourceRange Range) {
2132   QualType PointeeType = T->getPointeeType();
2133   manglePointerCVQualifiers(Quals);
2134   manglePointerExtQualifiers(Quals, PointeeType);
2135   // Object pointers never have qualifiers.
2136   Out << 'A';
2137   mangleType(PointeeType, Range);
2138 }
2139 
2140 // <type> ::= <reference-type>
2141 // <reference-type> ::= A E? <cvr-qualifiers> <type>
2142 //                 # the E is required for 64-bit non-static lvalue references
mangleType(const LValueReferenceType * T,Qualifiers Quals,SourceRange Range)2143 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
2144                                          Qualifiers Quals, SourceRange Range) {
2145   QualType PointeeType = T->getPointeeType();
2146   Out << (Quals.hasVolatile() ? 'B' : 'A');
2147   manglePointerExtQualifiers(Quals, PointeeType);
2148   mangleType(PointeeType, Range);
2149 }
2150 
2151 // <type> ::= <r-value-reference-type>
2152 // <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
2153 //                 # the E is required for 64-bit non-static rvalue references
mangleType(const RValueReferenceType * T,Qualifiers Quals,SourceRange Range)2154 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
2155                                          Qualifiers Quals, SourceRange Range) {
2156   QualType PointeeType = T->getPointeeType();
2157   Out << (Quals.hasVolatile() ? "$$R" : "$$Q");
2158   manglePointerExtQualifiers(Quals, PointeeType);
2159   mangleType(PointeeType, Range);
2160 }
2161 
mangleType(const ComplexType * T,Qualifiers,SourceRange Range)2162 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T, Qualifiers,
2163                                          SourceRange Range) {
2164   DiagnosticsEngine &Diags = Context.getDiags();
2165   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2166     "cannot mangle this complex number type yet");
2167   Diags.Report(Range.getBegin(), DiagID)
2168     << Range;
2169 }
2170 
mangleType(const VectorType * T,Qualifiers Quals,SourceRange Range)2171 void MicrosoftCXXNameMangler::mangleType(const VectorType *T, Qualifiers Quals,
2172                                          SourceRange Range) {
2173   const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>();
2174   assert(ET && "vectors with non-builtin elements are unsupported");
2175   uint64_t Width = getASTContext().getTypeSize(T);
2176   // Pattern match exactly the typedefs in our intrinsic headers.  Anything that
2177   // doesn't match the Intel types uses a custom mangling below.
2178   bool IsBuiltin = true;
2179   llvm::Triple::ArchType AT =
2180       getASTContext().getTargetInfo().getTriple().getArch();
2181   if (AT == llvm::Triple::x86 || AT == llvm::Triple::x86_64) {
2182     if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
2183       Out << "T__m64";
2184     } else if (Width >= 128) {
2185       if (ET->getKind() == BuiltinType::Float)
2186         Out << "T__m" << Width;
2187       else if (ET->getKind() == BuiltinType::LongLong)
2188         Out << "T__m" << Width << 'i';
2189       else if (ET->getKind() == BuiltinType::Double)
2190         Out << "U__m" << Width << 'd';
2191       else
2192         IsBuiltin = false;
2193     } else {
2194       IsBuiltin = false;
2195     }
2196   } else {
2197     IsBuiltin = false;
2198   }
2199 
2200   if (!IsBuiltin) {
2201     // The MS ABI doesn't have a special mangling for vector types, so we define
2202     // our own mangling to handle uses of __vector_size__ on user-specified
2203     // types, and for extensions like __v4sf.
2204     Out << "T__clang_vec" << T->getNumElements() << '_';
2205     mangleType(ET, Quals, Range);
2206   }
2207 
2208   Out << "@@";
2209 }
2210 
mangleType(const ExtVectorType * T,Qualifiers Quals,SourceRange Range)2211 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
2212                                          Qualifiers Quals, SourceRange Range) {
2213   mangleType(static_cast<const VectorType *>(T), Quals, Range);
2214 }
mangleType(const DependentSizedExtVectorType * T,Qualifiers,SourceRange Range)2215 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
2216                                          Qualifiers, SourceRange Range) {
2217   DiagnosticsEngine &Diags = Context.getDiags();
2218   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2219     "cannot mangle this dependent-sized extended vector type yet");
2220   Diags.Report(Range.getBegin(), DiagID)
2221     << Range;
2222 }
2223 
mangleType(const ObjCInterfaceType * T,Qualifiers,SourceRange)2224 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T, Qualifiers,
2225                                          SourceRange) {
2226   // ObjC interfaces have structs underlying them.
2227   Out << 'U';
2228   mangleName(T->getDecl());
2229 }
2230 
mangleType(const ObjCObjectType * T,Qualifiers,SourceRange Range)2231 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T, Qualifiers,
2232                                          SourceRange Range) {
2233   // We don't allow overloading by different protocol qualification,
2234   // so mangling them isn't necessary.
2235   mangleType(T->getBaseType(), Range);
2236 }
2237 
mangleType(const BlockPointerType * T,Qualifiers Quals,SourceRange Range)2238 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
2239                                          Qualifiers Quals, SourceRange Range) {
2240   QualType PointeeType = T->getPointeeType();
2241   manglePointerCVQualifiers(Quals);
2242   manglePointerExtQualifiers(Quals, PointeeType);
2243 
2244   Out << "_E";
2245 
2246   mangleFunctionType(PointeeType->castAs<FunctionProtoType>());
2247 }
2248 
mangleType(const InjectedClassNameType *,Qualifiers,SourceRange)2249 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
2250                                          Qualifiers, SourceRange) {
2251   llvm_unreachable("Cannot mangle injected class name type.");
2252 }
2253 
mangleType(const TemplateSpecializationType * T,Qualifiers,SourceRange Range)2254 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
2255                                          Qualifiers, SourceRange Range) {
2256   DiagnosticsEngine &Diags = Context.getDiags();
2257   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2258     "cannot mangle this template specialization type yet");
2259   Diags.Report(Range.getBegin(), DiagID)
2260     << Range;
2261 }
2262 
mangleType(const DependentNameType * T,Qualifiers,SourceRange Range)2263 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T, Qualifiers,
2264                                          SourceRange Range) {
2265   DiagnosticsEngine &Diags = Context.getDiags();
2266   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2267     "cannot mangle this dependent name type yet");
2268   Diags.Report(Range.getBegin(), DiagID)
2269     << Range;
2270 }
2271 
mangleType(const DependentTemplateSpecializationType * T,Qualifiers,SourceRange Range)2272 void MicrosoftCXXNameMangler::mangleType(
2273     const DependentTemplateSpecializationType *T, Qualifiers,
2274     SourceRange Range) {
2275   DiagnosticsEngine &Diags = Context.getDiags();
2276   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2277     "cannot mangle this dependent template specialization type yet");
2278   Diags.Report(Range.getBegin(), DiagID)
2279     << Range;
2280 }
2281 
mangleType(const PackExpansionType * T,Qualifiers,SourceRange Range)2282 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T, Qualifiers,
2283                                          SourceRange Range) {
2284   DiagnosticsEngine &Diags = Context.getDiags();
2285   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2286     "cannot mangle this pack expansion yet");
2287   Diags.Report(Range.getBegin(), DiagID)
2288     << Range;
2289 }
2290 
mangleType(const TypeOfType * T,Qualifiers,SourceRange Range)2291 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T, Qualifiers,
2292                                          SourceRange Range) {
2293   DiagnosticsEngine &Diags = Context.getDiags();
2294   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2295     "cannot mangle this typeof(type) yet");
2296   Diags.Report(Range.getBegin(), DiagID)
2297     << Range;
2298 }
2299 
mangleType(const TypeOfExprType * T,Qualifiers,SourceRange Range)2300 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T, Qualifiers,
2301                                          SourceRange Range) {
2302   DiagnosticsEngine &Diags = Context.getDiags();
2303   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2304     "cannot mangle this typeof(expression) yet");
2305   Diags.Report(Range.getBegin(), DiagID)
2306     << Range;
2307 }
2308 
mangleType(const DecltypeType * T,Qualifiers,SourceRange Range)2309 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T, Qualifiers,
2310                                          SourceRange Range) {
2311   DiagnosticsEngine &Diags = Context.getDiags();
2312   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2313     "cannot mangle this decltype() yet");
2314   Diags.Report(Range.getBegin(), DiagID)
2315     << Range;
2316 }
2317 
mangleType(const UnaryTransformType * T,Qualifiers,SourceRange Range)2318 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
2319                                          Qualifiers, SourceRange Range) {
2320   DiagnosticsEngine &Diags = Context.getDiags();
2321   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2322     "cannot mangle this unary transform type yet");
2323   Diags.Report(Range.getBegin(), DiagID)
2324     << Range;
2325 }
2326 
mangleType(const AutoType * T,Qualifiers,SourceRange Range)2327 void MicrosoftCXXNameMangler::mangleType(const AutoType *T, Qualifiers,
2328                                          SourceRange Range) {
2329   assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2330 
2331   DiagnosticsEngine &Diags = Context.getDiags();
2332   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2333     "cannot mangle this 'auto' type yet");
2334   Diags.Report(Range.getBegin(), DiagID)
2335     << Range;
2336 }
2337 
mangleType(const AtomicType * T,Qualifiers,SourceRange Range)2338 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T, Qualifiers,
2339                                          SourceRange Range) {
2340   DiagnosticsEngine &Diags = Context.getDiags();
2341   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2342     "cannot mangle this C11 atomic type yet");
2343   Diags.Report(Range.getBegin(), DiagID)
2344     << Range;
2345 }
2346 
mangleCXXName(const NamedDecl * D,raw_ostream & Out)2347 void MicrosoftMangleContextImpl::mangleCXXName(const NamedDecl *D,
2348                                                raw_ostream &Out) {
2349   assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
2350          "Invalid mangleName() call, argument is not a variable or function!");
2351   assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
2352          "Invalid mangleName() call on 'structor decl!");
2353 
2354   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
2355                                  getASTContext().getSourceManager(),
2356                                  "Mangling declaration");
2357 
2358   MicrosoftCXXNameMangler Mangler(*this, Out);
2359   return Mangler.mangle(D);
2360 }
2361 
2362 // <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
2363 //                       <virtual-adjustment>
2364 // <no-adjustment>      ::= A # private near
2365 //                      ::= B # private far
2366 //                      ::= I # protected near
2367 //                      ::= J # protected far
2368 //                      ::= Q # public near
2369 //                      ::= R # public far
2370 // <static-adjustment>  ::= G <static-offset> # private near
2371 //                      ::= H <static-offset> # private far
2372 //                      ::= O <static-offset> # protected near
2373 //                      ::= P <static-offset> # protected far
2374 //                      ::= W <static-offset> # public near
2375 //                      ::= X <static-offset> # public far
2376 // <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
2377 //                      ::= $1 <virtual-shift> <static-offset> # private far
2378 //                      ::= $2 <virtual-shift> <static-offset> # protected near
2379 //                      ::= $3 <virtual-shift> <static-offset> # protected far
2380 //                      ::= $4 <virtual-shift> <static-offset> # public near
2381 //                      ::= $5 <virtual-shift> <static-offset> # public far
2382 // <virtual-shift>      ::= <vtordisp-shift> | <vtordispex-shift>
2383 // <vtordisp-shift>     ::= <offset-to-vtordisp>
2384 // <vtordispex-shift>   ::= <offset-to-vbptr> <vbase-offset-offset>
2385 //                          <offset-to-vtordisp>
mangleThunkThisAdjustment(const CXXMethodDecl * MD,const ThisAdjustment & Adjustment,MicrosoftCXXNameMangler & Mangler,raw_ostream & Out)2386 static void mangleThunkThisAdjustment(const CXXMethodDecl *MD,
2387                                       const ThisAdjustment &Adjustment,
2388                                       MicrosoftCXXNameMangler &Mangler,
2389                                       raw_ostream &Out) {
2390   if (!Adjustment.Virtual.isEmpty()) {
2391     Out << '$';
2392     char AccessSpec;
2393     switch (MD->getAccess()) {
2394     case AS_none:
2395       llvm_unreachable("Unsupported access specifier");
2396     case AS_private:
2397       AccessSpec = '0';
2398       break;
2399     case AS_protected:
2400       AccessSpec = '2';
2401       break;
2402     case AS_public:
2403       AccessSpec = '4';
2404     }
2405     if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
2406       Out << 'R' << AccessSpec;
2407       Mangler.mangleNumber(
2408           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
2409       Mangler.mangleNumber(
2410           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
2411       Mangler.mangleNumber(
2412           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2413       Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
2414     } else {
2415       Out << AccessSpec;
2416       Mangler.mangleNumber(
2417           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2418       Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2419     }
2420   } else if (Adjustment.NonVirtual != 0) {
2421     switch (MD->getAccess()) {
2422     case AS_none:
2423       llvm_unreachable("Unsupported access specifier");
2424     case AS_private:
2425       Out << 'G';
2426       break;
2427     case AS_protected:
2428       Out << 'O';
2429       break;
2430     case AS_public:
2431       Out << 'W';
2432     }
2433     Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2434   } else {
2435     switch (MD->getAccess()) {
2436     case AS_none:
2437       llvm_unreachable("Unsupported access specifier");
2438     case AS_private:
2439       Out << 'A';
2440       break;
2441     case AS_protected:
2442       Out << 'I';
2443       break;
2444     case AS_public:
2445       Out << 'Q';
2446     }
2447   }
2448 }
2449 
2450 void
mangleVirtualMemPtrThunk(const CXXMethodDecl * MD,raw_ostream & Out)2451 MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
2452                                                      raw_ostream &Out) {
2453   MicrosoftVTableContext *VTContext =
2454       cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
2455   const MicrosoftVTableContext::MethodVFTableLocation &ML =
2456       VTContext->getMethodVFTableLocation(GlobalDecl(MD));
2457 
2458   MicrosoftCXXNameMangler Mangler(*this, Out);
2459   Mangler.getStream() << "\01?";
2460   Mangler.mangleVirtualMemPtrThunk(MD, ML);
2461 }
2462 
mangleThunk(const CXXMethodDecl * MD,const ThunkInfo & Thunk,raw_ostream & Out)2463 void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
2464                                              const ThunkInfo &Thunk,
2465                                              raw_ostream &Out) {
2466   MicrosoftCXXNameMangler Mangler(*this, Out);
2467   Out << "\01?";
2468   Mangler.mangleName(MD);
2469   mangleThunkThisAdjustment(MD, Thunk.This, Mangler, Out);
2470   if (!Thunk.Return.isEmpty())
2471     assert(Thunk.Method != nullptr &&
2472            "Thunk info should hold the overridee decl");
2473 
2474   const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
2475   Mangler.mangleFunctionType(
2476       DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
2477 }
2478 
mangleCXXDtorThunk(const CXXDestructorDecl * DD,CXXDtorType Type,const ThisAdjustment & Adjustment,raw_ostream & Out)2479 void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
2480     const CXXDestructorDecl *DD, CXXDtorType Type,
2481     const ThisAdjustment &Adjustment, raw_ostream &Out) {
2482   // FIXME: Actually, the dtor thunk should be emitted for vector deleting
2483   // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
2484   // mangling manually until we support both deleting dtor types.
2485   assert(Type == Dtor_Deleting);
2486   MicrosoftCXXNameMangler Mangler(*this, Out, DD, Type);
2487   Out << "\01??_E";
2488   Mangler.mangleName(DD->getParent());
2489   mangleThunkThisAdjustment(DD, Adjustment, Mangler, Out);
2490   Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
2491 }
2492 
mangleCXXVFTable(const CXXRecordDecl * Derived,ArrayRef<const CXXRecordDecl * > BasePath,raw_ostream & Out)2493 void MicrosoftMangleContextImpl::mangleCXXVFTable(
2494     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2495     raw_ostream &Out) {
2496   // <mangled-name> ::= ?_7 <class-name> <storage-class>
2497   //                    <cvr-qualifiers> [<name>] @
2498   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2499   // is always '6' for vftables.
2500   MicrosoftCXXNameMangler Mangler(*this, Out);
2501   Mangler.getStream() << "\01??_7";
2502   Mangler.mangleName(Derived);
2503   Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
2504   for (const CXXRecordDecl *RD : BasePath)
2505     Mangler.mangleName(RD);
2506   Mangler.getStream() << '@';
2507 }
2508 
mangleCXXVBTable(const CXXRecordDecl * Derived,ArrayRef<const CXXRecordDecl * > BasePath,raw_ostream & Out)2509 void MicrosoftMangleContextImpl::mangleCXXVBTable(
2510     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2511     raw_ostream &Out) {
2512   // <mangled-name> ::= ?_8 <class-name> <storage-class>
2513   //                    <cvr-qualifiers> [<name>] @
2514   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2515   // is always '7' for vbtables.
2516   MicrosoftCXXNameMangler Mangler(*this, Out);
2517   Mangler.getStream() << "\01??_8";
2518   Mangler.mangleName(Derived);
2519   Mangler.getStream() << "7B";  // '7' for vbtable, 'B' for const.
2520   for (const CXXRecordDecl *RD : BasePath)
2521     Mangler.mangleName(RD);
2522   Mangler.getStream() << '@';
2523 }
2524 
mangleCXXRTTI(QualType T,raw_ostream & Out)2525 void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) {
2526   MicrosoftCXXNameMangler Mangler(*this, Out);
2527   Mangler.getStream() << "\01??_R0";
2528   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2529   Mangler.getStream() << "@8";
2530 }
2531 
mangleCXXRTTIName(QualType T,raw_ostream & Out)2532 void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T,
2533                                                    raw_ostream &Out) {
2534   MicrosoftCXXNameMangler Mangler(*this, Out);
2535   Mangler.getStream() << '.';
2536   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2537 }
2538 
mangleCXXCatchHandlerType(QualType T,uint32_t Flags,raw_ostream & Out)2539 void MicrosoftMangleContextImpl::mangleCXXCatchHandlerType(QualType T,
2540                                                            uint32_t Flags,
2541                                                            raw_ostream &Out) {
2542   MicrosoftCXXNameMangler Mangler(*this, Out);
2543   Mangler.getStream() << "llvm.eh.handlertype.";
2544   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2545   Mangler.getStream() << '.' << Flags;
2546 }
2547 
mangleCXXVirtualDisplacementMap(const CXXRecordDecl * SrcRD,const CXXRecordDecl * DstRD,raw_ostream & Out)2548 void MicrosoftMangleContextImpl::mangleCXXVirtualDisplacementMap(
2549     const CXXRecordDecl *SrcRD, const CXXRecordDecl *DstRD, raw_ostream &Out) {
2550   MicrosoftCXXNameMangler Mangler(*this, Out);
2551   Mangler.getStream() << "\01??_K";
2552   Mangler.mangleName(SrcRD);
2553   Mangler.getStream() << "$C";
2554   Mangler.mangleName(DstRD);
2555 }
2556 
mangleCXXThrowInfo(QualType T,bool IsConst,bool IsVolatile,uint32_t NumEntries,raw_ostream & Out)2557 void MicrosoftMangleContextImpl::mangleCXXThrowInfo(QualType T,
2558                                                     bool IsConst,
2559                                                     bool IsVolatile,
2560                                                     uint32_t NumEntries,
2561                                                     raw_ostream &Out) {
2562   MicrosoftCXXNameMangler Mangler(*this, Out);
2563   Mangler.getStream() << "_TI";
2564   if (IsConst)
2565     Mangler.getStream() << 'C';
2566   if (IsVolatile)
2567     Mangler.getStream() << 'V';
2568   Mangler.getStream() << NumEntries;
2569   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2570 }
2571 
mangleCXXCatchableTypeArray(QualType T,uint32_t NumEntries,raw_ostream & Out)2572 void MicrosoftMangleContextImpl::mangleCXXCatchableTypeArray(
2573     QualType T, uint32_t NumEntries, raw_ostream &Out) {
2574   MicrosoftCXXNameMangler Mangler(*this, Out);
2575   Mangler.getStream() << "_CTA";
2576   Mangler.getStream() << NumEntries;
2577   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2578 }
2579 
mangleCXXCatchableType(QualType T,const CXXConstructorDecl * CD,CXXCtorType CT,uint32_t Size,uint32_t NVOffset,int32_t VBPtrOffset,uint32_t VBIndex,raw_ostream & Out)2580 void MicrosoftMangleContextImpl::mangleCXXCatchableType(
2581     QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size,
2582     uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex,
2583     raw_ostream &Out) {
2584   MicrosoftCXXNameMangler Mangler(*this, Out);
2585   Mangler.getStream() << "_CT";
2586 
2587   llvm::SmallString<64> RTTIMangling;
2588   {
2589     llvm::raw_svector_ostream Stream(RTTIMangling);
2590     mangleCXXRTTI(T, Stream);
2591   }
2592   Mangler.getStream() << RTTIMangling.substr(1);
2593 
2594   // VS2015 CTP6 omits the copy-constructor in the mangled name.  This name is,
2595   // in fact, superfluous but I'm not sure the change was made consciously.
2596   // TODO: Revisit this when VS2015 gets released.
2597   llvm::SmallString<64> CopyCtorMangling;
2598   if (CD) {
2599     llvm::raw_svector_ostream Stream(CopyCtorMangling);
2600     mangleCXXCtor(CD, CT, Stream);
2601   }
2602   Mangler.getStream() << CopyCtorMangling.substr(1);
2603 
2604   Mangler.getStream() << Size;
2605   if (VBPtrOffset == -1) {
2606     if (NVOffset) {
2607       Mangler.getStream() << NVOffset;
2608     }
2609   } else {
2610     Mangler.getStream() << NVOffset;
2611     Mangler.getStream() << VBPtrOffset;
2612     Mangler.getStream() << VBIndex;
2613   }
2614 }
2615 
mangleCXXRTTIBaseClassDescriptor(const CXXRecordDecl * Derived,uint32_t NVOffset,int32_t VBPtrOffset,uint32_t VBTableOffset,uint32_t Flags,raw_ostream & Out)2616 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor(
2617     const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset,
2618     uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) {
2619   MicrosoftCXXNameMangler Mangler(*this, Out);
2620   Mangler.getStream() << "\01??_R1";
2621   Mangler.mangleNumber(NVOffset);
2622   Mangler.mangleNumber(VBPtrOffset);
2623   Mangler.mangleNumber(VBTableOffset);
2624   Mangler.mangleNumber(Flags);
2625   Mangler.mangleName(Derived);
2626   Mangler.getStream() << "8";
2627 }
2628 
mangleCXXRTTIBaseClassArray(const CXXRecordDecl * Derived,raw_ostream & Out)2629 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray(
2630     const CXXRecordDecl *Derived, raw_ostream &Out) {
2631   MicrosoftCXXNameMangler Mangler(*this, Out);
2632   Mangler.getStream() << "\01??_R2";
2633   Mangler.mangleName(Derived);
2634   Mangler.getStream() << "8";
2635 }
2636 
mangleCXXRTTIClassHierarchyDescriptor(const CXXRecordDecl * Derived,raw_ostream & Out)2637 void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor(
2638     const CXXRecordDecl *Derived, raw_ostream &Out) {
2639   MicrosoftCXXNameMangler Mangler(*this, Out);
2640   Mangler.getStream() << "\01??_R3";
2641   Mangler.mangleName(Derived);
2642   Mangler.getStream() << "8";
2643 }
2644 
mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl * Derived,ArrayRef<const CXXRecordDecl * > BasePath,raw_ostream & Out)2645 void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator(
2646     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2647     raw_ostream &Out) {
2648   // <mangled-name> ::= ?_R4 <class-name> <storage-class>
2649   //                    <cvr-qualifiers> [<name>] @
2650   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2651   // is always '6' for vftables.
2652   MicrosoftCXXNameMangler Mangler(*this, Out);
2653   Mangler.getStream() << "\01??_R4";
2654   Mangler.mangleName(Derived);
2655   Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
2656   for (const CXXRecordDecl *RD : BasePath)
2657     Mangler.mangleName(RD);
2658   Mangler.getStream() << '@';
2659 }
2660 
mangleSEHFilterExpression(const NamedDecl * EnclosingDecl,raw_ostream & Out)2661 void MicrosoftMangleContextImpl::mangleSEHFilterExpression(
2662     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
2663   MicrosoftCXXNameMangler Mangler(*this, Out);
2664   // The function body is in the same comdat as the function with the handler,
2665   // so the numbering here doesn't have to be the same across TUs.
2666   //
2667   // <mangled-name> ::= ?filt$ <filter-number> @0
2668   Mangler.getStream() << "\01?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@";
2669   Mangler.mangleName(EnclosingDecl);
2670 }
2671 
mangleSEHFinallyBlock(const NamedDecl * EnclosingDecl,raw_ostream & Out)2672 void MicrosoftMangleContextImpl::mangleSEHFinallyBlock(
2673     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
2674   MicrosoftCXXNameMangler Mangler(*this, Out);
2675   // The function body is in the same comdat as the function with the handler,
2676   // so the numbering here doesn't have to be the same across TUs.
2677   //
2678   // <mangled-name> ::= ?fin$ <filter-number> @0
2679   Mangler.getStream() << "\01?fin$" << SEHFinallyIds[EnclosingDecl]++ << "@0@";
2680   Mangler.mangleName(EnclosingDecl);
2681 }
2682 
mangleTypeName(QualType T,raw_ostream & Out)2683 void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
2684   // This is just a made up unique string for the purposes of tbaa.  undname
2685   // does *not* know how to demangle it.
2686   MicrosoftCXXNameMangler Mangler(*this, Out);
2687   Mangler.getStream() << '?';
2688   Mangler.mangleType(T, SourceRange());
2689 }
2690 
mangleCXXCtor(const CXXConstructorDecl * D,CXXCtorType Type,raw_ostream & Out)2691 void MicrosoftMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
2692                                                CXXCtorType Type,
2693                                                raw_ostream &Out) {
2694   MicrosoftCXXNameMangler mangler(*this, Out, D, Type);
2695   mangler.mangle(D);
2696 }
2697 
mangleCXXDtor(const CXXDestructorDecl * D,CXXDtorType Type,raw_ostream & Out)2698 void MicrosoftMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
2699                                                CXXDtorType Type,
2700                                                raw_ostream &Out) {
2701   MicrosoftCXXNameMangler mangler(*this, Out, D, Type);
2702   mangler.mangle(D);
2703 }
2704 
mangleReferenceTemporary(const VarDecl * VD,unsigned,raw_ostream &)2705 void MicrosoftMangleContextImpl::mangleReferenceTemporary(const VarDecl *VD,
2706                                                           unsigned,
2707                                                           raw_ostream &) {
2708   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2709     "cannot mangle this reference temporary yet");
2710   getDiags().Report(VD->getLocation(), DiagID);
2711 }
2712 
mangleThreadSafeStaticGuardVariable(const VarDecl * VD,unsigned GuardNum,raw_ostream & Out)2713 void MicrosoftMangleContextImpl::mangleThreadSafeStaticGuardVariable(
2714     const VarDecl *VD, unsigned GuardNum, raw_ostream &Out) {
2715   MicrosoftCXXNameMangler Mangler(*this, Out);
2716 
2717   Mangler.getStream() << "\01?$TSS" << GuardNum << '@';
2718   Mangler.mangleNestedName(VD);
2719 }
2720 
mangleStaticGuardVariable(const VarDecl * VD,raw_ostream & Out)2721 void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
2722                                                            raw_ostream &Out) {
2723   // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
2724   //              ::= ?__J <postfix> @5 <scope-depth>
2725   //              ::= ?$S <guard-num> @ <postfix> @4IA
2726 
2727   // The first mangling is what MSVC uses to guard static locals in inline
2728   // functions.  It uses a different mangling in external functions to support
2729   // guarding more than 32 variables.  MSVC rejects inline functions with more
2730   // than 32 static locals.  We don't fully implement the second mangling
2731   // because those guards are not externally visible, and instead use LLVM's
2732   // default renaming when creating a new guard variable.
2733   MicrosoftCXXNameMangler Mangler(*this, Out);
2734 
2735   bool Visible = VD->isExternallyVisible();
2736   if (Visible) {
2737     Mangler.getStream() << (VD->getTLSKind() ? "\01??__J" : "\01??_B");
2738   } else {
2739     Mangler.getStream() << "\01?$S1@";
2740   }
2741   unsigned ScopeDepth = 0;
2742   if (Visible && !getNextDiscriminator(VD, ScopeDepth))
2743     // If we do not have a discriminator and are emitting a guard variable for
2744     // use at global scope, then mangling the nested name will not be enough to
2745     // remove ambiguities.
2746     Mangler.mangle(VD, "");
2747   else
2748     Mangler.mangleNestedName(VD);
2749   Mangler.getStream() << (Visible ? "@5" : "@4IA");
2750   if (ScopeDepth)
2751     Mangler.mangleNumber(ScopeDepth);
2752 }
2753 
mangleInitFiniStub(const VarDecl * D,raw_ostream & Out,char CharCode)2754 void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
2755                                                     raw_ostream &Out,
2756                                                     char CharCode) {
2757   MicrosoftCXXNameMangler Mangler(*this, Out);
2758   Mangler.getStream() << "\01??__" << CharCode;
2759   Mangler.mangleName(D);
2760   if (D->isStaticDataMember()) {
2761     Mangler.mangleVariableEncoding(D);
2762     Mangler.getStream() << '@';
2763   }
2764   // This is the function class mangling.  These stubs are global, non-variadic,
2765   // cdecl functions that return void and take no args.
2766   Mangler.getStream() << "YAXXZ";
2767 }
2768 
mangleDynamicInitializer(const VarDecl * D,raw_ostream & Out)2769 void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
2770                                                           raw_ostream &Out) {
2771   // <initializer-name> ::= ?__E <name> YAXXZ
2772   mangleInitFiniStub(D, Out, 'E');
2773 }
2774 
2775 void
mangleDynamicAtExitDestructor(const VarDecl * D,raw_ostream & Out)2776 MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
2777                                                           raw_ostream &Out) {
2778   // <destructor-name> ::= ?__F <name> YAXXZ
2779   mangleInitFiniStub(D, Out, 'F');
2780 }
2781 
mangleStringLiteral(const StringLiteral * SL,raw_ostream & Out)2782 void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
2783                                                      raw_ostream &Out) {
2784   // <char-type> ::= 0   # char
2785   //             ::= 1   # wchar_t
2786   //             ::= ??? # char16_t/char32_t will need a mangling too...
2787   //
2788   // <literal-length> ::= <non-negative integer>  # the length of the literal
2789   //
2790   // <encoded-crc>    ::= <hex digit>+ @          # crc of the literal including
2791   //                                              # null-terminator
2792   //
2793   // <encoded-string> ::= <simple character>           # uninteresting character
2794   //                  ::= '?$' <hex digit> <hex digit> # these two nibbles
2795   //                                                   # encode the byte for the
2796   //                                                   # character
2797   //                  ::= '?' [a-z]                    # \xe1 - \xfa
2798   //                  ::= '?' [A-Z]                    # \xc1 - \xda
2799   //                  ::= '?' [0-9]                    # [,/\:. \n\t'-]
2800   //
2801   // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
2802   //               <encoded-string> '@'
2803   MicrosoftCXXNameMangler Mangler(*this, Out);
2804   Mangler.getStream() << "\01??_C@_";
2805 
2806   // <char-type>: The "kind" of string literal is encoded into the mangled name.
2807   if (SL->isWide())
2808     Mangler.getStream() << '1';
2809   else
2810     Mangler.getStream() << '0';
2811 
2812   // <literal-length>: The next part of the mangled name consists of the length
2813   // of the string.
2814   // The StringLiteral does not consider the NUL terminator byte(s) but the
2815   // mangling does.
2816   // N.B. The length is in terms of bytes, not characters.
2817   Mangler.mangleNumber(SL->getByteLength() + SL->getCharByteWidth());
2818 
2819   auto GetLittleEndianByte = [&Mangler, &SL](unsigned Index) {
2820     unsigned CharByteWidth = SL->getCharByteWidth();
2821     uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
2822     unsigned OffsetInCodeUnit = Index % CharByteWidth;
2823     return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
2824   };
2825 
2826   auto GetBigEndianByte = [&Mangler, &SL](unsigned Index) {
2827     unsigned CharByteWidth = SL->getCharByteWidth();
2828     uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
2829     unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
2830     return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
2831   };
2832 
2833   // CRC all the bytes of the StringLiteral.
2834   llvm::JamCRC JC;
2835   for (unsigned I = 0, E = SL->getByteLength(); I != E; ++I)
2836     JC.update(GetLittleEndianByte(I));
2837 
2838   // The NUL terminator byte(s) were not present earlier,
2839   // we need to manually process those bytes into the CRC.
2840   for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
2841        ++NullTerminator)
2842     JC.update('\x00');
2843 
2844   // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
2845   // scheme.
2846   Mangler.mangleNumber(JC.getCRC());
2847 
2848   // <encoded-string>: The mangled name also contains the first 32 _characters_
2849   // (including null-terminator bytes) of the StringLiteral.
2850   // Each character is encoded by splitting them into bytes and then encoding
2851   // the constituent bytes.
2852   auto MangleByte = [&Mangler](char Byte) {
2853     // There are five different manglings for characters:
2854     // - [a-zA-Z0-9_$]: A one-to-one mapping.
2855     // - ?[a-z]: The range from \xe1 to \xfa.
2856     // - ?[A-Z]: The range from \xc1 to \xda.
2857     // - ?[0-9]: The set of [,/\:. \n\t'-].
2858     // - ?$XX: A fallback which maps nibbles.
2859     if (isIdentifierBody(Byte, /*AllowDollar=*/true)) {
2860       Mangler.getStream() << Byte;
2861     } else if (isLetter(Byte & 0x7f)) {
2862       Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
2863     } else {
2864       const char SpecialChars[] = {',', '/',  '\\', ':',  '.',
2865                                    ' ', '\n', '\t', '\'', '-'};
2866       const char *Pos =
2867           std::find(std::begin(SpecialChars), std::end(SpecialChars), Byte);
2868       if (Pos != std::end(SpecialChars)) {
2869         Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars));
2870       } else {
2871         Mangler.getStream() << "?$";
2872         Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
2873         Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
2874       }
2875     }
2876   };
2877 
2878   // Enforce our 32 character max.
2879   unsigned NumCharsToMangle = std::min(32U, SL->getLength());
2880   for (unsigned I = 0, E = NumCharsToMangle * SL->getCharByteWidth(); I != E;
2881        ++I)
2882     if (SL->isWide())
2883       MangleByte(GetBigEndianByte(I));
2884     else
2885       MangleByte(GetLittleEndianByte(I));
2886 
2887   // Encode the NUL terminator if there is room.
2888   if (NumCharsToMangle < 32)
2889     for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
2890          ++NullTerminator)
2891       MangleByte(0);
2892 
2893   Mangler.getStream() << '@';
2894 }
2895 
2896 MicrosoftMangleContext *
create(ASTContext & Context,DiagnosticsEngine & Diags)2897 MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
2898   return new MicrosoftMangleContextImpl(Context, Diags);
2899 }
2900