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