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