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