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