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