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