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