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