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