1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 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 coordinates the per-module state used while generating code. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CodeGenModule.h" 14 #include "ABIInfo.h" 15 #include "CGBlocks.h" 16 #include "CGCUDARuntime.h" 17 #include "CGCXXABI.h" 18 #include "CGCall.h" 19 #include "CGDebugInfo.h" 20 #include "CGHLSLRuntime.h" 21 #include "CGObjCRuntime.h" 22 #include "CGOpenCLRuntime.h" 23 #include "CGOpenMPRuntime.h" 24 #include "CGOpenMPRuntimeGPU.h" 25 #include "CodeGenFunction.h" 26 #include "CodeGenPGO.h" 27 #include "ConstantEmitter.h" 28 #include "CoverageMappingGen.h" 29 #include "TargetInfo.h" 30 #include "clang/AST/ASTContext.h" 31 #include "clang/AST/ASTLambda.h" 32 #include "clang/AST/CharUnits.h" 33 #include "clang/AST/DeclCXX.h" 34 #include "clang/AST/DeclObjC.h" 35 #include "clang/AST/DeclTemplate.h" 36 #include "clang/AST/Mangle.h" 37 #include "clang/AST/RecursiveASTVisitor.h" 38 #include "clang/AST/StmtVisitor.h" 39 #include "clang/Basic/Builtins.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/CodeGenOptions.h" 42 #include "clang/Basic/Diagnostic.h" 43 #include "clang/Basic/FileManager.h" 44 #include "clang/Basic/Module.h" 45 #include "clang/Basic/SourceManager.h" 46 #include "clang/Basic/TargetInfo.h" 47 #include "clang/Basic/Version.h" 48 #include "clang/CodeGen/BackendUtil.h" 49 #include "clang/CodeGen/ConstantInitBuilder.h" 50 #include "clang/Frontend/FrontendDiagnostic.h" 51 #include "llvm/ADT/STLExtras.h" 52 #include "llvm/ADT/StringExtras.h" 53 #include "llvm/ADT/StringSwitch.h" 54 #include "llvm/Analysis/TargetLibraryInfo.h" 55 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 56 #include "llvm/IR/AttributeMask.h" 57 #include "llvm/IR/CallingConv.h" 58 #include "llvm/IR/DataLayout.h" 59 #include "llvm/IR/Intrinsics.h" 60 #include "llvm/IR/LLVMContext.h" 61 #include "llvm/IR/Module.h" 62 #include "llvm/IR/ProfileSummary.h" 63 #include "llvm/ProfileData/InstrProfReader.h" 64 #include "llvm/ProfileData/SampleProf.h" 65 #include "llvm/Support/CRC.h" 66 #include "llvm/Support/CodeGen.h" 67 #include "llvm/Support/CommandLine.h" 68 #include "llvm/Support/ConvertUTF.h" 69 #include "llvm/Support/ErrorHandling.h" 70 #include "llvm/Support/TimeProfiler.h" 71 #include "llvm/Support/xxhash.h" 72 #include "llvm/TargetParser/Triple.h" 73 #include "llvm/TargetParser/X86TargetParser.h" 74 #include <optional> 75 76 using namespace clang; 77 using namespace CodeGen; 78 79 static llvm::cl::opt<bool> LimitedCoverage( 80 "limited-coverage-experimental", llvm::cl::Hidden, 81 llvm::cl::desc("Emit limited coverage mapping information (experimental)")); 82 83 static const char AnnotationSection[] = "llvm.metadata"; 84 85 static CGCXXABI *createCXXABI(CodeGenModule &CGM) { 86 switch (CGM.getContext().getCXXABIKind()) { 87 case TargetCXXABI::AppleARM64: 88 case TargetCXXABI::Fuchsia: 89 case TargetCXXABI::GenericAArch64: 90 case TargetCXXABI::GenericARM: 91 case TargetCXXABI::iOS: 92 case TargetCXXABI::WatchOS: 93 case TargetCXXABI::GenericMIPS: 94 case TargetCXXABI::GenericItanium: 95 case TargetCXXABI::WebAssembly: 96 case TargetCXXABI::XL: 97 return CreateItaniumCXXABI(CGM); 98 case TargetCXXABI::Microsoft: 99 return CreateMicrosoftCXXABI(CGM); 100 } 101 102 llvm_unreachable("invalid C++ ABI kind"); 103 } 104 105 static std::unique_ptr<TargetCodeGenInfo> 106 createTargetCodeGenInfo(CodeGenModule &CGM) { 107 const TargetInfo &Target = CGM.getTarget(); 108 const llvm::Triple &Triple = Target.getTriple(); 109 const CodeGenOptions &CodeGenOpts = CGM.getCodeGenOpts(); 110 111 switch (Triple.getArch()) { 112 default: 113 return createDefaultTargetCodeGenInfo(CGM); 114 115 case llvm::Triple::le32: 116 return createPNaClTargetCodeGenInfo(CGM); 117 case llvm::Triple::m68k: 118 return createM68kTargetCodeGenInfo(CGM); 119 case llvm::Triple::mips: 120 case llvm::Triple::mipsel: 121 if (Triple.getOS() == llvm::Triple::NaCl) 122 return createPNaClTargetCodeGenInfo(CGM); 123 return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/true); 124 125 case llvm::Triple::mips64: 126 case llvm::Triple::mips64el: 127 return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/false); 128 129 case llvm::Triple::avr: { 130 // For passing parameters, R8~R25 are used on avr, and R18~R25 are used 131 // on avrtiny. For passing return value, R18~R25 are used on avr, and 132 // R22~R25 are used on avrtiny. 133 unsigned NPR = Target.getABI() == "avrtiny" ? 6 : 18; 134 unsigned NRR = Target.getABI() == "avrtiny" ? 4 : 8; 135 return createAVRTargetCodeGenInfo(CGM, NPR, NRR); 136 } 137 138 case llvm::Triple::aarch64: 139 case llvm::Triple::aarch64_32: 140 case llvm::Triple::aarch64_be: { 141 AArch64ABIKind Kind = AArch64ABIKind::AAPCS; 142 if (Target.getABI() == "darwinpcs") 143 Kind = AArch64ABIKind::DarwinPCS; 144 else if (Triple.isOSWindows()) 145 return createWindowsAArch64TargetCodeGenInfo(CGM, AArch64ABIKind::Win64); 146 147 return createAArch64TargetCodeGenInfo(CGM, Kind); 148 } 149 150 case llvm::Triple::wasm32: 151 case llvm::Triple::wasm64: { 152 WebAssemblyABIKind Kind = WebAssemblyABIKind::MVP; 153 if (Target.getABI() == "experimental-mv") 154 Kind = WebAssemblyABIKind::ExperimentalMV; 155 return createWebAssemblyTargetCodeGenInfo(CGM, Kind); 156 } 157 158 case llvm::Triple::arm: 159 case llvm::Triple::armeb: 160 case llvm::Triple::thumb: 161 case llvm::Triple::thumbeb: { 162 if (Triple.getOS() == llvm::Triple::Win32) 163 return createWindowsARMTargetCodeGenInfo(CGM, ARMABIKind::AAPCS_VFP); 164 165 ARMABIKind Kind = ARMABIKind::AAPCS; 166 StringRef ABIStr = Target.getABI(); 167 if (ABIStr == "apcs-gnu") 168 Kind = ARMABIKind::APCS; 169 else if (ABIStr == "aapcs16") 170 Kind = ARMABIKind::AAPCS16_VFP; 171 else if (CodeGenOpts.FloatABI == "hard" || 172 (CodeGenOpts.FloatABI != "soft" && 173 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF || 174 Triple.getEnvironment() == llvm::Triple::MuslEABIHF || 175 Triple.getEnvironment() == llvm::Triple::EABIHF))) 176 Kind = ARMABIKind::AAPCS_VFP; 177 178 return createARMTargetCodeGenInfo(CGM, Kind); 179 } 180 181 case llvm::Triple::ppc: { 182 if (Triple.isOSAIX()) 183 return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/false); 184 185 bool IsSoftFloat = 186 CodeGenOpts.FloatABI == "soft" || Target.hasFeature("spe"); 187 return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat); 188 } 189 case llvm::Triple::ppcle: { 190 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 191 return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat); 192 } 193 case llvm::Triple::ppc64: 194 if (Triple.isOSAIX()) 195 return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/true); 196 197 if (Triple.isOSBinFormatELF()) { 198 PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv1; 199 if (Target.getABI() == "elfv2") 200 Kind = PPC64_SVR4_ABIKind::ELFv2; 201 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 202 203 return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat); 204 } 205 return createPPC64TargetCodeGenInfo(CGM); 206 case llvm::Triple::ppc64le: { 207 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!"); 208 PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv2; 209 if (Target.getABI() == "elfv1") 210 Kind = PPC64_SVR4_ABIKind::ELFv1; 211 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 212 213 return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat); 214 } 215 216 case llvm::Triple::nvptx: 217 case llvm::Triple::nvptx64: 218 return createNVPTXTargetCodeGenInfo(CGM); 219 220 case llvm::Triple::msp430: 221 return createMSP430TargetCodeGenInfo(CGM); 222 223 case llvm::Triple::riscv32: 224 case llvm::Triple::riscv64: { 225 StringRef ABIStr = Target.getABI(); 226 unsigned XLen = Target.getPointerWidth(LangAS::Default); 227 unsigned ABIFLen = 0; 228 if (ABIStr.ends_with("f")) 229 ABIFLen = 32; 230 else if (ABIStr.ends_with("d")) 231 ABIFLen = 64; 232 return createRISCVTargetCodeGenInfo(CGM, XLen, ABIFLen); 233 } 234 235 case llvm::Triple::systemz: { 236 bool SoftFloat = CodeGenOpts.FloatABI == "soft"; 237 bool HasVector = !SoftFloat && Target.getABI() == "vector"; 238 return createSystemZTargetCodeGenInfo(CGM, HasVector, SoftFloat); 239 } 240 241 case llvm::Triple::tce: 242 case llvm::Triple::tcele: 243 return createTCETargetCodeGenInfo(CGM); 244 245 case llvm::Triple::x86: { 246 bool IsDarwinVectorABI = Triple.isOSDarwin(); 247 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing(); 248 249 if (Triple.getOS() == llvm::Triple::Win32) { 250 return createWinX86_32TargetCodeGenInfo( 251 CGM, IsDarwinVectorABI, IsWin32FloatStructABI, 252 CodeGenOpts.NumRegisterParameters); 253 } 254 return createX86_32TargetCodeGenInfo( 255 CGM, IsDarwinVectorABI, IsWin32FloatStructABI, 256 CodeGenOpts.NumRegisterParameters, CodeGenOpts.FloatABI == "soft"); 257 } 258 259 case llvm::Triple::x86_64: { 260 StringRef ABI = Target.getABI(); 261 X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512 262 : ABI == "avx" ? X86AVXABILevel::AVX 263 : X86AVXABILevel::None); 264 265 switch (Triple.getOS()) { 266 case llvm::Triple::Win32: 267 return createWinX86_64TargetCodeGenInfo(CGM, AVXLevel); 268 default: 269 return createX86_64TargetCodeGenInfo(CGM, AVXLevel); 270 } 271 } 272 case llvm::Triple::hexagon: 273 return createHexagonTargetCodeGenInfo(CGM); 274 case llvm::Triple::lanai: 275 return createLanaiTargetCodeGenInfo(CGM); 276 case llvm::Triple::r600: 277 return createAMDGPUTargetCodeGenInfo(CGM); 278 case llvm::Triple::amdgcn: 279 return createAMDGPUTargetCodeGenInfo(CGM); 280 case llvm::Triple::sparc: 281 return createSparcV8TargetCodeGenInfo(CGM); 282 case llvm::Triple::sparcv9: 283 return createSparcV9TargetCodeGenInfo(CGM); 284 case llvm::Triple::xcore: 285 return createXCoreTargetCodeGenInfo(CGM); 286 case llvm::Triple::arc: 287 return createARCTargetCodeGenInfo(CGM); 288 case llvm::Triple::spir: 289 case llvm::Triple::spir64: 290 return createCommonSPIRTargetCodeGenInfo(CGM); 291 case llvm::Triple::spirv32: 292 case llvm::Triple::spirv64: 293 return createSPIRVTargetCodeGenInfo(CGM); 294 case llvm::Triple::ve: 295 return createVETargetCodeGenInfo(CGM); 296 case llvm::Triple::csky: { 297 bool IsSoftFloat = !Target.hasFeature("hard-float-abi"); 298 bool hasFP64 = 299 Target.hasFeature("fpuv2_df") || Target.hasFeature("fpuv3_df"); 300 return createCSKYTargetCodeGenInfo(CGM, IsSoftFloat ? 0 301 : hasFP64 ? 64 302 : 32); 303 } 304 case llvm::Triple::bpfeb: 305 case llvm::Triple::bpfel: 306 return createBPFTargetCodeGenInfo(CGM); 307 case llvm::Triple::loongarch32: 308 case llvm::Triple::loongarch64: { 309 StringRef ABIStr = Target.getABI(); 310 unsigned ABIFRLen = 0; 311 if (ABIStr.ends_with("f")) 312 ABIFRLen = 32; 313 else if (ABIStr.ends_with("d")) 314 ABIFRLen = 64; 315 return createLoongArchTargetCodeGenInfo( 316 CGM, Target.getPointerWidth(LangAS::Default), ABIFRLen); 317 } 318 } 319 } 320 321 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { 322 if (!TheTargetCodeGenInfo) 323 TheTargetCodeGenInfo = createTargetCodeGenInfo(*this); 324 return *TheTargetCodeGenInfo; 325 } 326 327 CodeGenModule::CodeGenModule(ASTContext &C, 328 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS, 329 const HeaderSearchOptions &HSO, 330 const PreprocessorOptions &PPO, 331 const CodeGenOptions &CGO, llvm::Module &M, 332 DiagnosticsEngine &diags, 333 CoverageSourceInfo *CoverageInfo) 334 : Context(C), LangOpts(C.getLangOpts()), FS(FS), HeaderSearchOpts(HSO), 335 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags), 336 Target(C.getTargetInfo()), ABI(createCXXABI(*this)), 337 VMContext(M.getContext()), Types(*this), VTables(*this), 338 SanitizerMD(new SanitizerMetadata(*this)) { 339 340 // Initialize the type cache. 341 llvm::LLVMContext &LLVMContext = M.getContext(); 342 VoidTy = llvm::Type::getVoidTy(LLVMContext); 343 Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 344 Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 345 Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 346 Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 347 HalfTy = llvm::Type::getHalfTy(LLVMContext); 348 BFloatTy = llvm::Type::getBFloatTy(LLVMContext); 349 FloatTy = llvm::Type::getFloatTy(LLVMContext); 350 DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 351 PointerWidthInBits = C.getTargetInfo().getPointerWidth(LangAS::Default); 352 PointerAlignInBytes = 353 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(LangAS::Default)) 354 .getQuantity(); 355 SizeSizeInBytes = 356 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity(); 357 IntAlignInBytes = 358 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity(); 359 CharTy = 360 llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth()); 361 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 362 IntPtrTy = llvm::IntegerType::get(LLVMContext, 363 C.getTargetInfo().getMaxPointerWidth()); 364 Int8PtrTy = llvm::PointerType::get(LLVMContext, 0); 365 const llvm::DataLayout &DL = M.getDataLayout(); 366 AllocaInt8PtrTy = 367 llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace()); 368 GlobalsInt8PtrTy = 369 llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace()); 370 ConstGlobalsPtrTy = llvm::PointerType::get( 371 LLVMContext, C.getTargetAddressSpace(GetGlobalConstantAddressSpace())); 372 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace(); 373 374 // Build C++20 Module initializers. 375 // TODO: Add Microsoft here once we know the mangling required for the 376 // initializers. 377 CXX20ModuleInits = 378 LangOpts.CPlusPlusModules && getCXXABI().getMangleContext().getKind() == 379 ItaniumMangleContext::MK_Itanium; 380 381 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 382 383 if (LangOpts.ObjC) 384 createObjCRuntime(); 385 if (LangOpts.OpenCL) 386 createOpenCLRuntime(); 387 if (LangOpts.OpenMP) 388 createOpenMPRuntime(); 389 if (LangOpts.CUDA) 390 createCUDARuntime(); 391 if (LangOpts.HLSL) 392 createHLSLRuntime(); 393 394 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 395 if (LangOpts.Sanitize.has(SanitizerKind::Thread) || 396 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 397 TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(), 398 getCXXABI().getMangleContext())); 399 400 // If debug info or coverage generation is enabled, create the CGDebugInfo 401 // object. 402 if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo || 403 CodeGenOpts.CoverageNotesFile.size() || 404 CodeGenOpts.CoverageDataFile.size()) 405 DebugInfo.reset(new CGDebugInfo(*this)); 406 407 Block.GlobalUniqueCount = 0; 408 409 if (C.getLangOpts().ObjC) 410 ObjCData.reset(new ObjCEntrypoints()); 411 412 if (CodeGenOpts.hasProfileClangUse()) { 413 auto ReaderOrErr = llvm::IndexedInstrProfReader::create( 414 CodeGenOpts.ProfileInstrumentUsePath, *FS, 415 CodeGenOpts.ProfileRemappingFile); 416 // We're checking for profile read errors in CompilerInvocation, so if 417 // there was an error it should've already been caught. If it hasn't been 418 // somehow, trip an assertion. 419 assert(ReaderOrErr); 420 PGOReader = std::move(ReaderOrErr.get()); 421 } 422 423 // If coverage mapping generation is enabled, create the 424 // CoverageMappingModuleGen object. 425 if (CodeGenOpts.CoverageMapping) 426 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); 427 428 // Generate the module name hash here if needed. 429 if (CodeGenOpts.UniqueInternalLinkageNames && 430 !getModule().getSourceFileName().empty()) { 431 std::string Path = getModule().getSourceFileName(); 432 // Check if a path substitution is needed from the MacroPrefixMap. 433 for (const auto &Entry : LangOpts.MacroPrefixMap) 434 if (Path.rfind(Entry.first, 0) != std::string::npos) { 435 Path = Entry.second + Path.substr(Entry.first.size()); 436 break; 437 } 438 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path); 439 } 440 } 441 442 CodeGenModule::~CodeGenModule() {} 443 444 void CodeGenModule::createObjCRuntime() { 445 // This is just isGNUFamily(), but we want to force implementors of 446 // new ABIs to decide how best to do this. 447 switch (LangOpts.ObjCRuntime.getKind()) { 448 case ObjCRuntime::GNUstep: 449 case ObjCRuntime::GCC: 450 case ObjCRuntime::ObjFW: 451 ObjCRuntime.reset(CreateGNUObjCRuntime(*this)); 452 return; 453 454 case ObjCRuntime::FragileMacOSX: 455 case ObjCRuntime::MacOSX: 456 case ObjCRuntime::iOS: 457 case ObjCRuntime::WatchOS: 458 ObjCRuntime.reset(CreateMacObjCRuntime(*this)); 459 return; 460 } 461 llvm_unreachable("bad runtime kind"); 462 } 463 464 void CodeGenModule::createOpenCLRuntime() { 465 OpenCLRuntime.reset(new CGOpenCLRuntime(*this)); 466 } 467 468 void CodeGenModule::createOpenMPRuntime() { 469 // Select a specialized code generation class based on the target, if any. 470 // If it does not exist use the default implementation. 471 switch (getTriple().getArch()) { 472 case llvm::Triple::nvptx: 473 case llvm::Triple::nvptx64: 474 case llvm::Triple::amdgcn: 475 assert(getLangOpts().OpenMPIsTargetDevice && 476 "OpenMP AMDGPU/NVPTX is only prepared to deal with device code."); 477 OpenMPRuntime.reset(new CGOpenMPRuntimeGPU(*this)); 478 break; 479 default: 480 if (LangOpts.OpenMPSimd) 481 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this)); 482 else 483 OpenMPRuntime.reset(new CGOpenMPRuntime(*this)); 484 break; 485 } 486 } 487 488 void CodeGenModule::createCUDARuntime() { 489 CUDARuntime.reset(CreateNVCUDARuntime(*this)); 490 } 491 492 void CodeGenModule::createHLSLRuntime() { 493 HLSLRuntime.reset(new CGHLSLRuntime(*this)); 494 } 495 496 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { 497 Replacements[Name] = C; 498 } 499 500 void CodeGenModule::applyReplacements() { 501 for (auto &I : Replacements) { 502 StringRef MangledName = I.first; 503 llvm::Constant *Replacement = I.second; 504 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 505 if (!Entry) 506 continue; 507 auto *OldF = cast<llvm::Function>(Entry); 508 auto *NewF = dyn_cast<llvm::Function>(Replacement); 509 if (!NewF) { 510 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 511 NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 512 } else { 513 auto *CE = cast<llvm::ConstantExpr>(Replacement); 514 assert(CE->getOpcode() == llvm::Instruction::BitCast || 515 CE->getOpcode() == llvm::Instruction::GetElementPtr); 516 NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 517 } 518 } 519 520 // Replace old with new, but keep the old order. 521 OldF->replaceAllUsesWith(Replacement); 522 if (NewF) { 523 NewF->removeFromParent(); 524 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(), 525 NewF); 526 } 527 OldF->eraseFromParent(); 528 } 529 } 530 531 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { 532 GlobalValReplacements.push_back(std::make_pair(GV, C)); 533 } 534 535 void CodeGenModule::applyGlobalValReplacements() { 536 for (auto &I : GlobalValReplacements) { 537 llvm::GlobalValue *GV = I.first; 538 llvm::Constant *C = I.second; 539 540 GV->replaceAllUsesWith(C); 541 GV->eraseFromParent(); 542 } 543 } 544 545 // This is only used in aliases that we created and we know they have a 546 // linear structure. 547 static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) { 548 const llvm::Constant *C; 549 if (auto *GA = dyn_cast<llvm::GlobalAlias>(GV)) 550 C = GA->getAliasee(); 551 else if (auto *GI = dyn_cast<llvm::GlobalIFunc>(GV)) 552 C = GI->getResolver(); 553 else 554 return GV; 555 556 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(C->stripPointerCasts()); 557 if (!AliaseeGV) 558 return nullptr; 559 560 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject(); 561 if (FinalGV == GV) 562 return nullptr; 563 564 return FinalGV; 565 } 566 567 static bool checkAliasedGlobal( 568 const ASTContext &Context, DiagnosticsEngine &Diags, SourceLocation Location, 569 bool IsIFunc, const llvm::GlobalValue *Alias, const llvm::GlobalValue *&GV, 570 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames, 571 SourceRange AliasRange) { 572 GV = getAliasedGlobal(Alias); 573 if (!GV) { 574 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc; 575 return false; 576 } 577 578 if (GV->hasCommonLinkage()) { 579 const llvm::Triple &Triple = Context.getTargetInfo().getTriple(); 580 if (Triple.getObjectFormat() == llvm::Triple::XCOFF) { 581 Diags.Report(Location, diag::err_alias_to_common); 582 return false; 583 } 584 } 585 586 if (GV->isDeclaration()) { 587 Diags.Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc; 588 Diags.Report(Location, diag::note_alias_requires_mangled_name) 589 << IsIFunc << IsIFunc; 590 // Provide a note if the given function is not found and exists as a 591 // mangled name. 592 for (const auto &[Decl, Name] : MangledDeclNames) { 593 if (const auto *ND = dyn_cast<NamedDecl>(Decl.getDecl())) { 594 if (ND->getName() == GV->getName()) { 595 Diags.Report(Location, diag::note_alias_mangled_name_alternative) 596 << Name 597 << FixItHint::CreateReplacement( 598 AliasRange, 599 (Twine(IsIFunc ? "ifunc" : "alias") + "(\"" + Name + "\")") 600 .str()); 601 } 602 } 603 } 604 return false; 605 } 606 607 if (IsIFunc) { 608 // Check resolver function type. 609 const auto *F = dyn_cast<llvm::Function>(GV); 610 if (!F) { 611 Diags.Report(Location, diag::err_alias_to_undefined) 612 << IsIFunc << IsIFunc; 613 return false; 614 } 615 616 llvm::FunctionType *FTy = F->getFunctionType(); 617 if (!FTy->getReturnType()->isPointerTy()) { 618 Diags.Report(Location, diag::err_ifunc_resolver_return); 619 return false; 620 } 621 } 622 623 return true; 624 } 625 626 void CodeGenModule::checkAliases() { 627 // Check if the constructed aliases are well formed. It is really unfortunate 628 // that we have to do this in CodeGen, but we only construct mangled names 629 // and aliases during codegen. 630 bool Error = false; 631 DiagnosticsEngine &Diags = getDiags(); 632 for (const GlobalDecl &GD : Aliases) { 633 const auto *D = cast<ValueDecl>(GD.getDecl()); 634 SourceLocation Location; 635 SourceRange Range; 636 bool IsIFunc = D->hasAttr<IFuncAttr>(); 637 if (const Attr *A = D->getDefiningAttr()) { 638 Location = A->getLocation(); 639 Range = A->getRange(); 640 } else 641 llvm_unreachable("Not an alias or ifunc?"); 642 643 StringRef MangledName = getMangledName(GD); 644 llvm::GlobalValue *Alias = GetGlobalValue(MangledName); 645 const llvm::GlobalValue *GV = nullptr; 646 if (!checkAliasedGlobal(getContext(), Diags, Location, IsIFunc, Alias, GV, 647 MangledDeclNames, Range)) { 648 Error = true; 649 continue; 650 } 651 652 llvm::Constant *Aliasee = 653 IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver() 654 : cast<llvm::GlobalAlias>(Alias)->getAliasee(); 655 656 llvm::GlobalValue *AliaseeGV; 657 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 658 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 659 else 660 AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 661 662 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 663 StringRef AliasSection = SA->getName(); 664 if (AliasSection != AliaseeGV->getSection()) 665 Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 666 << AliasSection << IsIFunc << IsIFunc; 667 } 668 669 // We have to handle alias to weak aliases in here. LLVM itself disallows 670 // this since the object semantics would not match the IL one. For 671 // compatibility with gcc we implement it by just pointing the alias 672 // to its aliasee's aliasee. We also warn, since the user is probably 673 // expecting the link to be weak. 674 if (auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) { 675 if (GA->isInterposable()) { 676 Diags.Report(Location, diag::warn_alias_to_weak_alias) 677 << GV->getName() << GA->getName() << IsIFunc; 678 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 679 GA->getAliasee(), Alias->getType()); 680 681 if (IsIFunc) 682 cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee); 683 else 684 cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee); 685 } 686 } 687 } 688 if (!Error) 689 return; 690 691 for (const GlobalDecl &GD : Aliases) { 692 StringRef MangledName = getMangledName(GD); 693 llvm::GlobalValue *Alias = GetGlobalValue(MangledName); 694 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 695 Alias->eraseFromParent(); 696 } 697 } 698 699 void CodeGenModule::clear() { 700 DeferredDeclsToEmit.clear(); 701 EmittedDeferredDecls.clear(); 702 DeferredAnnotations.clear(); 703 if (OpenMPRuntime) 704 OpenMPRuntime->clear(); 705 } 706 707 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 708 StringRef MainFile) { 709 if (!hasDiagnostics()) 710 return; 711 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 712 if (MainFile.empty()) 713 MainFile = "<stdin>"; 714 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 715 } else { 716 if (Mismatched > 0) 717 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched; 718 719 if (Missing > 0) 720 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing; 721 } 722 } 723 724 static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO, 725 llvm::Module &M) { 726 if (!LO.VisibilityFromDLLStorageClass) 727 return; 728 729 llvm::GlobalValue::VisibilityTypes DLLExportVisibility = 730 CodeGenModule::GetLLVMVisibility(LO.getDLLExportVisibility()); 731 llvm::GlobalValue::VisibilityTypes NoDLLStorageClassVisibility = 732 CodeGenModule::GetLLVMVisibility(LO.getNoDLLStorageClassVisibility()); 733 llvm::GlobalValue::VisibilityTypes ExternDeclDLLImportVisibility = 734 CodeGenModule::GetLLVMVisibility(LO.getExternDeclDLLImportVisibility()); 735 llvm::GlobalValue::VisibilityTypes ExternDeclNoDLLStorageClassVisibility = 736 CodeGenModule::GetLLVMVisibility( 737 LO.getExternDeclNoDLLStorageClassVisibility()); 738 739 for (llvm::GlobalValue &GV : M.global_values()) { 740 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage()) 741 continue; 742 743 // Reset DSO locality before setting the visibility. This removes 744 // any effects that visibility options and annotations may have 745 // had on the DSO locality. Setting the visibility will implicitly set 746 // appropriate globals to DSO Local; however, this will be pessimistic 747 // w.r.t. to the normal compiler IRGen. 748 GV.setDSOLocal(false); 749 750 if (GV.isDeclarationForLinker()) { 751 GV.setVisibility(GV.getDLLStorageClass() == 752 llvm::GlobalValue::DLLImportStorageClass 753 ? ExternDeclDLLImportVisibility 754 : ExternDeclNoDLLStorageClassVisibility); 755 } else { 756 GV.setVisibility(GV.getDLLStorageClass() == 757 llvm::GlobalValue::DLLExportStorageClass 758 ? DLLExportVisibility 759 : NoDLLStorageClassVisibility); 760 } 761 762 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 763 } 764 } 765 766 static bool isStackProtectorOn(const LangOptions &LangOpts, 767 const llvm::Triple &Triple, 768 clang::LangOptions::StackProtectorMode Mode) { 769 if (Triple.isAMDGPU() || Triple.isNVPTX()) 770 return false; 771 return LangOpts.getStackProtector() == Mode; 772 } 773 774 void CodeGenModule::Release() { 775 Module *Primary = getContext().getCurrentNamedModule(); 776 if (CXX20ModuleInits && Primary && !Primary->isHeaderLikeModule()) 777 EmitModuleInitializers(Primary); 778 EmitDeferred(); 779 DeferredDecls.insert(EmittedDeferredDecls.begin(), 780 EmittedDeferredDecls.end()); 781 EmittedDeferredDecls.clear(); 782 EmitVTablesOpportunistically(); 783 applyGlobalValReplacements(); 784 applyReplacements(); 785 emitMultiVersionFunctions(); 786 787 if (Context.getLangOpts().IncrementalExtensions && 788 GlobalTopLevelStmtBlockInFlight.first) { 789 const TopLevelStmtDecl *TLSD = GlobalTopLevelStmtBlockInFlight.second; 790 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->getEndLoc()); 791 GlobalTopLevelStmtBlockInFlight = {nullptr, nullptr}; 792 } 793 794 // Module implementations are initialized the same way as a regular TU that 795 // imports one or more modules. 796 if (CXX20ModuleInits && Primary && Primary->isInterfaceOrPartition()) 797 EmitCXXModuleInitFunc(Primary); 798 else 799 EmitCXXGlobalInitFunc(); 800 EmitCXXGlobalCleanUpFunc(); 801 registerGlobalDtorsWithAtExit(); 802 EmitCXXThreadLocalInitFunc(); 803 if (ObjCRuntime) 804 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 805 AddGlobalCtor(ObjCInitFunction); 806 if (Context.getLangOpts().CUDA && CUDARuntime) { 807 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule()) 808 AddGlobalCtor(CudaCtorFunction); 809 } 810 if (OpenMPRuntime) { 811 if (llvm::Function *OpenMPRequiresDirectiveRegFun = 812 OpenMPRuntime->emitRequiresDirectiveRegFun()) { 813 AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0); 814 } 815 OpenMPRuntime->createOffloadEntriesAndInfoMetadata(); 816 OpenMPRuntime->clear(); 817 } 818 if (PGOReader) { 819 getModule().setProfileSummary( 820 PGOReader->getSummary(/* UseCS */ false).getMD(VMContext), 821 llvm::ProfileSummary::PSK_Instr); 822 if (PGOStats.hasDiagnostics()) 823 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 824 } 825 llvm::stable_sort(GlobalCtors, [](const Structor &L, const Structor &R) { 826 return L.LexOrder < R.LexOrder; 827 }); 828 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 829 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 830 EmitGlobalAnnotations(); 831 EmitStaticExternCAliases(); 832 checkAliases(); 833 EmitDeferredUnusedCoverageMappings(); 834 CodeGenPGO(*this).setValueProfilingFlag(getModule()); 835 if (CoverageMapping) 836 CoverageMapping->emit(); 837 if (CodeGenOpts.SanitizeCfiCrossDso) { 838 CodeGenFunction(*this).EmitCfiCheckFail(); 839 CodeGenFunction(*this).EmitCfiCheckStub(); 840 } 841 if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) 842 finalizeKCFITypes(); 843 emitAtAvailableLinkGuard(); 844 if (Context.getTargetInfo().getTriple().isWasm()) 845 EmitMainVoidAlias(); 846 847 if (getTriple().isAMDGPU()) { 848 // Emit amdgpu_code_object_version module flag, which is code object version 849 // times 100. 850 if (getTarget().getTargetOpts().CodeObjectVersion != 851 llvm::CodeObjectVersionKind::COV_None) { 852 getModule().addModuleFlag(llvm::Module::Error, 853 "amdgpu_code_object_version", 854 getTarget().getTargetOpts().CodeObjectVersion); 855 } 856 857 // Currently, "-mprintf-kind" option is only supported for HIP 858 if (LangOpts.HIP) { 859 auto *MDStr = llvm::MDString::get( 860 getLLVMContext(), (getTarget().getTargetOpts().AMDGPUPrintfKindVal == 861 TargetOptions::AMDGPUPrintfKind::Hostcall) 862 ? "hostcall" 863 : "buffered"); 864 getModule().addModuleFlag(llvm::Module::Error, "amdgpu_printf_kind", 865 MDStr); 866 } 867 } 868 869 // Emit a global array containing all external kernels or device variables 870 // used by host functions and mark it as used for CUDA/HIP. This is necessary 871 // to get kernels or device variables in archives linked in even if these 872 // kernels or device variables are only used in host functions. 873 if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) { 874 SmallVector<llvm::Constant *, 8> UsedArray; 875 for (auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) { 876 GlobalDecl GD; 877 if (auto *FD = dyn_cast<FunctionDecl>(D)) 878 GD = GlobalDecl(FD, KernelReferenceKind::Kernel); 879 else 880 GD = GlobalDecl(D); 881 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 882 GetAddrOfGlobal(GD), Int8PtrTy)); 883 } 884 885 llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size()); 886 887 auto *GV = new llvm::GlobalVariable( 888 getModule(), ATy, false, llvm::GlobalValue::InternalLinkage, 889 llvm::ConstantArray::get(ATy, UsedArray), "__clang_gpu_used_external"); 890 addCompilerUsedGlobal(GV); 891 } 892 893 emitLLVMUsed(); 894 if (SanStats) 895 SanStats->finish(); 896 897 if (CodeGenOpts.Autolink && 898 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 899 EmitModuleLinkOptions(); 900 } 901 902 // On ELF we pass the dependent library specifiers directly to the linker 903 // without manipulating them. This is in contrast to other platforms where 904 // they are mapped to a specific linker option by the compiler. This 905 // difference is a result of the greater variety of ELF linkers and the fact 906 // that ELF linkers tend to handle libraries in a more complicated fashion 907 // than on other platforms. This forces us to defer handling the dependent 908 // libs to the linker. 909 // 910 // CUDA/HIP device and host libraries are different. Currently there is no 911 // way to differentiate dependent libraries for host or device. Existing 912 // usage of #pragma comment(lib, *) is intended for host libraries on 913 // Windows. Therefore emit llvm.dependent-libraries only for host. 914 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) { 915 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries"); 916 for (auto *MD : ELFDependentLibraries) 917 NMD->addOperand(MD); 918 } 919 920 // Record mregparm value now so it is visible through rest of codegen. 921 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) 922 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters", 923 CodeGenOpts.NumRegisterParameters); 924 925 if (CodeGenOpts.DwarfVersion) { 926 getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version", 927 CodeGenOpts.DwarfVersion); 928 } 929 930 if (CodeGenOpts.Dwarf64) 931 getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1); 932 933 if (Context.getLangOpts().SemanticInterposition) 934 // Require various optimization to respect semantic interposition. 935 getModule().setSemanticInterposition(true); 936 937 if (CodeGenOpts.EmitCodeView) { 938 // Indicate that we want CodeView in the metadata. 939 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); 940 } 941 if (CodeGenOpts.CodeViewGHash) { 942 getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1); 943 } 944 if (CodeGenOpts.ControlFlowGuard) { 945 // Function ID tables and checks for Control Flow Guard (cfguard=2). 946 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2); 947 } else if (CodeGenOpts.ControlFlowGuardNoChecks) { 948 // Function ID tables for Control Flow Guard (cfguard=1). 949 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1); 950 } 951 if (CodeGenOpts.EHContGuard) { 952 // Function ID tables for EH Continuation Guard. 953 getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1); 954 } 955 if (Context.getLangOpts().Kernel) { 956 // Note if we are compiling with /kernel. 957 getModule().addModuleFlag(llvm::Module::Warning, "ms-kernel", 1); 958 } 959 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { 960 // We don't support LTO with 2 with different StrictVTablePointers 961 // FIXME: we could support it by stripping all the information introduced 962 // by StrictVTablePointers. 963 964 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); 965 966 llvm::Metadata *Ops[2] = { 967 llvm::MDString::get(VMContext, "StrictVTablePointers"), 968 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 969 llvm::Type::getInt32Ty(VMContext), 1))}; 970 971 getModule().addModuleFlag(llvm::Module::Require, 972 "StrictVTablePointersRequirement", 973 llvm::MDNode::get(VMContext, Ops)); 974 } 975 if (getModuleDebugInfo()) 976 // We support a single version in the linked module. The LLVM 977 // parser will drop debug info with a different version number 978 // (and warn about it, too). 979 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 980 llvm::DEBUG_METADATA_VERSION); 981 982 // We need to record the widths of enums and wchar_t, so that we can generate 983 // the correct build attributes in the ARM backend. wchar_size is also used by 984 // TargetLibraryInfo. 985 uint64_t WCharWidth = 986 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 987 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 988 989 if (getTriple().isOSzOS()) { 990 getModule().addModuleFlag(llvm::Module::Warning, 991 "zos_product_major_version", 992 uint32_t(CLANG_VERSION_MAJOR)); 993 getModule().addModuleFlag(llvm::Module::Warning, 994 "zos_product_minor_version", 995 uint32_t(CLANG_VERSION_MINOR)); 996 getModule().addModuleFlag(llvm::Module::Warning, "zos_product_patchlevel", 997 uint32_t(CLANG_VERSION_PATCHLEVEL)); 998 std::string ProductId = getClangVendor() + "clang"; 999 getModule().addModuleFlag(llvm::Module::Error, "zos_product_id", 1000 llvm::MDString::get(VMContext, ProductId)); 1001 1002 // Record the language because we need it for the PPA2. 1003 StringRef lang_str = languageToString( 1004 LangStandard::getLangStandardForKind(LangOpts.LangStd).Language); 1005 getModule().addModuleFlag(llvm::Module::Error, "zos_cu_language", 1006 llvm::MDString::get(VMContext, lang_str)); 1007 1008 time_t TT = PreprocessorOpts.SourceDateEpoch 1009 ? *PreprocessorOpts.SourceDateEpoch 1010 : std::time(nullptr); 1011 getModule().addModuleFlag(llvm::Module::Max, "zos_translation_time", 1012 static_cast<uint64_t>(TT)); 1013 1014 // Multiple modes will be supported here. 1015 getModule().addModuleFlag(llvm::Module::Error, "zos_le_char_mode", 1016 llvm::MDString::get(VMContext, "ascii")); 1017 } 1018 1019 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 1020 if ( Arch == llvm::Triple::arm 1021 || Arch == llvm::Triple::armeb 1022 || Arch == llvm::Triple::thumb 1023 || Arch == llvm::Triple::thumbeb) { 1024 // The minimum width of an enum in bytes 1025 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 1026 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 1027 } 1028 1029 if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) { 1030 StringRef ABIStr = Target.getABI(); 1031 llvm::LLVMContext &Ctx = TheModule.getContext(); 1032 getModule().addModuleFlag(llvm::Module::Error, "target-abi", 1033 llvm::MDString::get(Ctx, ABIStr)); 1034 } 1035 1036 if (CodeGenOpts.SanitizeCfiCrossDso) { 1037 // Indicate that we want cross-DSO control flow integrity checks. 1038 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); 1039 } 1040 1041 if (CodeGenOpts.WholeProgramVTables) { 1042 // Indicate whether VFE was enabled for this module, so that the 1043 // vcall_visibility metadata added under whole program vtables is handled 1044 // appropriately in the optimizer. 1045 getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim", 1046 CodeGenOpts.VirtualFunctionElimination); 1047 } 1048 1049 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) { 1050 getModule().addModuleFlag(llvm::Module::Override, 1051 "CFI Canonical Jump Tables", 1052 CodeGenOpts.SanitizeCfiCanonicalJumpTables); 1053 } 1054 1055 if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) { 1056 getModule().addModuleFlag(llvm::Module::Override, "kcfi", 1); 1057 // KCFI assumes patchable-function-prefix is the same for all indirectly 1058 // called functions. Store the expected offset for code generation. 1059 if (CodeGenOpts.PatchableFunctionEntryOffset) 1060 getModule().addModuleFlag(llvm::Module::Override, "kcfi-offset", 1061 CodeGenOpts.PatchableFunctionEntryOffset); 1062 } 1063 1064 if (CodeGenOpts.CFProtectionReturn && 1065 Target.checkCFProtectionReturnSupported(getDiags())) { 1066 // Indicate that we want to instrument return control flow protection. 1067 getModule().addModuleFlag(llvm::Module::Min, "cf-protection-return", 1068 1); 1069 } 1070 1071 if (CodeGenOpts.CFProtectionBranch && 1072 Target.checkCFProtectionBranchSupported(getDiags())) { 1073 // Indicate that we want to instrument branch control flow protection. 1074 getModule().addModuleFlag(llvm::Module::Min, "cf-protection-branch", 1075 1); 1076 } 1077 1078 if (CodeGenOpts.FunctionReturnThunks) 1079 getModule().addModuleFlag(llvm::Module::Override, "function_return_thunk_extern", 1); 1080 1081 if (CodeGenOpts.IndirectBranchCSPrefix) 1082 getModule().addModuleFlag(llvm::Module::Override, "indirect_branch_cs_prefix", 1); 1083 1084 // Add module metadata for return address signing (ignoring 1085 // non-leaf/all) and stack tagging. These are actually turned on by function 1086 // attributes, but we use module metadata to emit build attributes. This is 1087 // needed for LTO, where the function attributes are inside bitcode 1088 // serialised into a global variable by the time build attributes are 1089 // emitted, so we can't access them. LTO objects could be compiled with 1090 // different flags therefore module flags are set to "Min" behavior to achieve 1091 // the same end result of the normal build where e.g BTI is off if any object 1092 // doesn't support it. 1093 if (Context.getTargetInfo().hasFeature("ptrauth") && 1094 LangOpts.getSignReturnAddressScope() != 1095 LangOptions::SignReturnAddressScopeKind::None) 1096 getModule().addModuleFlag(llvm::Module::Override, 1097 "sign-return-address-buildattr", 1); 1098 if (LangOpts.Sanitize.has(SanitizerKind::MemtagStack)) 1099 getModule().addModuleFlag(llvm::Module::Override, 1100 "tag-stack-memory-buildattr", 1); 1101 1102 if (Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb || 1103 Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb || 1104 Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 || 1105 Arch == llvm::Triple::aarch64_be) { 1106 if (LangOpts.BranchTargetEnforcement) 1107 getModule().addModuleFlag(llvm::Module::Min, "branch-target-enforcement", 1108 1); 1109 if (LangOpts.BranchProtectionPAuthLR) 1110 getModule().addModuleFlag(llvm::Module::Min, "branch-protection-pauth-lr", 1111 1); 1112 if (LangOpts.hasSignReturnAddress()) 1113 getModule().addModuleFlag(llvm::Module::Min, "sign-return-address", 1); 1114 if (LangOpts.isSignReturnAddressScopeAll()) 1115 getModule().addModuleFlag(llvm::Module::Min, "sign-return-address-all", 1116 1); 1117 if (!LangOpts.isSignReturnAddressWithAKey()) 1118 getModule().addModuleFlag(llvm::Module::Min, 1119 "sign-return-address-with-bkey", 1); 1120 } 1121 1122 if (CodeGenOpts.StackClashProtector) 1123 getModule().addModuleFlag( 1124 llvm::Module::Override, "probe-stack", 1125 llvm::MDString::get(TheModule.getContext(), "inline-asm")); 1126 1127 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096) 1128 getModule().addModuleFlag(llvm::Module::Min, "stack-probe-size", 1129 CodeGenOpts.StackProbeSize); 1130 1131 if (!CodeGenOpts.MemoryProfileOutput.empty()) { 1132 llvm::LLVMContext &Ctx = TheModule.getContext(); 1133 getModule().addModuleFlag( 1134 llvm::Module::Error, "MemProfProfileFilename", 1135 llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput)); 1136 } 1137 1138 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) { 1139 // Indicate whether __nvvm_reflect should be configured to flush denormal 1140 // floating point values to 0. (This corresponds to its "__CUDA_FTZ" 1141 // property.) 1142 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", 1143 CodeGenOpts.FP32DenormalMode.Output != 1144 llvm::DenormalMode::IEEE); 1145 } 1146 1147 if (LangOpts.EHAsynch) 1148 getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1); 1149 1150 // Indicate whether this Module was compiled with -fopenmp 1151 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 1152 getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP); 1153 if (getLangOpts().OpenMPIsTargetDevice) 1154 getModule().addModuleFlag(llvm::Module::Max, "openmp-device", 1155 LangOpts.OpenMP); 1156 1157 // Emit OpenCL specific module metadata: OpenCL/SPIR version. 1158 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice && getTriple().isSPIRV())) { 1159 EmitOpenCLMetadata(); 1160 // Emit SPIR version. 1161 if (getTriple().isSPIR()) { 1162 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the 1163 // opencl.spir.version named metadata. 1164 // C++ for OpenCL has a distinct mapping for version compatibility with 1165 // OpenCL. 1166 auto Version = LangOpts.getOpenCLCompatibleVersion(); 1167 llvm::Metadata *SPIRVerElts[] = { 1168 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 1169 Int32Ty, Version / 100)), 1170 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 1171 Int32Ty, (Version / 100 > 1) ? 0 : 2))}; 1172 llvm::NamedMDNode *SPIRVerMD = 1173 TheModule.getOrInsertNamedMetadata("opencl.spir.version"); 1174 llvm::LLVMContext &Ctx = TheModule.getContext(); 1175 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts)); 1176 } 1177 } 1178 1179 // HLSL related end of code gen work items. 1180 if (LangOpts.HLSL) 1181 getHLSLRuntime().finishCodeGen(); 1182 1183 if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 1184 assert(PLevel < 3 && "Invalid PIC Level"); 1185 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel)); 1186 if (Context.getLangOpts().PIE) 1187 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel)); 1188 } 1189 1190 if (getCodeGenOpts().CodeModel.size() > 0) { 1191 unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel) 1192 .Case("tiny", llvm::CodeModel::Tiny) 1193 .Case("small", llvm::CodeModel::Small) 1194 .Case("kernel", llvm::CodeModel::Kernel) 1195 .Case("medium", llvm::CodeModel::Medium) 1196 .Case("large", llvm::CodeModel::Large) 1197 .Default(~0u); 1198 if (CM != ~0u) { 1199 llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM); 1200 getModule().setCodeModel(codeModel); 1201 1202 if (CM == llvm::CodeModel::Medium && 1203 Context.getTargetInfo().getTriple().getArch() == 1204 llvm::Triple::x86_64) { 1205 getModule().setLargeDataThreshold(getCodeGenOpts().LargeDataThreshold); 1206 } 1207 } 1208 } 1209 1210 if (CodeGenOpts.NoPLT) 1211 getModule().setRtLibUseGOT(); 1212 if (getTriple().isOSBinFormatELF() && 1213 CodeGenOpts.DirectAccessExternalData != 1214 getModule().getDirectAccessExternalData()) { 1215 getModule().setDirectAccessExternalData( 1216 CodeGenOpts.DirectAccessExternalData); 1217 } 1218 if (CodeGenOpts.UnwindTables) 1219 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables)); 1220 1221 switch (CodeGenOpts.getFramePointer()) { 1222 case CodeGenOptions::FramePointerKind::None: 1223 // 0 ("none") is the default. 1224 break; 1225 case CodeGenOptions::FramePointerKind::NonLeaf: 1226 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf); 1227 break; 1228 case CodeGenOptions::FramePointerKind::All: 1229 getModule().setFramePointer(llvm::FramePointerKind::All); 1230 break; 1231 } 1232 1233 SimplifyPersonality(); 1234 1235 if (getCodeGenOpts().EmitDeclMetadata) 1236 EmitDeclMetadata(); 1237 1238 if (getCodeGenOpts().CoverageNotesFile.size() || 1239 getCodeGenOpts().CoverageDataFile.size()) 1240 EmitCoverageFile(); 1241 1242 if (CGDebugInfo *DI = getModuleDebugInfo()) 1243 DI->finalize(); 1244 1245 if (getCodeGenOpts().EmitVersionIdentMetadata) 1246 EmitVersionIdentMetadata(); 1247 1248 if (!getCodeGenOpts().RecordCommandLine.empty()) 1249 EmitCommandLineMetadata(); 1250 1251 if (!getCodeGenOpts().StackProtectorGuard.empty()) 1252 getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard); 1253 if (!getCodeGenOpts().StackProtectorGuardReg.empty()) 1254 getModule().setStackProtectorGuardReg( 1255 getCodeGenOpts().StackProtectorGuardReg); 1256 if (!getCodeGenOpts().StackProtectorGuardSymbol.empty()) 1257 getModule().setStackProtectorGuardSymbol( 1258 getCodeGenOpts().StackProtectorGuardSymbol); 1259 if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX) 1260 getModule().setStackProtectorGuardOffset( 1261 getCodeGenOpts().StackProtectorGuardOffset); 1262 if (getCodeGenOpts().StackAlignment) 1263 getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment); 1264 if (getCodeGenOpts().SkipRaxSetup) 1265 getModule().addModuleFlag(llvm::Module::Override, "SkipRaxSetup", 1); 1266 if (getLangOpts().RegCall4) 1267 getModule().addModuleFlag(llvm::Module::Override, "RegCallv4", 1); 1268 1269 if (getContext().getTargetInfo().getMaxTLSAlign()) 1270 getModule().addModuleFlag(llvm::Module::Error, "MaxTLSAlign", 1271 getContext().getTargetInfo().getMaxTLSAlign()); 1272 1273 getTargetCodeGenInfo().emitTargetGlobals(*this); 1274 1275 getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames); 1276 1277 EmitBackendOptionsMetadata(getCodeGenOpts()); 1278 1279 // If there is device offloading code embed it in the host now. 1280 EmbedObject(&getModule(), CodeGenOpts, getDiags()); 1281 1282 // Set visibility from DLL storage class 1283 // We do this at the end of LLVM IR generation; after any operation 1284 // that might affect the DLL storage class or the visibility, and 1285 // before anything that might act on these. 1286 setVisibilityFromDLLStorageClass(LangOpts, getModule()); 1287 } 1288 1289 void CodeGenModule::EmitOpenCLMetadata() { 1290 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the 1291 // opencl.ocl.version named metadata node. 1292 // C++ for OpenCL has a distinct mapping for versions compatibile with OpenCL. 1293 auto Version = LangOpts.getOpenCLCompatibleVersion(); 1294 llvm::Metadata *OCLVerElts[] = { 1295 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 1296 Int32Ty, Version / 100)), 1297 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 1298 Int32Ty, (Version % 100) / 10))}; 1299 llvm::NamedMDNode *OCLVerMD = 1300 TheModule.getOrInsertNamedMetadata("opencl.ocl.version"); 1301 llvm::LLVMContext &Ctx = TheModule.getContext(); 1302 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts)); 1303 } 1304 1305 void CodeGenModule::EmitBackendOptionsMetadata( 1306 const CodeGenOptions &CodeGenOpts) { 1307 if (getTriple().isRISCV()) { 1308 getModule().addModuleFlag(llvm::Module::Min, "SmallDataLimit", 1309 CodeGenOpts.SmallDataLimit); 1310 } 1311 } 1312 1313 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 1314 // Make sure that this type is translated. 1315 Types.UpdateCompletedType(TD); 1316 } 1317 1318 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { 1319 // Make sure that this type is translated. 1320 Types.RefreshTypeCacheForClass(RD); 1321 } 1322 1323 llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) { 1324 if (!TBAA) 1325 return nullptr; 1326 return TBAA->getTypeInfo(QTy); 1327 } 1328 1329 TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) { 1330 if (!TBAA) 1331 return TBAAAccessInfo(); 1332 if (getLangOpts().CUDAIsDevice) { 1333 // As CUDA builtin surface/texture types are replaced, skip generating TBAA 1334 // access info. 1335 if (AccessType->isCUDADeviceBuiltinSurfaceType()) { 1336 if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() != 1337 nullptr) 1338 return TBAAAccessInfo(); 1339 } else if (AccessType->isCUDADeviceBuiltinTextureType()) { 1340 if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() != 1341 nullptr) 1342 return TBAAAccessInfo(); 1343 } 1344 } 1345 return TBAA->getAccessInfo(AccessType); 1346 } 1347 1348 TBAAAccessInfo 1349 CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) { 1350 if (!TBAA) 1351 return TBAAAccessInfo(); 1352 return TBAA->getVTablePtrAccessInfo(VTablePtrType); 1353 } 1354 1355 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 1356 if (!TBAA) 1357 return nullptr; 1358 return TBAA->getTBAAStructInfo(QTy); 1359 } 1360 1361 llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) { 1362 if (!TBAA) 1363 return nullptr; 1364 return TBAA->getBaseTypeInfo(QTy); 1365 } 1366 1367 llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) { 1368 if (!TBAA) 1369 return nullptr; 1370 return TBAA->getAccessTagInfo(Info); 1371 } 1372 1373 TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, 1374 TBAAAccessInfo TargetInfo) { 1375 if (!TBAA) 1376 return TBAAAccessInfo(); 1377 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo); 1378 } 1379 1380 TBAAAccessInfo 1381 CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, 1382 TBAAAccessInfo InfoB) { 1383 if (!TBAA) 1384 return TBAAAccessInfo(); 1385 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB); 1386 } 1387 1388 TBAAAccessInfo 1389 CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, 1390 TBAAAccessInfo SrcInfo) { 1391 if (!TBAA) 1392 return TBAAAccessInfo(); 1393 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo); 1394 } 1395 1396 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, 1397 TBAAAccessInfo TBAAInfo) { 1398 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo)) 1399 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag); 1400 } 1401 1402 void CodeGenModule::DecorateInstructionWithInvariantGroup( 1403 llvm::Instruction *I, const CXXRecordDecl *RD) { 1404 I->setMetadata(llvm::LLVMContext::MD_invariant_group, 1405 llvm::MDNode::get(getLLVMContext(), {})); 1406 } 1407 1408 void CodeGenModule::Error(SourceLocation loc, StringRef message) { 1409 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 1410 getDiags().Report(Context.getFullLoc(loc), diagID) << message; 1411 } 1412 1413 /// ErrorUnsupported - Print out an error that codegen doesn't support the 1414 /// specified stmt yet. 1415 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 1416 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 1417 "cannot compile this %0 yet"); 1418 std::string Msg = Type; 1419 getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID) 1420 << Msg << S->getSourceRange(); 1421 } 1422 1423 /// ErrorUnsupported - Print out an error that codegen doesn't support the 1424 /// specified decl yet. 1425 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 1426 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 1427 "cannot compile this %0 yet"); 1428 std::string Msg = Type; 1429 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 1430 } 1431 1432 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 1433 return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 1434 } 1435 1436 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 1437 const NamedDecl *D) const { 1438 // Internal definitions always have default visibility. 1439 if (GV->hasLocalLinkage()) { 1440 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 1441 return; 1442 } 1443 if (!D) 1444 return; 1445 1446 // Set visibility for definitions, and for declarations if requested globally 1447 // or set explicitly. 1448 LinkageInfo LV = D->getLinkageAndVisibility(); 1449 1450 // OpenMP declare target variables must be visible to the host so they can 1451 // be registered. We require protected visibility unless the variable has 1452 // the DT_nohost modifier and does not need to be registered. 1453 if (Context.getLangOpts().OpenMP && 1454 Context.getLangOpts().OpenMPIsTargetDevice && isa<VarDecl>(D) && 1455 D->hasAttr<OMPDeclareTargetDeclAttr>() && 1456 D->getAttr<OMPDeclareTargetDeclAttr>()->getDevType() != 1457 OMPDeclareTargetDeclAttr::DT_NoHost && 1458 LV.getVisibility() == HiddenVisibility) { 1459 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 1460 return; 1461 } 1462 1463 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) { 1464 // Reject incompatible dlllstorage and visibility annotations. 1465 if (!LV.isVisibilityExplicit()) 1466 return; 1467 if (GV->hasDLLExportStorageClass()) { 1468 if (LV.getVisibility() == HiddenVisibility) 1469 getDiags().Report(D->getLocation(), 1470 diag::err_hidden_visibility_dllexport); 1471 } else if (LV.getVisibility() != DefaultVisibility) { 1472 getDiags().Report(D->getLocation(), 1473 diag::err_non_default_visibility_dllimport); 1474 } 1475 return; 1476 } 1477 1478 if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls || 1479 !GV->isDeclarationForLinker()) 1480 GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 1481 } 1482 1483 static bool shouldAssumeDSOLocal(const CodeGenModule &CGM, 1484 llvm::GlobalValue *GV) { 1485 if (GV->hasLocalLinkage()) 1486 return true; 1487 1488 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()) 1489 return true; 1490 1491 // DLLImport explicitly marks the GV as external. 1492 if (GV->hasDLLImportStorageClass()) 1493 return false; 1494 1495 const llvm::Triple &TT = CGM.getTriple(); 1496 const auto &CGOpts = CGM.getCodeGenOpts(); 1497 if (TT.isWindowsGNUEnvironment()) { 1498 // In MinGW, variables without DLLImport can still be automatically 1499 // imported from a DLL by the linker; don't mark variables that 1500 // potentially could come from another DLL as DSO local. 1501 1502 // With EmulatedTLS, TLS variables can be autoimported from other DLLs 1503 // (and this actually happens in the public interface of libstdc++), so 1504 // such variables can't be marked as DSO local. (Native TLS variables 1505 // can't be dllimported at all, though.) 1506 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) && 1507 (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS) && 1508 CGOpts.AutoImport) 1509 return false; 1510 } 1511 1512 // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols 1513 // remain unresolved in the link, they can be resolved to zero, which is 1514 // outside the current DSO. 1515 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage()) 1516 return false; 1517 1518 // Every other GV is local on COFF. 1519 // Make an exception for windows OS in the triple: Some firmware builds use 1520 // *-win32-macho triples. This (accidentally?) produced windows relocations 1521 // without GOT tables in older clang versions; Keep this behaviour. 1522 // FIXME: even thread local variables? 1523 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO())) 1524 return true; 1525 1526 // Only handle COFF and ELF for now. 1527 if (!TT.isOSBinFormatELF()) 1528 return false; 1529 1530 // If this is not an executable, don't assume anything is local. 1531 llvm::Reloc::Model RM = CGOpts.RelocationModel; 1532 const auto &LOpts = CGM.getLangOpts(); 1533 if (RM != llvm::Reloc::Static && !LOpts.PIE) { 1534 // On ELF, if -fno-semantic-interposition is specified and the target 1535 // supports local aliases, there will be neither CC1 1536 // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set 1537 // dso_local on the function if using a local alias is preferable (can avoid 1538 // PLT indirection). 1539 if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias())) 1540 return false; 1541 return !(CGM.getLangOpts().SemanticInterposition || 1542 CGM.getLangOpts().HalfNoSemanticInterposition); 1543 } 1544 1545 // A definition cannot be preempted from an executable. 1546 if (!GV->isDeclarationForLinker()) 1547 return true; 1548 1549 // Most PIC code sequences that assume that a symbol is local cannot produce a 1550 // 0 if it turns out the symbol is undefined. While this is ABI and relocation 1551 // depended, it seems worth it to handle it here. 1552 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage()) 1553 return false; 1554 1555 // PowerPC64 prefers TOC indirection to avoid copy relocations. 1556 if (TT.isPPC64()) 1557 return false; 1558 1559 if (CGOpts.DirectAccessExternalData) { 1560 // If -fdirect-access-external-data (default for -fno-pic), set dso_local 1561 // for non-thread-local variables. If the symbol is not defined in the 1562 // executable, a copy relocation will be needed at link time. dso_local is 1563 // excluded for thread-local variables because they generally don't support 1564 // copy relocations. 1565 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV)) 1566 if (!Var->isThreadLocal()) 1567 return true; 1568 1569 // -fno-pic sets dso_local on a function declaration to allow direct 1570 // accesses when taking its address (similar to a data symbol). If the 1571 // function is not defined in the executable, a canonical PLT entry will be 1572 // needed at link time. -fno-direct-access-external-data can avoid the 1573 // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as 1574 // it could just cause trouble without providing perceptible benefits. 1575 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static) 1576 return true; 1577 } 1578 1579 // If we can use copy relocations we can assume it is local. 1580 1581 // Otherwise don't assume it is local. 1582 return false; 1583 } 1584 1585 void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const { 1586 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV)); 1587 } 1588 1589 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 1590 GlobalDecl GD) const { 1591 const auto *D = dyn_cast<NamedDecl>(GD.getDecl()); 1592 // C++ destructors have a few C++ ABI specific special cases. 1593 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) { 1594 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType()); 1595 return; 1596 } 1597 setDLLImportDLLExport(GV, D); 1598 } 1599 1600 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 1601 const NamedDecl *D) const { 1602 if (D && D->isExternallyVisible()) { 1603 if (D->hasAttr<DLLImportAttr>()) 1604 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 1605 else if ((D->hasAttr<DLLExportAttr>() || 1606 shouldMapVisibilityToDLLExport(D)) && 1607 !GV->isDeclarationForLinker()) 1608 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 1609 } 1610 } 1611 1612 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 1613 GlobalDecl GD) const { 1614 setDLLImportDLLExport(GV, GD); 1615 setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl())); 1616 } 1617 1618 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 1619 const NamedDecl *D) const { 1620 setDLLImportDLLExport(GV, D); 1621 setGVPropertiesAux(GV, D); 1622 } 1623 1624 void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV, 1625 const NamedDecl *D) const { 1626 setGlobalVisibility(GV, D); 1627 setDSOLocal(GV); 1628 GV->setPartition(CodeGenOpts.SymbolPartition); 1629 } 1630 1631 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 1632 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 1633 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 1634 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 1635 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 1636 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 1637 } 1638 1639 llvm::GlobalVariable::ThreadLocalMode 1640 CodeGenModule::GetDefaultLLVMTLSModel() const { 1641 switch (CodeGenOpts.getDefaultTLSModel()) { 1642 case CodeGenOptions::GeneralDynamicTLSModel: 1643 return llvm::GlobalVariable::GeneralDynamicTLSModel; 1644 case CodeGenOptions::LocalDynamicTLSModel: 1645 return llvm::GlobalVariable::LocalDynamicTLSModel; 1646 case CodeGenOptions::InitialExecTLSModel: 1647 return llvm::GlobalVariable::InitialExecTLSModel; 1648 case CodeGenOptions::LocalExecTLSModel: 1649 return llvm::GlobalVariable::LocalExecTLSModel; 1650 } 1651 llvm_unreachable("Invalid TLS model!"); 1652 } 1653 1654 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 1655 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 1656 1657 llvm::GlobalValue::ThreadLocalMode TLM; 1658 TLM = GetDefaultLLVMTLSModel(); 1659 1660 // Override the TLS model if it is explicitly specified. 1661 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 1662 TLM = GetLLVMTLSModel(Attr->getModel()); 1663 } 1664 1665 GV->setThreadLocalMode(TLM); 1666 } 1667 1668 static std::string getCPUSpecificMangling(const CodeGenModule &CGM, 1669 StringRef Name) { 1670 const TargetInfo &Target = CGM.getTarget(); 1671 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str(); 1672 } 1673 1674 static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, 1675 const CPUSpecificAttr *Attr, 1676 unsigned CPUIndex, 1677 raw_ostream &Out) { 1678 // cpu_specific gets the current name, dispatch gets the resolver if IFunc is 1679 // supported. 1680 if (Attr) 1681 Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName()); 1682 else if (CGM.getTarget().supportsIFunc()) 1683 Out << ".resolver"; 1684 } 1685 1686 static void AppendTargetVersionMangling(const CodeGenModule &CGM, 1687 const TargetVersionAttr *Attr, 1688 raw_ostream &Out) { 1689 if (Attr->isDefaultVersion()) 1690 return; 1691 Out << "._"; 1692 const TargetInfo &TI = CGM.getTarget(); 1693 llvm::SmallVector<StringRef, 8> Feats; 1694 Attr->getFeatures(Feats); 1695 llvm::stable_sort(Feats, [&TI](const StringRef FeatL, const StringRef FeatR) { 1696 return TI.multiVersionSortPriority(FeatL) < 1697 TI.multiVersionSortPriority(FeatR); 1698 }); 1699 for (const auto &Feat : Feats) { 1700 Out << 'M'; 1701 Out << Feat; 1702 } 1703 } 1704 1705 static void AppendTargetMangling(const CodeGenModule &CGM, 1706 const TargetAttr *Attr, raw_ostream &Out) { 1707 if (Attr->isDefaultVersion()) 1708 return; 1709 1710 Out << '.'; 1711 const TargetInfo &Target = CGM.getTarget(); 1712 ParsedTargetAttr Info = Target.parseTargetAttr(Attr->getFeaturesStr()); 1713 llvm::sort(Info.Features, [&Target](StringRef LHS, StringRef RHS) { 1714 // Multiversioning doesn't allow "no-${feature}", so we can 1715 // only have "+" prefixes here. 1716 assert(LHS.starts_with("+") && RHS.starts_with("+") && 1717 "Features should always have a prefix."); 1718 return Target.multiVersionSortPriority(LHS.substr(1)) > 1719 Target.multiVersionSortPriority(RHS.substr(1)); 1720 }); 1721 1722 bool IsFirst = true; 1723 1724 if (!Info.CPU.empty()) { 1725 IsFirst = false; 1726 Out << "arch_" << Info.CPU; 1727 } 1728 1729 for (StringRef Feat : Info.Features) { 1730 if (!IsFirst) 1731 Out << '_'; 1732 IsFirst = false; 1733 Out << Feat.substr(1); 1734 } 1735 } 1736 1737 // Returns true if GD is a function decl with internal linkage and 1738 // needs a unique suffix after the mangled name. 1739 static bool isUniqueInternalLinkageDecl(GlobalDecl GD, 1740 CodeGenModule &CGM) { 1741 const Decl *D = GD.getDecl(); 1742 return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) && 1743 (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage); 1744 } 1745 1746 static void AppendTargetClonesMangling(const CodeGenModule &CGM, 1747 const TargetClonesAttr *Attr, 1748 unsigned VersionIndex, 1749 raw_ostream &Out) { 1750 const TargetInfo &TI = CGM.getTarget(); 1751 if (TI.getTriple().isAArch64()) { 1752 StringRef FeatureStr = Attr->getFeatureStr(VersionIndex); 1753 if (FeatureStr == "default") 1754 return; 1755 Out << "._"; 1756 SmallVector<StringRef, 8> Features; 1757 FeatureStr.split(Features, "+"); 1758 llvm::stable_sort(Features, 1759 [&TI](const StringRef FeatL, const StringRef FeatR) { 1760 return TI.multiVersionSortPriority(FeatL) < 1761 TI.multiVersionSortPriority(FeatR); 1762 }); 1763 for (auto &Feat : Features) { 1764 Out << 'M'; 1765 Out << Feat; 1766 } 1767 } else { 1768 Out << '.'; 1769 StringRef FeatureStr = Attr->getFeatureStr(VersionIndex); 1770 if (FeatureStr.starts_with("arch=")) 1771 Out << "arch_" << FeatureStr.substr(sizeof("arch=") - 1); 1772 else 1773 Out << FeatureStr; 1774 1775 Out << '.' << Attr->getMangledIndex(VersionIndex); 1776 } 1777 } 1778 1779 static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD, 1780 const NamedDecl *ND, 1781 bool OmitMultiVersionMangling = false) { 1782 SmallString<256> Buffer; 1783 llvm::raw_svector_ostream Out(Buffer); 1784 MangleContext &MC = CGM.getCXXABI().getMangleContext(); 1785 if (!CGM.getModuleNameHash().empty()) 1786 MC.needsUniqueInternalLinkageNames(); 1787 bool ShouldMangle = MC.shouldMangleDeclName(ND); 1788 if (ShouldMangle) 1789 MC.mangleName(GD.getWithDecl(ND), Out); 1790 else { 1791 IdentifierInfo *II = ND->getIdentifier(); 1792 assert(II && "Attempt to mangle unnamed decl."); 1793 const auto *FD = dyn_cast<FunctionDecl>(ND); 1794 1795 if (FD && 1796 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { 1797 if (CGM.getLangOpts().RegCall4) 1798 Out << "__regcall4__" << II->getName(); 1799 else 1800 Out << "__regcall3__" << II->getName(); 1801 } else if (FD && FD->hasAttr<CUDAGlobalAttr>() && 1802 GD.getKernelReferenceKind() == KernelReferenceKind::Stub) { 1803 Out << "__device_stub__" << II->getName(); 1804 } else { 1805 Out << II->getName(); 1806 } 1807 } 1808 1809 // Check if the module name hash should be appended for internal linkage 1810 // symbols. This should come before multi-version target suffixes are 1811 // appended. This is to keep the name and module hash suffix of the 1812 // internal linkage function together. The unique suffix should only be 1813 // added when name mangling is done to make sure that the final name can 1814 // be properly demangled. For example, for C functions without prototypes, 1815 // name mangling is not done and the unique suffix should not be appeneded 1816 // then. 1817 if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) { 1818 assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames && 1819 "Hash computed when not explicitly requested"); 1820 Out << CGM.getModuleNameHash(); 1821 } 1822 1823 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 1824 if (FD->isMultiVersion() && !OmitMultiVersionMangling) { 1825 switch (FD->getMultiVersionKind()) { 1826 case MultiVersionKind::CPUDispatch: 1827 case MultiVersionKind::CPUSpecific: 1828 AppendCPUSpecificCPUDispatchMangling(CGM, 1829 FD->getAttr<CPUSpecificAttr>(), 1830 GD.getMultiVersionIndex(), Out); 1831 break; 1832 case MultiVersionKind::Target: 1833 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out); 1834 break; 1835 case MultiVersionKind::TargetVersion: 1836 AppendTargetVersionMangling(CGM, FD->getAttr<TargetVersionAttr>(), Out); 1837 break; 1838 case MultiVersionKind::TargetClones: 1839 AppendTargetClonesMangling(CGM, FD->getAttr<TargetClonesAttr>(), 1840 GD.getMultiVersionIndex(), Out); 1841 break; 1842 case MultiVersionKind::None: 1843 llvm_unreachable("None multiversion type isn't valid here"); 1844 } 1845 } 1846 1847 // Make unique name for device side static file-scope variable for HIP. 1848 if (CGM.getContext().shouldExternalize(ND) && 1849 CGM.getLangOpts().GPURelocatableDeviceCode && 1850 CGM.getLangOpts().CUDAIsDevice) 1851 CGM.printPostfixForExternalizedDecl(Out, ND); 1852 1853 return std::string(Out.str()); 1854 } 1855 1856 void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD, 1857 const FunctionDecl *FD, 1858 StringRef &CurName) { 1859 if (!FD->isMultiVersion()) 1860 return; 1861 1862 // Get the name of what this would be without the 'target' attribute. This 1863 // allows us to lookup the version that was emitted when this wasn't a 1864 // multiversion function. 1865 std::string NonTargetName = 1866 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 1867 GlobalDecl OtherGD; 1868 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) { 1869 assert(OtherGD.getCanonicalDecl() 1870 .getDecl() 1871 ->getAsFunction() 1872 ->isMultiVersion() && 1873 "Other GD should now be a multiversioned function"); 1874 // OtherFD is the version of this function that was mangled BEFORE 1875 // becoming a MultiVersion function. It potentially needs to be updated. 1876 const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl() 1877 .getDecl() 1878 ->getAsFunction() 1879 ->getMostRecentDecl(); 1880 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD); 1881 // This is so that if the initial version was already the 'default' 1882 // version, we don't try to update it. 1883 if (OtherName != NonTargetName) { 1884 // Remove instead of erase, since others may have stored the StringRef 1885 // to this. 1886 const auto ExistingRecord = Manglings.find(NonTargetName); 1887 if (ExistingRecord != std::end(Manglings)) 1888 Manglings.remove(&(*ExistingRecord)); 1889 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD)); 1890 StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] = 1891 Result.first->first(); 1892 // If this is the current decl is being created, make sure we update the name. 1893 if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl()) 1894 CurName = OtherNameRef; 1895 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName)) 1896 Entry->setName(OtherName); 1897 } 1898 } 1899 } 1900 1901 StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 1902 GlobalDecl CanonicalGD = GD.getCanonicalDecl(); 1903 1904 // Some ABIs don't have constructor variants. Make sure that base and 1905 // complete constructors get mangled the same. 1906 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { 1907 if (!getTarget().getCXXABI().hasConstructorVariants()) { 1908 CXXCtorType OrigCtorType = GD.getCtorType(); 1909 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); 1910 if (OrigCtorType == Ctor_Base) 1911 CanonicalGD = GlobalDecl(CD, Ctor_Complete); 1912 } 1913 } 1914 1915 // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a 1916 // static device variable depends on whether the variable is referenced by 1917 // a host or device host function. Therefore the mangled name cannot be 1918 // cached. 1919 if (!LangOpts.CUDAIsDevice || !getContext().mayExternalize(GD.getDecl())) { 1920 auto FoundName = MangledDeclNames.find(CanonicalGD); 1921 if (FoundName != MangledDeclNames.end()) 1922 return FoundName->second; 1923 } 1924 1925 // Keep the first result in the case of a mangling collision. 1926 const auto *ND = cast<NamedDecl>(GD.getDecl()); 1927 std::string MangledName = getMangledNameImpl(*this, GD, ND); 1928 1929 // Ensure either we have different ABIs between host and device compilations, 1930 // says host compilation following MSVC ABI but device compilation follows 1931 // Itanium C++ ABI or, if they follow the same ABI, kernel names after 1932 // mangling should be the same after name stubbing. The later checking is 1933 // very important as the device kernel name being mangled in host-compilation 1934 // is used to resolve the device binaries to be executed. Inconsistent naming 1935 // result in undefined behavior. Even though we cannot check that naming 1936 // directly between host- and device-compilations, the host- and 1937 // device-mangling in host compilation could help catching certain ones. 1938 assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || 1939 getContext().shouldExternalize(ND) || getLangOpts().CUDAIsDevice || 1940 (getContext().getAuxTargetInfo() && 1941 (getContext().getAuxTargetInfo()->getCXXABI() != 1942 getContext().getTargetInfo().getCXXABI())) || 1943 getCUDARuntime().getDeviceSideName(ND) == 1944 getMangledNameImpl( 1945 *this, 1946 GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), 1947 ND)); 1948 1949 auto Result = Manglings.insert(std::make_pair(MangledName, GD)); 1950 return MangledDeclNames[CanonicalGD] = Result.first->first(); 1951 } 1952 1953 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 1954 const BlockDecl *BD) { 1955 MangleContext &MangleCtx = getCXXABI().getMangleContext(); 1956 const Decl *D = GD.getDecl(); 1957 1958 SmallString<256> Buffer; 1959 llvm::raw_svector_ostream Out(Buffer); 1960 if (!D) 1961 MangleCtx.mangleGlobalBlock(BD, 1962 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 1963 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 1964 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 1965 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 1966 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 1967 else 1968 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 1969 1970 auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 1971 return Result.first->first(); 1972 } 1973 1974 const GlobalDecl CodeGenModule::getMangledNameDecl(StringRef Name) { 1975 auto it = MangledDeclNames.begin(); 1976 while (it != MangledDeclNames.end()) { 1977 if (it->second == Name) 1978 return it->first; 1979 it++; 1980 } 1981 return GlobalDecl(); 1982 } 1983 1984 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 1985 return getModule().getNamedValue(Name); 1986 } 1987 1988 /// AddGlobalCtor - Add a function to the list that will be called before 1989 /// main() runs. 1990 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 1991 unsigned LexOrder, 1992 llvm::Constant *AssociatedData) { 1993 // FIXME: Type coercion of void()* types. 1994 GlobalCtors.push_back(Structor(Priority, LexOrder, Ctor, AssociatedData)); 1995 } 1996 1997 /// AddGlobalDtor - Add a function to the list that will be called 1998 /// when the module is unloaded. 1999 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority, 2000 bool IsDtorAttrFunc) { 2001 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit && 2002 (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) { 2003 DtorsUsingAtExit[Priority].push_back(Dtor); 2004 return; 2005 } 2006 2007 // FIXME: Type coercion of void()* types. 2008 GlobalDtors.push_back(Structor(Priority, ~0U, Dtor, nullptr)); 2009 } 2010 2011 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { 2012 if (Fns.empty()) return; 2013 2014 // Ctor function type is void()*. 2015 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 2016 llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy, 2017 TheModule.getDataLayout().getProgramAddressSpace()); 2018 2019 // Get the type of a ctor entry, { i32, void ()*, i8* }. 2020 llvm::StructType *CtorStructTy = llvm::StructType::get( 2021 Int32Ty, CtorPFTy, VoidPtrTy); 2022 2023 // Construct the constructor and destructor arrays. 2024 ConstantInitBuilder builder(*this); 2025 auto ctors = builder.beginArray(CtorStructTy); 2026 for (const auto &I : Fns) { 2027 auto ctor = ctors.beginStruct(CtorStructTy); 2028 ctor.addInt(Int32Ty, I.Priority); 2029 ctor.add(I.Initializer); 2030 if (I.AssociatedData) 2031 ctor.add(I.AssociatedData); 2032 else 2033 ctor.addNullPointer(VoidPtrTy); 2034 ctor.finishAndAddTo(ctors); 2035 } 2036 2037 auto list = 2038 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(), 2039 /*constant*/ false, 2040 llvm::GlobalValue::AppendingLinkage); 2041 2042 // The LTO linker doesn't seem to like it when we set an alignment 2043 // on appending variables. Take it off as a workaround. 2044 list->setAlignment(std::nullopt); 2045 2046 Fns.clear(); 2047 } 2048 2049 llvm::GlobalValue::LinkageTypes 2050 CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 2051 const auto *D = cast<FunctionDecl>(GD.getDecl()); 2052 2053 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 2054 2055 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D)) 2056 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType()); 2057 2058 return getLLVMLinkageForDeclarator(D, Linkage); 2059 } 2060 2061 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { 2062 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 2063 if (!MDS) return nullptr; 2064 2065 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString())); 2066 } 2067 2068 llvm::ConstantInt *CodeGenModule::CreateKCFITypeId(QualType T) { 2069 if (auto *FnType = T->getAs<FunctionProtoType>()) 2070 T = getContext().getFunctionType( 2071 FnType->getReturnType(), FnType->getParamTypes(), 2072 FnType->getExtProtoInfo().withExceptionSpec(EST_None)); 2073 2074 std::string OutName; 2075 llvm::raw_string_ostream Out(OutName); 2076 getCXXABI().getMangleContext().mangleCanonicalTypeName( 2077 T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers); 2078 2079 if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers) 2080 Out << ".normalized"; 2081 2082 return llvm::ConstantInt::get(Int32Ty, 2083 static_cast<uint32_t>(llvm::xxHash64(OutName))); 2084 } 2085 2086 void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD, 2087 const CGFunctionInfo &Info, 2088 llvm::Function *F, bool IsThunk) { 2089 unsigned CallingConv; 2090 llvm::AttributeList PAL; 2091 ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, 2092 /*AttrOnCallSite=*/false, IsThunk); 2093 F->setAttributes(PAL); 2094 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 2095 } 2096 2097 static void removeImageAccessQualifier(std::string& TyName) { 2098 std::string ReadOnlyQual("__read_only"); 2099 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual); 2100 if (ReadOnlyPos != std::string::npos) 2101 // "+ 1" for the space after access qualifier. 2102 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1); 2103 else { 2104 std::string WriteOnlyQual("__write_only"); 2105 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual); 2106 if (WriteOnlyPos != std::string::npos) 2107 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1); 2108 else { 2109 std::string ReadWriteQual("__read_write"); 2110 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual); 2111 if (ReadWritePos != std::string::npos) 2112 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1); 2113 } 2114 } 2115 } 2116 2117 // Returns the address space id that should be produced to the 2118 // kernel_arg_addr_space metadata. This is always fixed to the ids 2119 // as specified in the SPIR 2.0 specification in order to differentiate 2120 // for example in clGetKernelArgInfo() implementation between the address 2121 // spaces with targets without unique mapping to the OpenCL address spaces 2122 // (basically all single AS CPUs). 2123 static unsigned ArgInfoAddressSpace(LangAS AS) { 2124 switch (AS) { 2125 case LangAS::opencl_global: 2126 return 1; 2127 case LangAS::opencl_constant: 2128 return 2; 2129 case LangAS::opencl_local: 2130 return 3; 2131 case LangAS::opencl_generic: 2132 return 4; // Not in SPIR 2.0 specs. 2133 case LangAS::opencl_global_device: 2134 return 5; 2135 case LangAS::opencl_global_host: 2136 return 6; 2137 default: 2138 return 0; // Assume private. 2139 } 2140 } 2141 2142 void CodeGenModule::GenKernelArgMetadata(llvm::Function *Fn, 2143 const FunctionDecl *FD, 2144 CodeGenFunction *CGF) { 2145 assert(((FD && CGF) || (!FD && !CGF)) && 2146 "Incorrect use - FD and CGF should either be both null or not!"); 2147 // Create MDNodes that represent the kernel arg metadata. 2148 // Each MDNode is a list in the form of "key", N number of values which is 2149 // the same number of values as their are kernel arguments. 2150 2151 const PrintingPolicy &Policy = Context.getPrintingPolicy(); 2152 2153 // MDNode for the kernel argument address space qualifiers. 2154 SmallVector<llvm::Metadata *, 8> addressQuals; 2155 2156 // MDNode for the kernel argument access qualifiers (images only). 2157 SmallVector<llvm::Metadata *, 8> accessQuals; 2158 2159 // MDNode for the kernel argument type names. 2160 SmallVector<llvm::Metadata *, 8> argTypeNames; 2161 2162 // MDNode for the kernel argument base type names. 2163 SmallVector<llvm::Metadata *, 8> argBaseTypeNames; 2164 2165 // MDNode for the kernel argument type qualifiers. 2166 SmallVector<llvm::Metadata *, 8> argTypeQuals; 2167 2168 // MDNode for the kernel argument names. 2169 SmallVector<llvm::Metadata *, 8> argNames; 2170 2171 if (FD && CGF) 2172 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { 2173 const ParmVarDecl *parm = FD->getParamDecl(i); 2174 // Get argument name. 2175 argNames.push_back(llvm::MDString::get(VMContext, parm->getName())); 2176 2177 if (!getLangOpts().OpenCL) 2178 continue; 2179 QualType ty = parm->getType(); 2180 std::string typeQuals; 2181 2182 // Get image and pipe access qualifier: 2183 if (ty->isImageType() || ty->isPipeType()) { 2184 const Decl *PDecl = parm; 2185 if (const auto *TD = ty->getAs<TypedefType>()) 2186 PDecl = TD->getDecl(); 2187 const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>(); 2188 if (A && A->isWriteOnly()) 2189 accessQuals.push_back(llvm::MDString::get(VMContext, "write_only")); 2190 else if (A && A->isReadWrite()) 2191 accessQuals.push_back(llvm::MDString::get(VMContext, "read_write")); 2192 else 2193 accessQuals.push_back(llvm::MDString::get(VMContext, "read_only")); 2194 } else 2195 accessQuals.push_back(llvm::MDString::get(VMContext, "none")); 2196 2197 auto getTypeSpelling = [&](QualType Ty) { 2198 auto typeName = Ty.getUnqualifiedType().getAsString(Policy); 2199 2200 if (Ty.isCanonical()) { 2201 StringRef typeNameRef = typeName; 2202 // Turn "unsigned type" to "utype" 2203 if (typeNameRef.consume_front("unsigned ")) 2204 return std::string("u") + typeNameRef.str(); 2205 if (typeNameRef.consume_front("signed ")) 2206 return typeNameRef.str(); 2207 } 2208 2209 return typeName; 2210 }; 2211 2212 if (ty->isPointerType()) { 2213 QualType pointeeTy = ty->getPointeeType(); 2214 2215 // Get address qualifier. 2216 addressQuals.push_back( 2217 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32( 2218 ArgInfoAddressSpace(pointeeTy.getAddressSpace())))); 2219 2220 // Get argument type name. 2221 std::string typeName = getTypeSpelling(pointeeTy) + "*"; 2222 std::string baseTypeName = 2223 getTypeSpelling(pointeeTy.getCanonicalType()) + "*"; 2224 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 2225 argBaseTypeNames.push_back( 2226 llvm::MDString::get(VMContext, baseTypeName)); 2227 2228 // Get argument type qualifiers: 2229 if (ty.isRestrictQualified()) 2230 typeQuals = "restrict"; 2231 if (pointeeTy.isConstQualified() || 2232 (pointeeTy.getAddressSpace() == LangAS::opencl_constant)) 2233 typeQuals += typeQuals.empty() ? "const" : " const"; 2234 if (pointeeTy.isVolatileQualified()) 2235 typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 2236 } else { 2237 uint32_t AddrSpc = 0; 2238 bool isPipe = ty->isPipeType(); 2239 if (ty->isImageType() || isPipe) 2240 AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global); 2241 2242 addressQuals.push_back( 2243 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc))); 2244 2245 // Get argument type name. 2246 ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty; 2247 std::string typeName = getTypeSpelling(ty); 2248 std::string baseTypeName = getTypeSpelling(ty.getCanonicalType()); 2249 2250 // Remove access qualifiers on images 2251 // (as they are inseparable from type in clang implementation, 2252 // but OpenCL spec provides a special query to get access qualifier 2253 // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER): 2254 if (ty->isImageType()) { 2255 removeImageAccessQualifier(typeName); 2256 removeImageAccessQualifier(baseTypeName); 2257 } 2258 2259 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 2260 argBaseTypeNames.push_back( 2261 llvm::MDString::get(VMContext, baseTypeName)); 2262 2263 if (isPipe) 2264 typeQuals = "pipe"; 2265 } 2266 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals)); 2267 } 2268 2269 if (getLangOpts().OpenCL) { 2270 Fn->setMetadata("kernel_arg_addr_space", 2271 llvm::MDNode::get(VMContext, addressQuals)); 2272 Fn->setMetadata("kernel_arg_access_qual", 2273 llvm::MDNode::get(VMContext, accessQuals)); 2274 Fn->setMetadata("kernel_arg_type", 2275 llvm::MDNode::get(VMContext, argTypeNames)); 2276 Fn->setMetadata("kernel_arg_base_type", 2277 llvm::MDNode::get(VMContext, argBaseTypeNames)); 2278 Fn->setMetadata("kernel_arg_type_qual", 2279 llvm::MDNode::get(VMContext, argTypeQuals)); 2280 } 2281 if (getCodeGenOpts().EmitOpenCLArgMetadata || 2282 getCodeGenOpts().HIPSaveKernelArgName) 2283 Fn->setMetadata("kernel_arg_name", 2284 llvm::MDNode::get(VMContext, argNames)); 2285 } 2286 2287 /// Determines whether the language options require us to model 2288 /// unwind exceptions. We treat -fexceptions as mandating this 2289 /// except under the fragile ObjC ABI with only ObjC exceptions 2290 /// enabled. This means, for example, that C with -fexceptions 2291 /// enables this. 2292 static bool hasUnwindExceptions(const LangOptions &LangOpts) { 2293 // If exceptions are completely disabled, obviously this is false. 2294 if (!LangOpts.Exceptions) return false; 2295 2296 // If C++ exceptions are enabled, this is true. 2297 if (LangOpts.CXXExceptions) return true; 2298 2299 // If ObjC exceptions are enabled, this depends on the ABI. 2300 if (LangOpts.ObjCExceptions) { 2301 return LangOpts.ObjCRuntime.hasUnwindExceptions(); 2302 } 2303 2304 return true; 2305 } 2306 2307 static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, 2308 const CXXMethodDecl *MD) { 2309 // Check that the type metadata can ever actually be used by a call. 2310 if (!CGM.getCodeGenOpts().LTOUnit || 2311 !CGM.HasHiddenLTOVisibility(MD->getParent())) 2312 return false; 2313 2314 // Only functions whose address can be taken with a member function pointer 2315 // need this sort of type metadata. 2316 return MD->isImplicitObjectMemberFunction() && !MD->isVirtual() && 2317 !isa<CXXConstructorDecl, CXXDestructorDecl>(MD); 2318 } 2319 2320 SmallVector<const CXXRecordDecl *, 0> 2321 CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) { 2322 llvm::SetVector<const CXXRecordDecl *> MostBases; 2323 2324 std::function<void (const CXXRecordDecl *)> CollectMostBases; 2325 CollectMostBases = [&](const CXXRecordDecl *RD) { 2326 if (RD->getNumBases() == 0) 2327 MostBases.insert(RD); 2328 for (const CXXBaseSpecifier &B : RD->bases()) 2329 CollectMostBases(B.getType()->getAsCXXRecordDecl()); 2330 }; 2331 CollectMostBases(RD); 2332 return MostBases.takeVector(); 2333 } 2334 2335 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 2336 llvm::Function *F) { 2337 llvm::AttrBuilder B(F->getContext()); 2338 2339 if ((!D || !D->hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables) 2340 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables)); 2341 2342 if (CodeGenOpts.StackClashProtector) 2343 B.addAttribute("probe-stack", "inline-asm"); 2344 2345 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096) 2346 B.addAttribute("stack-probe-size", 2347 std::to_string(CodeGenOpts.StackProbeSize)); 2348 2349 if (!hasUnwindExceptions(LangOpts)) 2350 B.addAttribute(llvm::Attribute::NoUnwind); 2351 2352 if (D && D->hasAttr<NoStackProtectorAttr>()) 2353 ; // Do nothing. 2354 else if (D && D->hasAttr<StrictGuardStackCheckAttr>() && 2355 isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn)) 2356 B.addAttribute(llvm::Attribute::StackProtectStrong); 2357 else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn)) 2358 B.addAttribute(llvm::Attribute::StackProtect); 2359 else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPStrong)) 2360 B.addAttribute(llvm::Attribute::StackProtectStrong); 2361 else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPReq)) 2362 B.addAttribute(llvm::Attribute::StackProtectReq); 2363 2364 if (!D) { 2365 // If we don't have a declaration to control inlining, the function isn't 2366 // explicitly marked as alwaysinline for semantic reasons, and inlining is 2367 // disabled, mark the function as noinline. 2368 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 2369 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) 2370 B.addAttribute(llvm::Attribute::NoInline); 2371 2372 F->addFnAttrs(B); 2373 return; 2374 } 2375 2376 // Handle SME attributes that apply to function definitions, 2377 // rather than to function prototypes. 2378 if (D->hasAttr<ArmLocallyStreamingAttr>()) 2379 B.addAttribute("aarch64_pstate_sm_body"); 2380 2381 if (D->hasAttr<ArmNewZAAttr>()) 2382 B.addAttribute("aarch64_pstate_za_new"); 2383 2384 // Track whether we need to add the optnone LLVM attribute, 2385 // starting with the default for this optimization level. 2386 bool ShouldAddOptNone = 2387 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0; 2388 // We can't add optnone in the following cases, it won't pass the verifier. 2389 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>(); 2390 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>(); 2391 2392 // Add optnone, but do so only if the function isn't always_inline. 2393 if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) && 2394 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 2395 B.addAttribute(llvm::Attribute::OptimizeNone); 2396 2397 // OptimizeNone implies noinline; we should not be inlining such functions. 2398 B.addAttribute(llvm::Attribute::NoInline); 2399 2400 // We still need to handle naked functions even though optnone subsumes 2401 // much of their semantics. 2402 if (D->hasAttr<NakedAttr>()) 2403 B.addAttribute(llvm::Attribute::Naked); 2404 2405 // OptimizeNone wins over OptimizeForSize and MinSize. 2406 F->removeFnAttr(llvm::Attribute::OptimizeForSize); 2407 F->removeFnAttr(llvm::Attribute::MinSize); 2408 } else if (D->hasAttr<NakedAttr>()) { 2409 // Naked implies noinline: we should not be inlining such functions. 2410 B.addAttribute(llvm::Attribute::Naked); 2411 B.addAttribute(llvm::Attribute::NoInline); 2412 } else if (D->hasAttr<NoDuplicateAttr>()) { 2413 B.addAttribute(llvm::Attribute::NoDuplicate); 2414 } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 2415 // Add noinline if the function isn't always_inline. 2416 B.addAttribute(llvm::Attribute::NoInline); 2417 } else if (D->hasAttr<AlwaysInlineAttr>() && 2418 !F->hasFnAttribute(llvm::Attribute::NoInline)) { 2419 // (noinline wins over always_inline, and we can't specify both in IR) 2420 B.addAttribute(llvm::Attribute::AlwaysInline); 2421 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { 2422 // If we're not inlining, then force everything that isn't always_inline to 2423 // carry an explicit noinline attribute. 2424 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) 2425 B.addAttribute(llvm::Attribute::NoInline); 2426 } else { 2427 // Otherwise, propagate the inline hint attribute and potentially use its 2428 // absence to mark things as noinline. 2429 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 2430 // Search function and template pattern redeclarations for inline. 2431 auto CheckForInline = [](const FunctionDecl *FD) { 2432 auto CheckRedeclForInline = [](const FunctionDecl *Redecl) { 2433 return Redecl->isInlineSpecified(); 2434 }; 2435 if (any_of(FD->redecls(), CheckRedeclForInline)) 2436 return true; 2437 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern(); 2438 if (!Pattern) 2439 return false; 2440 return any_of(Pattern->redecls(), CheckRedeclForInline); 2441 }; 2442 if (CheckForInline(FD)) { 2443 B.addAttribute(llvm::Attribute::InlineHint); 2444 } else if (CodeGenOpts.getInlining() == 2445 CodeGenOptions::OnlyHintInlining && 2446 !FD->isInlined() && 2447 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 2448 B.addAttribute(llvm::Attribute::NoInline); 2449 } 2450 } 2451 } 2452 2453 // Add other optimization related attributes if we are optimizing this 2454 // function. 2455 if (!D->hasAttr<OptimizeNoneAttr>()) { 2456 if (D->hasAttr<ColdAttr>()) { 2457 if (!ShouldAddOptNone) 2458 B.addAttribute(llvm::Attribute::OptimizeForSize); 2459 B.addAttribute(llvm::Attribute::Cold); 2460 } 2461 if (D->hasAttr<HotAttr>()) 2462 B.addAttribute(llvm::Attribute::Hot); 2463 if (D->hasAttr<MinSizeAttr>()) 2464 B.addAttribute(llvm::Attribute::MinSize); 2465 } 2466 2467 F->addFnAttrs(B); 2468 2469 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 2470 if (alignment) 2471 F->setAlignment(llvm::Align(alignment)); 2472 2473 if (!D->hasAttr<AlignedAttr>()) 2474 if (LangOpts.FunctionAlignment) 2475 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment)); 2476 2477 // Some C++ ABIs require 2-byte alignment for member functions, in order to 2478 // reserve a bit for differentiating between virtual and non-virtual member 2479 // functions. If the current target's C++ ABI requires this and this is a 2480 // member function, set its alignment accordingly. 2481 if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 2482 if (isa<CXXMethodDecl>(D) && F->getPointerAlignment(getDataLayout()) < 2) 2483 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne())); 2484 } 2485 2486 // In the cross-dso CFI mode with canonical jump tables, we want !type 2487 // attributes on definitions only. 2488 if (CodeGenOpts.SanitizeCfiCrossDso && 2489 CodeGenOpts.SanitizeCfiCanonicalJumpTables) { 2490 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 2491 // Skip available_externally functions. They won't be codegen'ed in the 2492 // current module anyway. 2493 if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally) 2494 CreateFunctionTypeMetadataForIcall(FD, F); 2495 } 2496 } 2497 2498 // Emit type metadata on member functions for member function pointer checks. 2499 // These are only ever necessary on definitions; we're guaranteed that the 2500 // definition will be present in the LTO unit as a result of LTO visibility. 2501 auto *MD = dyn_cast<CXXMethodDecl>(D); 2502 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) { 2503 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) { 2504 llvm::Metadata *Id = 2505 CreateMetadataIdentifierForType(Context.getMemberPointerType( 2506 MD->getType(), Context.getRecordType(Base).getTypePtr())); 2507 F->addTypeMetadata(0, Id); 2508 } 2509 } 2510 } 2511 2512 void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) { 2513 const Decl *D = GD.getDecl(); 2514 if (isa_and_nonnull<NamedDecl>(D)) 2515 setGVProperties(GV, GD); 2516 else 2517 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 2518 2519 if (D && D->hasAttr<UsedAttr>()) 2520 addUsedOrCompilerUsedGlobal(GV); 2521 2522 if (const auto *VD = dyn_cast_if_present<VarDecl>(D); 2523 VD && 2524 ((CodeGenOpts.KeepPersistentStorageVariables && 2525 (VD->getStorageDuration() == SD_Static || 2526 VD->getStorageDuration() == SD_Thread)) || 2527 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static && 2528 VD->getType().isConstQualified()))) 2529 addUsedOrCompilerUsedGlobal(GV); 2530 } 2531 2532 bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD, 2533 llvm::AttrBuilder &Attrs, 2534 bool SetTargetFeatures) { 2535 // Add target-cpu and target-features attributes to functions. If 2536 // we have a decl for the function and it has a target attribute then 2537 // parse that and add it to the feature set. 2538 StringRef TargetCPU = getTarget().getTargetOpts().CPU; 2539 StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU; 2540 std::vector<std::string> Features; 2541 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl()); 2542 FD = FD ? FD->getMostRecentDecl() : FD; 2543 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr; 2544 const auto *TV = FD ? FD->getAttr<TargetVersionAttr>() : nullptr; 2545 assert((!TD || !TV) && "both target_version and target specified"); 2546 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr; 2547 const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr; 2548 bool AddedAttr = false; 2549 if (TD || TV || SD || TC) { 2550 llvm::StringMap<bool> FeatureMap; 2551 getContext().getFunctionFeatureMap(FeatureMap, GD); 2552 2553 // Produce the canonical string for this set of features. 2554 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap) 2555 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str()); 2556 2557 // Now add the target-cpu and target-features to the function. 2558 // While we populated the feature map above, we still need to 2559 // get and parse the target attribute so we can get the cpu for 2560 // the function. 2561 if (TD) { 2562 ParsedTargetAttr ParsedAttr = 2563 Target.parseTargetAttr(TD->getFeaturesStr()); 2564 if (!ParsedAttr.CPU.empty() && 2565 getTarget().isValidCPUName(ParsedAttr.CPU)) { 2566 TargetCPU = ParsedAttr.CPU; 2567 TuneCPU = ""; // Clear the tune CPU. 2568 } 2569 if (!ParsedAttr.Tune.empty() && 2570 getTarget().isValidCPUName(ParsedAttr.Tune)) 2571 TuneCPU = ParsedAttr.Tune; 2572 } 2573 2574 if (SD) { 2575 // Apply the given CPU name as the 'tune-cpu' so that the optimizer can 2576 // favor this processor. 2577 TuneCPU = SD->getCPUName(GD.getMultiVersionIndex())->getName(); 2578 } 2579 } else { 2580 // Otherwise just add the existing target cpu and target features to the 2581 // function. 2582 Features = getTarget().getTargetOpts().Features; 2583 } 2584 2585 if (!TargetCPU.empty()) { 2586 Attrs.addAttribute("target-cpu", TargetCPU); 2587 AddedAttr = true; 2588 } 2589 if (!TuneCPU.empty()) { 2590 Attrs.addAttribute("tune-cpu", TuneCPU); 2591 AddedAttr = true; 2592 } 2593 if (!Features.empty() && SetTargetFeatures) { 2594 llvm::erase_if(Features, [&](const std::string& F) { 2595 return getTarget().isReadOnlyFeature(F.substr(1)); 2596 }); 2597 llvm::sort(Features); 2598 Attrs.addAttribute("target-features", llvm::join(Features, ",")); 2599 AddedAttr = true; 2600 } 2601 2602 return AddedAttr; 2603 } 2604 2605 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD, 2606 llvm::GlobalObject *GO) { 2607 const Decl *D = GD.getDecl(); 2608 SetCommonAttributes(GD, GO); 2609 2610 if (D) { 2611 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) { 2612 if (D->hasAttr<RetainAttr>()) 2613 addUsedGlobal(GV); 2614 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) 2615 GV->addAttribute("bss-section", SA->getName()); 2616 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) 2617 GV->addAttribute("data-section", SA->getName()); 2618 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) 2619 GV->addAttribute("rodata-section", SA->getName()); 2620 if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>()) 2621 GV->addAttribute("relro-section", SA->getName()); 2622 } 2623 2624 if (auto *F = dyn_cast<llvm::Function>(GO)) { 2625 if (D->hasAttr<RetainAttr>()) 2626 addUsedGlobal(F); 2627 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) 2628 if (!D->getAttr<SectionAttr>()) 2629 F->addFnAttr("implicit-section-name", SA->getName()); 2630 2631 llvm::AttrBuilder Attrs(F->getContext()); 2632 if (GetCPUAndFeaturesAttributes(GD, Attrs)) { 2633 // We know that GetCPUAndFeaturesAttributes will always have the 2634 // newest set, since it has the newest possible FunctionDecl, so the 2635 // new ones should replace the old. 2636 llvm::AttributeMask RemoveAttrs; 2637 RemoveAttrs.addAttribute("target-cpu"); 2638 RemoveAttrs.addAttribute("target-features"); 2639 RemoveAttrs.addAttribute("tune-cpu"); 2640 F->removeFnAttrs(RemoveAttrs); 2641 F->addFnAttrs(Attrs); 2642 } 2643 } 2644 2645 if (const auto *CSA = D->getAttr<CodeSegAttr>()) 2646 GO->setSection(CSA->getName()); 2647 else if (const auto *SA = D->getAttr<SectionAttr>()) 2648 GO->setSection(SA->getName()); 2649 } 2650 2651 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 2652 } 2653 2654 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD, 2655 llvm::Function *F, 2656 const CGFunctionInfo &FI) { 2657 const Decl *D = GD.getDecl(); 2658 SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false); 2659 SetLLVMFunctionAttributesForDefinition(D, F); 2660 2661 F->setLinkage(llvm::Function::InternalLinkage); 2662 2663 setNonAliasAttributes(GD, F); 2664 } 2665 2666 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) { 2667 // Set linkage and visibility in case we never see a definition. 2668 LinkageInfo LV = ND->getLinkageAndVisibility(); 2669 // Don't set internal linkage on declarations. 2670 // "extern_weak" is overloaded in LLVM; we probably should have 2671 // separate linkage types for this. 2672 if (isExternallyVisible(LV.getLinkage()) && 2673 (ND->hasAttr<WeakAttr>() || ND->isWeakImported())) 2674 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 2675 } 2676 2677 void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, 2678 llvm::Function *F) { 2679 // Only if we are checking indirect calls. 2680 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 2681 return; 2682 2683 // Non-static class methods are handled via vtable or member function pointer 2684 // checks elsewhere. 2685 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 2686 return; 2687 2688 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 2689 F->addTypeMetadata(0, MD); 2690 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType())); 2691 2692 // Emit a hash-based bit set entry for cross-DSO calls. 2693 if (CodeGenOpts.SanitizeCfiCrossDso) 2694 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 2695 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 2696 } 2697 2698 void CodeGenModule::setKCFIType(const FunctionDecl *FD, llvm::Function *F) { 2699 llvm::LLVMContext &Ctx = F->getContext(); 2700 llvm::MDBuilder MDB(Ctx); 2701 F->setMetadata(llvm::LLVMContext::MD_kcfi_type, 2702 llvm::MDNode::get( 2703 Ctx, MDB.createConstant(CreateKCFITypeId(FD->getType())))); 2704 } 2705 2706 static bool allowKCFIIdentifier(StringRef Name) { 2707 // KCFI type identifier constants are only necessary for external assembly 2708 // functions, which means it's safe to skip unusual names. Subset of 2709 // MCAsmInfo::isAcceptableChar() and MCAsmInfoXCOFF::isAcceptableChar(). 2710 return llvm::all_of(Name, [](const char &C) { 2711 return llvm::isAlnum(C) || C == '_' || C == '.'; 2712 }); 2713 } 2714 2715 void CodeGenModule::finalizeKCFITypes() { 2716 llvm::Module &M = getModule(); 2717 for (auto &F : M.functions()) { 2718 // Remove KCFI type metadata from non-address-taken local functions. 2719 bool AddressTaken = F.hasAddressTaken(); 2720 if (!AddressTaken && F.hasLocalLinkage()) 2721 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type); 2722 2723 // Generate a constant with the expected KCFI type identifier for all 2724 // address-taken function declarations to support annotating indirectly 2725 // called assembly functions. 2726 if (!AddressTaken || !F.isDeclaration()) 2727 continue; 2728 2729 const llvm::ConstantInt *Type; 2730 if (const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type)) 2731 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0)); 2732 else 2733 continue; 2734 2735 StringRef Name = F.getName(); 2736 if (!allowKCFIIdentifier(Name)) 2737 continue; 2738 2739 std::string Asm = (".weak __kcfi_typeid_" + Name + "\n.set __kcfi_typeid_" + 2740 Name + ", " + Twine(Type->getZExtValue()) + "\n") 2741 .str(); 2742 M.appendModuleInlineAsm(Asm); 2743 } 2744 } 2745 2746 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 2747 bool IsIncompleteFunction, 2748 bool IsThunk) { 2749 2750 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 2751 // If this is an intrinsic function, set the function's attributes 2752 // to the intrinsic's attributes. 2753 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 2754 return; 2755 } 2756 2757 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 2758 2759 if (!IsIncompleteFunction) 2760 SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F, 2761 IsThunk); 2762 2763 // Add the Returned attribute for "this", except for iOS 5 and earlier 2764 // where substantial code, including the libstdc++ dylib, was compiled with 2765 // GCC and does not actually return "this". 2766 if (!IsThunk && getCXXABI().HasThisReturn(GD) && 2767 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { 2768 assert(!F->arg_empty() && 2769 F->arg_begin()->getType() 2770 ->canLosslesslyBitCastTo(F->getReturnType()) && 2771 "unexpected this return"); 2772 F->addParamAttr(0, llvm::Attribute::Returned); 2773 } 2774 2775 // Only a few attributes are set on declarations; these may later be 2776 // overridden by a definition. 2777 2778 setLinkageForGV(F, FD); 2779 setGVProperties(F, FD); 2780 2781 // Setup target-specific attributes. 2782 if (!IsIncompleteFunction && F->isDeclaration()) 2783 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this); 2784 2785 if (const auto *CSA = FD->getAttr<CodeSegAttr>()) 2786 F->setSection(CSA->getName()); 2787 else if (const auto *SA = FD->getAttr<SectionAttr>()) 2788 F->setSection(SA->getName()); 2789 2790 if (const auto *EA = FD->getAttr<ErrorAttr>()) { 2791 if (EA->isError()) 2792 F->addFnAttr("dontcall-error", EA->getUserDiagnostic()); 2793 else if (EA->isWarning()) 2794 F->addFnAttr("dontcall-warn", EA->getUserDiagnostic()); 2795 } 2796 2797 // If we plan on emitting this inline builtin, we can't treat it as a builtin. 2798 if (FD->isInlineBuiltinDeclaration()) { 2799 const FunctionDecl *FDBody; 2800 bool HasBody = FD->hasBody(FDBody); 2801 (void)HasBody; 2802 assert(HasBody && "Inline builtin declarations should always have an " 2803 "available body!"); 2804 if (shouldEmitFunction(FDBody)) 2805 F->addFnAttr(llvm::Attribute::NoBuiltin); 2806 } 2807 2808 if (FD->isReplaceableGlobalAllocationFunction()) { 2809 // A replaceable global allocation function does not act like a builtin by 2810 // default, only if it is invoked by a new-expression or delete-expression. 2811 F->addFnAttr(llvm::Attribute::NoBuiltin); 2812 } 2813 2814 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 2815 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2816 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 2817 if (MD->isVirtual()) 2818 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2819 2820 // Don't emit entries for function declarations in the cross-DSO mode. This 2821 // is handled with better precision by the receiving DSO. But if jump tables 2822 // are non-canonical then we need type metadata in order to produce the local 2823 // jump table. 2824 if (!CodeGenOpts.SanitizeCfiCrossDso || 2825 !CodeGenOpts.SanitizeCfiCanonicalJumpTables) 2826 CreateFunctionTypeMetadataForIcall(FD, F); 2827 2828 if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) 2829 setKCFIType(FD, F); 2830 2831 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) 2832 getOpenMPRuntime().emitDeclareSimdFunction(FD, F); 2833 2834 if (CodeGenOpts.InlineMaxStackSize != UINT_MAX) 2835 F->addFnAttr("inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize)); 2836 2837 if (const auto *CB = FD->getAttr<CallbackAttr>()) { 2838 // Annotate the callback behavior as metadata: 2839 // - The callback callee (as argument number). 2840 // - The callback payloads (as argument numbers). 2841 llvm::LLVMContext &Ctx = F->getContext(); 2842 llvm::MDBuilder MDB(Ctx); 2843 2844 // The payload indices are all but the first one in the encoding. The first 2845 // identifies the callback callee. 2846 int CalleeIdx = *CB->encoding_begin(); 2847 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end()); 2848 F->addMetadata(llvm::LLVMContext::MD_callback, 2849 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding( 2850 CalleeIdx, PayloadIndices, 2851 /* VarArgsArePassed */ false)})); 2852 } 2853 } 2854 2855 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 2856 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 2857 "Only globals with definition can force usage."); 2858 LLVMUsed.emplace_back(GV); 2859 } 2860 2861 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 2862 assert(!GV->isDeclaration() && 2863 "Only globals with definition can force usage."); 2864 LLVMCompilerUsed.emplace_back(GV); 2865 } 2866 2867 void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) { 2868 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 2869 "Only globals with definition can force usage."); 2870 if (getTriple().isOSBinFormatELF()) 2871 LLVMCompilerUsed.emplace_back(GV); 2872 else 2873 LLVMUsed.emplace_back(GV); 2874 } 2875 2876 static void emitUsed(CodeGenModule &CGM, StringRef Name, 2877 std::vector<llvm::WeakTrackingVH> &List) { 2878 // Don't create llvm.used if there is no need. 2879 if (List.empty()) 2880 return; 2881 2882 // Convert List to what ConstantArray needs. 2883 SmallVector<llvm::Constant*, 8> UsedArray; 2884 UsedArray.resize(List.size()); 2885 for (unsigned i = 0, e = List.size(); i != e; ++i) { 2886 UsedArray[i] = 2887 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 2888 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 2889 } 2890 2891 if (UsedArray.empty()) 2892 return; 2893 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 2894 2895 auto *GV = new llvm::GlobalVariable( 2896 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 2897 llvm::ConstantArray::get(ATy, UsedArray), Name); 2898 2899 GV->setSection("llvm.metadata"); 2900 } 2901 2902 void CodeGenModule::emitLLVMUsed() { 2903 emitUsed(*this, "llvm.used", LLVMUsed); 2904 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 2905 } 2906 2907 void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 2908 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 2909 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 2910 } 2911 2912 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 2913 llvm::SmallString<32> Opt; 2914 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 2915 if (Opt.empty()) 2916 return; 2917 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 2918 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 2919 } 2920 2921 void CodeGenModule::AddDependentLib(StringRef Lib) { 2922 auto &C = getLLVMContext(); 2923 if (getTarget().getTriple().isOSBinFormatELF()) { 2924 ELFDependentLibraries.push_back( 2925 llvm::MDNode::get(C, llvm::MDString::get(C, Lib))); 2926 return; 2927 } 2928 2929 llvm::SmallString<24> Opt; 2930 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 2931 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 2932 LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts)); 2933 } 2934 2935 /// Add link options implied by the given module, including modules 2936 /// it depends on, using a postorder walk. 2937 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 2938 SmallVectorImpl<llvm::MDNode *> &Metadata, 2939 llvm::SmallPtrSet<Module *, 16> &Visited) { 2940 // Import this module's parent. 2941 if (Mod->Parent && Visited.insert(Mod->Parent).second) { 2942 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 2943 } 2944 2945 // Import this module's dependencies. 2946 for (Module *Import : llvm::reverse(Mod->Imports)) { 2947 if (Visited.insert(Import).second) 2948 addLinkOptionsPostorder(CGM, Import, Metadata, Visited); 2949 } 2950 2951 // Add linker options to link against the libraries/frameworks 2952 // described by this module. 2953 llvm::LLVMContext &Context = CGM.getLLVMContext(); 2954 bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF(); 2955 2956 // For modules that use export_as for linking, use that module 2957 // name instead. 2958 if (Mod->UseExportAsModuleLinkName) 2959 return; 2960 2961 for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) { 2962 // Link against a framework. Frameworks are currently Darwin only, so we 2963 // don't to ask TargetCodeGenInfo for the spelling of the linker option. 2964 if (LL.IsFramework) { 2965 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"), 2966 llvm::MDString::get(Context, LL.Library)}; 2967 2968 Metadata.push_back(llvm::MDNode::get(Context, Args)); 2969 continue; 2970 } 2971 2972 // Link against a library. 2973 if (IsELF) { 2974 llvm::Metadata *Args[2] = { 2975 llvm::MDString::get(Context, "lib"), 2976 llvm::MDString::get(Context, LL.Library), 2977 }; 2978 Metadata.push_back(llvm::MDNode::get(Context, Args)); 2979 } else { 2980 llvm::SmallString<24> Opt; 2981 CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt); 2982 auto *OptString = llvm::MDString::get(Context, Opt); 2983 Metadata.push_back(llvm::MDNode::get(Context, OptString)); 2984 } 2985 } 2986 } 2987 2988 void CodeGenModule::EmitModuleInitializers(clang::Module *Primary) { 2989 assert(Primary->isNamedModuleUnit() && 2990 "We should only emit module initializers for named modules."); 2991 2992 // Emit the initializers in the order that sub-modules appear in the 2993 // source, first Global Module Fragments, if present. 2994 if (auto GMF = Primary->getGlobalModuleFragment()) { 2995 for (Decl *D : getContext().getModuleInitializers(GMF)) { 2996 if (isa<ImportDecl>(D)) 2997 continue; 2998 assert(isa<VarDecl>(D) && "GMF initializer decl is not a var?"); 2999 EmitTopLevelDecl(D); 3000 } 3001 } 3002 // Second any associated with the module, itself. 3003 for (Decl *D : getContext().getModuleInitializers(Primary)) { 3004 // Skip import decls, the inits for those are called explicitly. 3005 if (isa<ImportDecl>(D)) 3006 continue; 3007 EmitTopLevelDecl(D); 3008 } 3009 // Third any associated with the Privat eMOdule Fragment, if present. 3010 if (auto PMF = Primary->getPrivateModuleFragment()) { 3011 for (Decl *D : getContext().getModuleInitializers(PMF)) { 3012 // Skip import decls, the inits for those are called explicitly. 3013 if (isa<ImportDecl>(D)) 3014 continue; 3015 assert(isa<VarDecl>(D) && "PMF initializer decl is not a var?"); 3016 EmitTopLevelDecl(D); 3017 } 3018 } 3019 } 3020 3021 void CodeGenModule::EmitModuleLinkOptions() { 3022 // Collect the set of all of the modules we want to visit to emit link 3023 // options, which is essentially the imported modules and all of their 3024 // non-explicit child modules. 3025 llvm::SetVector<clang::Module *> LinkModules; 3026 llvm::SmallPtrSet<clang::Module *, 16> Visited; 3027 SmallVector<clang::Module *, 16> Stack; 3028 3029 // Seed the stack with imported modules. 3030 for (Module *M : ImportedModules) { 3031 // Do not add any link flags when an implementation TU of a module imports 3032 // a header of that same module. 3033 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && 3034 !getLangOpts().isCompilingModule()) 3035 continue; 3036 if (Visited.insert(M).second) 3037 Stack.push_back(M); 3038 } 3039 3040 // Find all of the modules to import, making a little effort to prune 3041 // non-leaf modules. 3042 while (!Stack.empty()) { 3043 clang::Module *Mod = Stack.pop_back_val(); 3044 3045 bool AnyChildren = false; 3046 3047 // Visit the submodules of this module. 3048 for (const auto &SM : Mod->submodules()) { 3049 // Skip explicit children; they need to be explicitly imported to be 3050 // linked against. 3051 if (SM->IsExplicit) 3052 continue; 3053 3054 if (Visited.insert(SM).second) { 3055 Stack.push_back(SM); 3056 AnyChildren = true; 3057 } 3058 } 3059 3060 // We didn't find any children, so add this module to the list of 3061 // modules to link against. 3062 if (!AnyChildren) { 3063 LinkModules.insert(Mod); 3064 } 3065 } 3066 3067 // Add link options for all of the imported modules in reverse topological 3068 // order. We don't do anything to try to order import link flags with respect 3069 // to linker options inserted by things like #pragma comment(). 3070 SmallVector<llvm::MDNode *, 16> MetadataArgs; 3071 Visited.clear(); 3072 for (Module *M : LinkModules) 3073 if (Visited.insert(M).second) 3074 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 3075 std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 3076 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 3077 3078 // Add the linker options metadata flag. 3079 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options"); 3080 for (auto *MD : LinkerOptionsMetadata) 3081 NMD->addOperand(MD); 3082 } 3083 3084 void CodeGenModule::EmitDeferred() { 3085 // Emit deferred declare target declarations. 3086 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 3087 getOpenMPRuntime().emitDeferredTargetDecls(); 3088 3089 // Emit code for any potentially referenced deferred decls. Since a 3090 // previously unused static decl may become used during the generation of code 3091 // for a static function, iterate until no changes are made. 3092 3093 if (!DeferredVTables.empty()) { 3094 EmitDeferredVTables(); 3095 3096 // Emitting a vtable doesn't directly cause more vtables to 3097 // become deferred, although it can cause functions to be 3098 // emitted that then need those vtables. 3099 assert(DeferredVTables.empty()); 3100 } 3101 3102 // Emit CUDA/HIP static device variables referenced by host code only. 3103 // Note we should not clear CUDADeviceVarODRUsedByHost since it is still 3104 // needed for further handling. 3105 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) 3106 llvm::append_range(DeferredDeclsToEmit, 3107 getContext().CUDADeviceVarODRUsedByHost); 3108 3109 // Stop if we're out of both deferred vtables and deferred declarations. 3110 if (DeferredDeclsToEmit.empty()) 3111 return; 3112 3113 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 3114 // work, it will not interfere with this. 3115 std::vector<GlobalDecl> CurDeclsToEmit; 3116 CurDeclsToEmit.swap(DeferredDeclsToEmit); 3117 3118 for (GlobalDecl &D : CurDeclsToEmit) { 3119 // We should call GetAddrOfGlobal with IsForDefinition set to true in order 3120 // to get GlobalValue with exactly the type we need, not something that 3121 // might had been created for another decl with the same mangled name but 3122 // different type. 3123 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 3124 GetAddrOfGlobal(D, ForDefinition)); 3125 3126 // In case of different address spaces, we may still get a cast, even with 3127 // IsForDefinition equal to true. Query mangled names table to get 3128 // GlobalValue. 3129 if (!GV) 3130 GV = GetGlobalValue(getMangledName(D)); 3131 3132 // Make sure GetGlobalValue returned non-null. 3133 assert(GV); 3134 3135 // Check to see if we've already emitted this. This is necessary 3136 // for a couple of reasons: first, decls can end up in the 3137 // deferred-decls queue multiple times, and second, decls can end 3138 // up with definitions in unusual ways (e.g. by an extern inline 3139 // function acquiring a strong function redefinition). Just 3140 // ignore these cases. 3141 if (!GV->isDeclaration()) 3142 continue; 3143 3144 // If this is OpenMP, check if it is legal to emit this global normally. 3145 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D)) 3146 continue; 3147 3148 // Otherwise, emit the definition and move on to the next one. 3149 EmitGlobalDefinition(D, GV); 3150 3151 // If we found out that we need to emit more decls, do that recursively. 3152 // This has the advantage that the decls are emitted in a DFS and related 3153 // ones are close together, which is convenient for testing. 3154 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 3155 EmitDeferred(); 3156 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 3157 } 3158 } 3159 } 3160 3161 void CodeGenModule::EmitVTablesOpportunistically() { 3162 // Try to emit external vtables as available_externally if they have emitted 3163 // all inlined virtual functions. It runs after EmitDeferred() and therefore 3164 // is not allowed to create new references to things that need to be emitted 3165 // lazily. Note that it also uses fact that we eagerly emitting RTTI. 3166 3167 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) 3168 && "Only emit opportunistic vtables with optimizations"); 3169 3170 for (const CXXRecordDecl *RD : OpportunisticVTables) { 3171 assert(getVTables().isVTableExternal(RD) && 3172 "This queue should only contain external vtables"); 3173 if (getCXXABI().canSpeculativelyEmitVTable(RD)) 3174 VTables.GenerateClassData(RD); 3175 } 3176 OpportunisticVTables.clear(); 3177 } 3178 3179 void CodeGenModule::EmitGlobalAnnotations() { 3180 for (const auto& [MangledName, VD] : DeferredAnnotations) { 3181 llvm::GlobalValue *GV = GetGlobalValue(MangledName); 3182 if (GV) 3183 AddGlobalAnnotations(VD, GV); 3184 } 3185 DeferredAnnotations.clear(); 3186 3187 if (Annotations.empty()) 3188 return; 3189 3190 // Create a new global variable for the ConstantStruct in the Module. 3191 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 3192 Annotations[0]->getType(), Annotations.size()), Annotations); 3193 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 3194 llvm::GlobalValue::AppendingLinkage, 3195 Array, "llvm.global.annotations"); 3196 gv->setSection(AnnotationSection); 3197 } 3198 3199 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 3200 llvm::Constant *&AStr = AnnotationStrings[Str]; 3201 if (AStr) 3202 return AStr; 3203 3204 // Not found yet, create a new global. 3205 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 3206 auto *gv = new llvm::GlobalVariable( 3207 getModule(), s->getType(), true, llvm::GlobalValue::PrivateLinkage, s, 3208 ".str", nullptr, llvm::GlobalValue::NotThreadLocal, 3209 ConstGlobalsPtrTy->getAddressSpace()); 3210 gv->setSection(AnnotationSection); 3211 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3212 AStr = gv; 3213 return gv; 3214 } 3215 3216 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 3217 SourceManager &SM = getContext().getSourceManager(); 3218 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 3219 if (PLoc.isValid()) 3220 return EmitAnnotationString(PLoc.getFilename()); 3221 return EmitAnnotationString(SM.getBufferName(Loc)); 3222 } 3223 3224 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 3225 SourceManager &SM = getContext().getSourceManager(); 3226 PresumedLoc PLoc = SM.getPresumedLoc(L); 3227 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 3228 SM.getExpansionLineNumber(L); 3229 return llvm::ConstantInt::get(Int32Ty, LineNo); 3230 } 3231 3232 llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) { 3233 ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()}; 3234 if (Exprs.empty()) 3235 return llvm::ConstantPointerNull::get(ConstGlobalsPtrTy); 3236 3237 llvm::FoldingSetNodeID ID; 3238 for (Expr *E : Exprs) { 3239 ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult()); 3240 } 3241 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()]; 3242 if (Lookup) 3243 return Lookup; 3244 3245 llvm::SmallVector<llvm::Constant *, 4> LLVMArgs; 3246 LLVMArgs.reserve(Exprs.size()); 3247 ConstantEmitter ConstEmiter(*this); 3248 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) { 3249 const auto *CE = cast<clang::ConstantExpr>(E); 3250 return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(), 3251 CE->getType()); 3252 }); 3253 auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs); 3254 auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true, 3255 llvm::GlobalValue::PrivateLinkage, Struct, 3256 ".args"); 3257 GV->setSection(AnnotationSection); 3258 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3259 3260 Lookup = GV; 3261 return GV; 3262 } 3263 3264 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 3265 const AnnotateAttr *AA, 3266 SourceLocation L) { 3267 // Get the globals for file name, annotation, and the line number. 3268 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 3269 *UnitGV = EmitAnnotationUnit(L), 3270 *LineNoCst = EmitAnnotationLineNo(L), 3271 *Args = EmitAnnotationArgs(AA); 3272 3273 llvm::Constant *GVInGlobalsAS = GV; 3274 if (GV->getAddressSpace() != 3275 getDataLayout().getDefaultGlobalsAddressSpace()) { 3276 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast( 3277 GV, 3278 llvm::PointerType::get( 3279 GV->getContext(), getDataLayout().getDefaultGlobalsAddressSpace())); 3280 } 3281 3282 // Create the ConstantStruct for the global annotation. 3283 llvm::Constant *Fields[] = { 3284 GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args, 3285 }; 3286 return llvm::ConstantStruct::getAnon(Fields); 3287 } 3288 3289 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 3290 llvm::GlobalValue *GV) { 3291 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 3292 // Get the struct elements for these annotations. 3293 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 3294 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 3295 } 3296 3297 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, 3298 SourceLocation Loc) const { 3299 const auto &NoSanitizeL = getContext().getNoSanitizeList(); 3300 // NoSanitize by function name. 3301 if (NoSanitizeL.containsFunction(Kind, Fn->getName())) 3302 return true; 3303 // NoSanitize by location. Check "mainfile" prefix. 3304 auto &SM = Context.getSourceManager(); 3305 FileEntryRef MainFile = *SM.getFileEntryRefForID(SM.getMainFileID()); 3306 if (NoSanitizeL.containsMainFile(Kind, MainFile.getName())) 3307 return true; 3308 3309 // Check "src" prefix. 3310 if (Loc.isValid()) 3311 return NoSanitizeL.containsLocation(Kind, Loc); 3312 // If location is unknown, this may be a compiler-generated function. Assume 3313 // it's located in the main file. 3314 return NoSanitizeL.containsFile(Kind, MainFile.getName()); 3315 } 3316 3317 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, 3318 llvm::GlobalVariable *GV, 3319 SourceLocation Loc, QualType Ty, 3320 StringRef Category) const { 3321 const auto &NoSanitizeL = getContext().getNoSanitizeList(); 3322 if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category)) 3323 return true; 3324 auto &SM = Context.getSourceManager(); 3325 if (NoSanitizeL.containsMainFile( 3326 Kind, SM.getFileEntryRefForID(SM.getMainFileID())->getName(), 3327 Category)) 3328 return true; 3329 if (NoSanitizeL.containsLocation(Kind, Loc, Category)) 3330 return true; 3331 3332 // Check global type. 3333 if (!Ty.isNull()) { 3334 // Drill down the array types: if global variable of a fixed type is 3335 // not sanitized, we also don't instrument arrays of them. 3336 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 3337 Ty = AT->getElementType(); 3338 Ty = Ty.getCanonicalType().getUnqualifiedType(); 3339 // Only record types (classes, structs etc.) are ignored. 3340 if (Ty->isRecordType()) { 3341 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 3342 if (NoSanitizeL.containsType(Kind, TypeStr, Category)) 3343 return true; 3344 } 3345 } 3346 return false; 3347 } 3348 3349 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 3350 StringRef Category) const { 3351 const auto &XRayFilter = getContext().getXRayFilter(); 3352 using ImbueAttr = XRayFunctionFilter::ImbueAttribute; 3353 auto Attr = ImbueAttr::NONE; 3354 if (Loc.isValid()) 3355 Attr = XRayFilter.shouldImbueLocation(Loc, Category); 3356 if (Attr == ImbueAttr::NONE) 3357 Attr = XRayFilter.shouldImbueFunction(Fn->getName()); 3358 switch (Attr) { 3359 case ImbueAttr::NONE: 3360 return false; 3361 case ImbueAttr::ALWAYS: 3362 Fn->addFnAttr("function-instrument", "xray-always"); 3363 break; 3364 case ImbueAttr::ALWAYS_ARG1: 3365 Fn->addFnAttr("function-instrument", "xray-always"); 3366 Fn->addFnAttr("xray-log-args", "1"); 3367 break; 3368 case ImbueAttr::NEVER: 3369 Fn->addFnAttr("function-instrument", "xray-never"); 3370 break; 3371 } 3372 return true; 3373 } 3374 3375 ProfileList::ExclusionType 3376 CodeGenModule::isFunctionBlockedByProfileList(llvm::Function *Fn, 3377 SourceLocation Loc) const { 3378 const auto &ProfileList = getContext().getProfileList(); 3379 // If the profile list is empty, then instrument everything. 3380 if (ProfileList.isEmpty()) 3381 return ProfileList::Allow; 3382 CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr(); 3383 // First, check the function name. 3384 if (auto V = ProfileList.isFunctionExcluded(Fn->getName(), Kind)) 3385 return *V; 3386 // Next, check the source location. 3387 if (Loc.isValid()) 3388 if (auto V = ProfileList.isLocationExcluded(Loc, Kind)) 3389 return *V; 3390 // If location is unknown, this may be a compiler-generated function. Assume 3391 // it's located in the main file. 3392 auto &SM = Context.getSourceManager(); 3393 if (auto MainFile = SM.getFileEntryRefForID(SM.getMainFileID())) 3394 if (auto V = ProfileList.isFileExcluded(MainFile->getName(), Kind)) 3395 return *V; 3396 return ProfileList.getDefault(Kind); 3397 } 3398 3399 ProfileList::ExclusionType 3400 CodeGenModule::isFunctionBlockedFromProfileInstr(llvm::Function *Fn, 3401 SourceLocation Loc) const { 3402 auto V = isFunctionBlockedByProfileList(Fn, Loc); 3403 if (V != ProfileList::Allow) 3404 return V; 3405 3406 auto NumGroups = getCodeGenOpts().ProfileTotalFunctionGroups; 3407 if (NumGroups > 1) { 3408 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups; 3409 if (Group != getCodeGenOpts().ProfileSelectedFunctionGroup) 3410 return ProfileList::Skip; 3411 } 3412 return ProfileList::Allow; 3413 } 3414 3415 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 3416 // Never defer when EmitAllDecls is specified. 3417 if (LangOpts.EmitAllDecls) 3418 return true; 3419 3420 const auto *VD = dyn_cast<VarDecl>(Global); 3421 if (VD && 3422 ((CodeGenOpts.KeepPersistentStorageVariables && 3423 (VD->getStorageDuration() == SD_Static || 3424 VD->getStorageDuration() == SD_Thread)) || 3425 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static && 3426 VD->getType().isConstQualified()))) 3427 return true; 3428 3429 return getContext().DeclMustBeEmitted(Global); 3430 } 3431 3432 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 3433 // In OpenMP 5.0 variables and function may be marked as 3434 // device_type(host/nohost) and we should not emit them eagerly unless we sure 3435 // that they must be emitted on the host/device. To be sure we need to have 3436 // seen a declare target with an explicit mentioning of the function, we know 3437 // we have if the level of the declare target attribute is -1. Note that we 3438 // check somewhere else if we should emit this at all. 3439 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) { 3440 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr = 3441 OMPDeclareTargetDeclAttr::getActiveAttr(Global); 3442 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1) 3443 return false; 3444 } 3445 3446 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 3447 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 3448 // Implicit template instantiations may change linkage if they are later 3449 // explicitly instantiated, so they should not be emitted eagerly. 3450 return false; 3451 } 3452 if (const auto *VD = dyn_cast<VarDecl>(Global)) { 3453 if (Context.getInlineVariableDefinitionKind(VD) == 3454 ASTContext::InlineVariableDefinitionKind::WeakUnknown) 3455 // A definition of an inline constexpr static data member may change 3456 // linkage later if it's redeclared outside the class. 3457 return false; 3458 if (CXX20ModuleInits && VD->getOwningModule() && 3459 !VD->getOwningModule()->isModuleMapModule()) { 3460 // For CXX20, module-owned initializers need to be deferred, since it is 3461 // not known at this point if they will be run for the current module or 3462 // as part of the initializer for an imported one. 3463 return false; 3464 } 3465 } 3466 // If OpenMP is enabled and threadprivates must be generated like TLS, delay 3467 // codegen for global variables, because they may be marked as threadprivate. 3468 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 3469 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) && 3470 !Global->getType().isConstantStorage(getContext(), false, false) && 3471 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global)) 3472 return false; 3473 3474 return true; 3475 } 3476 3477 ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) { 3478 StringRef Name = getMangledName(GD); 3479 3480 // The UUID descriptor should be pointer aligned. 3481 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 3482 3483 // Look for an existing global. 3484 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 3485 return ConstantAddress(GV, GV->getValueType(), Alignment); 3486 3487 ConstantEmitter Emitter(*this); 3488 llvm::Constant *Init; 3489 3490 APValue &V = GD->getAsAPValue(); 3491 if (!V.isAbsent()) { 3492 // If possible, emit the APValue version of the initializer. In particular, 3493 // this gets the type of the constant right. 3494 Init = Emitter.emitForInitializer( 3495 GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType()); 3496 } else { 3497 // As a fallback, directly construct the constant. 3498 // FIXME: This may get padding wrong under esoteric struct layout rules. 3499 // MSVC appears to create a complete type 'struct __s_GUID' that it 3500 // presumably uses to represent these constants. 3501 MSGuidDecl::Parts Parts = GD->getParts(); 3502 llvm::Constant *Fields[4] = { 3503 llvm::ConstantInt::get(Int32Ty, Parts.Part1), 3504 llvm::ConstantInt::get(Int16Ty, Parts.Part2), 3505 llvm::ConstantInt::get(Int16Ty, Parts.Part3), 3506 llvm::ConstantDataArray::getRaw( 3507 StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8, 3508 Int8Ty)}; 3509 Init = llvm::ConstantStruct::getAnon(Fields); 3510 } 3511 3512 auto *GV = new llvm::GlobalVariable( 3513 getModule(), Init->getType(), 3514 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 3515 if (supportsCOMDAT()) 3516 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3517 setDSOLocal(GV); 3518 3519 if (!V.isAbsent()) { 3520 Emitter.finalize(GV); 3521 return ConstantAddress(GV, GV->getValueType(), Alignment); 3522 } 3523 3524 llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType()); 3525 return ConstantAddress(GV, Ty, Alignment); 3526 } 3527 3528 ConstantAddress CodeGenModule::GetAddrOfUnnamedGlobalConstantDecl( 3529 const UnnamedGlobalConstantDecl *GCD) { 3530 CharUnits Alignment = getContext().getTypeAlignInChars(GCD->getType()); 3531 3532 llvm::GlobalVariable **Entry = nullptr; 3533 Entry = &UnnamedGlobalConstantDeclMap[GCD]; 3534 if (*Entry) 3535 return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment); 3536 3537 ConstantEmitter Emitter(*this); 3538 llvm::Constant *Init; 3539 3540 const APValue &V = GCD->getValue(); 3541 3542 assert(!V.isAbsent()); 3543 Init = Emitter.emitForInitializer(V, GCD->getType().getAddressSpace(), 3544 GCD->getType()); 3545 3546 auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(), 3547 /*isConstant=*/true, 3548 llvm::GlobalValue::PrivateLinkage, Init, 3549 ".constant"); 3550 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3551 GV->setAlignment(Alignment.getAsAlign()); 3552 3553 Emitter.finalize(GV); 3554 3555 *Entry = GV; 3556 return ConstantAddress(GV, GV->getValueType(), Alignment); 3557 } 3558 3559 ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject( 3560 const TemplateParamObjectDecl *TPO) { 3561 StringRef Name = getMangledName(TPO); 3562 CharUnits Alignment = getNaturalTypeAlignment(TPO->getType()); 3563 3564 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 3565 return ConstantAddress(GV, GV->getValueType(), Alignment); 3566 3567 ConstantEmitter Emitter(*this); 3568 llvm::Constant *Init = Emitter.emitForInitializer( 3569 TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType()); 3570 3571 if (!Init) { 3572 ErrorUnsupported(TPO, "template parameter object"); 3573 return ConstantAddress::invalid(); 3574 } 3575 3576 llvm::GlobalValue::LinkageTypes Linkage = 3577 isExternallyVisible(TPO->getLinkageAndVisibility().getLinkage()) 3578 ? llvm::GlobalValue::LinkOnceODRLinkage 3579 : llvm::GlobalValue::InternalLinkage; 3580 auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(), 3581 /*isConstant=*/true, Linkage, Init, Name); 3582 setGVProperties(GV, TPO); 3583 if (supportsCOMDAT()) 3584 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3585 Emitter.finalize(GV); 3586 3587 return ConstantAddress(GV, GV->getValueType(), Alignment); 3588 } 3589 3590 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 3591 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 3592 assert(AA && "No alias?"); 3593 3594 CharUnits Alignment = getContext().getDeclAlign(VD); 3595 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 3596 3597 // See if there is already something with the target's name in the module. 3598 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 3599 if (Entry) 3600 return ConstantAddress(Entry, DeclTy, Alignment); 3601 3602 llvm::Constant *Aliasee; 3603 if (isa<llvm::FunctionType>(DeclTy)) 3604 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 3605 GlobalDecl(cast<FunctionDecl>(VD)), 3606 /*ForVTable=*/false); 3607 else 3608 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 3609 nullptr); 3610 3611 auto *F = cast<llvm::GlobalValue>(Aliasee); 3612 F->setLinkage(llvm::Function::ExternalWeakLinkage); 3613 WeakRefReferences.insert(F); 3614 3615 return ConstantAddress(Aliasee, DeclTy, Alignment); 3616 } 3617 3618 template <typename AttrT> static bool hasImplicitAttr(const ValueDecl *D) { 3619 if (!D) 3620 return false; 3621 if (auto *A = D->getAttr<AttrT>()) 3622 return A->isImplicit(); 3623 return D->isImplicit(); 3624 } 3625 3626 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 3627 const auto *Global = cast<ValueDecl>(GD.getDecl()); 3628 3629 // Weak references don't produce any output by themselves. 3630 if (Global->hasAttr<WeakRefAttr>()) 3631 return; 3632 3633 // If this is an alias definition (which otherwise looks like a declaration) 3634 // emit it now. 3635 if (Global->hasAttr<AliasAttr>()) 3636 return EmitAliasDefinition(GD); 3637 3638 // IFunc like an alias whose value is resolved at runtime by calling resolver. 3639 if (Global->hasAttr<IFuncAttr>()) 3640 return emitIFuncDefinition(GD); 3641 3642 // If this is a cpu_dispatch multiversion function, emit the resolver. 3643 if (Global->hasAttr<CPUDispatchAttr>()) 3644 return emitCPUDispatchDefinition(GD); 3645 3646 // If this is CUDA, be selective about which declarations we emit. 3647 // Non-constexpr non-lambda implicit host device functions are not emitted 3648 // unless they are used on device side. 3649 if (LangOpts.CUDA) { 3650 if (LangOpts.CUDAIsDevice) { 3651 const auto *FD = dyn_cast<FunctionDecl>(Global); 3652 if ((!Global->hasAttr<CUDADeviceAttr>() || 3653 (LangOpts.OffloadImplicitHostDeviceTemplates && FD && 3654 hasImplicitAttr<CUDAHostAttr>(FD) && 3655 hasImplicitAttr<CUDADeviceAttr>(FD) && !FD->isConstexpr() && 3656 !isLambdaCallOperator(FD) && 3657 !getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) && 3658 !Global->hasAttr<CUDAGlobalAttr>() && 3659 !Global->hasAttr<CUDAConstantAttr>() && 3660 !Global->hasAttr<CUDASharedAttr>() && 3661 !Global->getType()->isCUDADeviceBuiltinSurfaceType() && 3662 !Global->getType()->isCUDADeviceBuiltinTextureType() && 3663 !(LangOpts.HIPStdPar && isa<FunctionDecl>(Global) && 3664 !Global->hasAttr<CUDAHostAttr>())) 3665 return; 3666 } else { 3667 // We need to emit host-side 'shadows' for all global 3668 // device-side variables because the CUDA runtime needs their 3669 // size and host-side address in order to provide access to 3670 // their device-side incarnations. 3671 3672 // So device-only functions are the only things we skip. 3673 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 3674 Global->hasAttr<CUDADeviceAttr>()) 3675 return; 3676 3677 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 3678 "Expected Variable or Function"); 3679 } 3680 } 3681 3682 if (LangOpts.OpenMP) { 3683 // If this is OpenMP, check if it is legal to emit this global normally. 3684 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 3685 return; 3686 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 3687 if (MustBeEmitted(Global)) 3688 EmitOMPDeclareReduction(DRD); 3689 return; 3690 } 3691 if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) { 3692 if (MustBeEmitted(Global)) 3693 EmitOMPDeclareMapper(DMD); 3694 return; 3695 } 3696 } 3697 3698 // Ignore declarations, they will be emitted on their first use. 3699 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 3700 // Update deferred annotations with the latest declaration if the function 3701 // function was already used or defined. 3702 if (FD->hasAttr<AnnotateAttr>()) { 3703 StringRef MangledName = getMangledName(GD); 3704 if (GetGlobalValue(MangledName)) 3705 DeferredAnnotations[MangledName] = FD; 3706 } 3707 3708 // Forward declarations are emitted lazily on first use. 3709 if (!FD->doesThisDeclarationHaveABody()) { 3710 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 3711 return; 3712 3713 StringRef MangledName = getMangledName(GD); 3714 3715 // Compute the function info and LLVM type. 3716 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 3717 llvm::Type *Ty = getTypes().GetFunctionType(FI); 3718 3719 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 3720 /*DontDefer=*/false); 3721 return; 3722 } 3723 } else { 3724 const auto *VD = cast<VarDecl>(Global); 3725 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 3726 if (VD->isThisDeclarationADefinition() != VarDecl::Definition && 3727 !Context.isMSStaticDataMemberInlineDefinition(VD)) { 3728 if (LangOpts.OpenMP) { 3729 // Emit declaration of the must-be-emitted declare target variable. 3730 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 3731 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 3732 3733 // If this variable has external storage and doesn't require special 3734 // link handling we defer to its canonical definition. 3735 if (VD->hasExternalStorage() && 3736 Res != OMPDeclareTargetDeclAttr::MT_Link) 3737 return; 3738 3739 bool UnifiedMemoryEnabled = 3740 getOpenMPRuntime().hasRequiresUnifiedSharedMemory(); 3741 if ((*Res == OMPDeclareTargetDeclAttr::MT_To || 3742 *Res == OMPDeclareTargetDeclAttr::MT_Enter) && 3743 !UnifiedMemoryEnabled) { 3744 (void)GetAddrOfGlobalVar(VD); 3745 } else { 3746 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) || 3747 ((*Res == OMPDeclareTargetDeclAttr::MT_To || 3748 *Res == OMPDeclareTargetDeclAttr::MT_Enter) && 3749 UnifiedMemoryEnabled)) && 3750 "Link clause or to clause with unified memory expected."); 3751 (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD); 3752 } 3753 3754 return; 3755 } 3756 } 3757 // If this declaration may have caused an inline variable definition to 3758 // change linkage, make sure that it's emitted. 3759 if (Context.getInlineVariableDefinitionKind(VD) == 3760 ASTContext::InlineVariableDefinitionKind::Strong) 3761 GetAddrOfGlobalVar(VD); 3762 return; 3763 } 3764 } 3765 3766 // Defer code generation to first use when possible, e.g. if this is an inline 3767 // function. If the global must always be emitted, do it eagerly if possible 3768 // to benefit from cache locality. 3769 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 3770 // Emit the definition if it can't be deferred. 3771 EmitGlobalDefinition(GD); 3772 addEmittedDeferredDecl(GD); 3773 return; 3774 } 3775 3776 // If we're deferring emission of a C++ variable with an 3777 // initializer, remember the order in which it appeared in the file. 3778 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 3779 cast<VarDecl>(Global)->hasInit()) { 3780 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 3781 CXXGlobalInits.push_back(nullptr); 3782 } 3783 3784 StringRef MangledName = getMangledName(GD); 3785 if (GetGlobalValue(MangledName) != nullptr) { 3786 // The value has already been used and should therefore be emitted. 3787 addDeferredDeclToEmit(GD); 3788 } else if (MustBeEmitted(Global)) { 3789 // The value must be emitted, but cannot be emitted eagerly. 3790 assert(!MayBeEmittedEagerly(Global)); 3791 addDeferredDeclToEmit(GD); 3792 } else { 3793 // Otherwise, remember that we saw a deferred decl with this name. The 3794 // first use of the mangled name will cause it to move into 3795 // DeferredDeclsToEmit. 3796 DeferredDecls[MangledName] = GD; 3797 } 3798 } 3799 3800 // Check if T is a class type with a destructor that's not dllimport. 3801 static bool HasNonDllImportDtor(QualType T) { 3802 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) 3803 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 3804 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) 3805 return true; 3806 3807 return false; 3808 } 3809 3810 namespace { 3811 struct FunctionIsDirectlyRecursive 3812 : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> { 3813 const StringRef Name; 3814 const Builtin::Context &BI; 3815 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) 3816 : Name(N), BI(C) {} 3817 3818 bool VisitCallExpr(const CallExpr *E) { 3819 const FunctionDecl *FD = E->getDirectCallee(); 3820 if (!FD) 3821 return false; 3822 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 3823 if (Attr && Name == Attr->getLabel()) 3824 return true; 3825 unsigned BuiltinID = FD->getBuiltinID(); 3826 if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 3827 return false; 3828 StringRef BuiltinName = BI.getName(BuiltinID); 3829 if (BuiltinName.starts_with("__builtin_") && 3830 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 3831 return true; 3832 } 3833 return false; 3834 } 3835 3836 bool VisitStmt(const Stmt *S) { 3837 for (const Stmt *Child : S->children()) 3838 if (Child && this->Visit(Child)) 3839 return true; 3840 return false; 3841 } 3842 }; 3843 3844 // Make sure we're not referencing non-imported vars or functions. 3845 struct DLLImportFunctionVisitor 3846 : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 3847 bool SafeToInline = true; 3848 3849 bool shouldVisitImplicitCode() const { return true; } 3850 3851 bool VisitVarDecl(VarDecl *VD) { 3852 if (VD->getTLSKind()) { 3853 // A thread-local variable cannot be imported. 3854 SafeToInline = false; 3855 return SafeToInline; 3856 } 3857 3858 // A variable definition might imply a destructor call. 3859 if (VD->isThisDeclarationADefinition()) 3860 SafeToInline = !HasNonDllImportDtor(VD->getType()); 3861 3862 return SafeToInline; 3863 } 3864 3865 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 3866 if (const auto *D = E->getTemporary()->getDestructor()) 3867 SafeToInline = D->hasAttr<DLLImportAttr>(); 3868 return SafeToInline; 3869 } 3870 3871 bool VisitDeclRefExpr(DeclRefExpr *E) { 3872 ValueDecl *VD = E->getDecl(); 3873 if (isa<FunctionDecl>(VD)) 3874 SafeToInline = VD->hasAttr<DLLImportAttr>(); 3875 else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 3876 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 3877 return SafeToInline; 3878 } 3879 3880 bool VisitCXXConstructExpr(CXXConstructExpr *E) { 3881 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); 3882 return SafeToInline; 3883 } 3884 3885 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3886 CXXMethodDecl *M = E->getMethodDecl(); 3887 if (!M) { 3888 // Call through a pointer to member function. This is safe to inline. 3889 SafeToInline = true; 3890 } else { 3891 SafeToInline = M->hasAttr<DLLImportAttr>(); 3892 } 3893 return SafeToInline; 3894 } 3895 3896 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 3897 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 3898 return SafeToInline; 3899 } 3900 3901 bool VisitCXXNewExpr(CXXNewExpr *E) { 3902 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 3903 return SafeToInline; 3904 } 3905 }; 3906 } 3907 3908 // isTriviallyRecursive - Check if this function calls another 3909 // decl that, because of the asm attribute or the other decl being a builtin, 3910 // ends up pointing to itself. 3911 bool 3912 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 3913 StringRef Name; 3914 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 3915 // asm labels are a special kind of mangling we have to support. 3916 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 3917 if (!Attr) 3918 return false; 3919 Name = Attr->getLabel(); 3920 } else { 3921 Name = FD->getName(); 3922 } 3923 3924 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 3925 const Stmt *Body = FD->getBody(); 3926 return Body ? Walker.Visit(Body) : false; 3927 } 3928 3929 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 3930 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 3931 return true; 3932 3933 const auto *F = cast<FunctionDecl>(GD.getDecl()); 3934 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 3935 return false; 3936 3937 // We don't import function bodies from other named module units since that 3938 // behavior may break ABI compatibility of the current unit. 3939 if (const Module *M = F->getOwningModule(); 3940 M && M->getTopLevelModule()->isNamedModule() && 3941 getContext().getCurrentNamedModule() != M->getTopLevelModule() && 3942 !F->hasAttr<AlwaysInlineAttr>()) 3943 return false; 3944 3945 if (F->hasAttr<NoInlineAttr>()) 3946 return false; 3947 3948 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) { 3949 // Check whether it would be safe to inline this dllimport function. 3950 DLLImportFunctionVisitor Visitor; 3951 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 3952 if (!Visitor.SafeToInline) 3953 return false; 3954 3955 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { 3956 // Implicit destructor invocations aren't captured in the AST, so the 3957 // check above can't see them. Check for them manually here. 3958 for (const Decl *Member : Dtor->getParent()->decls()) 3959 if (isa<FieldDecl>(Member)) 3960 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) 3961 return false; 3962 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) 3963 if (HasNonDllImportDtor(B.getType())) 3964 return false; 3965 } 3966 } 3967 3968 // Inline builtins declaration must be emitted. They often are fortified 3969 // functions. 3970 if (F->isInlineBuiltinDeclaration()) 3971 return true; 3972 3973 // PR9614. Avoid cases where the source code is lying to us. An available 3974 // externally function should have an equivalent function somewhere else, 3975 // but a function that calls itself through asm label/`__builtin_` trickery is 3976 // clearly not equivalent to the real implementation. 3977 // This happens in glibc's btowc and in some configure checks. 3978 return !isTriviallyRecursive(F); 3979 } 3980 3981 bool CodeGenModule::shouldOpportunisticallyEmitVTables() { 3982 return CodeGenOpts.OptimizationLevel > 0; 3983 } 3984 3985 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD, 3986 llvm::GlobalValue *GV) { 3987 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3988 3989 if (FD->isCPUSpecificMultiVersion()) { 3990 auto *Spec = FD->getAttr<CPUSpecificAttr>(); 3991 for (unsigned I = 0; I < Spec->cpus_size(); ++I) 3992 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); 3993 } else if (FD->isTargetClonesMultiVersion()) { 3994 auto *Clone = FD->getAttr<TargetClonesAttr>(); 3995 for (unsigned I = 0; I < Clone->featuresStrs_size(); ++I) 3996 if (Clone->isFirstOfVersion(I)) 3997 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); 3998 // Ensure that the resolver function is also emitted. 3999 GetOrCreateMultiVersionResolver(GD); 4000 } else 4001 EmitGlobalFunctionDefinition(GD, GV); 4002 } 4003 4004 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 4005 const auto *D = cast<ValueDecl>(GD.getDecl()); 4006 4007 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 4008 Context.getSourceManager(), 4009 "Generating code for declaration"); 4010 4011 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 4012 // At -O0, don't generate IR for functions with available_externally 4013 // linkage. 4014 if (!shouldEmitFunction(GD)) 4015 return; 4016 4017 llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() { 4018 std::string Name; 4019 llvm::raw_string_ostream OS(Name); 4020 FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(), 4021 /*Qualified=*/true); 4022 return Name; 4023 }); 4024 4025 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 4026 // Make sure to emit the definition(s) before we emit the thunks. 4027 // This is necessary for the generation of certain thunks. 4028 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method)) 4029 ABI->emitCXXStructor(GD); 4030 else if (FD->isMultiVersion()) 4031 EmitMultiVersionFunctionDefinition(GD, GV); 4032 else 4033 EmitGlobalFunctionDefinition(GD, GV); 4034 4035 if (Method->isVirtual()) 4036 getVTables().EmitThunks(GD); 4037 4038 return; 4039 } 4040 4041 if (FD->isMultiVersion()) 4042 return EmitMultiVersionFunctionDefinition(GD, GV); 4043 return EmitGlobalFunctionDefinition(GD, GV); 4044 } 4045 4046 if (const auto *VD = dyn_cast<VarDecl>(D)) 4047 return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 4048 4049 llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 4050 } 4051 4052 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 4053 llvm::Function *NewFn); 4054 4055 static unsigned 4056 TargetMVPriority(const TargetInfo &TI, 4057 const CodeGenFunction::MultiVersionResolverOption &RO) { 4058 unsigned Priority = 0; 4059 unsigned NumFeatures = 0; 4060 for (StringRef Feat : RO.Conditions.Features) { 4061 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat)); 4062 NumFeatures++; 4063 } 4064 4065 if (!RO.Conditions.Architecture.empty()) 4066 Priority = std::max( 4067 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture)); 4068 4069 Priority += TI.multiVersionFeatureCost() * NumFeatures; 4070 4071 return Priority; 4072 } 4073 4074 // Multiversion functions should be at most 'WeakODRLinkage' so that a different 4075 // TU can forward declare the function without causing problems. Particularly 4076 // in the cases of CPUDispatch, this causes issues. This also makes sure we 4077 // work with internal linkage functions, so that the same function name can be 4078 // used with internal linkage in multiple TUs. 4079 llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM, 4080 GlobalDecl GD) { 4081 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 4082 if (FD->getFormalLinkage() == Linkage::Internal) 4083 return llvm::GlobalValue::InternalLinkage; 4084 return llvm::GlobalValue::WeakODRLinkage; 4085 } 4086 4087 void CodeGenModule::emitMultiVersionFunctions() { 4088 std::vector<GlobalDecl> MVFuncsToEmit; 4089 MultiVersionFuncs.swap(MVFuncsToEmit); 4090 for (GlobalDecl GD : MVFuncsToEmit) { 4091 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 4092 assert(FD && "Expected a FunctionDecl"); 4093 4094 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 4095 if (FD->isTargetMultiVersion()) { 4096 getContext().forEachMultiversionedFunctionVersion( 4097 FD, [this, &GD, &Options](const FunctionDecl *CurFD) { 4098 GlobalDecl CurGD{ 4099 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)}; 4100 StringRef MangledName = getMangledName(CurGD); 4101 llvm::Constant *Func = GetGlobalValue(MangledName); 4102 if (!Func) { 4103 if (CurFD->isDefined()) { 4104 EmitGlobalFunctionDefinition(CurGD, nullptr); 4105 Func = GetGlobalValue(MangledName); 4106 } else { 4107 const CGFunctionInfo &FI = 4108 getTypes().arrangeGlobalDeclaration(GD); 4109 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 4110 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, 4111 /*DontDefer=*/false, ForDefinition); 4112 } 4113 assert(Func && "This should have just been created"); 4114 } 4115 if (CurFD->getMultiVersionKind() == MultiVersionKind::Target) { 4116 const auto *TA = CurFD->getAttr<TargetAttr>(); 4117 llvm::SmallVector<StringRef, 8> Feats; 4118 TA->getAddedFeatures(Feats); 4119 Options.emplace_back(cast<llvm::Function>(Func), 4120 TA->getArchitecture(), Feats); 4121 } else { 4122 const auto *TVA = CurFD->getAttr<TargetVersionAttr>(); 4123 llvm::SmallVector<StringRef, 8> Feats; 4124 TVA->getFeatures(Feats); 4125 Options.emplace_back(cast<llvm::Function>(Func), 4126 /*Architecture*/ "", Feats); 4127 } 4128 }); 4129 } else if (FD->isTargetClonesMultiVersion()) { 4130 const auto *TC = FD->getAttr<TargetClonesAttr>(); 4131 for (unsigned VersionIndex = 0; VersionIndex < TC->featuresStrs_size(); 4132 ++VersionIndex) { 4133 if (!TC->isFirstOfVersion(VersionIndex)) 4134 continue; 4135 GlobalDecl CurGD{(FD->isDefined() ? FD->getDefinition() : FD), 4136 VersionIndex}; 4137 StringRef Version = TC->getFeatureStr(VersionIndex); 4138 StringRef MangledName = getMangledName(CurGD); 4139 llvm::Constant *Func = GetGlobalValue(MangledName); 4140 if (!Func) { 4141 if (FD->isDefined()) { 4142 EmitGlobalFunctionDefinition(CurGD, nullptr); 4143 Func = GetGlobalValue(MangledName); 4144 } else { 4145 const CGFunctionInfo &FI = 4146 getTypes().arrangeGlobalDeclaration(CurGD); 4147 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 4148 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, 4149 /*DontDefer=*/false, ForDefinition); 4150 } 4151 assert(Func && "This should have just been created"); 4152 } 4153 4154 StringRef Architecture; 4155 llvm::SmallVector<StringRef, 1> Feature; 4156 4157 if (getTarget().getTriple().isAArch64()) { 4158 if (Version != "default") { 4159 llvm::SmallVector<StringRef, 8> VerFeats; 4160 Version.split(VerFeats, "+"); 4161 for (auto &CurFeat : VerFeats) 4162 Feature.push_back(CurFeat.trim()); 4163 } 4164 } else { 4165 if (Version.starts_with("arch=")) 4166 Architecture = Version.drop_front(sizeof("arch=") - 1); 4167 else if (Version != "default") 4168 Feature.push_back(Version); 4169 } 4170 4171 Options.emplace_back(cast<llvm::Function>(Func), Architecture, Feature); 4172 } 4173 } else { 4174 assert(0 && "Expected a target or target_clones multiversion function"); 4175 continue; 4176 } 4177 4178 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD); 4179 if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) { 4180 ResolverConstant = IFunc->getResolver(); 4181 // In Aarch64, default versions of multiversioned functions are mangled to 4182 // their 'normal' assembly name. This deviates from other targets which 4183 // append a '.default' string. As a result we need to continue appending 4184 // .ifunc in Aarch64. 4185 // FIXME: Should Aarch64 mangling for 'default' multiversion function and 4186 // in turn ifunc function match that of other targets? 4187 if (FD->isTargetClonesMultiVersion() && 4188 !getTarget().getTriple().isAArch64()) { 4189 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 4190 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI); 4191 std::string MangledName = getMangledNameImpl( 4192 *this, GD, FD, /*OmitMultiVersionMangling=*/true); 4193 // In prior versions of Clang, the mangling for ifuncs incorrectly 4194 // included an .ifunc suffix. This alias is generated for backward 4195 // compatibility. It is deprecated, and may be removed in the future. 4196 auto *Alias = llvm::GlobalAlias::create( 4197 DeclTy, 0, getMultiversionLinkage(*this, GD), 4198 MangledName + ".ifunc", IFunc, &getModule()); 4199 SetCommonAttributes(FD, Alias); 4200 } 4201 } 4202 llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant); 4203 4204 ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD)); 4205 4206 if (!ResolverFunc->hasLocalLinkage() && supportsCOMDAT()) 4207 ResolverFunc->setComdat( 4208 getModule().getOrInsertComdat(ResolverFunc->getName())); 4209 4210 const TargetInfo &TI = getTarget(); 4211 llvm::stable_sort( 4212 Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS, 4213 const CodeGenFunction::MultiVersionResolverOption &RHS) { 4214 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS); 4215 }); 4216 CodeGenFunction CGF(*this); 4217 CGF.EmitMultiVersionResolver(ResolverFunc, Options); 4218 } 4219 4220 // Ensure that any additions to the deferred decls list caused by emitting a 4221 // variant are emitted. This can happen when the variant itself is inline and 4222 // calls a function without linkage. 4223 if (!MVFuncsToEmit.empty()) 4224 EmitDeferred(); 4225 4226 // Ensure that any additions to the multiversion funcs list from either the 4227 // deferred decls or the multiversion functions themselves are emitted. 4228 if (!MultiVersionFuncs.empty()) 4229 emitMultiVersionFunctions(); 4230 } 4231 4232 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) { 4233 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 4234 assert(FD && "Not a FunctionDecl?"); 4235 assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?"); 4236 const auto *DD = FD->getAttr<CPUDispatchAttr>(); 4237 assert(DD && "Not a cpu_dispatch Function?"); 4238 4239 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 4240 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI); 4241 4242 StringRef ResolverName = getMangledName(GD); 4243 UpdateMultiVersionNames(GD, FD, ResolverName); 4244 4245 llvm::Type *ResolverType; 4246 GlobalDecl ResolverGD; 4247 if (getTarget().supportsIFunc()) { 4248 ResolverType = llvm::FunctionType::get( 4249 llvm::PointerType::get(DeclTy, 4250 getTypes().getTargetAddressSpace(FD->getType())), 4251 false); 4252 } 4253 else { 4254 ResolverType = DeclTy; 4255 ResolverGD = GD; 4256 } 4257 4258 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction( 4259 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false)); 4260 ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD)); 4261 if (supportsCOMDAT()) 4262 ResolverFunc->setComdat( 4263 getModule().getOrInsertComdat(ResolverFunc->getName())); 4264 4265 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 4266 const TargetInfo &Target = getTarget(); 4267 unsigned Index = 0; 4268 for (const IdentifierInfo *II : DD->cpus()) { 4269 // Get the name of the target function so we can look it up/create it. 4270 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) + 4271 getCPUSpecificMangling(*this, II->getName()); 4272 4273 llvm::Constant *Func = GetGlobalValue(MangledName); 4274 4275 if (!Func) { 4276 GlobalDecl ExistingDecl = Manglings.lookup(MangledName); 4277 if (ExistingDecl.getDecl() && 4278 ExistingDecl.getDecl()->getAsFunction()->isDefined()) { 4279 EmitGlobalFunctionDefinition(ExistingDecl, nullptr); 4280 Func = GetGlobalValue(MangledName); 4281 } else { 4282 if (!ExistingDecl.getDecl()) 4283 ExistingDecl = GD.getWithMultiVersionIndex(Index); 4284 4285 Func = GetOrCreateLLVMFunction( 4286 MangledName, DeclTy, ExistingDecl, 4287 /*ForVTable=*/false, /*DontDefer=*/true, 4288 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition); 4289 } 4290 } 4291 4292 llvm::SmallVector<StringRef, 32> Features; 4293 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features); 4294 llvm::transform(Features, Features.begin(), 4295 [](StringRef Str) { return Str.substr(1); }); 4296 llvm::erase_if(Features, [&Target](StringRef Feat) { 4297 return !Target.validateCpuSupports(Feat); 4298 }); 4299 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features); 4300 ++Index; 4301 } 4302 4303 llvm::stable_sort( 4304 Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS, 4305 const CodeGenFunction::MultiVersionResolverOption &RHS) { 4306 return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) > 4307 llvm::X86::getCpuSupportsMask(RHS.Conditions.Features); 4308 }); 4309 4310 // If the list contains multiple 'default' versions, such as when it contains 4311 // 'pentium' and 'generic', don't emit the call to the generic one (since we 4312 // always run on at least a 'pentium'). We do this by deleting the 'least 4313 // advanced' (read, lowest mangling letter). 4314 while (Options.size() > 1 && 4315 llvm::all_of(llvm::X86::getCpuSupportsMask( 4316 (Options.end() - 2)->Conditions.Features), 4317 [](auto X) { return X == 0; })) { 4318 StringRef LHSName = (Options.end() - 2)->Function->getName(); 4319 StringRef RHSName = (Options.end() - 1)->Function->getName(); 4320 if (LHSName.compare(RHSName) < 0) 4321 Options.erase(Options.end() - 2); 4322 else 4323 Options.erase(Options.end() - 1); 4324 } 4325 4326 CodeGenFunction CGF(*this); 4327 CGF.EmitMultiVersionResolver(ResolverFunc, Options); 4328 4329 if (getTarget().supportsIFunc()) { 4330 llvm::GlobalValue::LinkageTypes Linkage = getMultiversionLinkage(*this, GD); 4331 auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD)); 4332 4333 // Fix up function declarations that were created for cpu_specific before 4334 // cpu_dispatch was known 4335 if (!isa<llvm::GlobalIFunc>(IFunc)) { 4336 assert(cast<llvm::Function>(IFunc)->isDeclaration()); 4337 auto *GI = llvm::GlobalIFunc::create(DeclTy, 0, Linkage, "", ResolverFunc, 4338 &getModule()); 4339 GI->takeName(IFunc); 4340 IFunc->replaceAllUsesWith(GI); 4341 IFunc->eraseFromParent(); 4342 IFunc = GI; 4343 } 4344 4345 std::string AliasName = getMangledNameImpl( 4346 *this, GD, FD, /*OmitMultiVersionMangling=*/true); 4347 llvm::Constant *AliasFunc = GetGlobalValue(AliasName); 4348 if (!AliasFunc) { 4349 auto *GA = llvm::GlobalAlias::create(DeclTy, 0, Linkage, AliasName, IFunc, 4350 &getModule()); 4351 SetCommonAttributes(GD, GA); 4352 } 4353 } 4354 } 4355 4356 /// If a dispatcher for the specified mangled name is not in the module, create 4357 /// and return an llvm Function with the specified type. 4358 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) { 4359 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 4360 assert(FD && "Not a FunctionDecl?"); 4361 4362 std::string MangledName = 4363 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 4364 4365 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has 4366 // a separate resolver). 4367 std::string ResolverName = MangledName; 4368 if (getTarget().supportsIFunc()) { 4369 // In Aarch64, default versions of multiversioned functions are mangled to 4370 // their 'normal' assembly name. This deviates from other targets which 4371 // append a '.default' string. As a result we need to continue appending 4372 // .ifunc in Aarch64. 4373 // FIXME: Should Aarch64 mangling for 'default' multiversion function and 4374 // in turn ifunc function match that of other targets? 4375 if (!FD->isTargetClonesMultiVersion() || 4376 getTarget().getTriple().isAArch64()) 4377 ResolverName += ".ifunc"; 4378 } else if (FD->isTargetMultiVersion()) { 4379 ResolverName += ".resolver"; 4380 } 4381 4382 // If the resolver has already been created, just return it. 4383 if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName)) 4384 return ResolverGV; 4385 4386 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 4387 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI); 4388 4389 // The resolver needs to be created. For target and target_clones, defer 4390 // creation until the end of the TU. 4391 if (FD->isTargetMultiVersion() || FD->isTargetClonesMultiVersion()) 4392 MultiVersionFuncs.push_back(GD); 4393 4394 // For cpu_specific, don't create an ifunc yet because we don't know if the 4395 // cpu_dispatch will be emitted in this translation unit. 4396 if (getTarget().supportsIFunc() && !FD->isCPUSpecificMultiVersion()) { 4397 llvm::Type *ResolverType = llvm::FunctionType::get( 4398 llvm::PointerType::get(DeclTy, 4399 getTypes().getTargetAddressSpace(FD->getType())), 4400 false); 4401 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 4402 MangledName + ".resolver", ResolverType, GlobalDecl{}, 4403 /*ForVTable=*/false); 4404 llvm::GlobalIFunc *GIF = 4405 llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD), 4406 "", Resolver, &getModule()); 4407 GIF->setName(ResolverName); 4408 SetCommonAttributes(FD, GIF); 4409 4410 return GIF; 4411 } 4412 4413 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 4414 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false); 4415 assert(isa<llvm::GlobalValue>(Resolver) && 4416 "Resolver should be created for the first time"); 4417 SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver)); 4418 return Resolver; 4419 } 4420 4421 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 4422 /// module, create and return an llvm Function with the specified type. If there 4423 /// is something in the module with the specified name, return it potentially 4424 /// bitcasted to the right type. 4425 /// 4426 /// If D is non-null, it specifies a decl that correspond to this. This is used 4427 /// to set the attributes on the function when it is first created. 4428 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( 4429 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, 4430 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, 4431 ForDefinition_t IsForDefinition) { 4432 const Decl *D = GD.getDecl(); 4433 4434 // Any attempts to use a MultiVersion function should result in retrieving 4435 // the iFunc instead. Name Mangling will handle the rest of the changes. 4436 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) { 4437 // For the device mark the function as one that should be emitted. 4438 if (getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime && 4439 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() && 4440 !DontDefer && !IsForDefinition) { 4441 if (const FunctionDecl *FDDef = FD->getDefinition()) { 4442 GlobalDecl GDDef; 4443 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef)) 4444 GDDef = GlobalDecl(CD, GD.getCtorType()); 4445 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef)) 4446 GDDef = GlobalDecl(DD, GD.getDtorType()); 4447 else 4448 GDDef = GlobalDecl(FDDef); 4449 EmitGlobal(GDDef); 4450 } 4451 } 4452 4453 if (FD->isMultiVersion()) { 4454 UpdateMultiVersionNames(GD, FD, MangledName); 4455 if (!IsForDefinition) 4456 return GetOrCreateMultiVersionResolver(GD); 4457 } 4458 } 4459 4460 // Lookup the entry, lazily creating it if necessary. 4461 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4462 if (Entry) { 4463 if (WeakRefReferences.erase(Entry)) { 4464 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 4465 if (FD && !FD->hasAttr<WeakAttr>()) 4466 Entry->setLinkage(llvm::Function::ExternalLinkage); 4467 } 4468 4469 // Handle dropped DLL attributes. 4470 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() && 4471 !shouldMapVisibilityToDLLExport(cast_or_null<NamedDecl>(D))) { 4472 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 4473 setDSOLocal(Entry); 4474 } 4475 4476 // If there are two attempts to define the same mangled name, issue an 4477 // error. 4478 if (IsForDefinition && !Entry->isDeclaration()) { 4479 GlobalDecl OtherGD; 4480 // Check that GD is not yet in DiagnosedConflictingDefinitions is required 4481 // to make sure that we issue an error only once. 4482 if (lookupRepresentativeDecl(MangledName, OtherGD) && 4483 (GD.getCanonicalDecl().getDecl() != 4484 OtherGD.getCanonicalDecl().getDecl()) && 4485 DiagnosedConflictingDefinitions.insert(GD).second) { 4486 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 4487 << MangledName; 4488 getDiags().Report(OtherGD.getDecl()->getLocation(), 4489 diag::note_previous_definition); 4490 } 4491 } 4492 4493 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 4494 (Entry->getValueType() == Ty)) { 4495 return Entry; 4496 } 4497 4498 // Make sure the result is of the correct type. 4499 // (If function is requested for a definition, we always need to create a new 4500 // function, not just return a bitcast.) 4501 if (!IsForDefinition) 4502 return Entry; 4503 } 4504 4505 // This function doesn't have a complete type (for example, the return 4506 // type is an incomplete struct). Use a fake type instead, and make 4507 // sure not to try to set attributes. 4508 bool IsIncompleteFunction = false; 4509 4510 llvm::FunctionType *FTy; 4511 if (isa<llvm::FunctionType>(Ty)) { 4512 FTy = cast<llvm::FunctionType>(Ty); 4513 } else { 4514 FTy = llvm::FunctionType::get(VoidTy, false); 4515 IsIncompleteFunction = true; 4516 } 4517 4518 llvm::Function *F = 4519 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 4520 Entry ? StringRef() : MangledName, &getModule()); 4521 4522 // Store the declaration associated with this function so it is potentially 4523 // updated by further declarations or definitions and emitted at the end. 4524 if (D && D->hasAttr<AnnotateAttr>()) 4525 DeferredAnnotations[MangledName] = cast<ValueDecl>(D); 4526 4527 // If we already created a function with the same mangled name (but different 4528 // type) before, take its name and add it to the list of functions to be 4529 // replaced with F at the end of CodeGen. 4530 // 4531 // This happens if there is a prototype for a function (e.g. "int f()") and 4532 // then a definition of a different type (e.g. "int f(int x)"). 4533 if (Entry) { 4534 F->takeName(Entry); 4535 4536 // This might be an implementation of a function without a prototype, in 4537 // which case, try to do special replacement of calls which match the new 4538 // prototype. The really key thing here is that we also potentially drop 4539 // arguments from the call site so as to make a direct call, which makes the 4540 // inliner happier and suppresses a number of optimizer warnings (!) about 4541 // dropping arguments. 4542 if (!Entry->use_empty()) { 4543 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 4544 Entry->removeDeadConstantUsers(); 4545 } 4546 4547 addGlobalValReplacement(Entry, F); 4548 } 4549 4550 assert(F->getName() == MangledName && "name was uniqued!"); 4551 if (D) 4552 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 4553 if (ExtraAttrs.hasFnAttrs()) { 4554 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs()); 4555 F->addFnAttrs(B); 4556 } 4557 4558 if (!DontDefer) { 4559 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 4560 // each other bottoming out with the base dtor. Therefore we emit non-base 4561 // dtors on usage, even if there is no dtor definition in the TU. 4562 if (isa_and_nonnull<CXXDestructorDecl>(D) && 4563 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 4564 GD.getDtorType())) 4565 addDeferredDeclToEmit(GD); 4566 4567 // This is the first use or definition of a mangled name. If there is a 4568 // deferred decl with this name, remember that we need to emit it at the end 4569 // of the file. 4570 auto DDI = DeferredDecls.find(MangledName); 4571 if (DDI != DeferredDecls.end()) { 4572 // Move the potentially referenced deferred decl to the 4573 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 4574 // don't need it anymore). 4575 addDeferredDeclToEmit(DDI->second); 4576 DeferredDecls.erase(DDI); 4577 4578 // Otherwise, there are cases we have to worry about where we're 4579 // using a declaration for which we must emit a definition but where 4580 // we might not find a top-level definition: 4581 // - member functions defined inline in their classes 4582 // - friend functions defined inline in some class 4583 // - special member functions with implicit definitions 4584 // If we ever change our AST traversal to walk into class methods, 4585 // this will be unnecessary. 4586 // 4587 // We also don't emit a definition for a function if it's going to be an 4588 // entry in a vtable, unless it's already marked as used. 4589 } else if (getLangOpts().CPlusPlus && D) { 4590 // Look for a declaration that's lexically in a record. 4591 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 4592 FD = FD->getPreviousDecl()) { 4593 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 4594 if (FD->doesThisDeclarationHaveABody()) { 4595 addDeferredDeclToEmit(GD.getWithDecl(FD)); 4596 break; 4597 } 4598 } 4599 } 4600 } 4601 } 4602 4603 // Make sure the result is of the requested type. 4604 if (!IsIncompleteFunction) { 4605 assert(F->getFunctionType() == Ty); 4606 return F; 4607 } 4608 4609 return F; 4610 } 4611 4612 /// GetAddrOfFunction - Return the address of the given function. If Ty is 4613 /// non-null, then this function will use the specified type if it has to 4614 /// create it (this occurs when we see a definition of the function). 4615 llvm::Constant * 4616 CodeGenModule::GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty, bool ForVTable, 4617 bool DontDefer, 4618 ForDefinition_t IsForDefinition) { 4619 // If there was no specific requested type, just convert it now. 4620 if (!Ty) { 4621 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 4622 Ty = getTypes().ConvertType(FD->getType()); 4623 } 4624 4625 // Devirtualized destructor calls may come through here instead of via 4626 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead 4627 // of the complete destructor when necessary. 4628 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) { 4629 if (getTarget().getCXXABI().isMicrosoft() && 4630 GD.getDtorType() == Dtor_Complete && 4631 DD->getParent()->getNumVBases() == 0) 4632 GD = GlobalDecl(DD, Dtor_Base); 4633 } 4634 4635 StringRef MangledName = getMangledName(GD); 4636 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 4637 /*IsThunk=*/false, llvm::AttributeList(), 4638 IsForDefinition); 4639 // Returns kernel handle for HIP kernel stub function. 4640 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice && 4641 cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) { 4642 auto *Handle = getCUDARuntime().getKernelHandle( 4643 cast<llvm::Function>(F->stripPointerCasts()), GD); 4644 if (IsForDefinition) 4645 return F; 4646 return Handle; 4647 } 4648 return F; 4649 } 4650 4651 llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) { 4652 llvm::GlobalValue *F = 4653 cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts()); 4654 4655 return llvm::NoCFIValue::get(F); 4656 } 4657 4658 static const FunctionDecl * 4659 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { 4660 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 4661 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 4662 4663 IdentifierInfo &CII = C.Idents.get(Name); 4664 for (const auto *Result : DC->lookup(&CII)) 4665 if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 4666 return FD; 4667 4668 if (!C.getLangOpts().CPlusPlus) 4669 return nullptr; 4670 4671 // Demangle the premangled name from getTerminateFn() 4672 IdentifierInfo &CXXII = 4673 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ") 4674 ? C.Idents.get("terminate") 4675 : C.Idents.get(Name); 4676 4677 for (const auto &N : {"__cxxabiv1", "std"}) { 4678 IdentifierInfo &NS = C.Idents.get(N); 4679 for (const auto *Result : DC->lookup(&NS)) { 4680 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); 4681 if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result)) 4682 for (const auto *Result : LSD->lookup(&NS)) 4683 if ((ND = dyn_cast<NamespaceDecl>(Result))) 4684 break; 4685 4686 if (ND) 4687 for (const auto *Result : ND->lookup(&CXXII)) 4688 if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 4689 return FD; 4690 } 4691 } 4692 4693 return nullptr; 4694 } 4695 4696 /// CreateRuntimeFunction - Create a new runtime function with the specified 4697 /// type and name. 4698 llvm::FunctionCallee 4699 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, 4700 llvm::AttributeList ExtraAttrs, bool Local, 4701 bool AssumeConvergent) { 4702 if (AssumeConvergent) { 4703 ExtraAttrs = 4704 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent); 4705 } 4706 4707 llvm::Constant *C = 4708 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 4709 /*DontDefer=*/false, /*IsThunk=*/false, 4710 ExtraAttrs); 4711 4712 if (auto *F = dyn_cast<llvm::Function>(C)) { 4713 if (F->empty()) { 4714 F->setCallingConv(getRuntimeCC()); 4715 4716 // In Windows Itanium environments, try to mark runtime functions 4717 // dllimport. For Mingw and MSVC, don't. We don't really know if the user 4718 // will link their standard library statically or dynamically. Marking 4719 // functions imported when they are not imported can cause linker errors 4720 // and warnings. 4721 if (!Local && getTriple().isWindowsItaniumEnvironment() && 4722 !getCodeGenOpts().LTOVisibilityPublicStd) { 4723 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); 4724 if (!FD || FD->hasAttr<DLLImportAttr>()) { 4725 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 4726 F->setLinkage(llvm::GlobalValue::ExternalLinkage); 4727 } 4728 } 4729 setDSOLocal(F); 4730 } 4731 } 4732 4733 return {FTy, C}; 4734 } 4735 4736 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 4737 /// create and return an llvm GlobalVariable with the specified type and address 4738 /// space. If there is something in the module with the specified name, return 4739 /// it potentially bitcasted to the right type. 4740 /// 4741 /// If D is non-null, it specifies a decl that correspond to this. This is used 4742 /// to set the attributes on the global when it is first created. 4743 /// 4744 /// If IsForDefinition is true, it is guaranteed that an actual global with 4745 /// type Ty will be returned, not conversion of a variable with the same 4746 /// mangled name but some other type. 4747 llvm::Constant * 4748 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, 4749 LangAS AddrSpace, const VarDecl *D, 4750 ForDefinition_t IsForDefinition) { 4751 // Lookup the entry, lazily creating it if necessary. 4752 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4753 unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace); 4754 if (Entry) { 4755 if (WeakRefReferences.erase(Entry)) { 4756 if (D && !D->hasAttr<WeakAttr>()) 4757 Entry->setLinkage(llvm::Function::ExternalLinkage); 4758 } 4759 4760 // Handle dropped DLL attributes. 4761 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() && 4762 !shouldMapVisibilityToDLLExport(D)) 4763 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 4764 4765 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D) 4766 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry); 4767 4768 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS) 4769 return Entry; 4770 4771 // If there are two attempts to define the same mangled name, issue an 4772 // error. 4773 if (IsForDefinition && !Entry->isDeclaration()) { 4774 GlobalDecl OtherGD; 4775 const VarDecl *OtherD; 4776 4777 // Check that D is not yet in DiagnosedConflictingDefinitions is required 4778 // to make sure that we issue an error only once. 4779 if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 4780 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 4781 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 4782 OtherD->hasInit() && 4783 DiagnosedConflictingDefinitions.insert(D).second) { 4784 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 4785 << MangledName; 4786 getDiags().Report(OtherGD.getDecl()->getLocation(), 4787 diag::note_previous_definition); 4788 } 4789 } 4790 4791 // Make sure the result is of the correct type. 4792 if (Entry->getType()->getAddressSpace() != TargetAS) 4793 return llvm::ConstantExpr::getAddrSpaceCast( 4794 Entry, llvm::PointerType::get(Ty->getContext(), TargetAS)); 4795 4796 // (If global is requested for a definition, we always need to create a new 4797 // global, not just return a bitcast.) 4798 if (!IsForDefinition) 4799 return Entry; 4800 } 4801 4802 auto DAddrSpace = GetGlobalVarAddressSpace(D); 4803 4804 auto *GV = new llvm::GlobalVariable( 4805 getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr, 4806 MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal, 4807 getContext().getTargetAddressSpace(DAddrSpace)); 4808 4809 // If we already created a global with the same mangled name (but different 4810 // type) before, take its name and remove it from its parent. 4811 if (Entry) { 4812 GV->takeName(Entry); 4813 4814 if (!Entry->use_empty()) { 4815 Entry->replaceAllUsesWith(GV); 4816 } 4817 4818 Entry->eraseFromParent(); 4819 } 4820 4821 // This is the first use or definition of a mangled name. If there is a 4822 // deferred decl with this name, remember that we need to emit it at the end 4823 // of the file. 4824 auto DDI = DeferredDecls.find(MangledName); 4825 if (DDI != DeferredDecls.end()) { 4826 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 4827 // list, and remove it from DeferredDecls (since we don't need it anymore). 4828 addDeferredDeclToEmit(DDI->second); 4829 DeferredDecls.erase(DDI); 4830 } 4831 4832 // Handle things which are present even on external declarations. 4833 if (D) { 4834 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd) 4835 getOpenMPRuntime().registerTargetGlobalVariable(D, GV); 4836 4837 // FIXME: This code is overly simple and should be merged with other global 4838 // handling. 4839 GV->setConstant(D->getType().isConstantStorage(getContext(), false, false)); 4840 4841 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); 4842 4843 setLinkageForGV(GV, D); 4844 4845 if (D->getTLSKind()) { 4846 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 4847 CXXThreadLocals.push_back(D); 4848 setTLSMode(GV, *D); 4849 } 4850 4851 setGVProperties(GV, D); 4852 4853 // If required by the ABI, treat declarations of static data members with 4854 // inline initializers as definitions. 4855 if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 4856 EmitGlobalVarDefinition(D); 4857 } 4858 4859 // Emit section information for extern variables. 4860 if (D->hasExternalStorage()) { 4861 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 4862 GV->setSection(SA->getName()); 4863 } 4864 4865 // Handle XCore specific ABI requirements. 4866 if (getTriple().getArch() == llvm::Triple::xcore && 4867 D->getLanguageLinkage() == CLanguageLinkage && 4868 D->getType().isConstant(Context) && 4869 isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 4870 GV->setSection(".cp.rodata"); 4871 4872 // Check if we a have a const declaration with an initializer, we may be 4873 // able to emit it as available_externally to expose it's value to the 4874 // optimizer. 4875 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() && 4876 D->getType().isConstQualified() && !GV->hasInitializer() && 4877 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) { 4878 const auto *Record = 4879 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl(); 4880 bool HasMutableFields = Record && Record->hasMutableFields(); 4881 if (!HasMutableFields) { 4882 const VarDecl *InitDecl; 4883 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 4884 if (InitExpr) { 4885 ConstantEmitter emitter(*this); 4886 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl); 4887 if (Init) { 4888 auto *InitType = Init->getType(); 4889 if (GV->getValueType() != InitType) { 4890 // The type of the initializer does not match the definition. 4891 // This happens when an initializer has a different type from 4892 // the type of the global (because of padding at the end of a 4893 // structure for instance). 4894 GV->setName(StringRef()); 4895 // Make a new global with the correct type, this is now guaranteed 4896 // to work. 4897 auto *NewGV = cast<llvm::GlobalVariable>( 4898 GetAddrOfGlobalVar(D, InitType, IsForDefinition) 4899 ->stripPointerCasts()); 4900 4901 // Erase the old global, since it is no longer used. 4902 GV->eraseFromParent(); 4903 GV = NewGV; 4904 } else { 4905 GV->setInitializer(Init); 4906 GV->setConstant(true); 4907 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 4908 } 4909 emitter.finalize(GV); 4910 } 4911 } 4912 } 4913 } 4914 } 4915 4916 if (D && 4917 D->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly) { 4918 getTargetCodeGenInfo().setTargetAttributes(D, GV, *this); 4919 // External HIP managed variables needed to be recorded for transformation 4920 // in both device and host compilations. 4921 if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() && 4922 D->hasExternalStorage()) 4923 getCUDARuntime().handleVarRegistration(D, *GV); 4924 } 4925 4926 if (D) 4927 SanitizerMD->reportGlobal(GV, *D); 4928 4929 LangAS ExpectedAS = 4930 D ? D->getType().getAddressSpace() 4931 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default); 4932 assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS); 4933 if (DAddrSpace != ExpectedAS) { 4934 return getTargetCodeGenInfo().performAddrSpaceCast( 4935 *this, GV, DAddrSpace, ExpectedAS, 4936 llvm::PointerType::get(getLLVMContext(), TargetAS)); 4937 } 4938 4939 return GV; 4940 } 4941 4942 llvm::Constant * 4943 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) { 4944 const Decl *D = GD.getDecl(); 4945 4946 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 4947 return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr, 4948 /*DontDefer=*/false, IsForDefinition); 4949 4950 if (isa<CXXMethodDecl>(D)) { 4951 auto FInfo = 4952 &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D)); 4953 auto Ty = getTypes().GetFunctionType(*FInfo); 4954 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 4955 IsForDefinition); 4956 } 4957 4958 if (isa<FunctionDecl>(D)) { 4959 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 4960 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 4961 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 4962 IsForDefinition); 4963 } 4964 4965 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition); 4966 } 4967 4968 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable( 4969 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, 4970 llvm::Align Alignment) { 4971 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 4972 llvm::GlobalVariable *OldGV = nullptr; 4973 4974 if (GV) { 4975 // Check if the variable has the right type. 4976 if (GV->getValueType() == Ty) 4977 return GV; 4978 4979 // Because C++ name mangling, the only way we can end up with an already 4980 // existing global with the same name is if it has been declared extern "C". 4981 assert(GV->isDeclaration() && "Declaration has wrong type!"); 4982 OldGV = GV; 4983 } 4984 4985 // Create a new variable. 4986 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 4987 Linkage, nullptr, Name); 4988 4989 if (OldGV) { 4990 // Replace occurrences of the old variable if needed. 4991 GV->takeName(OldGV); 4992 4993 if (!OldGV->use_empty()) { 4994 OldGV->replaceAllUsesWith(GV); 4995 } 4996 4997 OldGV->eraseFromParent(); 4998 } 4999 5000 if (supportsCOMDAT() && GV->isWeakForLinker() && 5001 !GV->hasAvailableExternallyLinkage()) 5002 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 5003 5004 GV->setAlignment(Alignment); 5005 5006 return GV; 5007 } 5008 5009 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 5010 /// given global variable. If Ty is non-null and if the global doesn't exist, 5011 /// then it will be created with the specified type instead of whatever the 5012 /// normal requested type would be. If IsForDefinition is true, it is guaranteed 5013 /// that an actual global with type Ty will be returned, not conversion of a 5014 /// variable with the same mangled name but some other type. 5015 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 5016 llvm::Type *Ty, 5017 ForDefinition_t IsForDefinition) { 5018 assert(D->hasGlobalStorage() && "Not a global variable"); 5019 QualType ASTTy = D->getType(); 5020 if (!Ty) 5021 Ty = getTypes().ConvertTypeForMem(ASTTy); 5022 5023 StringRef MangledName = getMangledName(D); 5024 return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D, 5025 IsForDefinition); 5026 } 5027 5028 /// CreateRuntimeVariable - Create a new runtime global variable with the 5029 /// specified type and name. 5030 llvm::Constant * 5031 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 5032 StringRef Name) { 5033 LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global 5034 : LangAS::Default; 5035 auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr); 5036 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts())); 5037 return Ret; 5038 } 5039 5040 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 5041 assert(!D->getInit() && "Cannot emit definite definitions here!"); 5042 5043 StringRef MangledName = getMangledName(D); 5044 llvm::GlobalValue *GV = GetGlobalValue(MangledName); 5045 5046 // We already have a definition, not declaration, with the same mangled name. 5047 // Emitting of declaration is not required (and actually overwrites emitted 5048 // definition). 5049 if (GV && !GV->isDeclaration()) 5050 return; 5051 5052 // If we have not seen a reference to this variable yet, place it into the 5053 // deferred declarations table to be emitted if needed later. 5054 if (!MustBeEmitted(D) && !GV) { 5055 DeferredDecls[MangledName] = D; 5056 return; 5057 } 5058 5059 // The tentative definition is the only definition. 5060 EmitGlobalVarDefinition(D); 5061 } 5062 5063 void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) { 5064 EmitExternalVarDeclaration(D); 5065 } 5066 5067 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 5068 return Context.toCharUnitsFromBits( 5069 getDataLayout().getTypeStoreSizeInBits(Ty)); 5070 } 5071 5072 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { 5073 if (LangOpts.OpenCL) { 5074 LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global; 5075 assert(AS == LangAS::opencl_global || 5076 AS == LangAS::opencl_global_device || 5077 AS == LangAS::opencl_global_host || 5078 AS == LangAS::opencl_constant || 5079 AS == LangAS::opencl_local || 5080 AS >= LangAS::FirstTargetAddressSpace); 5081 return AS; 5082 } 5083 5084 if (LangOpts.SYCLIsDevice && 5085 (!D || D->getType().getAddressSpace() == LangAS::Default)) 5086 return LangAS::sycl_global; 5087 5088 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { 5089 if (D) { 5090 if (D->hasAttr<CUDAConstantAttr>()) 5091 return LangAS::cuda_constant; 5092 if (D->hasAttr<CUDASharedAttr>()) 5093 return LangAS::cuda_shared; 5094 if (D->hasAttr<CUDADeviceAttr>()) 5095 return LangAS::cuda_device; 5096 if (D->getType().isConstQualified()) 5097 return LangAS::cuda_constant; 5098 } 5099 return LangAS::cuda_device; 5100 } 5101 5102 if (LangOpts.OpenMP) { 5103 LangAS AS; 5104 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS)) 5105 return AS; 5106 } 5107 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D); 5108 } 5109 5110 LangAS CodeGenModule::GetGlobalConstantAddressSpace() const { 5111 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 5112 if (LangOpts.OpenCL) 5113 return LangAS::opencl_constant; 5114 if (LangOpts.SYCLIsDevice) 5115 return LangAS::sycl_global; 5116 if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV()) 5117 // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V) 5118 // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up 5119 // with OpVariable instructions with Generic storage class which is not 5120 // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V 5121 // UniformConstant storage class is not viable as pointers to it may not be 5122 // casted to Generic pointers which are used to model HIP's "flat" pointers. 5123 return LangAS::cuda_device; 5124 if (auto AS = getTarget().getConstantAddressSpace()) 5125 return *AS; 5126 return LangAS::Default; 5127 } 5128 5129 // In address space agnostic languages, string literals are in default address 5130 // space in AST. However, certain targets (e.g. amdgcn) request them to be 5131 // emitted in constant address space in LLVM IR. To be consistent with other 5132 // parts of AST, string literal global variables in constant address space 5133 // need to be casted to default address space before being put into address 5134 // map and referenced by other part of CodeGen. 5135 // In OpenCL, string literals are in constant address space in AST, therefore 5136 // they should not be casted to default address space. 5137 static llvm::Constant * 5138 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, 5139 llvm::GlobalVariable *GV) { 5140 llvm::Constant *Cast = GV; 5141 if (!CGM.getLangOpts().OpenCL) { 5142 auto AS = CGM.GetGlobalConstantAddressSpace(); 5143 if (AS != LangAS::Default) 5144 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast( 5145 CGM, GV, AS, LangAS::Default, 5146 llvm::PointerType::get( 5147 CGM.getLLVMContext(), 5148 CGM.getContext().getTargetAddressSpace(LangAS::Default))); 5149 } 5150 return Cast; 5151 } 5152 5153 template<typename SomeDecl> 5154 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 5155 llvm::GlobalValue *GV) { 5156 if (!getLangOpts().CPlusPlus) 5157 return; 5158 5159 // Must have 'used' attribute, or else inline assembly can't rely on 5160 // the name existing. 5161 if (!D->template hasAttr<UsedAttr>()) 5162 return; 5163 5164 // Must have internal linkage and an ordinary name. 5165 if (!D->getIdentifier() || D->getFormalLinkage() != Linkage::Internal) 5166 return; 5167 5168 // Must be in an extern "C" context. Entities declared directly within 5169 // a record are not extern "C" even if the record is in such a context. 5170 const SomeDecl *First = D->getFirstDecl(); 5171 if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 5172 return; 5173 5174 // OK, this is an internal linkage entity inside an extern "C" linkage 5175 // specification. Make a note of that so we can give it the "expected" 5176 // mangled name if nothing else is using that name. 5177 std::pair<StaticExternCMap::iterator, bool> R = 5178 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 5179 5180 // If we have multiple internal linkage entities with the same name 5181 // in extern "C" regions, none of them gets that name. 5182 if (!R.second) 5183 R.first->second = nullptr; 5184 } 5185 5186 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 5187 if (!CGM.supportsCOMDAT()) 5188 return false; 5189 5190 if (D.hasAttr<SelectAnyAttr>()) 5191 return true; 5192 5193 GVALinkage Linkage; 5194 if (auto *VD = dyn_cast<VarDecl>(&D)) 5195 Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 5196 else 5197 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 5198 5199 switch (Linkage) { 5200 case GVA_Internal: 5201 case GVA_AvailableExternally: 5202 case GVA_StrongExternal: 5203 return false; 5204 case GVA_DiscardableODR: 5205 case GVA_StrongODR: 5206 return true; 5207 } 5208 llvm_unreachable("No such linkage"); 5209 } 5210 5211 bool CodeGenModule::supportsCOMDAT() const { 5212 return getTriple().supportsCOMDAT(); 5213 } 5214 5215 void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 5216 llvm::GlobalObject &GO) { 5217 if (!shouldBeInCOMDAT(*this, D)) 5218 return; 5219 GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 5220 } 5221 5222 /// Pass IsTentative as true if you want to create a tentative definition. 5223 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 5224 bool IsTentative) { 5225 // OpenCL global variables of sampler type are translated to function calls, 5226 // therefore no need to be translated. 5227 QualType ASTTy = D->getType(); 5228 if (getLangOpts().OpenCL && ASTTy->isSamplerT()) 5229 return; 5230 5231 // If this is OpenMP device, check if it is legal to emit this global 5232 // normally. 5233 if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime && 5234 OpenMPRuntime->emitTargetGlobalVariable(D)) 5235 return; 5236 5237 llvm::TrackingVH<llvm::Constant> Init; 5238 bool NeedsGlobalCtor = false; 5239 // Whether the definition of the variable is available externally. 5240 // If yes, we shouldn't emit the GloablCtor and GlobalDtor for the variable 5241 // since this is the job for its original source. 5242 bool IsDefinitionAvailableExternally = 5243 getContext().GetGVALinkageForVariable(D) == GVA_AvailableExternally; 5244 bool NeedsGlobalDtor = 5245 !IsDefinitionAvailableExternally && 5246 D->needsDestruction(getContext()) == QualType::DK_cxx_destructor; 5247 5248 const VarDecl *InitDecl; 5249 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 5250 5251 std::optional<ConstantEmitter> emitter; 5252 5253 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 5254 // as part of their declaration." Sema has already checked for 5255 // error cases, so we just need to set Init to UndefValue. 5256 bool IsCUDASharedVar = 5257 getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>(); 5258 // Shadows of initialized device-side global variables are also left 5259 // undefined. 5260 // Managed Variables should be initialized on both host side and device side. 5261 bool IsCUDAShadowVar = 5262 !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 5263 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() || 5264 D->hasAttr<CUDASharedAttr>()); 5265 bool IsCUDADeviceShadowVar = 5266 getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 5267 (D->getType()->isCUDADeviceBuiltinSurfaceType() || 5268 D->getType()->isCUDADeviceBuiltinTextureType()); 5269 if (getLangOpts().CUDA && 5270 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) 5271 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 5272 else if (D->hasAttr<LoaderUninitializedAttr>()) 5273 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 5274 else if (!InitExpr) { 5275 // This is a tentative definition; tentative definitions are 5276 // implicitly initialized with { 0 }. 5277 // 5278 // Note that tentative definitions are only emitted at the end of 5279 // a translation unit, so they should never have incomplete 5280 // type. In addition, EmitTentativeDefinition makes sure that we 5281 // never attempt to emit a tentative definition if a real one 5282 // exists. A use may still exists, however, so we still may need 5283 // to do a RAUW. 5284 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 5285 Init = EmitNullConstant(D->getType()); 5286 } else { 5287 initializedGlobalDecl = GlobalDecl(D); 5288 emitter.emplace(*this); 5289 llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl); 5290 if (!Initializer) { 5291 QualType T = InitExpr->getType(); 5292 if (D->getType()->isReferenceType()) 5293 T = D->getType(); 5294 5295 if (getLangOpts().CPlusPlus) { 5296 if (InitDecl->hasFlexibleArrayInit(getContext())) 5297 ErrorUnsupported(D, "flexible array initializer"); 5298 Init = EmitNullConstant(T); 5299 5300 if (!IsDefinitionAvailableExternally) 5301 NeedsGlobalCtor = true; 5302 } else { 5303 ErrorUnsupported(D, "static initializer"); 5304 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 5305 } 5306 } else { 5307 Init = Initializer; 5308 // We don't need an initializer, so remove the entry for the delayed 5309 // initializer position (just in case this entry was delayed) if we 5310 // also don't need to register a destructor. 5311 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 5312 DelayedCXXInitPosition.erase(D); 5313 5314 #ifndef NDEBUG 5315 CharUnits VarSize = getContext().getTypeSizeInChars(ASTTy) + 5316 InitDecl->getFlexibleArrayInitChars(getContext()); 5317 CharUnits CstSize = CharUnits::fromQuantity( 5318 getDataLayout().getTypeAllocSize(Init->getType())); 5319 assert(VarSize == CstSize && "Emitted constant has unexpected size"); 5320 #endif 5321 } 5322 } 5323 5324 llvm::Type* InitType = Init->getType(); 5325 llvm::Constant *Entry = 5326 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); 5327 5328 // Strip off pointer casts if we got them. 5329 Entry = Entry->stripPointerCasts(); 5330 5331 // Entry is now either a Function or GlobalVariable. 5332 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 5333 5334 // We have a definition after a declaration with the wrong type. 5335 // We must make a new GlobalVariable* and update everything that used OldGV 5336 // (a declaration or tentative definition) with the new GlobalVariable* 5337 // (which will be a definition). 5338 // 5339 // This happens if there is a prototype for a global (e.g. 5340 // "extern int x[];") and then a definition of a different type (e.g. 5341 // "int x[10];"). This also happens when an initializer has a different type 5342 // from the type of the global (this happens with unions). 5343 if (!GV || GV->getValueType() != InitType || 5344 GV->getType()->getAddressSpace() != 5345 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) { 5346 5347 // Move the old entry aside so that we'll create a new one. 5348 Entry->setName(StringRef()); 5349 5350 // Make a new global with the correct type, this is now guaranteed to work. 5351 GV = cast<llvm::GlobalVariable>( 5352 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)) 5353 ->stripPointerCasts()); 5354 5355 // Replace all uses of the old global with the new global 5356 llvm::Constant *NewPtrForOldDecl = 5357 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, 5358 Entry->getType()); 5359 Entry->replaceAllUsesWith(NewPtrForOldDecl); 5360 5361 // Erase the old global, since it is no longer used. 5362 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 5363 } 5364 5365 MaybeHandleStaticInExternC(D, GV); 5366 5367 if (D->hasAttr<AnnotateAttr>()) 5368 AddGlobalAnnotations(D, GV); 5369 5370 // Set the llvm linkage type as appropriate. 5371 llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(D); 5372 5373 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 5374 // the device. [...]" 5375 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 5376 // __device__, declares a variable that: [...] 5377 // Is accessible from all the threads within the grid and from the host 5378 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 5379 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 5380 if (LangOpts.CUDA) { 5381 if (LangOpts.CUDAIsDevice) { 5382 if (Linkage != llvm::GlobalValue::InternalLinkage && 5383 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 5384 D->getType()->isCUDADeviceBuiltinSurfaceType() || 5385 D->getType()->isCUDADeviceBuiltinTextureType())) 5386 GV->setExternallyInitialized(true); 5387 } else { 5388 getCUDARuntime().internalizeDeviceSideVar(D, Linkage); 5389 } 5390 getCUDARuntime().handleVarRegistration(D, *GV); 5391 } 5392 5393 GV->setInitializer(Init); 5394 if (emitter) 5395 emitter->finalize(GV); 5396 5397 // If it is safe to mark the global 'constant', do so now. 5398 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 5399 D->getType().isConstantStorage(getContext(), true, true)); 5400 5401 // If it is in a read-only section, mark it 'constant'. 5402 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 5403 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 5404 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 5405 GV->setConstant(true); 5406 } 5407 5408 CharUnits AlignVal = getContext().getDeclAlign(D); 5409 // Check for alignment specifed in an 'omp allocate' directive. 5410 if (std::optional<CharUnits> AlignValFromAllocate = 5411 getOMPAllocateAlignment(D)) 5412 AlignVal = *AlignValFromAllocate; 5413 GV->setAlignment(AlignVal.getAsAlign()); 5414 5415 // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper 5416 // function is only defined alongside the variable, not also alongside 5417 // callers. Normally, all accesses to a thread_local go through the 5418 // thread-wrapper in order to ensure initialization has occurred, underlying 5419 // variable will never be used other than the thread-wrapper, so it can be 5420 // converted to internal linkage. 5421 // 5422 // However, if the variable has the 'constinit' attribute, it _can_ be 5423 // referenced directly, without calling the thread-wrapper, so the linkage 5424 // must not be changed. 5425 // 5426 // Additionally, if the variable isn't plain external linkage, e.g. if it's 5427 // weak or linkonce, the de-duplication semantics are important to preserve, 5428 // so we don't change the linkage. 5429 if (D->getTLSKind() == VarDecl::TLS_Dynamic && 5430 Linkage == llvm::GlobalValue::ExternalLinkage && 5431 Context.getTargetInfo().getTriple().isOSDarwin() && 5432 !D->hasAttr<ConstInitAttr>()) 5433 Linkage = llvm::GlobalValue::InternalLinkage; 5434 5435 GV->setLinkage(Linkage); 5436 if (D->hasAttr<DLLImportAttr>()) 5437 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 5438 else if (D->hasAttr<DLLExportAttr>()) 5439 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 5440 else 5441 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 5442 5443 if (Linkage == llvm::GlobalVariable::CommonLinkage) { 5444 // common vars aren't constant even if declared const. 5445 GV->setConstant(false); 5446 // Tentative definition of global variables may be initialized with 5447 // non-zero null pointers. In this case they should have weak linkage 5448 // since common linkage must have zero initializer and must not have 5449 // explicit section therefore cannot have non-zero initial value. 5450 if (!GV->getInitializer()->isNullValue()) 5451 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 5452 } 5453 5454 setNonAliasAttributes(D, GV); 5455 5456 if (D->getTLSKind() && !GV->isThreadLocal()) { 5457 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 5458 CXXThreadLocals.push_back(D); 5459 setTLSMode(GV, *D); 5460 } 5461 5462 maybeSetTrivialComdat(*D, *GV); 5463 5464 // Emit the initializer function if necessary. 5465 if (NeedsGlobalCtor || NeedsGlobalDtor) 5466 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 5467 5468 SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor); 5469 5470 // Emit global variable debug information. 5471 if (CGDebugInfo *DI = getModuleDebugInfo()) 5472 if (getCodeGenOpts().hasReducedDebugInfo()) 5473 DI->EmitGlobalVariable(GV, D); 5474 } 5475 5476 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) { 5477 if (CGDebugInfo *DI = getModuleDebugInfo()) 5478 if (getCodeGenOpts().hasReducedDebugInfo()) { 5479 QualType ASTTy = D->getType(); 5480 llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType()); 5481 llvm::Constant *GV = 5482 GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D); 5483 DI->EmitExternalVariable( 5484 cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D); 5485 } 5486 } 5487 5488 static bool isVarDeclStrongDefinition(const ASTContext &Context, 5489 CodeGenModule &CGM, const VarDecl *D, 5490 bool NoCommon) { 5491 // Don't give variables common linkage if -fno-common was specified unless it 5492 // was overridden by a NoCommon attribute. 5493 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 5494 return true; 5495 5496 // C11 6.9.2/2: 5497 // A declaration of an identifier for an object that has file scope without 5498 // an initializer, and without a storage-class specifier or with the 5499 // storage-class specifier static, constitutes a tentative definition. 5500 if (D->getInit() || D->hasExternalStorage()) 5501 return true; 5502 5503 // A variable cannot be both common and exist in a section. 5504 if (D->hasAttr<SectionAttr>()) 5505 return true; 5506 5507 // A variable cannot be both common and exist in a section. 5508 // We don't try to determine which is the right section in the front-end. 5509 // If no specialized section name is applicable, it will resort to default. 5510 if (D->hasAttr<PragmaClangBSSSectionAttr>() || 5511 D->hasAttr<PragmaClangDataSectionAttr>() || 5512 D->hasAttr<PragmaClangRelroSectionAttr>() || 5513 D->hasAttr<PragmaClangRodataSectionAttr>()) 5514 return true; 5515 5516 // Thread local vars aren't considered common linkage. 5517 if (D->getTLSKind()) 5518 return true; 5519 5520 // Tentative definitions marked with WeakImportAttr are true definitions. 5521 if (D->hasAttr<WeakImportAttr>()) 5522 return true; 5523 5524 // A variable cannot be both common and exist in a comdat. 5525 if (shouldBeInCOMDAT(CGM, *D)) 5526 return true; 5527 5528 // Declarations with a required alignment do not have common linkage in MSVC 5529 // mode. 5530 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5531 if (D->hasAttr<AlignedAttr>()) 5532 return true; 5533 QualType VarType = D->getType(); 5534 if (Context.isAlignmentRequired(VarType)) 5535 return true; 5536 5537 if (const auto *RT = VarType->getAs<RecordType>()) { 5538 const RecordDecl *RD = RT->getDecl(); 5539 for (const FieldDecl *FD : RD->fields()) { 5540 if (FD->isBitField()) 5541 continue; 5542 if (FD->hasAttr<AlignedAttr>()) 5543 return true; 5544 if (Context.isAlignmentRequired(FD->getType())) 5545 return true; 5546 } 5547 } 5548 } 5549 5550 // Microsoft's link.exe doesn't support alignments greater than 32 bytes for 5551 // common symbols, so symbols with greater alignment requirements cannot be 5552 // common. 5553 // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two 5554 // alignments for common symbols via the aligncomm directive, so this 5555 // restriction only applies to MSVC environments. 5556 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() && 5557 Context.getTypeAlignIfKnown(D->getType()) > 5558 Context.toBits(CharUnits::fromQuantity(32))) 5559 return true; 5560 5561 return false; 5562 } 5563 5564 llvm::GlobalValue::LinkageTypes 5565 CodeGenModule::getLLVMLinkageForDeclarator(const DeclaratorDecl *D, 5566 GVALinkage Linkage) { 5567 if (Linkage == GVA_Internal) 5568 return llvm::Function::InternalLinkage; 5569 5570 if (D->hasAttr<WeakAttr>()) 5571 return llvm::GlobalVariable::WeakAnyLinkage; 5572 5573 if (const auto *FD = D->getAsFunction()) 5574 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally) 5575 return llvm::GlobalVariable::LinkOnceAnyLinkage; 5576 5577 // We are guaranteed to have a strong definition somewhere else, 5578 // so we can use available_externally linkage. 5579 if (Linkage == GVA_AvailableExternally) 5580 return llvm::GlobalValue::AvailableExternallyLinkage; 5581 5582 // Note that Apple's kernel linker doesn't support symbol 5583 // coalescing, so we need to avoid linkonce and weak linkages there. 5584 // Normally, this means we just map to internal, but for explicit 5585 // instantiations we'll map to external. 5586 5587 // In C++, the compiler has to emit a definition in every translation unit 5588 // that references the function. We should use linkonce_odr because 5589 // a) if all references in this translation unit are optimized away, we 5590 // don't need to codegen it. b) if the function persists, it needs to be 5591 // merged with other definitions. c) C++ has the ODR, so we know the 5592 // definition is dependable. 5593 if (Linkage == GVA_DiscardableODR) 5594 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 5595 : llvm::Function::InternalLinkage; 5596 5597 // An explicit instantiation of a template has weak linkage, since 5598 // explicit instantiations can occur in multiple translation units 5599 // and must all be equivalent. However, we are not allowed to 5600 // throw away these explicit instantiations. 5601 // 5602 // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU, 5603 // so say that CUDA templates are either external (for kernels) or internal. 5604 // This lets llvm perform aggressive inter-procedural optimizations. For 5605 // -fgpu-rdc case, device function calls across multiple TU's are allowed, 5606 // therefore we need to follow the normal linkage paradigm. 5607 if (Linkage == GVA_StrongODR) { 5608 if (getLangOpts().AppleKext) 5609 return llvm::Function::ExternalLinkage; 5610 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 5611 !getLangOpts().GPURelocatableDeviceCode) 5612 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage 5613 : llvm::Function::InternalLinkage; 5614 return llvm::Function::WeakODRLinkage; 5615 } 5616 5617 // C++ doesn't have tentative definitions and thus cannot have common 5618 // linkage. 5619 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 5620 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 5621 CodeGenOpts.NoCommon)) 5622 return llvm::GlobalVariable::CommonLinkage; 5623 5624 // selectany symbols are externally visible, so use weak instead of 5625 // linkonce. MSVC optimizes away references to const selectany globals, so 5626 // all definitions should be the same and ODR linkage should be used. 5627 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 5628 if (D->hasAttr<SelectAnyAttr>()) 5629 return llvm::GlobalVariable::WeakODRLinkage; 5630 5631 // Otherwise, we have strong external linkage. 5632 assert(Linkage == GVA_StrongExternal); 5633 return llvm::GlobalVariable::ExternalLinkage; 5634 } 5635 5636 llvm::GlobalValue::LinkageTypes 5637 CodeGenModule::getLLVMLinkageVarDefinition(const VarDecl *VD) { 5638 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 5639 return getLLVMLinkageForDeclarator(VD, Linkage); 5640 } 5641 5642 /// Replace the uses of a function that was declared with a non-proto type. 5643 /// We want to silently drop extra arguments from call sites 5644 static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 5645 llvm::Function *newFn) { 5646 // Fast path. 5647 if (old->use_empty()) return; 5648 5649 llvm::Type *newRetTy = newFn->getReturnType(); 5650 SmallVector<llvm::Value*, 4> newArgs; 5651 5652 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 5653 ui != ue; ) { 5654 llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 5655 llvm::User *user = use->getUser(); 5656 5657 // Recognize and replace uses of bitcasts. Most calls to 5658 // unprototyped functions will use bitcasts. 5659 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 5660 if (bitcast->getOpcode() == llvm::Instruction::BitCast) 5661 replaceUsesOfNonProtoConstant(bitcast, newFn); 5662 continue; 5663 } 5664 5665 // Recognize calls to the function. 5666 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user); 5667 if (!callSite) continue; 5668 if (!callSite->isCallee(&*use)) 5669 continue; 5670 5671 // If the return types don't match exactly, then we can't 5672 // transform this call unless it's dead. 5673 if (callSite->getType() != newRetTy && !callSite->use_empty()) 5674 continue; 5675 5676 // Get the call site's attribute list. 5677 SmallVector<llvm::AttributeSet, 8> newArgAttrs; 5678 llvm::AttributeList oldAttrs = callSite->getAttributes(); 5679 5680 // If the function was passed too few arguments, don't transform. 5681 unsigned newNumArgs = newFn->arg_size(); 5682 if (callSite->arg_size() < newNumArgs) 5683 continue; 5684 5685 // If extra arguments were passed, we silently drop them. 5686 // If any of the types mismatch, we don't transform. 5687 unsigned argNo = 0; 5688 bool dontTransform = false; 5689 for (llvm::Argument &A : newFn->args()) { 5690 if (callSite->getArgOperand(argNo)->getType() != A.getType()) { 5691 dontTransform = true; 5692 break; 5693 } 5694 5695 // Add any parameter attributes. 5696 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo)); 5697 argNo++; 5698 } 5699 if (dontTransform) 5700 continue; 5701 5702 // Okay, we can transform this. Create the new call instruction and copy 5703 // over the required information. 5704 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo); 5705 5706 // Copy over any operand bundles. 5707 SmallVector<llvm::OperandBundleDef, 1> newBundles; 5708 callSite->getOperandBundlesAsDefs(newBundles); 5709 5710 llvm::CallBase *newCall; 5711 if (isa<llvm::CallInst>(callSite)) { 5712 newCall = 5713 llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite); 5714 } else { 5715 auto *oldInvoke = cast<llvm::InvokeInst>(callSite); 5716 newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(), 5717 oldInvoke->getUnwindDest(), newArgs, 5718 newBundles, "", callSite); 5719 } 5720 newArgs.clear(); // for the next iteration 5721 5722 if (!newCall->getType()->isVoidTy()) 5723 newCall->takeName(callSite); 5724 newCall->setAttributes( 5725 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(), 5726 oldAttrs.getRetAttrs(), newArgAttrs)); 5727 newCall->setCallingConv(callSite->getCallingConv()); 5728 5729 // Finally, remove the old call, replacing any uses with the new one. 5730 if (!callSite->use_empty()) 5731 callSite->replaceAllUsesWith(newCall); 5732 5733 // Copy debug location attached to CI. 5734 if (callSite->getDebugLoc()) 5735 newCall->setDebugLoc(callSite->getDebugLoc()); 5736 5737 callSite->eraseFromParent(); 5738 } 5739 } 5740 5741 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 5742 /// implement a function with no prototype, e.g. "int foo() {}". If there are 5743 /// existing call uses of the old function in the module, this adjusts them to 5744 /// call the new function directly. 5745 /// 5746 /// This is not just a cleanup: the always_inline pass requires direct calls to 5747 /// functions to be able to inline them. If there is a bitcast in the way, it 5748 /// won't inline them. Instcombine normally deletes these calls, but it isn't 5749 /// run at -O0. 5750 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 5751 llvm::Function *NewFn) { 5752 // If we're redefining a global as a function, don't transform it. 5753 if (!isa<llvm::Function>(Old)) return; 5754 5755 replaceUsesOfNonProtoConstant(Old, NewFn); 5756 } 5757 5758 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 5759 auto DK = VD->isThisDeclarationADefinition(); 5760 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) 5761 return; 5762 5763 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 5764 // If we have a definition, this might be a deferred decl. If the 5765 // instantiation is explicit, make sure we emit it at the end. 5766 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 5767 GetAddrOfGlobalVar(VD); 5768 5769 EmitTopLevelDecl(VD); 5770 } 5771 5772 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 5773 llvm::GlobalValue *GV) { 5774 const auto *D = cast<FunctionDecl>(GD.getDecl()); 5775 5776 // Compute the function info and LLVM type. 5777 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 5778 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 5779 5780 // Get or create the prototype for the function. 5781 if (!GV || (GV->getValueType() != Ty)) 5782 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 5783 /*DontDefer=*/true, 5784 ForDefinition)); 5785 5786 // Already emitted. 5787 if (!GV->isDeclaration()) 5788 return; 5789 5790 // We need to set linkage and visibility on the function before 5791 // generating code for it because various parts of IR generation 5792 // want to propagate this information down (e.g. to local static 5793 // declarations). 5794 auto *Fn = cast<llvm::Function>(GV); 5795 setFunctionLinkage(GD, Fn); 5796 5797 // FIXME: this is redundant with part of setFunctionDefinitionAttributes 5798 setGVProperties(Fn, GD); 5799 5800 MaybeHandleStaticInExternC(D, Fn); 5801 5802 maybeSetTrivialComdat(*D, *Fn); 5803 5804 CodeGenFunction(*this).GenerateCode(GD, Fn, FI); 5805 5806 setNonAliasAttributes(GD, Fn); 5807 SetLLVMFunctionAttributesForDefinition(D, Fn); 5808 5809 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 5810 AddGlobalCtor(Fn, CA->getPriority()); 5811 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 5812 AddGlobalDtor(Fn, DA->getPriority(), true); 5813 if (getLangOpts().OpenMP && D->hasAttr<OMPDeclareTargetDeclAttr>()) 5814 getOpenMPRuntime().emitDeclareTargetFunction(D, GV); 5815 } 5816 5817 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 5818 const auto *D = cast<ValueDecl>(GD.getDecl()); 5819 const AliasAttr *AA = D->getAttr<AliasAttr>(); 5820 assert(AA && "Not an alias?"); 5821 5822 StringRef MangledName = getMangledName(GD); 5823 5824 if (AA->getAliasee() == MangledName) { 5825 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 5826 return; 5827 } 5828 5829 // If there is a definition in the module, then it wins over the alias. 5830 // This is dubious, but allow it to be safe. Just ignore the alias. 5831 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 5832 if (Entry && !Entry->isDeclaration()) 5833 return; 5834 5835 Aliases.push_back(GD); 5836 5837 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 5838 5839 // Create a reference to the named value. This ensures that it is emitted 5840 // if a deferred decl. 5841 llvm::Constant *Aliasee; 5842 llvm::GlobalValue::LinkageTypes LT; 5843 if (isa<llvm::FunctionType>(DeclTy)) { 5844 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 5845 /*ForVTable=*/false); 5846 LT = getFunctionLinkage(GD); 5847 } else { 5848 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 5849 /*D=*/nullptr); 5850 if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl())) 5851 LT = getLLVMLinkageVarDefinition(VD); 5852 else 5853 LT = getFunctionLinkage(GD); 5854 } 5855 5856 // Create the new alias itself, but don't set a name yet. 5857 unsigned AS = Aliasee->getType()->getPointerAddressSpace(); 5858 auto *GA = 5859 llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule()); 5860 5861 if (Entry) { 5862 if (GA->getAliasee() == Entry) { 5863 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 5864 return; 5865 } 5866 5867 assert(Entry->isDeclaration()); 5868 5869 // If there is a declaration in the module, then we had an extern followed 5870 // by the alias, as in: 5871 // extern int test6(); 5872 // ... 5873 // int test6() __attribute__((alias("test7"))); 5874 // 5875 // Remove it and replace uses of it with the alias. 5876 GA->takeName(Entry); 5877 5878 Entry->replaceAllUsesWith(GA); 5879 Entry->eraseFromParent(); 5880 } else { 5881 GA->setName(MangledName); 5882 } 5883 5884 // Set attributes which are particular to an alias; this is a 5885 // specialization of the attributes which may be set on a global 5886 // variable/function. 5887 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 5888 D->isWeakImported()) { 5889 GA->setLinkage(llvm::Function::WeakAnyLinkage); 5890 } 5891 5892 if (const auto *VD = dyn_cast<VarDecl>(D)) 5893 if (VD->getTLSKind()) 5894 setTLSMode(GA, *VD); 5895 5896 SetCommonAttributes(GD, GA); 5897 5898 // Emit global alias debug information. 5899 if (isa<VarDecl>(D)) 5900 if (CGDebugInfo *DI = getModuleDebugInfo()) 5901 DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD); 5902 } 5903 5904 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 5905 const auto *D = cast<ValueDecl>(GD.getDecl()); 5906 const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 5907 assert(IFA && "Not an ifunc?"); 5908 5909 StringRef MangledName = getMangledName(GD); 5910 5911 if (IFA->getResolver() == MangledName) { 5912 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 5913 return; 5914 } 5915 5916 // Report an error if some definition overrides ifunc. 5917 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 5918 if (Entry && !Entry->isDeclaration()) { 5919 GlobalDecl OtherGD; 5920 if (lookupRepresentativeDecl(MangledName, OtherGD) && 5921 DiagnosedConflictingDefinitions.insert(GD).second) { 5922 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name) 5923 << MangledName; 5924 Diags.Report(OtherGD.getDecl()->getLocation(), 5925 diag::note_previous_definition); 5926 } 5927 return; 5928 } 5929 5930 Aliases.push_back(GD); 5931 5932 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 5933 llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy); 5934 llvm::Constant *Resolver = 5935 GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {}, 5936 /*ForVTable=*/false); 5937 llvm::GlobalIFunc *GIF = 5938 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 5939 "", Resolver, &getModule()); 5940 if (Entry) { 5941 if (GIF->getResolver() == Entry) { 5942 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 5943 return; 5944 } 5945 assert(Entry->isDeclaration()); 5946 5947 // If there is a declaration in the module, then we had an extern followed 5948 // by the ifunc, as in: 5949 // extern int test(); 5950 // ... 5951 // int test() __attribute__((ifunc("resolver"))); 5952 // 5953 // Remove it and replace uses of it with the ifunc. 5954 GIF->takeName(Entry); 5955 5956 Entry->replaceAllUsesWith(GIF); 5957 Entry->eraseFromParent(); 5958 } else 5959 GIF->setName(MangledName); 5960 if (auto *F = dyn_cast<llvm::Function>(Resolver)) { 5961 F->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation); 5962 } 5963 SetCommonAttributes(GD, GIF); 5964 } 5965 5966 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 5967 ArrayRef<llvm::Type*> Tys) { 5968 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 5969 Tys); 5970 } 5971 5972 static llvm::StringMapEntry<llvm::GlobalVariable *> & 5973 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 5974 const StringLiteral *Literal, bool TargetIsLSB, 5975 bool &IsUTF16, unsigned &StringLength) { 5976 StringRef String = Literal->getString(); 5977 unsigned NumBytes = String.size(); 5978 5979 // Check for simple case. 5980 if (!Literal->containsNonAsciiOrNull()) { 5981 StringLength = NumBytes; 5982 return *Map.insert(std::make_pair(String, nullptr)).first; 5983 } 5984 5985 // Otherwise, convert the UTF8 literals into a string of shorts. 5986 IsUTF16 = true; 5987 5988 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 5989 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5990 llvm::UTF16 *ToPtr = &ToBuf[0]; 5991 5992 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5993 ToPtr + NumBytes, llvm::strictConversion); 5994 5995 // ConvertUTF8toUTF16 returns the length in ToPtr. 5996 StringLength = ToPtr - &ToBuf[0]; 5997 5998 // Add an explicit null. 5999 *ToPtr = 0; 6000 return *Map.insert(std::make_pair( 6001 StringRef(reinterpret_cast<const char *>(ToBuf.data()), 6002 (StringLength + 1) * 2), 6003 nullptr)).first; 6004 } 6005 6006 ConstantAddress 6007 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 6008 unsigned StringLength = 0; 6009 bool isUTF16 = false; 6010 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 6011 GetConstantCFStringEntry(CFConstantStringMap, Literal, 6012 getDataLayout().isLittleEndian(), isUTF16, 6013 StringLength); 6014 6015 if (auto *C = Entry.second) 6016 return ConstantAddress( 6017 C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment())); 6018 6019 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 6020 llvm::Constant *Zeros[] = { Zero, Zero }; 6021 6022 const ASTContext &Context = getContext(); 6023 const llvm::Triple &Triple = getTriple(); 6024 6025 const auto CFRuntime = getLangOpts().CFRuntime; 6026 const bool IsSwiftABI = 6027 static_cast<unsigned>(CFRuntime) >= 6028 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift); 6029 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1; 6030 6031 // If we don't already have it, get __CFConstantStringClassReference. 6032 if (!CFConstantStringClassRef) { 6033 const char *CFConstantStringClassName = "__CFConstantStringClassReference"; 6034 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 6035 Ty = llvm::ArrayType::get(Ty, 0); 6036 6037 switch (CFRuntime) { 6038 default: break; 6039 case LangOptions::CoreFoundationABI::Swift: [[fallthrough]]; 6040 case LangOptions::CoreFoundationABI::Swift5_0: 6041 CFConstantStringClassName = 6042 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN" 6043 : "$s10Foundation19_NSCFConstantStringCN"; 6044 Ty = IntPtrTy; 6045 break; 6046 case LangOptions::CoreFoundationABI::Swift4_2: 6047 CFConstantStringClassName = 6048 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN" 6049 : "$S10Foundation19_NSCFConstantStringCN"; 6050 Ty = IntPtrTy; 6051 break; 6052 case LangOptions::CoreFoundationABI::Swift4_1: 6053 CFConstantStringClassName = 6054 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN" 6055 : "__T010Foundation19_NSCFConstantStringCN"; 6056 Ty = IntPtrTy; 6057 break; 6058 } 6059 6060 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName); 6061 6062 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) { 6063 llvm::GlobalValue *GV = nullptr; 6064 6065 if ((GV = dyn_cast<llvm::GlobalValue>(C))) { 6066 IdentifierInfo &II = Context.Idents.get(GV->getName()); 6067 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl(); 6068 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 6069 6070 const VarDecl *VD = nullptr; 6071 for (const auto *Result : DC->lookup(&II)) 6072 if ((VD = dyn_cast<VarDecl>(Result))) 6073 break; 6074 6075 if (Triple.isOSBinFormatELF()) { 6076 if (!VD) 6077 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 6078 } else { 6079 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 6080 if (!VD || !VD->hasAttr<DLLExportAttr>()) 6081 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 6082 else 6083 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 6084 } 6085 6086 setDSOLocal(GV); 6087 } 6088 } 6089 6090 // Decay array -> ptr 6091 CFConstantStringClassRef = 6092 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) 6093 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros); 6094 } 6095 6096 QualType CFTy = Context.getCFConstantStringType(); 6097 6098 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 6099 6100 ConstantInitBuilder Builder(*this); 6101 auto Fields = Builder.beginStruct(STy); 6102 6103 // Class pointer. 6104 Fields.add(cast<llvm::Constant>(CFConstantStringClassRef)); 6105 6106 // Flags. 6107 if (IsSwiftABI) { 6108 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01); 6109 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8); 6110 } else { 6111 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); 6112 } 6113 6114 // String pointer. 6115 llvm::Constant *C = nullptr; 6116 if (isUTF16) { 6117 auto Arr = llvm::ArrayRef( 6118 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 6119 Entry.first().size() / 2); 6120 C = llvm::ConstantDataArray::get(VMContext, Arr); 6121 } else { 6122 C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 6123 } 6124 6125 // Note: -fwritable-strings doesn't make the backing store strings of 6126 // CFStrings writable. 6127 auto *GV = 6128 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 6129 llvm::GlobalValue::PrivateLinkage, C, ".str"); 6130 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 6131 // Don't enforce the target's minimum global alignment, since the only use 6132 // of the string is via this class initializer. 6133 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy) 6134 : Context.getTypeAlignInChars(Context.CharTy); 6135 GV->setAlignment(Align.getAsAlign()); 6136 6137 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 6138 // Without it LLVM can merge the string with a non unnamed_addr one during 6139 // LTO. Doing that changes the section it ends in, which surprises ld64. 6140 if (Triple.isOSBinFormatMachO()) 6141 GV->setSection(isUTF16 ? "__TEXT,__ustring" 6142 : "__TEXT,__cstring,cstring_literals"); 6143 // Make sure the literal ends up in .rodata to allow for safe ICF and for 6144 // the static linker to adjust permissions to read-only later on. 6145 else if (Triple.isOSBinFormatELF()) 6146 GV->setSection(".rodata"); 6147 6148 // String. 6149 llvm::Constant *Str = 6150 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 6151 6152 Fields.add(Str); 6153 6154 // String length. 6155 llvm::IntegerType *LengthTy = 6156 llvm::IntegerType::get(getModule().getContext(), 6157 Context.getTargetInfo().getLongWidth()); 6158 if (IsSwiftABI) { 6159 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 6160 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 6161 LengthTy = Int32Ty; 6162 else 6163 LengthTy = IntPtrTy; 6164 } 6165 Fields.addInt(LengthTy, StringLength); 6166 6167 // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is 6168 // properly aligned on 32-bit platforms. 6169 CharUnits Alignment = 6170 IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign(); 6171 6172 // The struct. 6173 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, 6174 /*isConstant=*/false, 6175 llvm::GlobalVariable::PrivateLinkage); 6176 GV->addAttribute("objc_arc_inert"); 6177 switch (Triple.getObjectFormat()) { 6178 case llvm::Triple::UnknownObjectFormat: 6179 llvm_unreachable("unknown file format"); 6180 case llvm::Triple::DXContainer: 6181 case llvm::Triple::GOFF: 6182 case llvm::Triple::SPIRV: 6183 case llvm::Triple::XCOFF: 6184 llvm_unreachable("unimplemented"); 6185 case llvm::Triple::COFF: 6186 case llvm::Triple::ELF: 6187 case llvm::Triple::Wasm: 6188 GV->setSection("cfstring"); 6189 break; 6190 case llvm::Triple::MachO: 6191 GV->setSection("__DATA,__cfstring"); 6192 break; 6193 } 6194 Entry.second = GV; 6195 6196 return ConstantAddress(GV, GV->getValueType(), Alignment); 6197 } 6198 6199 bool CodeGenModule::getExpressionLocationsEnabled() const { 6200 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo; 6201 } 6202 6203 QualType CodeGenModule::getObjCFastEnumerationStateType() { 6204 if (ObjCFastEnumerationStateType.isNull()) { 6205 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 6206 D->startDefinition(); 6207 6208 QualType FieldTypes[] = { 6209 Context.UnsignedLongTy, Context.getPointerType(Context.getObjCIdType()), 6210 Context.getPointerType(Context.UnsignedLongTy), 6211 Context.getConstantArrayType(Context.UnsignedLongTy, llvm::APInt(32, 5), 6212 nullptr, ArraySizeModifier::Normal, 0)}; 6213 6214 for (size_t i = 0; i < 4; ++i) { 6215 FieldDecl *Field = FieldDecl::Create(Context, 6216 D, 6217 SourceLocation(), 6218 SourceLocation(), nullptr, 6219 FieldTypes[i], /*TInfo=*/nullptr, 6220 /*BitWidth=*/nullptr, 6221 /*Mutable=*/false, 6222 ICIS_NoInit); 6223 Field->setAccess(AS_public); 6224 D->addDecl(Field); 6225 } 6226 6227 D->completeDefinition(); 6228 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 6229 } 6230 6231 return ObjCFastEnumerationStateType; 6232 } 6233 6234 llvm::Constant * 6235 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 6236 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 6237 6238 // Don't emit it as the address of the string, emit the string data itself 6239 // as an inline array. 6240 if (E->getCharByteWidth() == 1) { 6241 SmallString<64> Str(E->getString()); 6242 6243 // Resize the string to the right size, which is indicated by its type. 6244 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 6245 assert(CAT && "String literal not of constant array type!"); 6246 Str.resize(CAT->getSize().getZExtValue()); 6247 return llvm::ConstantDataArray::getString(VMContext, Str, false); 6248 } 6249 6250 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 6251 llvm::Type *ElemTy = AType->getElementType(); 6252 unsigned NumElements = AType->getNumElements(); 6253 6254 // Wide strings have either 2-byte or 4-byte elements. 6255 if (ElemTy->getPrimitiveSizeInBits() == 16) { 6256 SmallVector<uint16_t, 32> Elements; 6257 Elements.reserve(NumElements); 6258 6259 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 6260 Elements.push_back(E->getCodeUnit(i)); 6261 Elements.resize(NumElements); 6262 return llvm::ConstantDataArray::get(VMContext, Elements); 6263 } 6264 6265 assert(ElemTy->getPrimitiveSizeInBits() == 32); 6266 SmallVector<uint32_t, 32> Elements; 6267 Elements.reserve(NumElements); 6268 6269 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 6270 Elements.push_back(E->getCodeUnit(i)); 6271 Elements.resize(NumElements); 6272 return llvm::ConstantDataArray::get(VMContext, Elements); 6273 } 6274 6275 static llvm::GlobalVariable * 6276 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 6277 CodeGenModule &CGM, StringRef GlobalName, 6278 CharUnits Alignment) { 6279 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace( 6280 CGM.GetGlobalConstantAddressSpace()); 6281 6282 llvm::Module &M = CGM.getModule(); 6283 // Create a global variable for this string 6284 auto *GV = new llvm::GlobalVariable( 6285 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 6286 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 6287 GV->setAlignment(Alignment.getAsAlign()); 6288 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 6289 if (GV->isWeakForLinker()) { 6290 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 6291 GV->setComdat(M.getOrInsertComdat(GV->getName())); 6292 } 6293 CGM.setDSOLocal(GV); 6294 6295 return GV; 6296 } 6297 6298 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 6299 /// constant array for the given string literal. 6300 ConstantAddress 6301 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 6302 StringRef Name) { 6303 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 6304 6305 llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 6306 llvm::GlobalVariable **Entry = nullptr; 6307 if (!LangOpts.WritableStrings) { 6308 Entry = &ConstantStringMap[C]; 6309 if (auto GV = *Entry) { 6310 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 6311 GV->setAlignment(Alignment.getAsAlign()); 6312 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 6313 GV->getValueType(), Alignment); 6314 } 6315 } 6316 6317 SmallString<256> MangledNameBuffer; 6318 StringRef GlobalVariableName; 6319 llvm::GlobalValue::LinkageTypes LT; 6320 6321 // Mangle the string literal if that's how the ABI merges duplicate strings. 6322 // Don't do it if they are writable, since we don't want writes in one TU to 6323 // affect strings in another. 6324 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) && 6325 !LangOpts.WritableStrings) { 6326 llvm::raw_svector_ostream Out(MangledNameBuffer); 6327 getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 6328 LT = llvm::GlobalValue::LinkOnceODRLinkage; 6329 GlobalVariableName = MangledNameBuffer; 6330 } else { 6331 LT = llvm::GlobalValue::PrivateLinkage; 6332 GlobalVariableName = Name; 6333 } 6334 6335 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 6336 6337 CGDebugInfo *DI = getModuleDebugInfo(); 6338 if (DI && getCodeGenOpts().hasReducedDebugInfo()) 6339 DI->AddStringLiteralDebugInfo(GV, S); 6340 6341 if (Entry) 6342 *Entry = GV; 6343 6344 SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0), "<string literal>"); 6345 6346 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 6347 GV->getValueType(), Alignment); 6348 } 6349 6350 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 6351 /// array for the given ObjCEncodeExpr node. 6352 ConstantAddress 6353 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 6354 std::string Str; 6355 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 6356 6357 return GetAddrOfConstantCString(Str); 6358 } 6359 6360 /// GetAddrOfConstantCString - Returns a pointer to a character array containing 6361 /// the literal and a terminating '\0' character. 6362 /// The result has pointer to array type. 6363 ConstantAddress CodeGenModule::GetAddrOfConstantCString( 6364 const std::string &Str, const char *GlobalName) { 6365 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 6366 CharUnits Alignment = 6367 getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 6368 6369 llvm::Constant *C = 6370 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 6371 6372 // Don't share any string literals if strings aren't constant. 6373 llvm::GlobalVariable **Entry = nullptr; 6374 if (!LangOpts.WritableStrings) { 6375 Entry = &ConstantStringMap[C]; 6376 if (auto GV = *Entry) { 6377 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 6378 GV->setAlignment(Alignment.getAsAlign()); 6379 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 6380 GV->getValueType(), Alignment); 6381 } 6382 } 6383 6384 // Get the default prefix if a name wasn't specified. 6385 if (!GlobalName) 6386 GlobalName = ".str"; 6387 // Create a global variable for this. 6388 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 6389 GlobalName, Alignment); 6390 if (Entry) 6391 *Entry = GV; 6392 6393 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 6394 GV->getValueType(), Alignment); 6395 } 6396 6397 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 6398 const MaterializeTemporaryExpr *E, const Expr *Init) { 6399 assert((E->getStorageDuration() == SD_Static || 6400 E->getStorageDuration() == SD_Thread) && "not a global temporary"); 6401 const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 6402 6403 // If we're not materializing a subobject of the temporary, keep the 6404 // cv-qualifiers from the type of the MaterializeTemporaryExpr. 6405 QualType MaterializedType = Init->getType(); 6406 if (Init == E->getSubExpr()) 6407 MaterializedType = E->getType(); 6408 6409 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 6410 6411 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr}); 6412 if (!InsertResult.second) { 6413 // We've seen this before: either we already created it or we're in the 6414 // process of doing so. 6415 if (!InsertResult.first->second) { 6416 // We recursively re-entered this function, probably during emission of 6417 // the initializer. Create a placeholder. We'll clean this up in the 6418 // outer call, at the end of this function. 6419 llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType); 6420 InsertResult.first->second = new llvm::GlobalVariable( 6421 getModule(), Type, false, llvm::GlobalVariable::InternalLinkage, 6422 nullptr); 6423 } 6424 return ConstantAddress(InsertResult.first->second, 6425 llvm::cast<llvm::GlobalVariable>( 6426 InsertResult.first->second->stripPointerCasts()) 6427 ->getValueType(), 6428 Align); 6429 } 6430 6431 // FIXME: If an externally-visible declaration extends multiple temporaries, 6432 // we need to give each temporary the same name in every translation unit (and 6433 // we also need to make the temporaries externally-visible). 6434 SmallString<256> Name; 6435 llvm::raw_svector_ostream Out(Name); 6436 getCXXABI().getMangleContext().mangleReferenceTemporary( 6437 VD, E->getManglingNumber(), Out); 6438 6439 APValue *Value = nullptr; 6440 if (E->getStorageDuration() == SD_Static && VD->evaluateValue()) { 6441 // If the initializer of the extending declaration is a constant 6442 // initializer, we should have a cached constant initializer for this 6443 // temporary. Note that this might have a different value from the value 6444 // computed by evaluating the initializer if the surrounding constant 6445 // expression modifies the temporary. 6446 Value = E->getOrCreateValue(false); 6447 } 6448 6449 // Try evaluating it now, it might have a constant initializer. 6450 Expr::EvalResult EvalResult; 6451 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 6452 !EvalResult.hasSideEffects()) 6453 Value = &EvalResult.Val; 6454 6455 LangAS AddrSpace = GetGlobalVarAddressSpace(VD); 6456 6457 std::optional<ConstantEmitter> emitter; 6458 llvm::Constant *InitialValue = nullptr; 6459 bool Constant = false; 6460 llvm::Type *Type; 6461 if (Value) { 6462 // The temporary has a constant initializer, use it. 6463 emitter.emplace(*this); 6464 InitialValue = emitter->emitForInitializer(*Value, AddrSpace, 6465 MaterializedType); 6466 Constant = 6467 MaterializedType.isConstantStorage(getContext(), /*ExcludeCtor*/ Value, 6468 /*ExcludeDtor*/ false); 6469 Type = InitialValue->getType(); 6470 } else { 6471 // No initializer, the initialization will be provided when we 6472 // initialize the declaration which performed lifetime extension. 6473 Type = getTypes().ConvertTypeForMem(MaterializedType); 6474 } 6475 6476 // Create a global variable for this lifetime-extended temporary. 6477 llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(VD); 6478 if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 6479 const VarDecl *InitVD; 6480 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 6481 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 6482 // Temporaries defined inside a class get linkonce_odr linkage because the 6483 // class can be defined in multiple translation units. 6484 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 6485 } else { 6486 // There is no need for this temporary to have external linkage if the 6487 // VarDecl has external linkage. 6488 Linkage = llvm::GlobalVariable::InternalLinkage; 6489 } 6490 } 6491 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace); 6492 auto *GV = new llvm::GlobalVariable( 6493 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 6494 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); 6495 if (emitter) emitter->finalize(GV); 6496 // Don't assign dllimport or dllexport to local linkage globals. 6497 if (!llvm::GlobalValue::isLocalLinkage(Linkage)) { 6498 setGVProperties(GV, VD); 6499 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass) 6500 // The reference temporary should never be dllexport. 6501 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 6502 } 6503 GV->setAlignment(Align.getAsAlign()); 6504 if (supportsCOMDAT() && GV->isWeakForLinker()) 6505 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 6506 if (VD->getTLSKind()) 6507 setTLSMode(GV, *VD); 6508 llvm::Constant *CV = GV; 6509 if (AddrSpace != LangAS::Default) 6510 CV = getTargetCodeGenInfo().performAddrSpaceCast( 6511 *this, GV, AddrSpace, LangAS::Default, 6512 llvm::PointerType::get( 6513 getLLVMContext(), 6514 getContext().getTargetAddressSpace(LangAS::Default))); 6515 6516 // Update the map with the new temporary. If we created a placeholder above, 6517 // replace it with the new global now. 6518 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E]; 6519 if (Entry) { 6520 Entry->replaceAllUsesWith(CV); 6521 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent(); 6522 } 6523 Entry = CV; 6524 6525 return ConstantAddress(CV, Type, Align); 6526 } 6527 6528 /// EmitObjCPropertyImplementations - Emit information for synthesized 6529 /// properties for an implementation. 6530 void CodeGenModule::EmitObjCPropertyImplementations(const 6531 ObjCImplementationDecl *D) { 6532 for (const auto *PID : D->property_impls()) { 6533 // Dynamic is just for type-checking. 6534 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 6535 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 6536 6537 // Determine which methods need to be implemented, some may have 6538 // been overridden. Note that ::isPropertyAccessor is not the method 6539 // we want, that just indicates if the decl came from a 6540 // property. What we want to know is if the method is defined in 6541 // this implementation. 6542 auto *Getter = PID->getGetterMethodDecl(); 6543 if (!Getter || Getter->isSynthesizedAccessorStub()) 6544 CodeGenFunction(*this).GenerateObjCGetter( 6545 const_cast<ObjCImplementationDecl *>(D), PID); 6546 auto *Setter = PID->getSetterMethodDecl(); 6547 if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub())) 6548 CodeGenFunction(*this).GenerateObjCSetter( 6549 const_cast<ObjCImplementationDecl *>(D), PID); 6550 } 6551 } 6552 } 6553 6554 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 6555 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 6556 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 6557 ivar; ivar = ivar->getNextIvar()) 6558 if (ivar->getType().isDestructedType()) 6559 return true; 6560 6561 return false; 6562 } 6563 6564 static bool AllTrivialInitializers(CodeGenModule &CGM, 6565 ObjCImplementationDecl *D) { 6566 CodeGenFunction CGF(CGM); 6567 for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 6568 E = D->init_end(); B != E; ++B) { 6569 CXXCtorInitializer *CtorInitExp = *B; 6570 Expr *Init = CtorInitExp->getInit(); 6571 if (!CGF.isTrivialInitializer(Init)) 6572 return false; 6573 } 6574 return true; 6575 } 6576 6577 /// EmitObjCIvarInitializations - Emit information for ivar initialization 6578 /// for an implementation. 6579 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 6580 // We might need a .cxx_destruct even if we don't have any ivar initializers. 6581 if (needsDestructMethod(D)) { 6582 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 6583 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 6584 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create( 6585 getContext(), D->getLocation(), D->getLocation(), cxxSelector, 6586 getContext().VoidTy, nullptr, D, 6587 /*isInstance=*/true, /*isVariadic=*/false, 6588 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 6589 /*isImplicitlyDeclared=*/true, 6590 /*isDefined=*/false, ObjCImplementationControl::Required); 6591 D->addInstanceMethod(DTORMethod); 6592 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 6593 D->setHasDestructors(true); 6594 } 6595 6596 // If the implementation doesn't have any ivar initializers, we don't need 6597 // a .cxx_construct. 6598 if (D->getNumIvarInitializers() == 0 || 6599 AllTrivialInitializers(*this, D)) 6600 return; 6601 6602 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 6603 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 6604 // The constructor returns 'self'. 6605 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create( 6606 getContext(), D->getLocation(), D->getLocation(), cxxSelector, 6607 getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true, 6608 /*isVariadic=*/false, 6609 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 6610 /*isImplicitlyDeclared=*/true, 6611 /*isDefined=*/false, ObjCImplementationControl::Required); 6612 D->addInstanceMethod(CTORMethod); 6613 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 6614 D->setHasNonZeroConstructors(true); 6615 } 6616 6617 // EmitLinkageSpec - Emit all declarations in a linkage spec. 6618 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 6619 if (LSD->getLanguage() != LinkageSpecLanguageIDs::C && 6620 LSD->getLanguage() != LinkageSpecLanguageIDs::CXX) { 6621 ErrorUnsupported(LSD, "linkage spec"); 6622 return; 6623 } 6624 6625 EmitDeclContext(LSD); 6626 } 6627 6628 void CodeGenModule::EmitTopLevelStmt(const TopLevelStmtDecl *D) { 6629 // Device code should not be at top level. 6630 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 6631 return; 6632 6633 std::unique_ptr<CodeGenFunction> &CurCGF = 6634 GlobalTopLevelStmtBlockInFlight.first; 6635 6636 // We emitted a top-level stmt but after it there is initialization. 6637 // Stop squashing the top-level stmts into a single function. 6638 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) { 6639 CurCGF->FinishFunction(D->getEndLoc()); 6640 CurCGF = nullptr; 6641 } 6642 6643 if (!CurCGF) { 6644 // void __stmts__N(void) 6645 // FIXME: Ask the ABI name mangler to pick a name. 6646 std::string Name = "__stmts__" + llvm::utostr(CXXGlobalInits.size()); 6647 FunctionArgList Args; 6648 QualType RetTy = getContext().VoidTy; 6649 const CGFunctionInfo &FnInfo = 6650 getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args); 6651 llvm::FunctionType *FnTy = getTypes().GetFunctionType(FnInfo); 6652 llvm::Function *Fn = llvm::Function::Create( 6653 FnTy, llvm::GlobalValue::InternalLinkage, Name, &getModule()); 6654 6655 CurCGF.reset(new CodeGenFunction(*this)); 6656 GlobalTopLevelStmtBlockInFlight.second = D; 6657 CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args, 6658 D->getBeginLoc(), D->getBeginLoc()); 6659 CXXGlobalInits.push_back(Fn); 6660 } 6661 6662 CurCGF->EmitStmt(D->getStmt()); 6663 } 6664 6665 void CodeGenModule::EmitDeclContext(const DeclContext *DC) { 6666 for (auto *I : DC->decls()) { 6667 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope 6668 // are themselves considered "top-level", so EmitTopLevelDecl on an 6669 // ObjCImplDecl does not recursively visit them. We need to do that in 6670 // case they're nested inside another construct (LinkageSpecDecl / 6671 // ExportDecl) that does stop them from being considered "top-level". 6672 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 6673 for (auto *M : OID->methods()) 6674 EmitTopLevelDecl(M); 6675 } 6676 6677 EmitTopLevelDecl(I); 6678 } 6679 } 6680 6681 /// EmitTopLevelDecl - Emit code for a single top level declaration. 6682 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 6683 // Ignore dependent declarations. 6684 if (D->isTemplated()) 6685 return; 6686 6687 // Consteval function shouldn't be emitted. 6688 if (auto *FD = dyn_cast<FunctionDecl>(D); FD && FD->isImmediateFunction()) 6689 return; 6690 6691 switch (D->getKind()) { 6692 case Decl::CXXConversion: 6693 case Decl::CXXMethod: 6694 case Decl::Function: 6695 EmitGlobal(cast<FunctionDecl>(D)); 6696 // Always provide some coverage mapping 6697 // even for the functions that aren't emitted. 6698 AddDeferredUnusedCoverageMapping(D); 6699 break; 6700 6701 case Decl::CXXDeductionGuide: 6702 // Function-like, but does not result in code emission. 6703 break; 6704 6705 case Decl::Var: 6706 case Decl::Decomposition: 6707 case Decl::VarTemplateSpecialization: 6708 EmitGlobal(cast<VarDecl>(D)); 6709 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 6710 for (auto *B : DD->bindings()) 6711 if (auto *HD = B->getHoldingVar()) 6712 EmitGlobal(HD); 6713 break; 6714 6715 // Indirect fields from global anonymous structs and unions can be 6716 // ignored; only the actual variable requires IR gen support. 6717 case Decl::IndirectField: 6718 break; 6719 6720 // C++ Decls 6721 case Decl::Namespace: 6722 EmitDeclContext(cast<NamespaceDecl>(D)); 6723 break; 6724 case Decl::ClassTemplateSpecialization: { 6725 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 6726 if (CGDebugInfo *DI = getModuleDebugInfo()) 6727 if (Spec->getSpecializationKind() == 6728 TSK_ExplicitInstantiationDefinition && 6729 Spec->hasDefinition()) 6730 DI->completeTemplateDefinition(*Spec); 6731 } [[fallthrough]]; 6732 case Decl::CXXRecord: { 6733 CXXRecordDecl *CRD = cast<CXXRecordDecl>(D); 6734 if (CGDebugInfo *DI = getModuleDebugInfo()) { 6735 if (CRD->hasDefinition()) 6736 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 6737 if (auto *ES = D->getASTContext().getExternalSource()) 6738 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) 6739 DI->completeUnusedClass(*CRD); 6740 } 6741 // Emit any static data members, they may be definitions. 6742 for (auto *I : CRD->decls()) 6743 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) 6744 EmitTopLevelDecl(I); 6745 break; 6746 } 6747 // No code generation needed. 6748 case Decl::UsingShadow: 6749 case Decl::ClassTemplate: 6750 case Decl::VarTemplate: 6751 case Decl::Concept: 6752 case Decl::VarTemplatePartialSpecialization: 6753 case Decl::FunctionTemplate: 6754 case Decl::TypeAliasTemplate: 6755 case Decl::Block: 6756 case Decl::Empty: 6757 case Decl::Binding: 6758 break; 6759 case Decl::Using: // using X; [C++] 6760 if (CGDebugInfo *DI = getModuleDebugInfo()) 6761 DI->EmitUsingDecl(cast<UsingDecl>(*D)); 6762 break; 6763 case Decl::UsingEnum: // using enum X; [C++] 6764 if (CGDebugInfo *DI = getModuleDebugInfo()) 6765 DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D)); 6766 break; 6767 case Decl::NamespaceAlias: 6768 if (CGDebugInfo *DI = getModuleDebugInfo()) 6769 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 6770 break; 6771 case Decl::UsingDirective: // using namespace X; [C++] 6772 if (CGDebugInfo *DI = getModuleDebugInfo()) 6773 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 6774 break; 6775 case Decl::CXXConstructor: 6776 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 6777 break; 6778 case Decl::CXXDestructor: 6779 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 6780 break; 6781 6782 case Decl::StaticAssert: 6783 // Nothing to do. 6784 break; 6785 6786 // Objective-C Decls 6787 6788 // Forward declarations, no (immediate) code generation. 6789 case Decl::ObjCInterface: 6790 case Decl::ObjCCategory: 6791 break; 6792 6793 case Decl::ObjCProtocol: { 6794 auto *Proto = cast<ObjCProtocolDecl>(D); 6795 if (Proto->isThisDeclarationADefinition()) 6796 ObjCRuntime->GenerateProtocol(Proto); 6797 break; 6798 } 6799 6800 case Decl::ObjCCategoryImpl: 6801 // Categories have properties but don't support synthesize so we 6802 // can ignore them here. 6803 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 6804 break; 6805 6806 case Decl::ObjCImplementation: { 6807 auto *OMD = cast<ObjCImplementationDecl>(D); 6808 EmitObjCPropertyImplementations(OMD); 6809 EmitObjCIvarInitializations(OMD); 6810 ObjCRuntime->GenerateClass(OMD); 6811 // Emit global variable debug information. 6812 if (CGDebugInfo *DI = getModuleDebugInfo()) 6813 if (getCodeGenOpts().hasReducedDebugInfo()) 6814 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 6815 OMD->getClassInterface()), OMD->getLocation()); 6816 break; 6817 } 6818 case Decl::ObjCMethod: { 6819 auto *OMD = cast<ObjCMethodDecl>(D); 6820 // If this is not a prototype, emit the body. 6821 if (OMD->getBody()) 6822 CodeGenFunction(*this).GenerateObjCMethod(OMD); 6823 break; 6824 } 6825 case Decl::ObjCCompatibleAlias: 6826 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 6827 break; 6828 6829 case Decl::PragmaComment: { 6830 const auto *PCD = cast<PragmaCommentDecl>(D); 6831 switch (PCD->getCommentKind()) { 6832 case PCK_Unknown: 6833 llvm_unreachable("unexpected pragma comment kind"); 6834 case PCK_Linker: 6835 AppendLinkerOptions(PCD->getArg()); 6836 break; 6837 case PCK_Lib: 6838 AddDependentLib(PCD->getArg()); 6839 break; 6840 case PCK_Compiler: 6841 case PCK_ExeStr: 6842 case PCK_User: 6843 break; // We ignore all of these. 6844 } 6845 break; 6846 } 6847 6848 case Decl::PragmaDetectMismatch: { 6849 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 6850 AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 6851 break; 6852 } 6853 6854 case Decl::LinkageSpec: 6855 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 6856 break; 6857 6858 case Decl::FileScopeAsm: { 6859 // File-scope asm is ignored during device-side CUDA compilation. 6860 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 6861 break; 6862 // File-scope asm is ignored during device-side OpenMP compilation. 6863 if (LangOpts.OpenMPIsTargetDevice) 6864 break; 6865 // File-scope asm is ignored during device-side SYCL compilation. 6866 if (LangOpts.SYCLIsDevice) 6867 break; 6868 auto *AD = cast<FileScopeAsmDecl>(D); 6869 getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 6870 break; 6871 } 6872 6873 case Decl::TopLevelStmt: 6874 EmitTopLevelStmt(cast<TopLevelStmtDecl>(D)); 6875 break; 6876 6877 case Decl::Import: { 6878 auto *Import = cast<ImportDecl>(D); 6879 6880 // If we've already imported this module, we're done. 6881 if (!ImportedModules.insert(Import->getImportedModule())) 6882 break; 6883 6884 // Emit debug information for direct imports. 6885 if (!Import->getImportedOwningModule()) { 6886 if (CGDebugInfo *DI = getModuleDebugInfo()) 6887 DI->EmitImportDecl(*Import); 6888 } 6889 6890 // For C++ standard modules we are done - we will call the module 6891 // initializer for imported modules, and that will likewise call those for 6892 // any imports it has. 6893 if (CXX20ModuleInits && Import->getImportedOwningModule() && 6894 !Import->getImportedOwningModule()->isModuleMapModule()) 6895 break; 6896 6897 // For clang C++ module map modules the initializers for sub-modules are 6898 // emitted here. 6899 6900 // Find all of the submodules and emit the module initializers. 6901 llvm::SmallPtrSet<clang::Module *, 16> Visited; 6902 SmallVector<clang::Module *, 16> Stack; 6903 Visited.insert(Import->getImportedModule()); 6904 Stack.push_back(Import->getImportedModule()); 6905 6906 while (!Stack.empty()) { 6907 clang::Module *Mod = Stack.pop_back_val(); 6908 if (!EmittedModuleInitializers.insert(Mod).second) 6909 continue; 6910 6911 for (auto *D : Context.getModuleInitializers(Mod)) 6912 EmitTopLevelDecl(D); 6913 6914 // Visit the submodules of this module. 6915 for (auto *Submodule : Mod->submodules()) { 6916 // Skip explicit children; they need to be explicitly imported to emit 6917 // the initializers. 6918 if (Submodule->IsExplicit) 6919 continue; 6920 6921 if (Visited.insert(Submodule).second) 6922 Stack.push_back(Submodule); 6923 } 6924 } 6925 break; 6926 } 6927 6928 case Decl::Export: 6929 EmitDeclContext(cast<ExportDecl>(D)); 6930 break; 6931 6932 case Decl::OMPThreadPrivate: 6933 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 6934 break; 6935 6936 case Decl::OMPAllocate: 6937 EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D)); 6938 break; 6939 6940 case Decl::OMPDeclareReduction: 6941 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 6942 break; 6943 6944 case Decl::OMPDeclareMapper: 6945 EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D)); 6946 break; 6947 6948 case Decl::OMPRequires: 6949 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D)); 6950 break; 6951 6952 case Decl::Typedef: 6953 case Decl::TypeAlias: // using foo = bar; [C++11] 6954 if (CGDebugInfo *DI = getModuleDebugInfo()) 6955 DI->EmitAndRetainType( 6956 getContext().getTypedefType(cast<TypedefNameDecl>(D))); 6957 break; 6958 6959 case Decl::Record: 6960 if (CGDebugInfo *DI = getModuleDebugInfo()) 6961 if (cast<RecordDecl>(D)->getDefinition()) 6962 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 6963 break; 6964 6965 case Decl::Enum: 6966 if (CGDebugInfo *DI = getModuleDebugInfo()) 6967 if (cast<EnumDecl>(D)->getDefinition()) 6968 DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D))); 6969 break; 6970 6971 case Decl::HLSLBuffer: 6972 getHLSLRuntime().addBuffer(cast<HLSLBufferDecl>(D)); 6973 break; 6974 6975 default: 6976 // Make sure we handled everything we should, every other kind is a 6977 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 6978 // function. Need to recode Decl::Kind to do that easily. 6979 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 6980 break; 6981 } 6982 } 6983 6984 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 6985 // Do we need to generate coverage mapping? 6986 if (!CodeGenOpts.CoverageMapping) 6987 return; 6988 switch (D->getKind()) { 6989 case Decl::CXXConversion: 6990 case Decl::CXXMethod: 6991 case Decl::Function: 6992 case Decl::ObjCMethod: 6993 case Decl::CXXConstructor: 6994 case Decl::CXXDestructor: { 6995 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 6996 break; 6997 SourceManager &SM = getContext().getSourceManager(); 6998 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc())) 6999 break; 7000 DeferredEmptyCoverageMappingDecls.try_emplace(D, true); 7001 break; 7002 } 7003 default: 7004 break; 7005 }; 7006 } 7007 7008 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 7009 // Do we need to generate coverage mapping? 7010 if (!CodeGenOpts.CoverageMapping) 7011 return; 7012 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 7013 if (Fn->isTemplateInstantiation()) 7014 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 7015 } 7016 DeferredEmptyCoverageMappingDecls.insert_or_assign(D, false); 7017 } 7018 7019 void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 7020 // We call takeVector() here to avoid use-after-free. 7021 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because 7022 // we deserialize function bodies to emit coverage info for them, and that 7023 // deserializes more declarations. How should we handle that case? 7024 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) { 7025 if (!Entry.second) 7026 continue; 7027 const Decl *D = Entry.first; 7028 switch (D->getKind()) { 7029 case Decl::CXXConversion: 7030 case Decl::CXXMethod: 7031 case Decl::Function: 7032 case Decl::ObjCMethod: { 7033 CodeGenPGO PGO(*this); 7034 GlobalDecl GD(cast<FunctionDecl>(D)); 7035 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 7036 getFunctionLinkage(GD)); 7037 break; 7038 } 7039 case Decl::CXXConstructor: { 7040 CodeGenPGO PGO(*this); 7041 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 7042 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 7043 getFunctionLinkage(GD)); 7044 break; 7045 } 7046 case Decl::CXXDestructor: { 7047 CodeGenPGO PGO(*this); 7048 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 7049 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 7050 getFunctionLinkage(GD)); 7051 break; 7052 } 7053 default: 7054 break; 7055 }; 7056 } 7057 } 7058 7059 void CodeGenModule::EmitMainVoidAlias() { 7060 // In order to transition away from "__original_main" gracefully, emit an 7061 // alias for "main" in the no-argument case so that libc can detect when 7062 // new-style no-argument main is in used. 7063 if (llvm::Function *F = getModule().getFunction("main")) { 7064 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() && 7065 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) { 7066 auto *GA = llvm::GlobalAlias::create("__main_void", F); 7067 GA->setVisibility(llvm::GlobalValue::HiddenVisibility); 7068 } 7069 } 7070 } 7071 7072 /// Turns the given pointer into a constant. 7073 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 7074 const void *Ptr) { 7075 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 7076 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 7077 return llvm::ConstantInt::get(i64, PtrInt); 7078 } 7079 7080 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 7081 llvm::NamedMDNode *&GlobalMetadata, 7082 GlobalDecl D, 7083 llvm::GlobalValue *Addr) { 7084 if (!GlobalMetadata) 7085 GlobalMetadata = 7086 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 7087 7088 // TODO: should we report variant information for ctors/dtors? 7089 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 7090 llvm::ConstantAsMetadata::get(GetPointerConstant( 7091 CGM.getLLVMContext(), D.getDecl()))}; 7092 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 7093 } 7094 7095 bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem, 7096 llvm::GlobalValue *CppFunc) { 7097 // Store the list of ifuncs we need to replace uses in. 7098 llvm::SmallVector<llvm::GlobalIFunc *> IFuncs; 7099 // List of ConstantExprs that we should be able to delete when we're done 7100 // here. 7101 llvm::SmallVector<llvm::ConstantExpr *> CEs; 7102 7103 // It isn't valid to replace the extern-C ifuncs if all we find is itself! 7104 if (Elem == CppFunc) 7105 return false; 7106 7107 // First make sure that all users of this are ifuncs (or ifuncs via a 7108 // bitcast), and collect the list of ifuncs and CEs so we can work on them 7109 // later. 7110 for (llvm::User *User : Elem->users()) { 7111 // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an 7112 // ifunc directly. In any other case, just give up, as we don't know what we 7113 // could break by changing those. 7114 if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) { 7115 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast) 7116 return false; 7117 7118 for (llvm::User *CEUser : ConstExpr->users()) { 7119 if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) { 7120 IFuncs.push_back(IFunc); 7121 } else { 7122 return false; 7123 } 7124 } 7125 CEs.push_back(ConstExpr); 7126 } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) { 7127 IFuncs.push_back(IFunc); 7128 } else { 7129 // This user is one we don't know how to handle, so fail redirection. This 7130 // will result in an ifunc retaining a resolver name that will ultimately 7131 // fail to be resolved to a defined function. 7132 return false; 7133 } 7134 } 7135 7136 // Now we know this is a valid case where we can do this alias replacement, we 7137 // need to remove all of the references to Elem (and the bitcasts!) so we can 7138 // delete it. 7139 for (llvm::GlobalIFunc *IFunc : IFuncs) 7140 IFunc->setResolver(nullptr); 7141 for (llvm::ConstantExpr *ConstExpr : CEs) 7142 ConstExpr->destroyConstant(); 7143 7144 // We should now be out of uses for the 'old' version of this function, so we 7145 // can erase it as well. 7146 Elem->eraseFromParent(); 7147 7148 for (llvm::GlobalIFunc *IFunc : IFuncs) { 7149 // The type of the resolver is always just a function-type that returns the 7150 // type of the IFunc, so create that here. If the type of the actual 7151 // resolver doesn't match, it just gets bitcast to the right thing. 7152 auto *ResolverTy = 7153 llvm::FunctionType::get(IFunc->getType(), /*isVarArg*/ false); 7154 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 7155 CppFunc->getName(), ResolverTy, {}, /*ForVTable*/ false); 7156 IFunc->setResolver(Resolver); 7157 } 7158 return true; 7159 } 7160 7161 /// For each function which is declared within an extern "C" region and marked 7162 /// as 'used', but has internal linkage, create an alias from the unmangled 7163 /// name to the mangled name if possible. People expect to be able to refer 7164 /// to such functions with an unmangled name from inline assembly within the 7165 /// same translation unit. 7166 void CodeGenModule::EmitStaticExternCAliases() { 7167 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases()) 7168 return; 7169 for (auto &I : StaticExternCValues) { 7170 IdentifierInfo *Name = I.first; 7171 llvm::GlobalValue *Val = I.second; 7172 7173 // If Val is null, that implies there were multiple declarations that each 7174 // had a claim to the unmangled name. In this case, generation of the alias 7175 // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC. 7176 if (!Val) 7177 break; 7178 7179 llvm::GlobalValue *ExistingElem = 7180 getModule().getNamedValue(Name->getName()); 7181 7182 // If there is either not something already by this name, or we were able to 7183 // replace all uses from IFuncs, create the alias. 7184 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val)) 7185 addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 7186 } 7187 } 7188 7189 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 7190 GlobalDecl &Result) const { 7191 auto Res = Manglings.find(MangledName); 7192 if (Res == Manglings.end()) 7193 return false; 7194 Result = Res->getValue(); 7195 return true; 7196 } 7197 7198 /// Emits metadata nodes associating all the global values in the 7199 /// current module with the Decls they came from. This is useful for 7200 /// projects using IR gen as a subroutine. 7201 /// 7202 /// Since there's currently no way to associate an MDNode directly 7203 /// with an llvm::GlobalValue, we create a global named metadata 7204 /// with the name 'clang.global.decl.ptrs'. 7205 void CodeGenModule::EmitDeclMetadata() { 7206 llvm::NamedMDNode *GlobalMetadata = nullptr; 7207 7208 for (auto &I : MangledDeclNames) { 7209 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 7210 // Some mangled names don't necessarily have an associated GlobalValue 7211 // in this module, e.g. if we mangled it for DebugInfo. 7212 if (Addr) 7213 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 7214 } 7215 } 7216 7217 /// Emits metadata nodes for all the local variables in the current 7218 /// function. 7219 void CodeGenFunction::EmitDeclMetadata() { 7220 if (LocalDeclMap.empty()) return; 7221 7222 llvm::LLVMContext &Context = getLLVMContext(); 7223 7224 // Find the unique metadata ID for this name. 7225 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 7226 7227 llvm::NamedMDNode *GlobalMetadata = nullptr; 7228 7229 for (auto &I : LocalDeclMap) { 7230 const Decl *D = I.first; 7231 llvm::Value *Addr = I.second.getPointer(); 7232 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 7233 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 7234 Alloca->setMetadata( 7235 DeclPtrKind, llvm::MDNode::get( 7236 Context, llvm::ValueAsMetadata::getConstant(DAddr))); 7237 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 7238 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 7239 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 7240 } 7241 } 7242 } 7243 7244 void CodeGenModule::EmitVersionIdentMetadata() { 7245 llvm::NamedMDNode *IdentMetadata = 7246 TheModule.getOrInsertNamedMetadata("llvm.ident"); 7247 std::string Version = getClangFullVersion(); 7248 llvm::LLVMContext &Ctx = TheModule.getContext(); 7249 7250 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 7251 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 7252 } 7253 7254 void CodeGenModule::EmitCommandLineMetadata() { 7255 llvm::NamedMDNode *CommandLineMetadata = 7256 TheModule.getOrInsertNamedMetadata("llvm.commandline"); 7257 std::string CommandLine = getCodeGenOpts().RecordCommandLine; 7258 llvm::LLVMContext &Ctx = TheModule.getContext(); 7259 7260 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)}; 7261 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode)); 7262 } 7263 7264 void CodeGenModule::EmitCoverageFile() { 7265 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); 7266 if (!CUNode) 7267 return; 7268 7269 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 7270 llvm::LLVMContext &Ctx = TheModule.getContext(); 7271 auto *CoverageDataFile = 7272 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); 7273 auto *CoverageNotesFile = 7274 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); 7275 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 7276 llvm::MDNode *CU = CUNode->getOperand(i); 7277 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; 7278 GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 7279 } 7280 } 7281 7282 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 7283 bool ForEH) { 7284 // Return a bogus pointer if RTTI is disabled, unless it's for EH. 7285 // FIXME: should we even be calling this method if RTTI is disabled 7286 // and it's not for EH? 7287 if (!shouldEmitRTTI(ForEH)) 7288 return llvm::Constant::getNullValue(GlobalsInt8PtrTy); 7289 7290 if (ForEH && Ty->isObjCObjectPointerType() && 7291 LangOpts.ObjCRuntime.isGNUFamily()) 7292 return ObjCRuntime->GetEHType(Ty); 7293 7294 return getCXXABI().getAddrOfRTTIDescriptor(Ty); 7295 } 7296 7297 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 7298 // Do not emit threadprivates in simd-only mode. 7299 if (LangOpts.OpenMP && LangOpts.OpenMPSimd) 7300 return; 7301 for (auto RefExpr : D->varlists()) { 7302 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 7303 bool PerformInit = 7304 VD->getAnyInitializer() && 7305 !VD->getAnyInitializer()->isConstantInitializer(getContext(), 7306 /*ForRef=*/false); 7307 7308 Address Addr(GetAddrOfGlobalVar(VD), 7309 getTypes().ConvertTypeForMem(VD->getType()), 7310 getContext().getDeclAlign(VD)); 7311 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 7312 VD, Addr, RefExpr->getBeginLoc(), PerformInit)) 7313 CXXGlobalInits.push_back(InitFunction); 7314 } 7315 } 7316 7317 llvm::Metadata * 7318 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, 7319 StringRef Suffix) { 7320 if (auto *FnType = T->getAs<FunctionProtoType>()) 7321 T = getContext().getFunctionType( 7322 FnType->getReturnType(), FnType->getParamTypes(), 7323 FnType->getExtProtoInfo().withExceptionSpec(EST_None)); 7324 7325 llvm::Metadata *&InternalId = Map[T.getCanonicalType()]; 7326 if (InternalId) 7327 return InternalId; 7328 7329 if (isExternallyVisible(T->getLinkage())) { 7330 std::string OutName; 7331 llvm::raw_string_ostream Out(OutName); 7332 getCXXABI().getMangleContext().mangleCanonicalTypeName( 7333 T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers); 7334 7335 if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers) 7336 Out << ".normalized"; 7337 7338 Out << Suffix; 7339 7340 InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 7341 } else { 7342 InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 7343 llvm::ArrayRef<llvm::Metadata *>()); 7344 } 7345 7346 return InternalId; 7347 } 7348 7349 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 7350 return CreateMetadataIdentifierImpl(T, MetadataIdMap, ""); 7351 } 7352 7353 llvm::Metadata * 7354 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) { 7355 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual"); 7356 } 7357 7358 // Generalize pointer types to a void pointer with the qualifiers of the 7359 // originally pointed-to type, e.g. 'const char *' and 'char * const *' 7360 // generalize to 'const void *' while 'char *' and 'const char **' generalize to 7361 // 'void *'. 7362 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) { 7363 if (!Ty->isPointerType()) 7364 return Ty; 7365 7366 return Ctx.getPointerType( 7367 QualType(Ctx.VoidTy).withCVRQualifiers( 7368 Ty->getPointeeType().getCVRQualifiers())); 7369 } 7370 7371 // Apply type generalization to a FunctionType's return and argument types 7372 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) { 7373 if (auto *FnType = Ty->getAs<FunctionProtoType>()) { 7374 SmallVector<QualType, 8> GeneralizedParams; 7375 for (auto &Param : FnType->param_types()) 7376 GeneralizedParams.push_back(GeneralizeType(Ctx, Param)); 7377 7378 return Ctx.getFunctionType( 7379 GeneralizeType(Ctx, FnType->getReturnType()), 7380 GeneralizedParams, FnType->getExtProtoInfo()); 7381 } 7382 7383 if (auto *FnType = Ty->getAs<FunctionNoProtoType>()) 7384 return Ctx.getFunctionNoProtoType( 7385 GeneralizeType(Ctx, FnType->getReturnType())); 7386 7387 llvm_unreachable("Encountered unknown FunctionType"); 7388 } 7389 7390 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) { 7391 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T), 7392 GeneralizedMetadataIdMap, ".generalized"); 7393 } 7394 7395 /// Returns whether this module needs the "all-vtables" type identifier. 7396 bool CodeGenModule::NeedAllVtablesTypeId() const { 7397 // Returns true if at least one of vtable-based CFI checkers is enabled and 7398 // is not in the trapping mode. 7399 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 7400 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 7401 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 7402 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 7403 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 7404 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 7405 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 7406 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 7407 } 7408 7409 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 7410 CharUnits Offset, 7411 const CXXRecordDecl *RD) { 7412 llvm::Metadata *MD = 7413 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 7414 VTable->addTypeMetadata(Offset.getQuantity(), MD); 7415 7416 if (CodeGenOpts.SanitizeCfiCrossDso) 7417 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 7418 VTable->addTypeMetadata(Offset.getQuantity(), 7419 llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 7420 7421 if (NeedAllVtablesTypeId()) { 7422 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 7423 VTable->addTypeMetadata(Offset.getQuantity(), MD); 7424 } 7425 } 7426 7427 llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 7428 if (!SanStats) 7429 SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule()); 7430 7431 return *SanStats; 7432 } 7433 7434 llvm::Value * 7435 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, 7436 CodeGenFunction &CGF) { 7437 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType()); 7438 auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr()); 7439 auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); 7440 auto *Call = CGF.EmitRuntimeCall( 7441 CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C}); 7442 return Call; 7443 } 7444 7445 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment( 7446 QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) { 7447 return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo, 7448 /* forPointeeType= */ true); 7449 } 7450 7451 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T, 7452 LValueBaseInfo *BaseInfo, 7453 TBAAAccessInfo *TBAAInfo, 7454 bool forPointeeType) { 7455 if (TBAAInfo) 7456 *TBAAInfo = getTBAAAccessInfo(T); 7457 7458 // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But 7459 // that doesn't return the information we need to compute BaseInfo. 7460 7461 // Honor alignment typedef attributes even on incomplete types. 7462 // We also honor them straight for C++ class types, even as pointees; 7463 // there's an expressivity gap here. 7464 if (auto TT = T->getAs<TypedefType>()) { 7465 if (auto Align = TT->getDecl()->getMaxAlignment()) { 7466 if (BaseInfo) 7467 *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType); 7468 return getContext().toCharUnitsFromBits(Align); 7469 } 7470 } 7471 7472 bool AlignForArray = T->isArrayType(); 7473 7474 // Analyze the base element type, so we don't get confused by incomplete 7475 // array types. 7476 T = getContext().getBaseElementType(T); 7477 7478 if (T->isIncompleteType()) { 7479 // We could try to replicate the logic from 7480 // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the 7481 // type is incomplete, so it's impossible to test. We could try to reuse 7482 // getTypeAlignIfKnown, but that doesn't return the information we need 7483 // to set BaseInfo. So just ignore the possibility that the alignment is 7484 // greater than one. 7485 if (BaseInfo) 7486 *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 7487 return CharUnits::One(); 7488 } 7489 7490 if (BaseInfo) 7491 *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 7492 7493 CharUnits Alignment; 7494 const CXXRecordDecl *RD; 7495 if (T.getQualifiers().hasUnaligned()) { 7496 Alignment = CharUnits::One(); 7497 } else if (forPointeeType && !AlignForArray && 7498 (RD = T->getAsCXXRecordDecl())) { 7499 // For C++ class pointees, we don't know whether we're pointing at a 7500 // base or a complete object, so we generally need to use the 7501 // non-virtual alignment. 7502 Alignment = getClassPointerAlignment(RD); 7503 } else { 7504 Alignment = getContext().getTypeAlignInChars(T); 7505 } 7506 7507 // Cap to the global maximum type alignment unless the alignment 7508 // was somehow explicit on the type. 7509 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { 7510 if (Alignment.getQuantity() > MaxAlign && 7511 !getContext().isAlignmentRequired(T)) 7512 Alignment = CharUnits::fromQuantity(MaxAlign); 7513 } 7514 return Alignment; 7515 } 7516 7517 bool CodeGenModule::stopAutoInit() { 7518 unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter; 7519 if (StopAfter) { 7520 // This number is positive only when -ftrivial-auto-var-init-stop-after=* is 7521 // used 7522 if (NumAutoVarInit >= StopAfter) { 7523 return true; 7524 } 7525 if (!NumAutoVarInit) { 7526 unsigned DiagID = getDiags().getCustomDiagID( 7527 DiagnosticsEngine::Warning, 7528 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the " 7529 "number of times ftrivial-auto-var-init=%1 gets applied."); 7530 getDiags().Report(DiagID) 7531 << StopAfter 7532 << (getContext().getLangOpts().getTrivialAutoVarInit() == 7533 LangOptions::TrivialAutoVarInitKind::Zero 7534 ? "zero" 7535 : "pattern"); 7536 } 7537 ++NumAutoVarInit; 7538 } 7539 return false; 7540 } 7541 7542 void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS, 7543 const Decl *D) const { 7544 // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers 7545 // postfix beginning with '.' since the symbol name can be demangled. 7546 if (LangOpts.HIP) 7547 OS << (isa<VarDecl>(D) ? ".static." : ".intern."); 7548 else 7549 OS << (isa<VarDecl>(D) ? "__static__" : "__intern__"); 7550 7551 // If the CUID is not specified we try to generate a unique postfix. 7552 if (getLangOpts().CUID.empty()) { 7553 SourceManager &SM = getContext().getSourceManager(); 7554 PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation()); 7555 assert(PLoc.isValid() && "Source location is expected to be valid."); 7556 7557 // Get the hash of the user defined macros. 7558 llvm::MD5 Hash; 7559 llvm::MD5::MD5Result Result; 7560 for (const auto &Arg : PreprocessorOpts.Macros) 7561 Hash.update(Arg.first); 7562 Hash.final(Result); 7563 7564 // Get the UniqueID for the file containing the decl. 7565 llvm::sys::fs::UniqueID ID; 7566 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) { 7567 PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false); 7568 assert(PLoc.isValid() && "Source location is expected to be valid."); 7569 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) 7570 SM.getDiagnostics().Report(diag::err_cannot_open_file) 7571 << PLoc.getFilename() << EC.message(); 7572 } 7573 OS << llvm::format("%x", ID.getFile()) << llvm::format("%x", ID.getDevice()) 7574 << "_" << llvm::utohexstr(Result.low(), /*LowerCase=*/true, /*Width=*/8); 7575 } else { 7576 OS << getContext().getCUIDHash(); 7577 } 7578 } 7579 7580 void CodeGenModule::moveLazyEmissionStates(CodeGenModule *NewBuilder) { 7581 assert(DeferredDeclsToEmit.empty() && 7582 "Should have emitted all decls deferred to emit."); 7583 assert(NewBuilder->DeferredDecls.empty() && 7584 "Newly created module should not have deferred decls"); 7585 NewBuilder->DeferredDecls = std::move(DeferredDecls); 7586 assert(EmittedDeferredDecls.empty() && 7587 "Still have (unmerged) EmittedDeferredDecls deferred decls"); 7588 7589 assert(NewBuilder->DeferredVTables.empty() && 7590 "Newly created module should not have deferred vtables"); 7591 NewBuilder->DeferredVTables = std::move(DeferredVTables); 7592 7593 assert(NewBuilder->MangledDeclNames.empty() && 7594 "Newly created module should not have mangled decl names"); 7595 assert(NewBuilder->Manglings.empty() && 7596 "Newly created module should not have manglings"); 7597 NewBuilder->Manglings = std::move(Manglings); 7598 7599 NewBuilder->WeakRefReferences = std::move(WeakRefReferences); 7600 7601 NewBuilder->TBAA = std::move(TBAA); 7602 7603 NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx); 7604 } 7605