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