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