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