1 //===--- Mangle.cpp - Mangle C++ Names --------------------------*- C++ -*-===// 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 // Implements generic name mangling support for blocks and Objective-C. 10 // 11 //===----------------------------------------------------------------------===// 12 #include "clang/AST/Attr.h" 13 #include "clang/AST/ASTContext.h" 14 #include "clang/AST/Decl.h" 15 #include "clang/AST/DeclCXX.h" 16 #include "clang/AST/DeclObjC.h" 17 #include "clang/AST/DeclTemplate.h" 18 #include "clang/AST/ExprCXX.h" 19 #include "clang/AST/Mangle.h" 20 #include "clang/AST/VTableBuilder.h" 21 #include "clang/Basic/ABI.h" 22 #include "clang/Basic/SourceManager.h" 23 #include "clang/Basic/TargetInfo.h" 24 #include "llvm/ADT/StringExtras.h" 25 #include "llvm/IR/DataLayout.h" 26 #include "llvm/IR/Mangler.h" 27 #include "llvm/Support/ErrorHandling.h" 28 #include "llvm/Support/Format.h" 29 #include "llvm/Support/raw_ostream.h" 30 31 using namespace clang; 32 33 // FIXME: For blocks we currently mimic GCC's mangling scheme, which leaves 34 // much to be desired. Come up with a better mangling scheme. 35 36 static void mangleFunctionBlock(MangleContext &Context, 37 StringRef Outer, 38 const BlockDecl *BD, 39 raw_ostream &Out) { 40 unsigned discriminator = Context.getBlockId(BD, true); 41 if (discriminator == 0) 42 Out << "__" << Outer << "_block_invoke"; 43 else 44 Out << "__" << Outer << "_block_invoke_" << discriminator+1; 45 } 46 47 void MangleContext::anchor() { } 48 49 enum CCMangling { 50 CCM_Other, 51 CCM_Fast, 52 CCM_RegCall, 53 CCM_Vector, 54 CCM_Std, 55 CCM_WasmMainArgcArgv 56 }; 57 58 static bool isExternC(const NamedDecl *ND) { 59 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) 60 return FD->isExternC(); 61 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) 62 return VD->isExternC(); 63 return false; 64 } 65 66 static CCMangling getCallingConvMangling(const ASTContext &Context, 67 const NamedDecl *ND) { 68 const TargetInfo &TI = Context.getTargetInfo(); 69 const llvm::Triple &Triple = TI.getTriple(); 70 71 // On wasm, the argc/argv form of "main" is renamed so that the startup code 72 // can call it with the correct function signature. 73 // On Emscripten, users may be exporting "main" and expecting to call it 74 // themselves, so we can't mangle it. 75 if (Triple.isWasm() && !Triple.isOSEmscripten()) 76 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) 77 if (FD->isMain() && FD->hasPrototype() && FD->param_size() == 2) 78 return CCM_WasmMainArgcArgv; 79 80 if (!Triple.isOSWindows() || !Triple.isX86()) 81 return CCM_Other; 82 83 if (Context.getLangOpts().CPlusPlus && !isExternC(ND) && 84 TI.getCXXABI() == TargetCXXABI::Microsoft) 85 return CCM_Other; 86 87 const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND); 88 if (!FD) 89 return CCM_Other; 90 QualType T = FD->getType(); 91 92 const FunctionType *FT = T->castAs<FunctionType>(); 93 94 CallingConv CC = FT->getCallConv(); 95 switch (CC) { 96 default: 97 return CCM_Other; 98 case CC_X86FastCall: 99 return CCM_Fast; 100 case CC_X86StdCall: 101 return CCM_Std; 102 case CC_X86VectorCall: 103 return CCM_Vector; 104 } 105 } 106 107 bool MangleContext::shouldMangleDeclName(const NamedDecl *D) { 108 const ASTContext &ASTContext = getASTContext(); 109 110 CCMangling CC = getCallingConvMangling(ASTContext, D); 111 if (CC != CCM_Other) 112 return true; 113 114 // If the declaration has an owning module for linkage purposes that needs to 115 // be mangled, we must mangle its name. 116 if (!D->hasExternalFormalLinkage() && D->getOwningModuleForLinkage()) 117 return true; 118 119 // In C, functions with no attributes never need to be mangled. Fastpath them. 120 if (!getASTContext().getLangOpts().CPlusPlus && !D->hasAttrs()) 121 return false; 122 123 // Any decl can be declared with __asm("foo") on it, and this takes precedence 124 // over all other naming in the .o file. 125 if (D->hasAttr<AsmLabelAttr>()) 126 return true; 127 128 // Declarations that don't have identifier names always need to be mangled. 129 if (isa<MSGuidDecl>(D)) 130 return true; 131 132 return shouldMangleCXXName(D); 133 } 134 135 void MangleContext::mangleName(GlobalDecl GD, raw_ostream &Out) { 136 const NamedDecl *D = cast<NamedDecl>(GD.getDecl()); 137 // Any decl can be declared with __asm("foo") on it, and this takes precedence 138 // over all other naming in the .o file. 139 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) { 140 // If we have an asm name, then we use it as the mangling. 141 142 // If the label isn't literal, or if this is an alias for an LLVM intrinsic, 143 // do not add a "\01" prefix. 144 if (!ALA->getIsLiteralLabel() || ALA->getLabel().startswith("llvm.")) { 145 Out << ALA->getLabel(); 146 return; 147 } 148 149 // Adding the prefix can cause problems when one file has a "foo" and 150 // another has a "\01foo". That is known to happen on ELF with the 151 // tricks normally used for producing aliases (PR9177). Fortunately the 152 // llvm mangler on ELF is a nop, so we can just avoid adding the \01 153 // marker. 154 char GlobalPrefix = 155 getASTContext().getTargetInfo().getDataLayout().getGlobalPrefix(); 156 if (GlobalPrefix) 157 Out << '\01'; // LLVM IR Marker for __asm("foo") 158 159 Out << ALA->getLabel(); 160 return; 161 } 162 163 if (auto *GD = dyn_cast<MSGuidDecl>(D)) 164 return mangleMSGuidDecl(GD, Out); 165 166 const ASTContext &ASTContext = getASTContext(); 167 CCMangling CC = getCallingConvMangling(ASTContext, D); 168 169 if (CC == CCM_WasmMainArgcArgv) { 170 Out << "__main_argc_argv"; 171 return; 172 } 173 174 bool MCXX = shouldMangleCXXName(D); 175 const TargetInfo &TI = Context.getTargetInfo(); 176 if (CC == CCM_Other || (MCXX && TI.getCXXABI() == TargetCXXABI::Microsoft)) { 177 if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) 178 mangleObjCMethodName(OMD, Out); 179 else 180 mangleCXXName(GD, Out); 181 return; 182 } 183 184 Out << '\01'; 185 if (CC == CCM_Std) 186 Out << '_'; 187 else if (CC == CCM_Fast) 188 Out << '@'; 189 else if (CC == CCM_RegCall) 190 Out << "__regcall3__"; 191 192 if (!MCXX) 193 Out << D->getIdentifier()->getName(); 194 else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) 195 mangleObjCMethodName(OMD, Out); 196 else 197 mangleCXXName(GD, Out); 198 199 const FunctionDecl *FD = cast<FunctionDecl>(D); 200 const FunctionType *FT = FD->getType()->castAs<FunctionType>(); 201 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT); 202 if (CC == CCM_Vector) 203 Out << '@'; 204 Out << '@'; 205 if (!Proto) { 206 Out << '0'; 207 return; 208 } 209 assert(!Proto->isVariadic()); 210 unsigned ArgWords = 0; 211 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 212 if (!MD->isStatic()) 213 ++ArgWords; 214 for (const auto &AT : Proto->param_types()) 215 // Size should be aligned to pointer size. 216 ArgWords += 217 llvm::alignTo(ASTContext.getTypeSize(AT), TI.getPointerWidth(0)) / 218 TI.getPointerWidth(0); 219 Out << ((TI.getPointerWidth(0) / 8) * ArgWords); 220 } 221 222 void MangleContext::mangleMSGuidDecl(const MSGuidDecl *GD, raw_ostream &Out) { 223 // For now, follow the MSVC naming convention for GUID objects on all 224 // targets. 225 MSGuidDecl::Parts P = GD->getParts(); 226 Out << llvm::format("_GUID_%08" PRIx32 "_%04" PRIx32 "_%04" PRIx32 "_", 227 P.Part1, P.Part2, P.Part3); 228 unsigned I = 0; 229 for (uint8_t C : P.Part4And5) { 230 Out << llvm::format("%02" PRIx8, C); 231 if (++I == 2) 232 Out << "_"; 233 } 234 } 235 236 void MangleContext::mangleGlobalBlock(const BlockDecl *BD, 237 const NamedDecl *ID, 238 raw_ostream &Out) { 239 unsigned discriminator = getBlockId(BD, false); 240 if (ID) { 241 if (shouldMangleDeclName(ID)) 242 mangleName(ID, Out); 243 else { 244 Out << ID->getIdentifier()->getName(); 245 } 246 } 247 if (discriminator == 0) 248 Out << "_block_invoke"; 249 else 250 Out << "_block_invoke_" << discriminator+1; 251 } 252 253 void MangleContext::mangleCtorBlock(const CXXConstructorDecl *CD, 254 CXXCtorType CT, const BlockDecl *BD, 255 raw_ostream &ResStream) { 256 SmallString<64> Buffer; 257 llvm::raw_svector_ostream Out(Buffer); 258 mangleName(GlobalDecl(CD, CT), Out); 259 mangleFunctionBlock(*this, Buffer, BD, ResStream); 260 } 261 262 void MangleContext::mangleDtorBlock(const CXXDestructorDecl *DD, 263 CXXDtorType DT, const BlockDecl *BD, 264 raw_ostream &ResStream) { 265 SmallString<64> Buffer; 266 llvm::raw_svector_ostream Out(Buffer); 267 mangleName(GlobalDecl(DD, DT), Out); 268 mangleFunctionBlock(*this, Buffer, BD, ResStream); 269 } 270 271 void MangleContext::mangleBlock(const DeclContext *DC, const BlockDecl *BD, 272 raw_ostream &Out) { 273 assert(!isa<CXXConstructorDecl>(DC) && !isa<CXXDestructorDecl>(DC)); 274 275 SmallString<64> Buffer; 276 llvm::raw_svector_ostream Stream(Buffer); 277 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) { 278 mangleObjCMethodName(Method, Stream); 279 } else { 280 assert((isa<NamedDecl>(DC) || isa<BlockDecl>(DC)) && 281 "expected a NamedDecl or BlockDecl"); 282 if (isa<BlockDecl>(DC)) 283 for (; DC && isa<BlockDecl>(DC); DC = DC->getParent()) 284 (void) getBlockId(cast<BlockDecl>(DC), true); 285 assert((isa<TranslationUnitDecl>(DC) || isa<NamedDecl>(DC)) && 286 "expected a TranslationUnitDecl or a NamedDecl"); 287 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC)) 288 mangleCtorBlock(CD, /*CT*/ Ctor_Complete, BD, Out); 289 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC)) 290 mangleDtorBlock(DD, /*DT*/ Dtor_Complete, BD, Out); 291 else if (auto ND = dyn_cast<NamedDecl>(DC)) { 292 if (!shouldMangleDeclName(ND) && ND->getIdentifier()) 293 Stream << ND->getIdentifier()->getName(); 294 else { 295 // FIXME: We were doing a mangleUnqualifiedName() before, but that's 296 // a private member of a class that will soon itself be private to the 297 // Itanium C++ ABI object. What should we do now? Right now, I'm just 298 // calling the mangleName() method on the MangleContext; is there a 299 // better way? 300 mangleName(ND, Stream); 301 } 302 } 303 } 304 mangleFunctionBlock(*this, Buffer, BD, Out); 305 } 306 307 void MangleContext::mangleObjCMethodNameWithoutSize(const ObjCMethodDecl *MD, 308 raw_ostream &OS) { 309 const ObjCContainerDecl *CD = 310 dyn_cast<ObjCContainerDecl>(MD->getDeclContext()); 311 assert (CD && "Missing container decl in GetNameForMethod"); 312 OS << (MD->isInstanceMethod() ? '-' : '+') << '['; 313 if (const ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(CD)) { 314 OS << CID->getClassInterface()->getName(); 315 OS << '(' << *CID << ')'; 316 } else { 317 OS << CD->getName(); 318 } 319 OS << ' '; 320 MD->getSelector().print(OS); 321 OS << ']'; 322 } 323 324 void MangleContext::mangleObjCMethodName(const ObjCMethodDecl *MD, 325 raw_ostream &Out) { 326 SmallString<64> Name; 327 llvm::raw_svector_ostream OS(Name); 328 329 mangleObjCMethodNameWithoutSize(MD, OS); 330 Out << OS.str().size() << OS.str(); 331 } 332 333 class ASTNameGenerator::Implementation { 334 std::unique_ptr<MangleContext> MC; 335 llvm::DataLayout DL; 336 337 public: 338 explicit Implementation(ASTContext &Ctx) 339 : MC(Ctx.createMangleContext()), DL(Ctx.getTargetInfo().getDataLayout()) { 340 } 341 342 bool writeName(const Decl *D, raw_ostream &OS) { 343 // First apply frontend mangling. 344 SmallString<128> FrontendBuf; 345 llvm::raw_svector_ostream FrontendBufOS(FrontendBuf); 346 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 347 if (FD->isDependentContext()) 348 return true; 349 if (writeFuncOrVarName(FD, FrontendBufOS)) 350 return true; 351 } else if (auto *VD = dyn_cast<VarDecl>(D)) { 352 if (writeFuncOrVarName(VD, FrontendBufOS)) 353 return true; 354 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D)) { 355 MC->mangleObjCMethodNameWithoutSize(MD, OS); 356 return false; 357 } else if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) { 358 writeObjCClassName(ID, FrontendBufOS); 359 } else { 360 return true; 361 } 362 363 // Now apply backend mangling. 364 llvm::Mangler::getNameWithPrefix(OS, FrontendBufOS.str(), DL); 365 return false; 366 } 367 368 std::string getName(const Decl *D) { 369 std::string Name; 370 { 371 llvm::raw_string_ostream OS(Name); 372 writeName(D, OS); 373 } 374 return Name; 375 } 376 377 enum ObjCKind { 378 ObjCClass, 379 ObjCMetaclass, 380 }; 381 382 static StringRef getClassSymbolPrefix(ObjCKind Kind, 383 const ASTContext &Context) { 384 if (Context.getLangOpts().ObjCRuntime.isGNUFamily()) 385 return Kind == ObjCMetaclass ? "_OBJC_METACLASS_" : "_OBJC_CLASS_"; 386 return Kind == ObjCMetaclass ? "OBJC_METACLASS_$_" : "OBJC_CLASS_$_"; 387 } 388 389 std::vector<std::string> getAllManglings(const ObjCContainerDecl *OCD) { 390 StringRef ClassName; 391 if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(OCD)) 392 ClassName = OID->getObjCRuntimeNameAsString(); 393 else if (const auto *OID = dyn_cast<ObjCImplementationDecl>(OCD)) 394 ClassName = OID->getObjCRuntimeNameAsString(); 395 396 if (ClassName.empty()) 397 return {}; 398 399 auto Mangle = [&](ObjCKind Kind, StringRef ClassName) -> std::string { 400 SmallString<40> Mangled; 401 auto Prefix = getClassSymbolPrefix(Kind, OCD->getASTContext()); 402 llvm::Mangler::getNameWithPrefix(Mangled, Prefix + ClassName, DL); 403 return std::string(Mangled.str()); 404 }; 405 406 return { 407 Mangle(ObjCClass, ClassName), 408 Mangle(ObjCMetaclass, ClassName), 409 }; 410 } 411 412 std::vector<std::string> getAllManglings(const Decl *D) { 413 if (const auto *OCD = dyn_cast<ObjCContainerDecl>(D)) 414 return getAllManglings(OCD); 415 416 if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D))) 417 return {}; 418 419 const NamedDecl *ND = cast<NamedDecl>(D); 420 421 ASTContext &Ctx = ND->getASTContext(); 422 std::unique_ptr<MangleContext> M(Ctx.createMangleContext()); 423 424 std::vector<std::string> Manglings; 425 426 auto hasDefaultCXXMethodCC = [](ASTContext &C, const CXXMethodDecl *MD) { 427 auto DefaultCC = C.getDefaultCallingConvention(/*IsVariadic=*/false, 428 /*IsCXXMethod=*/true); 429 auto CC = MD->getType()->castAs<FunctionProtoType>()->getCallConv(); 430 return CC == DefaultCC; 431 }; 432 433 if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(ND)) { 434 Manglings.emplace_back(getMangledStructor(CD, Ctor_Base)); 435 436 if (Ctx.getTargetInfo().getCXXABI().isItaniumFamily()) 437 if (!CD->getParent()->isAbstract()) 438 Manglings.emplace_back(getMangledStructor(CD, Ctor_Complete)); 439 440 if (Ctx.getTargetInfo().getCXXABI().isMicrosoft()) 441 if (CD->hasAttr<DLLExportAttr>() && CD->isDefaultConstructor()) 442 if (!(hasDefaultCXXMethodCC(Ctx, CD) && CD->getNumParams() == 0)) 443 Manglings.emplace_back(getMangledStructor(CD, Ctor_DefaultClosure)); 444 } else if (const auto *DD = dyn_cast_or_null<CXXDestructorDecl>(ND)) { 445 Manglings.emplace_back(getMangledStructor(DD, Dtor_Base)); 446 if (Ctx.getTargetInfo().getCXXABI().isItaniumFamily()) { 447 Manglings.emplace_back(getMangledStructor(DD, Dtor_Complete)); 448 if (DD->isVirtual()) 449 Manglings.emplace_back(getMangledStructor(DD, Dtor_Deleting)); 450 } 451 } else if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(ND)) { 452 Manglings.emplace_back(getName(ND)); 453 if (MD->isVirtual()) 454 if (const auto *TIV = Ctx.getVTableContext()->getThunkInfo(MD)) 455 for (const auto &T : *TIV) 456 Manglings.emplace_back(getMangledThunk(MD, T)); 457 } 458 459 return Manglings; 460 } 461 462 private: 463 bool writeFuncOrVarName(const NamedDecl *D, raw_ostream &OS) { 464 if (MC->shouldMangleDeclName(D)) { 465 GlobalDecl GD; 466 if (const auto *CtorD = dyn_cast<CXXConstructorDecl>(D)) 467 GD = GlobalDecl(CtorD, Ctor_Complete); 468 else if (const auto *DtorD = dyn_cast<CXXDestructorDecl>(D)) 469 GD = GlobalDecl(DtorD, Dtor_Complete); 470 else if (D->hasAttr<CUDAGlobalAttr>()) 471 GD = GlobalDecl(cast<FunctionDecl>(D)); 472 else 473 GD = GlobalDecl(D); 474 MC->mangleName(GD, OS); 475 return false; 476 } else { 477 IdentifierInfo *II = D->getIdentifier(); 478 if (!II) 479 return true; 480 OS << II->getName(); 481 return false; 482 } 483 } 484 485 void writeObjCClassName(const ObjCInterfaceDecl *D, raw_ostream &OS) { 486 OS << getClassSymbolPrefix(ObjCClass, D->getASTContext()); 487 OS << D->getObjCRuntimeNameAsString(); 488 } 489 490 std::string getMangledStructor(const NamedDecl *ND, unsigned StructorType) { 491 std::string FrontendBuf; 492 llvm::raw_string_ostream FOS(FrontendBuf); 493 494 GlobalDecl GD; 495 if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(ND)) 496 GD = GlobalDecl(CD, static_cast<CXXCtorType>(StructorType)); 497 else if (const auto *DD = dyn_cast_or_null<CXXDestructorDecl>(ND)) 498 GD = GlobalDecl(DD, static_cast<CXXDtorType>(StructorType)); 499 MC->mangleName(GD, FOS); 500 501 std::string BackendBuf; 502 llvm::raw_string_ostream BOS(BackendBuf); 503 504 llvm::Mangler::getNameWithPrefix(BOS, FOS.str(), DL); 505 506 return BOS.str(); 507 } 508 509 std::string getMangledThunk(const CXXMethodDecl *MD, const ThunkInfo &T) { 510 std::string FrontendBuf; 511 llvm::raw_string_ostream FOS(FrontendBuf); 512 513 MC->mangleThunk(MD, T, FOS); 514 515 std::string BackendBuf; 516 llvm::raw_string_ostream BOS(BackendBuf); 517 518 llvm::Mangler::getNameWithPrefix(BOS, FOS.str(), DL); 519 520 return BOS.str(); 521 } 522 }; 523 524 ASTNameGenerator::ASTNameGenerator(ASTContext &Ctx) 525 : Impl(std::make_unique<Implementation>(Ctx)) {} 526 527 ASTNameGenerator::~ASTNameGenerator() {} 528 529 bool ASTNameGenerator::writeName(const Decl *D, raw_ostream &OS) { 530 return Impl->writeName(D, OS); 531 } 532 533 std::string ASTNameGenerator::getName(const Decl *D) { 534 return Impl->getName(D); 535 } 536 537 std::vector<std::string> ASTNameGenerator::getAllManglings(const Decl *D) { 538 return Impl->getAllManglings(D); 539 } 540