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