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