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