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