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