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