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