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