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