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