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