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