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