10b57cec5SDimitry Andric //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // This coordinates the per-module state used while generating code. 100b57cec5SDimitry Andric // 110b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 120b57cec5SDimitry Andric 130b57cec5SDimitry Andric #include "CodeGenModule.h" 14fcaf7f86SDimitry Andric #include "ABIInfo.h" 150b57cec5SDimitry Andric #include "CGBlocks.h" 160b57cec5SDimitry Andric #include "CGCUDARuntime.h" 170b57cec5SDimitry Andric #include "CGCXXABI.h" 180b57cec5SDimitry Andric #include "CGCall.h" 190b57cec5SDimitry Andric #include "CGDebugInfo.h" 2081ad6265SDimitry Andric #include "CGHLSLRuntime.h" 210b57cec5SDimitry Andric #include "CGObjCRuntime.h" 220b57cec5SDimitry Andric #include "CGOpenCLRuntime.h" 230b57cec5SDimitry Andric #include "CGOpenMPRuntime.h" 24349cc55cSDimitry Andric #include "CGOpenMPRuntimeGPU.h" 250b57cec5SDimitry Andric #include "CodeGenFunction.h" 260b57cec5SDimitry Andric #include "CodeGenPGO.h" 270b57cec5SDimitry Andric #include "ConstantEmitter.h" 280b57cec5SDimitry Andric #include "CoverageMappingGen.h" 290b57cec5SDimitry Andric #include "TargetInfo.h" 300b57cec5SDimitry Andric #include "clang/AST/ASTContext.h" 31c9157d92SDimitry Andric #include "clang/AST/ASTLambda.h" 320b57cec5SDimitry Andric #include "clang/AST/CharUnits.h" 330b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h" 340b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h" 350b57cec5SDimitry Andric #include "clang/AST/DeclTemplate.h" 360b57cec5SDimitry Andric #include "clang/AST/Mangle.h" 370b57cec5SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h" 380b57cec5SDimitry Andric #include "clang/AST/StmtVisitor.h" 390b57cec5SDimitry Andric #include "clang/Basic/Builtins.h" 400b57cec5SDimitry Andric #include "clang/Basic/CharInfo.h" 410b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h" 420b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h" 435ffd83dbSDimitry Andric #include "clang/Basic/FileManager.h" 440b57cec5SDimitry Andric #include "clang/Basic/Module.h" 450b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h" 460b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h" 470b57cec5SDimitry Andric #include "clang/Basic/Version.h" 4881ad6265SDimitry Andric #include "clang/CodeGen/BackendUtil.h" 490b57cec5SDimitry Andric #include "clang/CodeGen/ConstantInitBuilder.h" 500b57cec5SDimitry Andric #include "clang/Frontend/FrontendDiagnostic.h" 51bdd1243dSDimitry Andric #include "llvm/ADT/STLExtras.h" 52bdd1243dSDimitry Andric #include "llvm/ADT/StringExtras.h" 530b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h" 540b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h" 55480093f4SDimitry Andric #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 56fe013be4SDimitry Andric #include "llvm/IR/AttributeMask.h" 570b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h" 580b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h" 590b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h" 600b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h" 610b57cec5SDimitry Andric #include "llvm/IR/Module.h" 620b57cec5SDimitry Andric #include "llvm/IR/ProfileSummary.h" 630b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfReader.h" 64bdd1243dSDimitry Andric #include "llvm/ProfileData/SampleProf.h" 65fcaf7f86SDimitry Andric #include "llvm/Support/CRC.h" 660b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h" 67480093f4SDimitry Andric #include "llvm/Support/CommandLine.h" 680b57cec5SDimitry Andric #include "llvm/Support/ConvertUTF.h" 690b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h" 700b57cec5SDimitry Andric #include "llvm/Support/TimeProfiler.h" 71bdd1243dSDimitry Andric #include "llvm/Support/xxhash.h" 72fe013be4SDimitry Andric #include "llvm/TargetParser/Triple.h" 73fe013be4SDimitry Andric #include "llvm/TargetParser/X86TargetParser.h" 74bdd1243dSDimitry Andric #include <optional> 750b57cec5SDimitry Andric 760b57cec5SDimitry Andric using namespace clang; 770b57cec5SDimitry Andric using namespace CodeGen; 780b57cec5SDimitry Andric 790b57cec5SDimitry Andric static llvm::cl::opt<bool> LimitedCoverage( 8081ad6265SDimitry Andric "limited-coverage-experimental", llvm::cl::Hidden, 8181ad6265SDimitry Andric llvm::cl::desc("Emit limited coverage mapping information (experimental)")); 820b57cec5SDimitry Andric 830b57cec5SDimitry Andric static const char AnnotationSection[] = "llvm.metadata"; 840b57cec5SDimitry Andric 850b57cec5SDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) { 86fe6060f1SDimitry Andric switch (CGM.getContext().getCXXABIKind()) { 87e8d8bef9SDimitry Andric case TargetCXXABI::AppleARM64: 88480093f4SDimitry Andric case TargetCXXABI::Fuchsia: 890b57cec5SDimitry Andric case TargetCXXABI::GenericAArch64: 900b57cec5SDimitry Andric case TargetCXXABI::GenericARM: 910b57cec5SDimitry Andric case TargetCXXABI::iOS: 920b57cec5SDimitry Andric case TargetCXXABI::WatchOS: 930b57cec5SDimitry Andric case TargetCXXABI::GenericMIPS: 940b57cec5SDimitry Andric case TargetCXXABI::GenericItanium: 950b57cec5SDimitry Andric case TargetCXXABI::WebAssembly: 965ffd83dbSDimitry Andric case TargetCXXABI::XL: 970b57cec5SDimitry Andric return CreateItaniumCXXABI(CGM); 980b57cec5SDimitry Andric case TargetCXXABI::Microsoft: 990b57cec5SDimitry Andric return CreateMicrosoftCXXABI(CGM); 1000b57cec5SDimitry Andric } 1010b57cec5SDimitry Andric 1020b57cec5SDimitry Andric llvm_unreachable("invalid C++ ABI kind"); 1030b57cec5SDimitry Andric } 1040b57cec5SDimitry Andric 105fe013be4SDimitry Andric static std::unique_ptr<TargetCodeGenInfo> 106fe013be4SDimitry Andric createTargetCodeGenInfo(CodeGenModule &CGM) { 107fe013be4SDimitry Andric const TargetInfo &Target = CGM.getTarget(); 108fe013be4SDimitry Andric const llvm::Triple &Triple = Target.getTriple(); 109fe013be4SDimitry Andric const CodeGenOptions &CodeGenOpts = CGM.getCodeGenOpts(); 110fe013be4SDimitry Andric 111fe013be4SDimitry Andric switch (Triple.getArch()) { 112fe013be4SDimitry Andric default: 113fe013be4SDimitry Andric return createDefaultTargetCodeGenInfo(CGM); 114fe013be4SDimitry Andric 115fe013be4SDimitry Andric case llvm::Triple::le32: 116fe013be4SDimitry Andric return createPNaClTargetCodeGenInfo(CGM); 117fe013be4SDimitry Andric case llvm::Triple::m68k: 118fe013be4SDimitry Andric return createM68kTargetCodeGenInfo(CGM); 119fe013be4SDimitry Andric case llvm::Triple::mips: 120fe013be4SDimitry Andric case llvm::Triple::mipsel: 121fe013be4SDimitry Andric if (Triple.getOS() == llvm::Triple::NaCl) 122fe013be4SDimitry Andric return createPNaClTargetCodeGenInfo(CGM); 123fe013be4SDimitry Andric return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/true); 124fe013be4SDimitry Andric 125fe013be4SDimitry Andric case llvm::Triple::mips64: 126fe013be4SDimitry Andric case llvm::Triple::mips64el: 127fe013be4SDimitry Andric return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/false); 128fe013be4SDimitry Andric 129fe013be4SDimitry Andric case llvm::Triple::avr: { 130fe013be4SDimitry Andric // For passing parameters, R8~R25 are used on avr, and R18~R25 are used 131fe013be4SDimitry Andric // on avrtiny. For passing return value, R18~R25 are used on avr, and 132fe013be4SDimitry Andric // R22~R25 are used on avrtiny. 133fe013be4SDimitry Andric unsigned NPR = Target.getABI() == "avrtiny" ? 6 : 18; 134fe013be4SDimitry Andric unsigned NRR = Target.getABI() == "avrtiny" ? 4 : 8; 135fe013be4SDimitry Andric return createAVRTargetCodeGenInfo(CGM, NPR, NRR); 136fe013be4SDimitry Andric } 137fe013be4SDimitry Andric 138fe013be4SDimitry Andric case llvm::Triple::aarch64: 139fe013be4SDimitry Andric case llvm::Triple::aarch64_32: 140fe013be4SDimitry Andric case llvm::Triple::aarch64_be: { 141fe013be4SDimitry Andric AArch64ABIKind Kind = AArch64ABIKind::AAPCS; 142fe013be4SDimitry Andric if (Target.getABI() == "darwinpcs") 143fe013be4SDimitry Andric Kind = AArch64ABIKind::DarwinPCS; 144fe013be4SDimitry Andric else if (Triple.isOSWindows()) 145fe013be4SDimitry Andric return createWindowsAArch64TargetCodeGenInfo(CGM, AArch64ABIKind::Win64); 146fe013be4SDimitry Andric 147fe013be4SDimitry Andric return createAArch64TargetCodeGenInfo(CGM, Kind); 148fe013be4SDimitry Andric } 149fe013be4SDimitry Andric 150fe013be4SDimitry Andric case llvm::Triple::wasm32: 151fe013be4SDimitry Andric case llvm::Triple::wasm64: { 152fe013be4SDimitry Andric WebAssemblyABIKind Kind = WebAssemblyABIKind::MVP; 153fe013be4SDimitry Andric if (Target.getABI() == "experimental-mv") 154fe013be4SDimitry Andric Kind = WebAssemblyABIKind::ExperimentalMV; 155fe013be4SDimitry Andric return createWebAssemblyTargetCodeGenInfo(CGM, Kind); 156fe013be4SDimitry Andric } 157fe013be4SDimitry Andric 158fe013be4SDimitry Andric case llvm::Triple::arm: 159fe013be4SDimitry Andric case llvm::Triple::armeb: 160fe013be4SDimitry Andric case llvm::Triple::thumb: 161fe013be4SDimitry Andric case llvm::Triple::thumbeb: { 162fe013be4SDimitry Andric if (Triple.getOS() == llvm::Triple::Win32) 163fe013be4SDimitry Andric return createWindowsARMTargetCodeGenInfo(CGM, ARMABIKind::AAPCS_VFP); 164fe013be4SDimitry Andric 165fe013be4SDimitry Andric ARMABIKind Kind = ARMABIKind::AAPCS; 166fe013be4SDimitry Andric StringRef ABIStr = Target.getABI(); 167fe013be4SDimitry Andric if (ABIStr == "apcs-gnu") 168fe013be4SDimitry Andric Kind = ARMABIKind::APCS; 169fe013be4SDimitry Andric else if (ABIStr == "aapcs16") 170fe013be4SDimitry Andric Kind = ARMABIKind::AAPCS16_VFP; 171fe013be4SDimitry Andric else if (CodeGenOpts.FloatABI == "hard" || 172fe013be4SDimitry Andric (CodeGenOpts.FloatABI != "soft" && 173fe013be4SDimitry Andric (Triple.getEnvironment() == llvm::Triple::GNUEABIHF || 174fe013be4SDimitry Andric Triple.getEnvironment() == llvm::Triple::MuslEABIHF || 175fe013be4SDimitry Andric Triple.getEnvironment() == llvm::Triple::EABIHF))) 176fe013be4SDimitry Andric Kind = ARMABIKind::AAPCS_VFP; 177fe013be4SDimitry Andric 178fe013be4SDimitry Andric return createARMTargetCodeGenInfo(CGM, Kind); 179fe013be4SDimitry Andric } 180fe013be4SDimitry Andric 181fe013be4SDimitry Andric case llvm::Triple::ppc: { 182fe013be4SDimitry Andric if (Triple.isOSAIX()) 183fe013be4SDimitry Andric return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/false); 184fe013be4SDimitry Andric 185fe013be4SDimitry Andric bool IsSoftFloat = 186fe013be4SDimitry Andric CodeGenOpts.FloatABI == "soft" || Target.hasFeature("spe"); 187fe013be4SDimitry Andric return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat); 188fe013be4SDimitry Andric } 189fe013be4SDimitry Andric case llvm::Triple::ppcle: { 190fe013be4SDimitry Andric bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 191fe013be4SDimitry Andric return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat); 192fe013be4SDimitry Andric } 193fe013be4SDimitry Andric case llvm::Triple::ppc64: 194fe013be4SDimitry Andric if (Triple.isOSAIX()) 195fe013be4SDimitry Andric return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/true); 196fe013be4SDimitry Andric 197fe013be4SDimitry Andric if (Triple.isOSBinFormatELF()) { 198fe013be4SDimitry Andric PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv1; 199fe013be4SDimitry Andric if (Target.getABI() == "elfv2") 200fe013be4SDimitry Andric Kind = PPC64_SVR4_ABIKind::ELFv2; 201fe013be4SDimitry Andric bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 202fe013be4SDimitry Andric 203fe013be4SDimitry Andric return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat); 204fe013be4SDimitry Andric } 205fe013be4SDimitry Andric return createPPC64TargetCodeGenInfo(CGM); 206fe013be4SDimitry Andric case llvm::Triple::ppc64le: { 207fe013be4SDimitry Andric assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!"); 208fe013be4SDimitry Andric PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv2; 209fe013be4SDimitry Andric if (Target.getABI() == "elfv1") 210fe013be4SDimitry Andric Kind = PPC64_SVR4_ABIKind::ELFv1; 211fe013be4SDimitry Andric bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 212fe013be4SDimitry Andric 213fe013be4SDimitry Andric return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat); 214fe013be4SDimitry Andric } 215fe013be4SDimitry Andric 216fe013be4SDimitry Andric case llvm::Triple::nvptx: 217fe013be4SDimitry Andric case llvm::Triple::nvptx64: 218fe013be4SDimitry Andric return createNVPTXTargetCodeGenInfo(CGM); 219fe013be4SDimitry Andric 220fe013be4SDimitry Andric case llvm::Triple::msp430: 221fe013be4SDimitry Andric return createMSP430TargetCodeGenInfo(CGM); 222fe013be4SDimitry Andric 223fe013be4SDimitry Andric case llvm::Triple::riscv32: 224fe013be4SDimitry Andric case llvm::Triple::riscv64: { 225fe013be4SDimitry Andric StringRef ABIStr = Target.getABI(); 226fe013be4SDimitry Andric unsigned XLen = Target.getPointerWidth(LangAS::Default); 227fe013be4SDimitry Andric unsigned ABIFLen = 0; 228c9157d92SDimitry Andric if (ABIStr.ends_with("f")) 229fe013be4SDimitry Andric ABIFLen = 32; 230c9157d92SDimitry Andric else if (ABIStr.ends_with("d")) 231fe013be4SDimitry Andric ABIFLen = 64; 232*a58f00eaSDimitry Andric bool EABI = ABIStr.ends_with("e"); 233*a58f00eaSDimitry Andric return createRISCVTargetCodeGenInfo(CGM, XLen, ABIFLen, EABI); 234fe013be4SDimitry Andric } 235fe013be4SDimitry Andric 236fe013be4SDimitry Andric case llvm::Triple::systemz: { 237fe013be4SDimitry Andric bool SoftFloat = CodeGenOpts.FloatABI == "soft"; 238fe013be4SDimitry Andric bool HasVector = !SoftFloat && Target.getABI() == "vector"; 239fe013be4SDimitry Andric return createSystemZTargetCodeGenInfo(CGM, HasVector, SoftFloat); 240fe013be4SDimitry Andric } 241fe013be4SDimitry Andric 242fe013be4SDimitry Andric case llvm::Triple::tce: 243fe013be4SDimitry Andric case llvm::Triple::tcele: 244fe013be4SDimitry Andric return createTCETargetCodeGenInfo(CGM); 245fe013be4SDimitry Andric 246fe013be4SDimitry Andric case llvm::Triple::x86: { 247fe013be4SDimitry Andric bool IsDarwinVectorABI = Triple.isOSDarwin(); 248fe013be4SDimitry Andric bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing(); 249fe013be4SDimitry Andric 250fe013be4SDimitry Andric if (Triple.getOS() == llvm::Triple::Win32) { 251fe013be4SDimitry Andric return createWinX86_32TargetCodeGenInfo( 252fe013be4SDimitry Andric CGM, IsDarwinVectorABI, IsWin32FloatStructABI, 253fe013be4SDimitry Andric CodeGenOpts.NumRegisterParameters); 254fe013be4SDimitry Andric } 255fe013be4SDimitry Andric return createX86_32TargetCodeGenInfo( 256fe013be4SDimitry Andric CGM, IsDarwinVectorABI, IsWin32FloatStructABI, 257fe013be4SDimitry Andric CodeGenOpts.NumRegisterParameters, CodeGenOpts.FloatABI == "soft"); 258fe013be4SDimitry Andric } 259fe013be4SDimitry Andric 260fe013be4SDimitry Andric case llvm::Triple::x86_64: { 261fe013be4SDimitry Andric StringRef ABI = Target.getABI(); 262fe013be4SDimitry Andric X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512 263fe013be4SDimitry Andric : ABI == "avx" ? X86AVXABILevel::AVX 264fe013be4SDimitry Andric : X86AVXABILevel::None); 265fe013be4SDimitry Andric 266fe013be4SDimitry Andric switch (Triple.getOS()) { 267fe013be4SDimitry Andric case llvm::Triple::Win32: 268fe013be4SDimitry Andric return createWinX86_64TargetCodeGenInfo(CGM, AVXLevel); 269fe013be4SDimitry Andric default: 270fe013be4SDimitry Andric return createX86_64TargetCodeGenInfo(CGM, AVXLevel); 271fe013be4SDimitry Andric } 272fe013be4SDimitry Andric } 273fe013be4SDimitry Andric case llvm::Triple::hexagon: 274fe013be4SDimitry Andric return createHexagonTargetCodeGenInfo(CGM); 275fe013be4SDimitry Andric case llvm::Triple::lanai: 276fe013be4SDimitry Andric return createLanaiTargetCodeGenInfo(CGM); 277fe013be4SDimitry Andric case llvm::Triple::r600: 278fe013be4SDimitry Andric return createAMDGPUTargetCodeGenInfo(CGM); 279fe013be4SDimitry Andric case llvm::Triple::amdgcn: 280fe013be4SDimitry Andric return createAMDGPUTargetCodeGenInfo(CGM); 281fe013be4SDimitry Andric case llvm::Triple::sparc: 282fe013be4SDimitry Andric return createSparcV8TargetCodeGenInfo(CGM); 283fe013be4SDimitry Andric case llvm::Triple::sparcv9: 284fe013be4SDimitry Andric return createSparcV9TargetCodeGenInfo(CGM); 285fe013be4SDimitry Andric case llvm::Triple::xcore: 286fe013be4SDimitry Andric return createXCoreTargetCodeGenInfo(CGM); 287fe013be4SDimitry Andric case llvm::Triple::arc: 288fe013be4SDimitry Andric return createARCTargetCodeGenInfo(CGM); 289fe013be4SDimitry Andric case llvm::Triple::spir: 290fe013be4SDimitry Andric case llvm::Triple::spir64: 291fe013be4SDimitry Andric return createCommonSPIRTargetCodeGenInfo(CGM); 292fe013be4SDimitry Andric case llvm::Triple::spirv32: 293fe013be4SDimitry Andric case llvm::Triple::spirv64: 294fe013be4SDimitry Andric return createSPIRVTargetCodeGenInfo(CGM); 295fe013be4SDimitry Andric case llvm::Triple::ve: 296fe013be4SDimitry Andric return createVETargetCodeGenInfo(CGM); 297fe013be4SDimitry Andric case llvm::Triple::csky: { 298fe013be4SDimitry Andric bool IsSoftFloat = !Target.hasFeature("hard-float-abi"); 299fe013be4SDimitry Andric bool hasFP64 = 300fe013be4SDimitry Andric Target.hasFeature("fpuv2_df") || Target.hasFeature("fpuv3_df"); 301fe013be4SDimitry Andric return createCSKYTargetCodeGenInfo(CGM, IsSoftFloat ? 0 302fe013be4SDimitry Andric : hasFP64 ? 64 303fe013be4SDimitry Andric : 32); 304fe013be4SDimitry Andric } 305fe013be4SDimitry Andric case llvm::Triple::bpfeb: 306fe013be4SDimitry Andric case llvm::Triple::bpfel: 307fe013be4SDimitry Andric return createBPFTargetCodeGenInfo(CGM); 308fe013be4SDimitry Andric case llvm::Triple::loongarch32: 309fe013be4SDimitry Andric case llvm::Triple::loongarch64: { 310fe013be4SDimitry Andric StringRef ABIStr = Target.getABI(); 311fe013be4SDimitry Andric unsigned ABIFRLen = 0; 312c9157d92SDimitry Andric if (ABIStr.ends_with("f")) 313fe013be4SDimitry Andric ABIFRLen = 32; 314c9157d92SDimitry Andric else if (ABIStr.ends_with("d")) 315fe013be4SDimitry Andric ABIFRLen = 64; 316fe013be4SDimitry Andric return createLoongArchTargetCodeGenInfo( 317fe013be4SDimitry Andric CGM, Target.getPointerWidth(LangAS::Default), ABIFRLen); 318fe013be4SDimitry Andric } 319fe013be4SDimitry Andric } 320fe013be4SDimitry Andric } 321fe013be4SDimitry Andric 322fe013be4SDimitry Andric const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { 323fe013be4SDimitry Andric if (!TheTargetCodeGenInfo) 324fe013be4SDimitry Andric TheTargetCodeGenInfo = createTargetCodeGenInfo(*this); 325fe013be4SDimitry Andric return *TheTargetCodeGenInfo; 326fe013be4SDimitry Andric } 327fe013be4SDimitry Andric 328972a253aSDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, 329972a253aSDimitry Andric IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS, 330972a253aSDimitry Andric const HeaderSearchOptions &HSO, 3310b57cec5SDimitry Andric const PreprocessorOptions &PPO, 3320b57cec5SDimitry Andric const CodeGenOptions &CGO, llvm::Module &M, 3330b57cec5SDimitry Andric DiagnosticsEngine &diags, 3340b57cec5SDimitry Andric CoverageSourceInfo *CoverageInfo) 335fe013be4SDimitry Andric : Context(C), LangOpts(C.getLangOpts()), FS(FS), HeaderSearchOpts(HSO), 336fe013be4SDimitry Andric PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags), 337fe013be4SDimitry Andric Target(C.getTargetInfo()), ABI(createCXXABI(*this)), 338fe013be4SDimitry Andric VMContext(M.getContext()), Types(*this), VTables(*this), 339fe013be4SDimitry Andric SanitizerMD(new SanitizerMetadata(*this)) { 3400b57cec5SDimitry Andric 3410b57cec5SDimitry Andric // Initialize the type cache. 3420b57cec5SDimitry Andric llvm::LLVMContext &LLVMContext = M.getContext(); 3430b57cec5SDimitry Andric VoidTy = llvm::Type::getVoidTy(LLVMContext); 3440b57cec5SDimitry Andric Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 3450b57cec5SDimitry Andric Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 3460b57cec5SDimitry Andric Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 3470b57cec5SDimitry Andric Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 3480b57cec5SDimitry Andric HalfTy = llvm::Type::getHalfTy(LLVMContext); 3495ffd83dbSDimitry Andric BFloatTy = llvm::Type::getBFloatTy(LLVMContext); 3500b57cec5SDimitry Andric FloatTy = llvm::Type::getFloatTy(LLVMContext); 3510b57cec5SDimitry Andric DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 352bdd1243dSDimitry Andric PointerWidthInBits = C.getTargetInfo().getPointerWidth(LangAS::Default); 3530b57cec5SDimitry Andric PointerAlignInBytes = 354bdd1243dSDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(LangAS::Default)) 355bdd1243dSDimitry Andric .getQuantity(); 3560b57cec5SDimitry Andric SizeSizeInBytes = 3570b57cec5SDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity(); 3580b57cec5SDimitry Andric IntAlignInBytes = 3590b57cec5SDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity(); 360e8d8bef9SDimitry Andric CharTy = 361e8d8bef9SDimitry Andric llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth()); 3620b57cec5SDimitry Andric IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 3630b57cec5SDimitry Andric IntPtrTy = llvm::IntegerType::get(LLVMContext, 3640b57cec5SDimitry Andric C.getTargetInfo().getMaxPointerWidth()); 365c9157d92SDimitry Andric Int8PtrTy = llvm::PointerType::get(LLVMContext, 0); 366349cc55cSDimitry Andric const llvm::DataLayout &DL = M.getDataLayout(); 367c9157d92SDimitry Andric AllocaInt8PtrTy = 368c9157d92SDimitry Andric llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace()); 369c9157d92SDimitry Andric GlobalsInt8PtrTy = 370c9157d92SDimitry Andric llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace()); 371c9157d92SDimitry Andric ConstGlobalsPtrTy = llvm::PointerType::get( 372c9157d92SDimitry Andric LLVMContext, C.getTargetAddressSpace(GetGlobalConstantAddressSpace())); 3730b57cec5SDimitry Andric ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace(); 3740b57cec5SDimitry Andric 375fcaf7f86SDimitry Andric // Build C++20 Module initializers. 376fcaf7f86SDimitry Andric // TODO: Add Microsoft here once we know the mangling required for the 377fcaf7f86SDimitry Andric // initializers. 378fcaf7f86SDimitry Andric CXX20ModuleInits = 379fcaf7f86SDimitry Andric LangOpts.CPlusPlusModules && getCXXABI().getMangleContext().getKind() == 380fcaf7f86SDimitry Andric ItaniumMangleContext::MK_Itanium; 381fcaf7f86SDimitry Andric 3820b57cec5SDimitry Andric RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 3830b57cec5SDimitry Andric 3840b57cec5SDimitry Andric if (LangOpts.ObjC) 3850b57cec5SDimitry Andric createObjCRuntime(); 3860b57cec5SDimitry Andric if (LangOpts.OpenCL) 3870b57cec5SDimitry Andric createOpenCLRuntime(); 3880b57cec5SDimitry Andric if (LangOpts.OpenMP) 3890b57cec5SDimitry Andric createOpenMPRuntime(); 3900b57cec5SDimitry Andric if (LangOpts.CUDA) 3910b57cec5SDimitry Andric createCUDARuntime(); 39281ad6265SDimitry Andric if (LangOpts.HLSL) 39381ad6265SDimitry Andric createHLSLRuntime(); 3940b57cec5SDimitry Andric 3950b57cec5SDimitry Andric // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 3960b57cec5SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::Thread) || 3970b57cec5SDimitry Andric (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 3980b57cec5SDimitry Andric TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(), 3990b57cec5SDimitry Andric getCXXABI().getMangleContext())); 4000b57cec5SDimitry Andric 4010b57cec5SDimitry Andric // If debug info or coverage generation is enabled, create the CGDebugInfo 4020b57cec5SDimitry Andric // object. 403fe013be4SDimitry Andric if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo || 404fe013be4SDimitry Andric CodeGenOpts.CoverageNotesFile.size() || 405fe013be4SDimitry Andric CodeGenOpts.CoverageDataFile.size()) 4060b57cec5SDimitry Andric DebugInfo.reset(new CGDebugInfo(*this)); 4070b57cec5SDimitry Andric 4080b57cec5SDimitry Andric Block.GlobalUniqueCount = 0; 4090b57cec5SDimitry Andric 4100b57cec5SDimitry Andric if (C.getLangOpts().ObjC) 4110b57cec5SDimitry Andric ObjCData.reset(new ObjCEntrypoints()); 4120b57cec5SDimitry Andric 4130b57cec5SDimitry Andric if (CodeGenOpts.hasProfileClangUse()) { 4140b57cec5SDimitry Andric auto ReaderOrErr = llvm::IndexedInstrProfReader::create( 415fe013be4SDimitry Andric CodeGenOpts.ProfileInstrumentUsePath, *FS, 416fe013be4SDimitry Andric CodeGenOpts.ProfileRemappingFile); 417bdd1243dSDimitry Andric // We're checking for profile read errors in CompilerInvocation, so if 418bdd1243dSDimitry Andric // there was an error it should've already been caught. If it hasn't been 419bdd1243dSDimitry Andric // somehow, trip an assertion. 420bdd1243dSDimitry Andric assert(ReaderOrErr); 4210b57cec5SDimitry Andric PGOReader = std::move(ReaderOrErr.get()); 4220b57cec5SDimitry Andric } 4230b57cec5SDimitry Andric 4240b57cec5SDimitry Andric // If coverage mapping generation is enabled, create the 4250b57cec5SDimitry Andric // CoverageMappingModuleGen object. 4260b57cec5SDimitry Andric if (CodeGenOpts.CoverageMapping) 4270b57cec5SDimitry Andric CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); 428fe6060f1SDimitry Andric 429fe6060f1SDimitry Andric // Generate the module name hash here if needed. 430fe6060f1SDimitry Andric if (CodeGenOpts.UniqueInternalLinkageNames && 431fe6060f1SDimitry Andric !getModule().getSourceFileName().empty()) { 432fe6060f1SDimitry Andric std::string Path = getModule().getSourceFileName(); 433fe6060f1SDimitry Andric // Check if a path substitution is needed from the MacroPrefixMap. 4346e75b2fbSDimitry Andric for (const auto &Entry : LangOpts.MacroPrefixMap) 435fe6060f1SDimitry Andric if (Path.rfind(Entry.first, 0) != std::string::npos) { 436fe6060f1SDimitry Andric Path = Entry.second + Path.substr(Entry.first.size()); 437fe6060f1SDimitry Andric break; 438fe6060f1SDimitry Andric } 439bdd1243dSDimitry Andric ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path); 440fe6060f1SDimitry Andric } 4410b57cec5SDimitry Andric } 4420b57cec5SDimitry Andric 4430b57cec5SDimitry Andric CodeGenModule::~CodeGenModule() {} 4440b57cec5SDimitry Andric 4450b57cec5SDimitry Andric void CodeGenModule::createObjCRuntime() { 4460b57cec5SDimitry Andric // This is just isGNUFamily(), but we want to force implementors of 4470b57cec5SDimitry Andric // new ABIs to decide how best to do this. 4480b57cec5SDimitry Andric switch (LangOpts.ObjCRuntime.getKind()) { 4490b57cec5SDimitry Andric case ObjCRuntime::GNUstep: 4500b57cec5SDimitry Andric case ObjCRuntime::GCC: 4510b57cec5SDimitry Andric case ObjCRuntime::ObjFW: 4520b57cec5SDimitry Andric ObjCRuntime.reset(CreateGNUObjCRuntime(*this)); 4530b57cec5SDimitry Andric return; 4540b57cec5SDimitry Andric 4550b57cec5SDimitry Andric case ObjCRuntime::FragileMacOSX: 4560b57cec5SDimitry Andric case ObjCRuntime::MacOSX: 4570b57cec5SDimitry Andric case ObjCRuntime::iOS: 4580b57cec5SDimitry Andric case ObjCRuntime::WatchOS: 4590b57cec5SDimitry Andric ObjCRuntime.reset(CreateMacObjCRuntime(*this)); 4600b57cec5SDimitry Andric return; 4610b57cec5SDimitry Andric } 4620b57cec5SDimitry Andric llvm_unreachable("bad runtime kind"); 4630b57cec5SDimitry Andric } 4640b57cec5SDimitry Andric 4650b57cec5SDimitry Andric void CodeGenModule::createOpenCLRuntime() { 4660b57cec5SDimitry Andric OpenCLRuntime.reset(new CGOpenCLRuntime(*this)); 4670b57cec5SDimitry Andric } 4680b57cec5SDimitry Andric 4690b57cec5SDimitry Andric void CodeGenModule::createOpenMPRuntime() { 4700b57cec5SDimitry Andric // Select a specialized code generation class based on the target, if any. 4710b57cec5SDimitry Andric // If it does not exist use the default implementation. 4720b57cec5SDimitry Andric switch (getTriple().getArch()) { 4730b57cec5SDimitry Andric case llvm::Triple::nvptx: 4740b57cec5SDimitry Andric case llvm::Triple::nvptx64: 475e8d8bef9SDimitry Andric case llvm::Triple::amdgcn: 476fe013be4SDimitry Andric assert(getLangOpts().OpenMPIsTargetDevice && 477349cc55cSDimitry Andric "OpenMP AMDGPU/NVPTX is only prepared to deal with device code."); 478349cc55cSDimitry Andric OpenMPRuntime.reset(new CGOpenMPRuntimeGPU(*this)); 479e8d8bef9SDimitry Andric break; 4800b57cec5SDimitry Andric default: 4810b57cec5SDimitry Andric if (LangOpts.OpenMPSimd) 4820b57cec5SDimitry Andric OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this)); 4830b57cec5SDimitry Andric else 4840b57cec5SDimitry Andric OpenMPRuntime.reset(new CGOpenMPRuntime(*this)); 4850b57cec5SDimitry Andric break; 4860b57cec5SDimitry Andric } 4870b57cec5SDimitry Andric } 4880b57cec5SDimitry Andric 4890b57cec5SDimitry Andric void CodeGenModule::createCUDARuntime() { 4900b57cec5SDimitry Andric CUDARuntime.reset(CreateNVCUDARuntime(*this)); 4910b57cec5SDimitry Andric } 4920b57cec5SDimitry Andric 49381ad6265SDimitry Andric void CodeGenModule::createHLSLRuntime() { 49481ad6265SDimitry Andric HLSLRuntime.reset(new CGHLSLRuntime(*this)); 49581ad6265SDimitry Andric } 49681ad6265SDimitry Andric 4970b57cec5SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { 4980b57cec5SDimitry Andric Replacements[Name] = C; 4990b57cec5SDimitry Andric } 5000b57cec5SDimitry Andric 5010b57cec5SDimitry Andric void CodeGenModule::applyReplacements() { 5020b57cec5SDimitry Andric for (auto &I : Replacements) { 503fe013be4SDimitry Andric StringRef MangledName = I.first; 5040b57cec5SDimitry Andric llvm::Constant *Replacement = I.second; 5050b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 5060b57cec5SDimitry Andric if (!Entry) 5070b57cec5SDimitry Andric continue; 5080b57cec5SDimitry Andric auto *OldF = cast<llvm::Function>(Entry); 5090b57cec5SDimitry Andric auto *NewF = dyn_cast<llvm::Function>(Replacement); 5100b57cec5SDimitry Andric if (!NewF) { 5110b57cec5SDimitry Andric if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 5120b57cec5SDimitry Andric NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 5130b57cec5SDimitry Andric } else { 5140b57cec5SDimitry Andric auto *CE = cast<llvm::ConstantExpr>(Replacement); 5150b57cec5SDimitry Andric assert(CE->getOpcode() == llvm::Instruction::BitCast || 5160b57cec5SDimitry Andric CE->getOpcode() == llvm::Instruction::GetElementPtr); 5170b57cec5SDimitry Andric NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 5180b57cec5SDimitry Andric } 5190b57cec5SDimitry Andric } 5200b57cec5SDimitry Andric 5210b57cec5SDimitry Andric // Replace old with new, but keep the old order. 5220b57cec5SDimitry Andric OldF->replaceAllUsesWith(Replacement); 5230b57cec5SDimitry Andric if (NewF) { 5240b57cec5SDimitry Andric NewF->removeFromParent(); 5250b57cec5SDimitry Andric OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(), 5260b57cec5SDimitry Andric NewF); 5270b57cec5SDimitry Andric } 5280b57cec5SDimitry Andric OldF->eraseFromParent(); 5290b57cec5SDimitry Andric } 5300b57cec5SDimitry Andric } 5310b57cec5SDimitry Andric 5320b57cec5SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { 5330b57cec5SDimitry Andric GlobalValReplacements.push_back(std::make_pair(GV, C)); 5340b57cec5SDimitry Andric } 5350b57cec5SDimitry Andric 5360b57cec5SDimitry Andric void CodeGenModule::applyGlobalValReplacements() { 5370b57cec5SDimitry Andric for (auto &I : GlobalValReplacements) { 5380b57cec5SDimitry Andric llvm::GlobalValue *GV = I.first; 5390b57cec5SDimitry Andric llvm::Constant *C = I.second; 5400b57cec5SDimitry Andric 5410b57cec5SDimitry Andric GV->replaceAllUsesWith(C); 5420b57cec5SDimitry Andric GV->eraseFromParent(); 5430b57cec5SDimitry Andric } 5440b57cec5SDimitry Andric } 5450b57cec5SDimitry Andric 5460b57cec5SDimitry Andric // This is only used in aliases that we created and we know they have a 5470b57cec5SDimitry Andric // linear structure. 548349cc55cSDimitry Andric static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) { 549349cc55cSDimitry Andric const llvm::Constant *C; 550349cc55cSDimitry Andric if (auto *GA = dyn_cast<llvm::GlobalAlias>(GV)) 551349cc55cSDimitry Andric C = GA->getAliasee(); 552349cc55cSDimitry Andric else if (auto *GI = dyn_cast<llvm::GlobalIFunc>(GV)) 553349cc55cSDimitry Andric C = GI->getResolver(); 554349cc55cSDimitry Andric else 555349cc55cSDimitry Andric return GV; 556349cc55cSDimitry Andric 557349cc55cSDimitry Andric const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(C->stripPointerCasts()); 558349cc55cSDimitry Andric if (!AliaseeGV) 5590b57cec5SDimitry Andric return nullptr; 560349cc55cSDimitry Andric 561349cc55cSDimitry Andric const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject(); 562349cc55cSDimitry Andric if (FinalGV == GV) 5630b57cec5SDimitry Andric return nullptr; 564349cc55cSDimitry Andric 565349cc55cSDimitry Andric return FinalGV; 5660b57cec5SDimitry Andric } 567349cc55cSDimitry Andric 568fe013be4SDimitry Andric static bool checkAliasedGlobal( 569c9157d92SDimitry Andric const ASTContext &Context, DiagnosticsEngine &Diags, SourceLocation Location, 570c9157d92SDimitry Andric bool IsIFunc, const llvm::GlobalValue *Alias, const llvm::GlobalValue *&GV, 571fe013be4SDimitry Andric const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames, 572fe013be4SDimitry Andric SourceRange AliasRange) { 573349cc55cSDimitry Andric GV = getAliasedGlobal(Alias); 574349cc55cSDimitry Andric if (!GV) { 575349cc55cSDimitry Andric Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc; 576349cc55cSDimitry Andric return false; 577349cc55cSDimitry Andric } 578349cc55cSDimitry Andric 579c9157d92SDimitry Andric if (GV->hasCommonLinkage()) { 580c9157d92SDimitry Andric const llvm::Triple &Triple = Context.getTargetInfo().getTriple(); 581c9157d92SDimitry Andric if (Triple.getObjectFormat() == llvm::Triple::XCOFF) { 582c9157d92SDimitry Andric Diags.Report(Location, diag::err_alias_to_common); 583c9157d92SDimitry Andric return false; 584c9157d92SDimitry Andric } 585c9157d92SDimitry Andric } 586c9157d92SDimitry Andric 587349cc55cSDimitry Andric if (GV->isDeclaration()) { 588349cc55cSDimitry Andric Diags.Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc; 589fe013be4SDimitry Andric Diags.Report(Location, diag::note_alias_requires_mangled_name) 590fe013be4SDimitry Andric << IsIFunc << IsIFunc; 591fe013be4SDimitry Andric // Provide a note if the given function is not found and exists as a 592fe013be4SDimitry Andric // mangled name. 593fe013be4SDimitry Andric for (const auto &[Decl, Name] : MangledDeclNames) { 594fe013be4SDimitry Andric if (const auto *ND = dyn_cast<NamedDecl>(Decl.getDecl())) { 595fe013be4SDimitry Andric if (ND->getName() == GV->getName()) { 596fe013be4SDimitry Andric Diags.Report(Location, diag::note_alias_mangled_name_alternative) 597fe013be4SDimitry Andric << Name 598fe013be4SDimitry Andric << FixItHint::CreateReplacement( 599fe013be4SDimitry Andric AliasRange, 600fe013be4SDimitry Andric (Twine(IsIFunc ? "ifunc" : "alias") + "(\"" + Name + "\")") 601fe013be4SDimitry Andric .str()); 602fe013be4SDimitry Andric } 603fe013be4SDimitry Andric } 604fe013be4SDimitry Andric } 605349cc55cSDimitry Andric return false; 606349cc55cSDimitry Andric } 607349cc55cSDimitry Andric 608349cc55cSDimitry Andric if (IsIFunc) { 609349cc55cSDimitry Andric // Check resolver function type. 610349cc55cSDimitry Andric const auto *F = dyn_cast<llvm::Function>(GV); 611349cc55cSDimitry Andric if (!F) { 612349cc55cSDimitry Andric Diags.Report(Location, diag::err_alias_to_undefined) 613349cc55cSDimitry Andric << IsIFunc << IsIFunc; 614349cc55cSDimitry Andric return false; 615349cc55cSDimitry Andric } 616349cc55cSDimitry Andric 617349cc55cSDimitry Andric llvm::FunctionType *FTy = F->getFunctionType(); 618349cc55cSDimitry Andric if (!FTy->getReturnType()->isPointerTy()) { 619349cc55cSDimitry Andric Diags.Report(Location, diag::err_ifunc_resolver_return); 620349cc55cSDimitry Andric return false; 621349cc55cSDimitry Andric } 622349cc55cSDimitry Andric } 623349cc55cSDimitry Andric 624349cc55cSDimitry Andric return true; 6250b57cec5SDimitry Andric } 6260b57cec5SDimitry Andric 6270b57cec5SDimitry Andric void CodeGenModule::checkAliases() { 6280b57cec5SDimitry Andric // Check if the constructed aliases are well formed. It is really unfortunate 6290b57cec5SDimitry Andric // that we have to do this in CodeGen, but we only construct mangled names 6300b57cec5SDimitry Andric // and aliases during codegen. 6310b57cec5SDimitry Andric bool Error = false; 6320b57cec5SDimitry Andric DiagnosticsEngine &Diags = getDiags(); 6330b57cec5SDimitry Andric for (const GlobalDecl &GD : Aliases) { 6340b57cec5SDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 6350b57cec5SDimitry Andric SourceLocation Location; 636fe013be4SDimitry Andric SourceRange Range; 6370b57cec5SDimitry Andric bool IsIFunc = D->hasAttr<IFuncAttr>(); 638fe013be4SDimitry Andric if (const Attr *A = D->getDefiningAttr()) { 6390b57cec5SDimitry Andric Location = A->getLocation(); 640fe013be4SDimitry Andric Range = A->getRange(); 641fe013be4SDimitry Andric } else 6420b57cec5SDimitry Andric llvm_unreachable("Not an alias or ifunc?"); 643349cc55cSDimitry Andric 6440b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 645349cc55cSDimitry Andric llvm::GlobalValue *Alias = GetGlobalValue(MangledName); 646349cc55cSDimitry Andric const llvm::GlobalValue *GV = nullptr; 647c9157d92SDimitry Andric if (!checkAliasedGlobal(getContext(), Diags, Location, IsIFunc, Alias, GV, 648fe013be4SDimitry Andric MangledDeclNames, Range)) { 6490b57cec5SDimitry Andric Error = true; 650349cc55cSDimitry Andric continue; 6510b57cec5SDimitry Andric } 6520b57cec5SDimitry Andric 653349cc55cSDimitry Andric llvm::Constant *Aliasee = 654349cc55cSDimitry Andric IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver() 655349cc55cSDimitry Andric : cast<llvm::GlobalAlias>(Alias)->getAliasee(); 656349cc55cSDimitry Andric 6570b57cec5SDimitry Andric llvm::GlobalValue *AliaseeGV; 6580b57cec5SDimitry Andric if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 6590b57cec5SDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 6600b57cec5SDimitry Andric else 6610b57cec5SDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 6620b57cec5SDimitry Andric 6630b57cec5SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 6640b57cec5SDimitry Andric StringRef AliasSection = SA->getName(); 6650b57cec5SDimitry Andric if (AliasSection != AliaseeGV->getSection()) 6660b57cec5SDimitry Andric Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 6670b57cec5SDimitry Andric << AliasSection << IsIFunc << IsIFunc; 6680b57cec5SDimitry Andric } 6690b57cec5SDimitry Andric 6700b57cec5SDimitry Andric // We have to handle alias to weak aliases in here. LLVM itself disallows 6710b57cec5SDimitry Andric // this since the object semantics would not match the IL one. For 6720b57cec5SDimitry Andric // compatibility with gcc we implement it by just pointing the alias 6730b57cec5SDimitry Andric // to its aliasee's aliasee. We also warn, since the user is probably 6740b57cec5SDimitry Andric // expecting the link to be weak. 675349cc55cSDimitry Andric if (auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) { 6760b57cec5SDimitry Andric if (GA->isInterposable()) { 6770b57cec5SDimitry Andric Diags.Report(Location, diag::warn_alias_to_weak_alias) 6780b57cec5SDimitry Andric << GV->getName() << GA->getName() << IsIFunc; 6790b57cec5SDimitry Andric Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 680349cc55cSDimitry Andric GA->getAliasee(), Alias->getType()); 681349cc55cSDimitry Andric 682349cc55cSDimitry Andric if (IsIFunc) 683349cc55cSDimitry Andric cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee); 684349cc55cSDimitry Andric else 685349cc55cSDimitry Andric cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee); 6860b57cec5SDimitry Andric } 6870b57cec5SDimitry Andric } 6880b57cec5SDimitry Andric } 6890b57cec5SDimitry Andric if (!Error) 6900b57cec5SDimitry Andric return; 6910b57cec5SDimitry Andric 6920b57cec5SDimitry Andric for (const GlobalDecl &GD : Aliases) { 6930b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 694349cc55cSDimitry Andric llvm::GlobalValue *Alias = GetGlobalValue(MangledName); 6950b57cec5SDimitry Andric Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 6960b57cec5SDimitry Andric Alias->eraseFromParent(); 6970b57cec5SDimitry Andric } 6980b57cec5SDimitry Andric } 6990b57cec5SDimitry Andric 7000b57cec5SDimitry Andric void CodeGenModule::clear() { 7010b57cec5SDimitry Andric DeferredDeclsToEmit.clear(); 702753f127fSDimitry Andric EmittedDeferredDecls.clear(); 703c9157d92SDimitry Andric DeferredAnnotations.clear(); 7040b57cec5SDimitry Andric if (OpenMPRuntime) 7050b57cec5SDimitry Andric OpenMPRuntime->clear(); 7060b57cec5SDimitry Andric } 7070b57cec5SDimitry Andric 7080b57cec5SDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 7090b57cec5SDimitry Andric StringRef MainFile) { 7100b57cec5SDimitry Andric if (!hasDiagnostics()) 7110b57cec5SDimitry Andric return; 7120b57cec5SDimitry Andric if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 7130b57cec5SDimitry Andric if (MainFile.empty()) 7140b57cec5SDimitry Andric MainFile = "<stdin>"; 7150b57cec5SDimitry Andric Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 7160b57cec5SDimitry Andric } else { 7170b57cec5SDimitry Andric if (Mismatched > 0) 7180b57cec5SDimitry Andric Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched; 7190b57cec5SDimitry Andric 7200b57cec5SDimitry Andric if (Missing > 0) 7210b57cec5SDimitry Andric Diags.Report(diag::warn_profile_data_missing) << Visited << Missing; 7220b57cec5SDimitry Andric } 7230b57cec5SDimitry Andric } 7240b57cec5SDimitry Andric 725*a58f00eaSDimitry Andric static std::optional<llvm::GlobalValue::VisibilityTypes> 726*a58f00eaSDimitry Andric getLLVMVisibility(clang::LangOptions::VisibilityFromDLLStorageClassKinds K) { 727*a58f00eaSDimitry Andric // Map to LLVM visibility. 728*a58f00eaSDimitry Andric switch (K) { 729*a58f00eaSDimitry Andric case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Keep: 730*a58f00eaSDimitry Andric return std::nullopt; 731*a58f00eaSDimitry Andric case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Default: 732*a58f00eaSDimitry Andric return llvm::GlobalValue::DefaultVisibility; 733*a58f00eaSDimitry Andric case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Hidden: 734*a58f00eaSDimitry Andric return llvm::GlobalValue::HiddenVisibility; 735*a58f00eaSDimitry Andric case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Protected: 736*a58f00eaSDimitry Andric return llvm::GlobalValue::ProtectedVisibility; 737*a58f00eaSDimitry Andric } 738*a58f00eaSDimitry Andric llvm_unreachable("unknown option value!"); 739*a58f00eaSDimitry Andric } 740*a58f00eaSDimitry Andric 741*a58f00eaSDimitry Andric void setLLVMVisibility(llvm::GlobalValue &GV, 742*a58f00eaSDimitry Andric std::optional<llvm::GlobalValue::VisibilityTypes> V) { 743*a58f00eaSDimitry Andric if (!V) 744e8d8bef9SDimitry Andric return; 745e8d8bef9SDimitry Andric 746e8d8bef9SDimitry Andric // Reset DSO locality before setting the visibility. This removes 747e8d8bef9SDimitry Andric // any effects that visibility options and annotations may have 748e8d8bef9SDimitry Andric // had on the DSO locality. Setting the visibility will implicitly set 749e8d8bef9SDimitry Andric // appropriate globals to DSO Local; however, this will be pessimistic 750e8d8bef9SDimitry Andric // w.r.t. to the normal compiler IRGen. 751e8d8bef9SDimitry Andric GV.setDSOLocal(false); 752*a58f00eaSDimitry Andric GV.setVisibility(*V); 753*a58f00eaSDimitry Andric } 754e8d8bef9SDimitry Andric 755*a58f00eaSDimitry Andric static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO, 756*a58f00eaSDimitry Andric llvm::Module &M) { 757*a58f00eaSDimitry Andric if (!LO.VisibilityFromDLLStorageClass) 758*a58f00eaSDimitry Andric return; 759*a58f00eaSDimitry Andric 760*a58f00eaSDimitry Andric std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility = 761*a58f00eaSDimitry Andric getLLVMVisibility(LO.getDLLExportVisibility()); 762*a58f00eaSDimitry Andric 763*a58f00eaSDimitry Andric std::optional<llvm::GlobalValue::VisibilityTypes> 764*a58f00eaSDimitry Andric NoDLLStorageClassVisibility = 765*a58f00eaSDimitry Andric getLLVMVisibility(LO.getNoDLLStorageClassVisibility()); 766*a58f00eaSDimitry Andric 767*a58f00eaSDimitry Andric std::optional<llvm::GlobalValue::VisibilityTypes> 768*a58f00eaSDimitry Andric ExternDeclDLLImportVisibility = 769*a58f00eaSDimitry Andric getLLVMVisibility(LO.getExternDeclDLLImportVisibility()); 770*a58f00eaSDimitry Andric 771*a58f00eaSDimitry Andric std::optional<llvm::GlobalValue::VisibilityTypes> 772*a58f00eaSDimitry Andric ExternDeclNoDLLStorageClassVisibility = 773*a58f00eaSDimitry Andric getLLVMVisibility(LO.getExternDeclNoDLLStorageClassVisibility()); 774*a58f00eaSDimitry Andric 775*a58f00eaSDimitry Andric for (llvm::GlobalValue &GV : M.global_values()) { 776*a58f00eaSDimitry Andric if (GV.hasAppendingLinkage() || GV.hasLocalLinkage()) 777*a58f00eaSDimitry Andric continue; 778*a58f00eaSDimitry Andric 779*a58f00eaSDimitry Andric if (GV.isDeclarationForLinker()) 780*a58f00eaSDimitry Andric setLLVMVisibility(GV, GV.getDLLStorageClass() == 781e8d8bef9SDimitry Andric llvm::GlobalValue::DLLImportStorageClass 782e8d8bef9SDimitry Andric ? ExternDeclDLLImportVisibility 783e8d8bef9SDimitry Andric : ExternDeclNoDLLStorageClassVisibility); 784*a58f00eaSDimitry Andric else 785*a58f00eaSDimitry Andric setLLVMVisibility(GV, GV.getDLLStorageClass() == 786e8d8bef9SDimitry Andric llvm::GlobalValue::DLLExportStorageClass 787e8d8bef9SDimitry Andric ? DLLExportVisibility 788e8d8bef9SDimitry Andric : NoDLLStorageClassVisibility); 789e8d8bef9SDimitry Andric 790e8d8bef9SDimitry Andric GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 791e8d8bef9SDimitry Andric } 792e8d8bef9SDimitry Andric } 793e8d8bef9SDimitry Andric 794c9157d92SDimitry Andric static bool isStackProtectorOn(const LangOptions &LangOpts, 795c9157d92SDimitry Andric const llvm::Triple &Triple, 796c9157d92SDimitry Andric clang::LangOptions::StackProtectorMode Mode) { 797c9157d92SDimitry Andric if (Triple.isAMDGPU() || Triple.isNVPTX()) 798c9157d92SDimitry Andric return false; 799c9157d92SDimitry Andric return LangOpts.getStackProtector() == Mode; 800c9157d92SDimitry Andric } 801c9157d92SDimitry Andric 8020b57cec5SDimitry Andric void CodeGenModule::Release() { 803fe013be4SDimitry Andric Module *Primary = getContext().getCurrentNamedModule(); 80461cfbce3SDimitry Andric if (CXX20ModuleInits && Primary && !Primary->isHeaderLikeModule()) 805fcaf7f86SDimitry Andric EmitModuleInitializers(Primary); 8060b57cec5SDimitry Andric EmitDeferred(); 807753f127fSDimitry Andric DeferredDecls.insert(EmittedDeferredDecls.begin(), 808753f127fSDimitry Andric EmittedDeferredDecls.end()); 809753f127fSDimitry Andric EmittedDeferredDecls.clear(); 8100b57cec5SDimitry Andric EmitVTablesOpportunistically(); 8110b57cec5SDimitry Andric applyGlobalValReplacements(); 8120b57cec5SDimitry Andric applyReplacements(); 8130b57cec5SDimitry Andric emitMultiVersionFunctions(); 814bdd1243dSDimitry Andric 815bdd1243dSDimitry Andric if (Context.getLangOpts().IncrementalExtensions && 816bdd1243dSDimitry Andric GlobalTopLevelStmtBlockInFlight.first) { 817bdd1243dSDimitry Andric const TopLevelStmtDecl *TLSD = GlobalTopLevelStmtBlockInFlight.second; 818bdd1243dSDimitry Andric GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->getEndLoc()); 819bdd1243dSDimitry Andric GlobalTopLevelStmtBlockInFlight = {nullptr, nullptr}; 820bdd1243dSDimitry Andric } 821bdd1243dSDimitry Andric 822fe013be4SDimitry Andric // Module implementations are initialized the same way as a regular TU that 823fe013be4SDimitry Andric // imports one or more modules. 824fcaf7f86SDimitry Andric if (CXX20ModuleInits && Primary && Primary->isInterfaceOrPartition()) 825fcaf7f86SDimitry Andric EmitCXXModuleInitFunc(Primary); 826fcaf7f86SDimitry Andric else 8270b57cec5SDimitry Andric EmitCXXGlobalInitFunc(); 8285ffd83dbSDimitry Andric EmitCXXGlobalCleanUpFunc(); 8290b57cec5SDimitry Andric registerGlobalDtorsWithAtExit(); 8300b57cec5SDimitry Andric EmitCXXThreadLocalInitFunc(); 8310b57cec5SDimitry Andric if (ObjCRuntime) 8320b57cec5SDimitry Andric if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 8330b57cec5SDimitry Andric AddGlobalCtor(ObjCInitFunction); 834fe6060f1SDimitry Andric if (Context.getLangOpts().CUDA && CUDARuntime) { 835fe6060f1SDimitry Andric if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule()) 8360b57cec5SDimitry Andric AddGlobalCtor(CudaCtorFunction); 8370b57cec5SDimitry Andric } 8380b57cec5SDimitry Andric if (OpenMPRuntime) { 8390b57cec5SDimitry Andric if (llvm::Function *OpenMPRequiresDirectiveRegFun = 8400b57cec5SDimitry Andric OpenMPRuntime->emitRequiresDirectiveRegFun()) { 8410b57cec5SDimitry Andric AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0); 8420b57cec5SDimitry Andric } 843a7dea167SDimitry Andric OpenMPRuntime->createOffloadEntriesAndInfoMetadata(); 8440b57cec5SDimitry Andric OpenMPRuntime->clear(); 8450b57cec5SDimitry Andric } 8460b57cec5SDimitry Andric if (PGOReader) { 8470b57cec5SDimitry Andric getModule().setProfileSummary( 8480b57cec5SDimitry Andric PGOReader->getSummary(/* UseCS */ false).getMD(VMContext), 8490b57cec5SDimitry Andric llvm::ProfileSummary::PSK_Instr); 8500b57cec5SDimitry Andric if (PGOStats.hasDiagnostics()) 8510b57cec5SDimitry Andric PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 8520b57cec5SDimitry Andric } 853bdd1243dSDimitry Andric llvm::stable_sort(GlobalCtors, [](const Structor &L, const Structor &R) { 854bdd1243dSDimitry Andric return L.LexOrder < R.LexOrder; 855bdd1243dSDimitry Andric }); 8560b57cec5SDimitry Andric EmitCtorList(GlobalCtors, "llvm.global_ctors"); 8570b57cec5SDimitry Andric EmitCtorList(GlobalDtors, "llvm.global_dtors"); 8580b57cec5SDimitry Andric EmitGlobalAnnotations(); 8590b57cec5SDimitry Andric EmitStaticExternCAliases(); 86081ad6265SDimitry Andric checkAliases(); 8610b57cec5SDimitry Andric EmitDeferredUnusedCoverageMappings(); 862fe6060f1SDimitry Andric CodeGenPGO(*this).setValueProfilingFlag(getModule()); 8630b57cec5SDimitry Andric if (CoverageMapping) 8640b57cec5SDimitry Andric CoverageMapping->emit(); 8650b57cec5SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 8660b57cec5SDimitry Andric CodeGenFunction(*this).EmitCfiCheckFail(); 8670b57cec5SDimitry Andric CodeGenFunction(*this).EmitCfiCheckStub(); 8680b57cec5SDimitry Andric } 869bdd1243dSDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) 870bdd1243dSDimitry Andric finalizeKCFITypes(); 8710b57cec5SDimitry Andric emitAtAvailableLinkGuard(); 87281ad6265SDimitry Andric if (Context.getTargetInfo().getTriple().isWasm()) 8735ffd83dbSDimitry Andric EmitMainVoidAlias(); 874fe6060f1SDimitry Andric 87581ad6265SDimitry Andric if (getTriple().isAMDGPU()) { 87681ad6265SDimitry Andric // Emit amdgpu_code_object_version module flag, which is code object version 87781ad6265SDimitry Andric // times 100. 878bdd1243dSDimitry Andric if (getTarget().getTargetOpts().CodeObjectVersion != 879c9157d92SDimitry Andric llvm::CodeObjectVersionKind::COV_None) { 88081ad6265SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, 88181ad6265SDimitry Andric "amdgpu_code_object_version", 88281ad6265SDimitry Andric getTarget().getTargetOpts().CodeObjectVersion); 88381ad6265SDimitry Andric } 884fe013be4SDimitry Andric 885fe013be4SDimitry Andric // Currently, "-mprintf-kind" option is only supported for HIP 886fe013be4SDimitry Andric if (LangOpts.HIP) { 887fe013be4SDimitry Andric auto *MDStr = llvm::MDString::get( 888fe013be4SDimitry Andric getLLVMContext(), (getTarget().getTargetOpts().AMDGPUPrintfKindVal == 889fe013be4SDimitry Andric TargetOptions::AMDGPUPrintfKind::Hostcall) 890fe013be4SDimitry Andric ? "hostcall" 891fe013be4SDimitry Andric : "buffered"); 892fe013be4SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "amdgpu_printf_kind", 893fe013be4SDimitry Andric MDStr); 894fe013be4SDimitry Andric } 89581ad6265SDimitry Andric } 89681ad6265SDimitry Andric 89781ad6265SDimitry Andric // Emit a global array containing all external kernels or device variables 89881ad6265SDimitry Andric // used by host functions and mark it as used for CUDA/HIP. This is necessary 89981ad6265SDimitry Andric // to get kernels or device variables in archives linked in even if these 90081ad6265SDimitry Andric // kernels or device variables are only used in host functions. 90181ad6265SDimitry Andric if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) { 90281ad6265SDimitry Andric SmallVector<llvm::Constant *, 8> UsedArray; 90381ad6265SDimitry Andric for (auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) { 90481ad6265SDimitry Andric GlobalDecl GD; 90581ad6265SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) 90681ad6265SDimitry Andric GD = GlobalDecl(FD, KernelReferenceKind::Kernel); 90781ad6265SDimitry Andric else 90881ad6265SDimitry Andric GD = GlobalDecl(D); 90981ad6265SDimitry Andric UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 91081ad6265SDimitry Andric GetAddrOfGlobal(GD), Int8PtrTy)); 91181ad6265SDimitry Andric } 91281ad6265SDimitry Andric 91381ad6265SDimitry Andric llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size()); 91481ad6265SDimitry Andric 91581ad6265SDimitry Andric auto *GV = new llvm::GlobalVariable( 91681ad6265SDimitry Andric getModule(), ATy, false, llvm::GlobalValue::InternalLinkage, 91781ad6265SDimitry Andric llvm::ConstantArray::get(ATy, UsedArray), "__clang_gpu_used_external"); 91881ad6265SDimitry Andric addCompilerUsedGlobal(GV); 91904eeddc0SDimitry Andric } 920fe6060f1SDimitry Andric 9210b57cec5SDimitry Andric emitLLVMUsed(); 9220b57cec5SDimitry Andric if (SanStats) 9230b57cec5SDimitry Andric SanStats->finish(); 9240b57cec5SDimitry Andric 9250b57cec5SDimitry Andric if (CodeGenOpts.Autolink && 9260b57cec5SDimitry Andric (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 9270b57cec5SDimitry Andric EmitModuleLinkOptions(); 9280b57cec5SDimitry Andric } 9290b57cec5SDimitry Andric 9300b57cec5SDimitry Andric // On ELF we pass the dependent library specifiers directly to the linker 9310b57cec5SDimitry Andric // without manipulating them. This is in contrast to other platforms where 9320b57cec5SDimitry Andric // they are mapped to a specific linker option by the compiler. This 9330b57cec5SDimitry Andric // difference is a result of the greater variety of ELF linkers and the fact 9340b57cec5SDimitry Andric // that ELF linkers tend to handle libraries in a more complicated fashion 9350b57cec5SDimitry Andric // than on other platforms. This forces us to defer handling the dependent 9360b57cec5SDimitry Andric // libs to the linker. 9370b57cec5SDimitry Andric // 9380b57cec5SDimitry Andric // CUDA/HIP device and host libraries are different. Currently there is no 9390b57cec5SDimitry Andric // way to differentiate dependent libraries for host or device. Existing 9400b57cec5SDimitry Andric // usage of #pragma comment(lib, *) is intended for host libraries on 9410b57cec5SDimitry Andric // Windows. Therefore emit llvm.dependent-libraries only for host. 9420b57cec5SDimitry Andric if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) { 9430b57cec5SDimitry Andric auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries"); 9440b57cec5SDimitry Andric for (auto *MD : ELFDependentLibraries) 9450b57cec5SDimitry Andric NMD->addOperand(MD); 9460b57cec5SDimitry Andric } 9470b57cec5SDimitry Andric 9480b57cec5SDimitry Andric // Record mregparm value now so it is visible through rest of codegen. 9490b57cec5SDimitry Andric if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) 9500b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters", 9510b57cec5SDimitry Andric CodeGenOpts.NumRegisterParameters); 9520b57cec5SDimitry Andric 9530b57cec5SDimitry Andric if (CodeGenOpts.DwarfVersion) { 954480093f4SDimitry Andric getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version", 9550b57cec5SDimitry Andric CodeGenOpts.DwarfVersion); 9560b57cec5SDimitry Andric } 9575ffd83dbSDimitry Andric 958fe6060f1SDimitry Andric if (CodeGenOpts.Dwarf64) 959fe6060f1SDimitry Andric getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1); 960fe6060f1SDimitry Andric 9615ffd83dbSDimitry Andric if (Context.getLangOpts().SemanticInterposition) 9625ffd83dbSDimitry Andric // Require various optimization to respect semantic interposition. 96304eeddc0SDimitry Andric getModule().setSemanticInterposition(true); 9645ffd83dbSDimitry Andric 9650b57cec5SDimitry Andric if (CodeGenOpts.EmitCodeView) { 9660b57cec5SDimitry Andric // Indicate that we want CodeView in the metadata. 9670b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); 9680b57cec5SDimitry Andric } 9690b57cec5SDimitry Andric if (CodeGenOpts.CodeViewGHash) { 9700b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1); 9710b57cec5SDimitry Andric } 9720b57cec5SDimitry Andric if (CodeGenOpts.ControlFlowGuard) { 973480093f4SDimitry Andric // Function ID tables and checks for Control Flow Guard (cfguard=2). 974480093f4SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2); 975480093f4SDimitry Andric } else if (CodeGenOpts.ControlFlowGuardNoChecks) { 976480093f4SDimitry Andric // Function ID tables for Control Flow Guard (cfguard=1). 977480093f4SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1); 9780b57cec5SDimitry Andric } 979fe6060f1SDimitry Andric if (CodeGenOpts.EHContGuard) { 980fe6060f1SDimitry Andric // Function ID tables for EH Continuation Guard. 981fe6060f1SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1); 982fe6060f1SDimitry Andric } 983bdd1243dSDimitry Andric if (Context.getLangOpts().Kernel) { 984bdd1243dSDimitry Andric // Note if we are compiling with /kernel. 985bdd1243dSDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "ms-kernel", 1); 986bdd1243dSDimitry Andric } 9870b57cec5SDimitry Andric if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { 9880b57cec5SDimitry Andric // We don't support LTO with 2 with different StrictVTablePointers 9890b57cec5SDimitry Andric // FIXME: we could support it by stripping all the information introduced 9900b57cec5SDimitry Andric // by StrictVTablePointers. 9910b57cec5SDimitry Andric 9920b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); 9930b57cec5SDimitry Andric 9940b57cec5SDimitry Andric llvm::Metadata *Ops[2] = { 9950b57cec5SDimitry Andric llvm::MDString::get(VMContext, "StrictVTablePointers"), 9960b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 9970b57cec5SDimitry Andric llvm::Type::getInt32Ty(VMContext), 1))}; 9980b57cec5SDimitry Andric 9990b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Require, 10000b57cec5SDimitry Andric "StrictVTablePointersRequirement", 10010b57cec5SDimitry Andric llvm::MDNode::get(VMContext, Ops)); 10020b57cec5SDimitry Andric } 10035ffd83dbSDimitry Andric if (getModuleDebugInfo()) 10040b57cec5SDimitry Andric // We support a single version in the linked module. The LLVM 10050b57cec5SDimitry Andric // parser will drop debug info with a different version number 10060b57cec5SDimitry Andric // (and warn about it, too). 10070b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 10080b57cec5SDimitry Andric llvm::DEBUG_METADATA_VERSION); 10090b57cec5SDimitry Andric 10100b57cec5SDimitry Andric // We need to record the widths of enums and wchar_t, so that we can generate 10110b57cec5SDimitry Andric // the correct build attributes in the ARM backend. wchar_size is also used by 10120b57cec5SDimitry Andric // TargetLibraryInfo. 10130b57cec5SDimitry Andric uint64_t WCharWidth = 10140b57cec5SDimitry Andric Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 10150b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 10160b57cec5SDimitry Andric 1017c9157d92SDimitry Andric if (getTriple().isOSzOS()) { 1018c9157d92SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, 1019c9157d92SDimitry Andric "zos_product_major_version", 1020c9157d92SDimitry Andric uint32_t(CLANG_VERSION_MAJOR)); 1021c9157d92SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, 1022c9157d92SDimitry Andric "zos_product_minor_version", 1023c9157d92SDimitry Andric uint32_t(CLANG_VERSION_MINOR)); 1024c9157d92SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "zos_product_patchlevel", 1025c9157d92SDimitry Andric uint32_t(CLANG_VERSION_PATCHLEVEL)); 1026e710425bSDimitry Andric std::string ProductId = getClangVendor() + "clang"; 1027c9157d92SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "zos_product_id", 1028c9157d92SDimitry Andric llvm::MDString::get(VMContext, ProductId)); 1029c9157d92SDimitry Andric 1030c9157d92SDimitry Andric // Record the language because we need it for the PPA2. 1031c9157d92SDimitry Andric StringRef lang_str = languageToString( 1032c9157d92SDimitry Andric LangStandard::getLangStandardForKind(LangOpts.LangStd).Language); 1033c9157d92SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "zos_cu_language", 1034c9157d92SDimitry Andric llvm::MDString::get(VMContext, lang_str)); 1035c9157d92SDimitry Andric 1036c9157d92SDimitry Andric time_t TT = PreprocessorOpts.SourceDateEpoch 1037c9157d92SDimitry Andric ? *PreprocessorOpts.SourceDateEpoch 1038c9157d92SDimitry Andric : std::time(nullptr); 1039c9157d92SDimitry Andric getModule().addModuleFlag(llvm::Module::Max, "zos_translation_time", 1040c9157d92SDimitry Andric static_cast<uint64_t>(TT)); 1041c9157d92SDimitry Andric 1042c9157d92SDimitry Andric // Multiple modes will be supported here. 1043c9157d92SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "zos_le_char_mode", 1044c9157d92SDimitry Andric llvm::MDString::get(VMContext, "ascii")); 1045c9157d92SDimitry Andric } 1046c9157d92SDimitry Andric 10470b57cec5SDimitry Andric llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 10480b57cec5SDimitry Andric if ( Arch == llvm::Triple::arm 10490b57cec5SDimitry Andric || Arch == llvm::Triple::armeb 10500b57cec5SDimitry Andric || Arch == llvm::Triple::thumb 10510b57cec5SDimitry Andric || Arch == llvm::Triple::thumbeb) { 10520b57cec5SDimitry Andric // The minimum width of an enum in bytes 10530b57cec5SDimitry Andric uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 10540b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 10550b57cec5SDimitry Andric } 10560b57cec5SDimitry Andric 105713138422SDimitry Andric if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) { 105813138422SDimitry Andric StringRef ABIStr = Target.getABI(); 105913138422SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 106013138422SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "target-abi", 106113138422SDimitry Andric llvm::MDString::get(Ctx, ABIStr)); 106213138422SDimitry Andric } 106313138422SDimitry Andric 10640b57cec5SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 10650b57cec5SDimitry Andric // Indicate that we want cross-DSO control flow integrity checks. 10660b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); 10670b57cec5SDimitry Andric } 10680b57cec5SDimitry Andric 10695ffd83dbSDimitry Andric if (CodeGenOpts.WholeProgramVTables) { 10705ffd83dbSDimitry Andric // Indicate whether VFE was enabled for this module, so that the 10715ffd83dbSDimitry Andric // vcall_visibility metadata added under whole program vtables is handled 10725ffd83dbSDimitry Andric // appropriately in the optimizer. 10735ffd83dbSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim", 10745ffd83dbSDimitry Andric CodeGenOpts.VirtualFunctionElimination); 10755ffd83dbSDimitry Andric } 10765ffd83dbSDimitry Andric 1077a7dea167SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) { 1078a7dea167SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, 1079a7dea167SDimitry Andric "CFI Canonical Jump Tables", 1080a7dea167SDimitry Andric CodeGenOpts.SanitizeCfiCanonicalJumpTables); 1081a7dea167SDimitry Andric } 1082a7dea167SDimitry Andric 1083bdd1243dSDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) { 1084bdd1243dSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "kcfi", 1); 1085bdd1243dSDimitry Andric // KCFI assumes patchable-function-prefix is the same for all indirectly 1086bdd1243dSDimitry Andric // called functions. Store the expected offset for code generation. 1087bdd1243dSDimitry Andric if (CodeGenOpts.PatchableFunctionEntryOffset) 1088bdd1243dSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "kcfi-offset", 1089bdd1243dSDimitry Andric CodeGenOpts.PatchableFunctionEntryOffset); 1090bdd1243dSDimitry Andric } 1091bdd1243dSDimitry Andric 10920b57cec5SDimitry Andric if (CodeGenOpts.CFProtectionReturn && 10930b57cec5SDimitry Andric Target.checkCFProtectionReturnSupported(getDiags())) { 10940b57cec5SDimitry Andric // Indicate that we want to instrument return control flow protection. 1095fcaf7f86SDimitry Andric getModule().addModuleFlag(llvm::Module::Min, "cf-protection-return", 10960b57cec5SDimitry Andric 1); 10970b57cec5SDimitry Andric } 10980b57cec5SDimitry Andric 10990b57cec5SDimitry Andric if (CodeGenOpts.CFProtectionBranch && 11000b57cec5SDimitry Andric Target.checkCFProtectionBranchSupported(getDiags())) { 11010b57cec5SDimitry Andric // Indicate that we want to instrument branch control flow protection. 1102fcaf7f86SDimitry Andric getModule().addModuleFlag(llvm::Module::Min, "cf-protection-branch", 11030b57cec5SDimitry Andric 1); 11040b57cec5SDimitry Andric } 11050b57cec5SDimitry Andric 1106fcaf7f86SDimitry Andric if (CodeGenOpts.FunctionReturnThunks) 1107fcaf7f86SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "function_return_thunk_extern", 1); 110804eeddc0SDimitry Andric 1109bdd1243dSDimitry Andric if (CodeGenOpts.IndirectBranchCSPrefix) 1110bdd1243dSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "indirect_branch_cs_prefix", 1); 1111bdd1243dSDimitry Andric 11124824e7fdSDimitry Andric // Add module metadata for return address signing (ignoring 11134824e7fdSDimitry Andric // non-leaf/all) and stack tagging. These are actually turned on by function 11144824e7fdSDimitry Andric // attributes, but we use module metadata to emit build attributes. This is 11154824e7fdSDimitry Andric // needed for LTO, where the function attributes are inside bitcode 11164824e7fdSDimitry Andric // serialised into a global variable by the time build attributes are 111781ad6265SDimitry Andric // emitted, so we can't access them. LTO objects could be compiled with 111881ad6265SDimitry Andric // different flags therefore module flags are set to "Min" behavior to achieve 111981ad6265SDimitry Andric // the same end result of the normal build where e.g BTI is off if any object 112081ad6265SDimitry Andric // doesn't support it. 11214824e7fdSDimitry Andric if (Context.getTargetInfo().hasFeature("ptrauth") && 11224824e7fdSDimitry Andric LangOpts.getSignReturnAddressScope() != 11234824e7fdSDimitry Andric LangOptions::SignReturnAddressScopeKind::None) 11244824e7fdSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, 11254824e7fdSDimitry Andric "sign-return-address-buildattr", 1); 112681ad6265SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::MemtagStack)) 11274824e7fdSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, 11284824e7fdSDimitry Andric "tag-stack-memory-buildattr", 1); 11294824e7fdSDimitry Andric 11304824e7fdSDimitry Andric if (Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb || 11311fd87a68SDimitry Andric Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb || 11324824e7fdSDimitry Andric Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 || 1133e8d8bef9SDimitry Andric Arch == llvm::Triple::aarch64_be) { 1134972a253aSDimitry Andric if (LangOpts.BranchTargetEnforcement) 113581ad6265SDimitry Andric getModule().addModuleFlag(llvm::Module::Min, "branch-target-enforcement", 1136972a253aSDimitry Andric 1); 1137e710425bSDimitry Andric if (LangOpts.BranchProtectionPAuthLR) 1138e710425bSDimitry Andric getModule().addModuleFlag(llvm::Module::Min, "branch-protection-pauth-lr", 1139e710425bSDimitry Andric 1); 11406c20abcdSDimitry Andric if (LangOpts.GuardedControlStack) 11416c20abcdSDimitry Andric getModule().addModuleFlag(llvm::Module::Min, "guarded-control-stack", 1); 1142972a253aSDimitry Andric if (LangOpts.hasSignReturnAddress()) 1143972a253aSDimitry Andric getModule().addModuleFlag(llvm::Module::Min, "sign-return-address", 1); 1144972a253aSDimitry Andric if (LangOpts.isSignReturnAddressScopeAll()) 114581ad6265SDimitry Andric getModule().addModuleFlag(llvm::Module::Min, "sign-return-address-all", 1146972a253aSDimitry Andric 1); 1147972a253aSDimitry Andric if (!LangOpts.isSignReturnAddressWithAKey()) 114881ad6265SDimitry Andric getModule().addModuleFlag(llvm::Module::Min, 1149972a253aSDimitry Andric "sign-return-address-with-bkey", 1); 1150e8d8bef9SDimitry Andric } 1151e8d8bef9SDimitry Andric 1152c9157d92SDimitry Andric if (CodeGenOpts.StackClashProtector) 1153c9157d92SDimitry Andric getModule().addModuleFlag( 1154c9157d92SDimitry Andric llvm::Module::Override, "probe-stack", 1155c9157d92SDimitry Andric llvm::MDString::get(TheModule.getContext(), "inline-asm")); 1156c9157d92SDimitry Andric 1157c9157d92SDimitry Andric if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096) 1158c9157d92SDimitry Andric getModule().addModuleFlag(llvm::Module::Min, "stack-probe-size", 1159c9157d92SDimitry Andric CodeGenOpts.StackProbeSize); 1160c9157d92SDimitry Andric 1161e8d8bef9SDimitry Andric if (!CodeGenOpts.MemoryProfileOutput.empty()) { 1162e8d8bef9SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 1163e8d8bef9SDimitry Andric getModule().addModuleFlag( 1164e8d8bef9SDimitry Andric llvm::Module::Error, "MemProfProfileFilename", 1165e8d8bef9SDimitry Andric llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput)); 1166e8d8bef9SDimitry Andric } 1167e8d8bef9SDimitry Andric 11680b57cec5SDimitry Andric if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) { 11690b57cec5SDimitry Andric // Indicate whether __nvvm_reflect should be configured to flush denormal 11700b57cec5SDimitry Andric // floating point values to 0. (This corresponds to its "__CUDA_FTZ" 11710b57cec5SDimitry Andric // property.) 11720b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", 11735ffd83dbSDimitry Andric CodeGenOpts.FP32DenormalMode.Output != 11745ffd83dbSDimitry Andric llvm::DenormalMode::IEEE); 11750b57cec5SDimitry Andric } 11760b57cec5SDimitry Andric 1177fe6060f1SDimitry Andric if (LangOpts.EHAsynch) 1178fe6060f1SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1); 1179fe6060f1SDimitry Andric 1180fe6060f1SDimitry Andric // Indicate whether this Module was compiled with -fopenmp 1181fe6060f1SDimitry Andric if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 1182fe6060f1SDimitry Andric getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP); 1183fe013be4SDimitry Andric if (getLangOpts().OpenMPIsTargetDevice) 1184fe6060f1SDimitry Andric getModule().addModuleFlag(llvm::Module::Max, "openmp-device", 1185fe6060f1SDimitry Andric LangOpts.OpenMP); 1186fe6060f1SDimitry Andric 11870b57cec5SDimitry Andric // Emit OpenCL specific module metadata: OpenCL/SPIR version. 118881ad6265SDimitry Andric if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice && getTriple().isSPIRV())) { 11890b57cec5SDimitry Andric EmitOpenCLMetadata(); 11900b57cec5SDimitry Andric // Emit SPIR version. 11910b57cec5SDimitry Andric if (getTriple().isSPIR()) { 11920b57cec5SDimitry Andric // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the 11930b57cec5SDimitry Andric // opencl.spir.version named metadata. 1194349cc55cSDimitry Andric // C++ for OpenCL has a distinct mapping for version compatibility with 1195349cc55cSDimitry Andric // OpenCL. 1196349cc55cSDimitry Andric auto Version = LangOpts.getOpenCLCompatibleVersion(); 11970b57cec5SDimitry Andric llvm::Metadata *SPIRVerElts[] = { 11980b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 11990b57cec5SDimitry Andric Int32Ty, Version / 100)), 12000b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 12010b57cec5SDimitry Andric Int32Ty, (Version / 100 > 1) ? 0 : 2))}; 12020b57cec5SDimitry Andric llvm::NamedMDNode *SPIRVerMD = 12030b57cec5SDimitry Andric TheModule.getOrInsertNamedMetadata("opencl.spir.version"); 12040b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 12050b57cec5SDimitry Andric SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts)); 12060b57cec5SDimitry Andric } 12070b57cec5SDimitry Andric } 12080b57cec5SDimitry Andric 120981ad6265SDimitry Andric // HLSL related end of code gen work items. 121081ad6265SDimitry Andric if (LangOpts.HLSL) 121181ad6265SDimitry Andric getHLSLRuntime().finishCodeGen(); 121281ad6265SDimitry Andric 12130b57cec5SDimitry Andric if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 12140b57cec5SDimitry Andric assert(PLevel < 3 && "Invalid PIC Level"); 12150b57cec5SDimitry Andric getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel)); 12160b57cec5SDimitry Andric if (Context.getLangOpts().PIE) 12170b57cec5SDimitry Andric getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel)); 12180b57cec5SDimitry Andric } 12190b57cec5SDimitry Andric 12200b57cec5SDimitry Andric if (getCodeGenOpts().CodeModel.size() > 0) { 12210b57cec5SDimitry Andric unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel) 12220b57cec5SDimitry Andric .Case("tiny", llvm::CodeModel::Tiny) 12230b57cec5SDimitry Andric .Case("small", llvm::CodeModel::Small) 12240b57cec5SDimitry Andric .Case("kernel", llvm::CodeModel::Kernel) 12250b57cec5SDimitry Andric .Case("medium", llvm::CodeModel::Medium) 12260b57cec5SDimitry Andric .Case("large", llvm::CodeModel::Large) 12270b57cec5SDimitry Andric .Default(~0u); 12280b57cec5SDimitry Andric if (CM != ~0u) { 12290b57cec5SDimitry Andric llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM); 12300b57cec5SDimitry Andric getModule().setCodeModel(codeModel); 1231c9157d92SDimitry Andric 1232*a58f00eaSDimitry Andric if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) && 1233c9157d92SDimitry Andric Context.getTargetInfo().getTriple().getArch() == 1234c9157d92SDimitry Andric llvm::Triple::x86_64) { 1235c9157d92SDimitry Andric getModule().setLargeDataThreshold(getCodeGenOpts().LargeDataThreshold); 1236c9157d92SDimitry Andric } 12370b57cec5SDimitry Andric } 12380b57cec5SDimitry Andric } 12390b57cec5SDimitry Andric 12400b57cec5SDimitry Andric if (CodeGenOpts.NoPLT) 12410b57cec5SDimitry Andric getModule().setRtLibUseGOT(); 1242fe013be4SDimitry Andric if (getTriple().isOSBinFormatELF() && 1243fe013be4SDimitry Andric CodeGenOpts.DirectAccessExternalData != 1244fe013be4SDimitry Andric getModule().getDirectAccessExternalData()) { 1245fe013be4SDimitry Andric getModule().setDirectAccessExternalData( 1246fe013be4SDimitry Andric CodeGenOpts.DirectAccessExternalData); 1247fe013be4SDimitry Andric } 1248fe6060f1SDimitry Andric if (CodeGenOpts.UnwindTables) 124981ad6265SDimitry Andric getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables)); 1250fe6060f1SDimitry Andric 1251fe6060f1SDimitry Andric switch (CodeGenOpts.getFramePointer()) { 1252fe6060f1SDimitry Andric case CodeGenOptions::FramePointerKind::None: 1253fe6060f1SDimitry Andric // 0 ("none") is the default. 1254fe6060f1SDimitry Andric break; 1255fe6060f1SDimitry Andric case CodeGenOptions::FramePointerKind::NonLeaf: 1256fe6060f1SDimitry Andric getModule().setFramePointer(llvm::FramePointerKind::NonLeaf); 1257fe6060f1SDimitry Andric break; 1258fe6060f1SDimitry Andric case CodeGenOptions::FramePointerKind::All: 1259fe6060f1SDimitry Andric getModule().setFramePointer(llvm::FramePointerKind::All); 1260fe6060f1SDimitry Andric break; 1261fe6060f1SDimitry Andric } 12620b57cec5SDimitry Andric 12630b57cec5SDimitry Andric SimplifyPersonality(); 12640b57cec5SDimitry Andric 12650b57cec5SDimitry Andric if (getCodeGenOpts().EmitDeclMetadata) 12660b57cec5SDimitry Andric EmitDeclMetadata(); 12670b57cec5SDimitry Andric 1268fe013be4SDimitry Andric if (getCodeGenOpts().CoverageNotesFile.size() || 1269fe013be4SDimitry Andric getCodeGenOpts().CoverageDataFile.size()) 12700b57cec5SDimitry Andric EmitCoverageFile(); 12710b57cec5SDimitry Andric 12725ffd83dbSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 12735ffd83dbSDimitry Andric DI->finalize(); 12740b57cec5SDimitry Andric 12750b57cec5SDimitry Andric if (getCodeGenOpts().EmitVersionIdentMetadata) 12760b57cec5SDimitry Andric EmitVersionIdentMetadata(); 12770b57cec5SDimitry Andric 12780b57cec5SDimitry Andric if (!getCodeGenOpts().RecordCommandLine.empty()) 12790b57cec5SDimitry Andric EmitCommandLineMetadata(); 12800b57cec5SDimitry Andric 1281fe6060f1SDimitry Andric if (!getCodeGenOpts().StackProtectorGuard.empty()) 1282fe6060f1SDimitry Andric getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard); 1283fe6060f1SDimitry Andric if (!getCodeGenOpts().StackProtectorGuardReg.empty()) 1284fe6060f1SDimitry Andric getModule().setStackProtectorGuardReg( 1285fe6060f1SDimitry Andric getCodeGenOpts().StackProtectorGuardReg); 1286753f127fSDimitry Andric if (!getCodeGenOpts().StackProtectorGuardSymbol.empty()) 1287753f127fSDimitry Andric getModule().setStackProtectorGuardSymbol( 1288753f127fSDimitry Andric getCodeGenOpts().StackProtectorGuardSymbol); 1289fe6060f1SDimitry Andric if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX) 1290fe6060f1SDimitry Andric getModule().setStackProtectorGuardOffset( 1291fe6060f1SDimitry Andric getCodeGenOpts().StackProtectorGuardOffset); 1292fe6060f1SDimitry Andric if (getCodeGenOpts().StackAlignment) 1293fe6060f1SDimitry Andric getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment); 1294349cc55cSDimitry Andric if (getCodeGenOpts().SkipRaxSetup) 1295349cc55cSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "SkipRaxSetup", 1); 1296c9157d92SDimitry Andric if (getLangOpts().RegCall4) 1297c9157d92SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "RegCallv4", 1); 1298fe6060f1SDimitry Andric 1299fe013be4SDimitry Andric if (getContext().getTargetInfo().getMaxTLSAlign()) 1300fe013be4SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "MaxTLSAlign", 1301fe013be4SDimitry Andric getContext().getTargetInfo().getMaxTLSAlign()); 1302fe013be4SDimitry Andric 1303c9157d92SDimitry Andric getTargetCodeGenInfo().emitTargetGlobals(*this); 1304c9157d92SDimitry Andric 13055ffd83dbSDimitry Andric getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames); 13065ffd83dbSDimitry Andric 13075ffd83dbSDimitry Andric EmitBackendOptionsMetadata(getCodeGenOpts()); 1308e8d8bef9SDimitry Andric 130981ad6265SDimitry Andric // If there is device offloading code embed it in the host now. 131081ad6265SDimitry Andric EmbedObject(&getModule(), CodeGenOpts, getDiags()); 131181ad6265SDimitry Andric 1312e8d8bef9SDimitry Andric // Set visibility from DLL storage class 1313e8d8bef9SDimitry Andric // We do this at the end of LLVM IR generation; after any operation 1314e8d8bef9SDimitry Andric // that might affect the DLL storage class or the visibility, and 1315e8d8bef9SDimitry Andric // before anything that might act on these. 1316e8d8bef9SDimitry Andric setVisibilityFromDLLStorageClass(LangOpts, getModule()); 13170b57cec5SDimitry Andric } 13180b57cec5SDimitry Andric 13190b57cec5SDimitry Andric void CodeGenModule::EmitOpenCLMetadata() { 13200b57cec5SDimitry Andric // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the 13210b57cec5SDimitry Andric // opencl.ocl.version named metadata node. 1322349cc55cSDimitry Andric // C++ for OpenCL has a distinct mapping for versions compatibile with OpenCL. 1323349cc55cSDimitry Andric auto Version = LangOpts.getOpenCLCompatibleVersion(); 13240b57cec5SDimitry Andric llvm::Metadata *OCLVerElts[] = { 13250b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 13260b57cec5SDimitry Andric Int32Ty, Version / 100)), 13270b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 13280b57cec5SDimitry Andric Int32Ty, (Version % 100) / 10))}; 13290b57cec5SDimitry Andric llvm::NamedMDNode *OCLVerMD = 13300b57cec5SDimitry Andric TheModule.getOrInsertNamedMetadata("opencl.ocl.version"); 13310b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 13320b57cec5SDimitry Andric OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts)); 13330b57cec5SDimitry Andric } 13340b57cec5SDimitry Andric 13355ffd83dbSDimitry Andric void CodeGenModule::EmitBackendOptionsMetadata( 1336fe013be4SDimitry Andric const CodeGenOptions &CodeGenOpts) { 1337bdd1243dSDimitry Andric if (getTriple().isRISCV()) { 1338fe013be4SDimitry Andric getModule().addModuleFlag(llvm::Module::Min, "SmallDataLimit", 13395ffd83dbSDimitry Andric CodeGenOpts.SmallDataLimit); 13405ffd83dbSDimitry Andric } 13415ffd83dbSDimitry Andric } 13425ffd83dbSDimitry Andric 13430b57cec5SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 13440b57cec5SDimitry Andric // Make sure that this type is translated. 13450b57cec5SDimitry Andric Types.UpdateCompletedType(TD); 13460b57cec5SDimitry Andric } 13470b57cec5SDimitry Andric 13480b57cec5SDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { 13490b57cec5SDimitry Andric // Make sure that this type is translated. 13500b57cec5SDimitry Andric Types.RefreshTypeCacheForClass(RD); 13510b57cec5SDimitry Andric } 13520b57cec5SDimitry Andric 13530b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) { 13540b57cec5SDimitry Andric if (!TBAA) 13550b57cec5SDimitry Andric return nullptr; 13560b57cec5SDimitry Andric return TBAA->getTypeInfo(QTy); 13570b57cec5SDimitry Andric } 13580b57cec5SDimitry Andric 13590b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) { 13600b57cec5SDimitry Andric if (!TBAA) 13610b57cec5SDimitry Andric return TBAAAccessInfo(); 13625ffd83dbSDimitry Andric if (getLangOpts().CUDAIsDevice) { 13635ffd83dbSDimitry Andric // As CUDA builtin surface/texture types are replaced, skip generating TBAA 13645ffd83dbSDimitry Andric // access info. 13655ffd83dbSDimitry Andric if (AccessType->isCUDADeviceBuiltinSurfaceType()) { 13665ffd83dbSDimitry Andric if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() != 13675ffd83dbSDimitry Andric nullptr) 13685ffd83dbSDimitry Andric return TBAAAccessInfo(); 13695ffd83dbSDimitry Andric } else if (AccessType->isCUDADeviceBuiltinTextureType()) { 13705ffd83dbSDimitry Andric if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() != 13715ffd83dbSDimitry Andric nullptr) 13725ffd83dbSDimitry Andric return TBAAAccessInfo(); 13735ffd83dbSDimitry Andric } 13745ffd83dbSDimitry Andric } 13750b57cec5SDimitry Andric return TBAA->getAccessInfo(AccessType); 13760b57cec5SDimitry Andric } 13770b57cec5SDimitry Andric 13780b57cec5SDimitry Andric TBAAAccessInfo 13790b57cec5SDimitry Andric CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) { 13800b57cec5SDimitry Andric if (!TBAA) 13810b57cec5SDimitry Andric return TBAAAccessInfo(); 13820b57cec5SDimitry Andric return TBAA->getVTablePtrAccessInfo(VTablePtrType); 13830b57cec5SDimitry Andric } 13840b57cec5SDimitry Andric 13850b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 13860b57cec5SDimitry Andric if (!TBAA) 13870b57cec5SDimitry Andric return nullptr; 13880b57cec5SDimitry Andric return TBAA->getTBAAStructInfo(QTy); 13890b57cec5SDimitry Andric } 13900b57cec5SDimitry Andric 13910b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) { 13920b57cec5SDimitry Andric if (!TBAA) 13930b57cec5SDimitry Andric return nullptr; 13940b57cec5SDimitry Andric return TBAA->getBaseTypeInfo(QTy); 13950b57cec5SDimitry Andric } 13960b57cec5SDimitry Andric 13970b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) { 13980b57cec5SDimitry Andric if (!TBAA) 13990b57cec5SDimitry Andric return nullptr; 14000b57cec5SDimitry Andric return TBAA->getAccessTagInfo(Info); 14010b57cec5SDimitry Andric } 14020b57cec5SDimitry Andric 14030b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, 14040b57cec5SDimitry Andric TBAAAccessInfo TargetInfo) { 14050b57cec5SDimitry Andric if (!TBAA) 14060b57cec5SDimitry Andric return TBAAAccessInfo(); 14070b57cec5SDimitry Andric return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo); 14080b57cec5SDimitry Andric } 14090b57cec5SDimitry Andric 14100b57cec5SDimitry Andric TBAAAccessInfo 14110b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, 14120b57cec5SDimitry Andric TBAAAccessInfo InfoB) { 14130b57cec5SDimitry Andric if (!TBAA) 14140b57cec5SDimitry Andric return TBAAAccessInfo(); 14150b57cec5SDimitry Andric return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB); 14160b57cec5SDimitry Andric } 14170b57cec5SDimitry Andric 14180b57cec5SDimitry Andric TBAAAccessInfo 14190b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, 14200b57cec5SDimitry Andric TBAAAccessInfo SrcInfo) { 14210b57cec5SDimitry Andric if (!TBAA) 14220b57cec5SDimitry Andric return TBAAAccessInfo(); 14230b57cec5SDimitry Andric return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo); 14240b57cec5SDimitry Andric } 14250b57cec5SDimitry Andric 14260b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, 14270b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo) { 14280b57cec5SDimitry Andric if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo)) 14290b57cec5SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag); 14300b57cec5SDimitry Andric } 14310b57cec5SDimitry Andric 14320b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup( 14330b57cec5SDimitry Andric llvm::Instruction *I, const CXXRecordDecl *RD) { 14340b57cec5SDimitry Andric I->setMetadata(llvm::LLVMContext::MD_invariant_group, 14350b57cec5SDimitry Andric llvm::MDNode::get(getLLVMContext(), {})); 14360b57cec5SDimitry Andric } 14370b57cec5SDimitry Andric 14380b57cec5SDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) { 14390b57cec5SDimitry Andric unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 14400b57cec5SDimitry Andric getDiags().Report(Context.getFullLoc(loc), diagID) << message; 14410b57cec5SDimitry Andric } 14420b57cec5SDimitry Andric 14430b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the 14440b57cec5SDimitry Andric /// specified stmt yet. 14450b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 14460b57cec5SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 14470b57cec5SDimitry Andric "cannot compile this %0 yet"); 14480b57cec5SDimitry Andric std::string Msg = Type; 14490b57cec5SDimitry Andric getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID) 14500b57cec5SDimitry Andric << Msg << S->getSourceRange(); 14510b57cec5SDimitry Andric } 14520b57cec5SDimitry Andric 14530b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the 14540b57cec5SDimitry Andric /// specified decl yet. 14550b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 14560b57cec5SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 14570b57cec5SDimitry Andric "cannot compile this %0 yet"); 14580b57cec5SDimitry Andric std::string Msg = Type; 14590b57cec5SDimitry Andric getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 14600b57cec5SDimitry Andric } 14610b57cec5SDimitry Andric 14620b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 14630b57cec5SDimitry Andric return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 14640b57cec5SDimitry Andric } 14650b57cec5SDimitry Andric 14660b57cec5SDimitry Andric void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 14670b57cec5SDimitry Andric const NamedDecl *D) const { 14680b57cec5SDimitry Andric // Internal definitions always have default visibility. 14690b57cec5SDimitry Andric if (GV->hasLocalLinkage()) { 14700b57cec5SDimitry Andric GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 14710b57cec5SDimitry Andric return; 14720b57cec5SDimitry Andric } 14730b57cec5SDimitry Andric if (!D) 14740b57cec5SDimitry Andric return; 1475c9157d92SDimitry Andric 14760b57cec5SDimitry Andric // Set visibility for definitions, and for declarations if requested globally 14770b57cec5SDimitry Andric // or set explicitly. 14780b57cec5SDimitry Andric LinkageInfo LV = D->getLinkageAndVisibility(); 1479c9157d92SDimitry Andric 1480c9157d92SDimitry Andric // OpenMP declare target variables must be visible to the host so they can 1481c9157d92SDimitry Andric // be registered. We require protected visibility unless the variable has 1482c9157d92SDimitry Andric // the DT_nohost modifier and does not need to be registered. 1483c9157d92SDimitry Andric if (Context.getLangOpts().OpenMP && 1484c9157d92SDimitry Andric Context.getLangOpts().OpenMPIsTargetDevice && isa<VarDecl>(D) && 1485c9157d92SDimitry Andric D->hasAttr<OMPDeclareTargetDeclAttr>() && 1486c9157d92SDimitry Andric D->getAttr<OMPDeclareTargetDeclAttr>()->getDevType() != 1487c9157d92SDimitry Andric OMPDeclareTargetDeclAttr::DT_NoHost && 1488c9157d92SDimitry Andric LV.getVisibility() == HiddenVisibility) { 1489c9157d92SDimitry Andric GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 1490c9157d92SDimitry Andric return; 1491c9157d92SDimitry Andric } 1492c9157d92SDimitry Andric 1493bdd1243dSDimitry Andric if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) { 1494bdd1243dSDimitry Andric // Reject incompatible dlllstorage and visibility annotations. 1495bdd1243dSDimitry Andric if (!LV.isVisibilityExplicit()) 1496bdd1243dSDimitry Andric return; 1497bdd1243dSDimitry Andric if (GV->hasDLLExportStorageClass()) { 1498bdd1243dSDimitry Andric if (LV.getVisibility() == HiddenVisibility) 1499bdd1243dSDimitry Andric getDiags().Report(D->getLocation(), 1500bdd1243dSDimitry Andric diag::err_hidden_visibility_dllexport); 1501bdd1243dSDimitry Andric } else if (LV.getVisibility() != DefaultVisibility) { 1502bdd1243dSDimitry Andric getDiags().Report(D->getLocation(), 1503bdd1243dSDimitry Andric diag::err_non_default_visibility_dllimport); 1504bdd1243dSDimitry Andric } 1505bdd1243dSDimitry Andric return; 1506bdd1243dSDimitry Andric } 1507bdd1243dSDimitry Andric 15080b57cec5SDimitry Andric if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls || 15090b57cec5SDimitry Andric !GV->isDeclarationForLinker()) 15100b57cec5SDimitry Andric GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 15110b57cec5SDimitry Andric } 15120b57cec5SDimitry Andric 15130b57cec5SDimitry Andric static bool shouldAssumeDSOLocal(const CodeGenModule &CGM, 15140b57cec5SDimitry Andric llvm::GlobalValue *GV) { 15150b57cec5SDimitry Andric if (GV->hasLocalLinkage()) 15160b57cec5SDimitry Andric return true; 15170b57cec5SDimitry Andric 15180b57cec5SDimitry Andric if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()) 15190b57cec5SDimitry Andric return true; 15200b57cec5SDimitry Andric 15210b57cec5SDimitry Andric // DLLImport explicitly marks the GV as external. 15220b57cec5SDimitry Andric if (GV->hasDLLImportStorageClass()) 15230b57cec5SDimitry Andric return false; 15240b57cec5SDimitry Andric 15250b57cec5SDimitry Andric const llvm::Triple &TT = CGM.getTriple(); 1526c9157d92SDimitry Andric const auto &CGOpts = CGM.getCodeGenOpts(); 15270b57cec5SDimitry Andric if (TT.isWindowsGNUEnvironment()) { 15280b57cec5SDimitry Andric // In MinGW, variables without DLLImport can still be automatically 15290b57cec5SDimitry Andric // imported from a DLL by the linker; don't mark variables that 15300b57cec5SDimitry Andric // potentially could come from another DLL as DSO local. 1531fe6060f1SDimitry Andric 1532fe6060f1SDimitry Andric // With EmulatedTLS, TLS variables can be autoimported from other DLLs 1533fe6060f1SDimitry Andric // (and this actually happens in the public interface of libstdc++), so 1534fe6060f1SDimitry Andric // such variables can't be marked as DSO local. (Native TLS variables 1535fe6060f1SDimitry Andric // can't be dllimported at all, though.) 15360b57cec5SDimitry Andric if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) && 1537c9157d92SDimitry Andric (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS) && 1538c9157d92SDimitry Andric CGOpts.AutoImport) 15390b57cec5SDimitry Andric return false; 15400b57cec5SDimitry Andric } 15410b57cec5SDimitry Andric 15420b57cec5SDimitry Andric // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols 15430b57cec5SDimitry Andric // remain unresolved in the link, they can be resolved to zero, which is 15440b57cec5SDimitry Andric // outside the current DSO. 15450b57cec5SDimitry Andric if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage()) 15460b57cec5SDimitry Andric return false; 15470b57cec5SDimitry Andric 15480b57cec5SDimitry Andric // Every other GV is local on COFF. 15490b57cec5SDimitry Andric // Make an exception for windows OS in the triple: Some firmware builds use 15500b57cec5SDimitry Andric // *-win32-macho triples. This (accidentally?) produced windows relocations 15510b57cec5SDimitry Andric // without GOT tables in older clang versions; Keep this behaviour. 15520b57cec5SDimitry Andric // FIXME: even thread local variables? 15530b57cec5SDimitry Andric if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO())) 15540b57cec5SDimitry Andric return true; 15550b57cec5SDimitry Andric 15560b57cec5SDimitry Andric // Only handle COFF and ELF for now. 15570b57cec5SDimitry Andric if (!TT.isOSBinFormatELF()) 15580b57cec5SDimitry Andric return false; 15590b57cec5SDimitry Andric 1560fe6060f1SDimitry Andric // If this is not an executable, don't assume anything is local. 1561fe6060f1SDimitry Andric llvm::Reloc::Model RM = CGOpts.RelocationModel; 1562fe6060f1SDimitry Andric const auto &LOpts = CGM.getLangOpts(); 1563e8d8bef9SDimitry Andric if (RM != llvm::Reloc::Static && !LOpts.PIE) { 1564e8d8bef9SDimitry Andric // On ELF, if -fno-semantic-interposition is specified and the target 1565e8d8bef9SDimitry Andric // supports local aliases, there will be neither CC1 1566e8d8bef9SDimitry Andric // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set 1567fe6060f1SDimitry Andric // dso_local on the function if using a local alias is preferable (can avoid 1568fe6060f1SDimitry Andric // PLT indirection). 1569fe6060f1SDimitry Andric if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias())) 15700b57cec5SDimitry Andric return false; 1571e8d8bef9SDimitry Andric return !(CGM.getLangOpts().SemanticInterposition || 1572e8d8bef9SDimitry Andric CGM.getLangOpts().HalfNoSemanticInterposition); 1573e8d8bef9SDimitry Andric } 15740b57cec5SDimitry Andric 15750b57cec5SDimitry Andric // A definition cannot be preempted from an executable. 15760b57cec5SDimitry Andric if (!GV->isDeclarationForLinker()) 15770b57cec5SDimitry Andric return true; 15780b57cec5SDimitry Andric 15790b57cec5SDimitry Andric // Most PIC code sequences that assume that a symbol is local cannot produce a 15800b57cec5SDimitry Andric // 0 if it turns out the symbol is undefined. While this is ABI and relocation 15810b57cec5SDimitry Andric // depended, it seems worth it to handle it here. 15820b57cec5SDimitry Andric if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage()) 15830b57cec5SDimitry Andric return false; 15840b57cec5SDimitry Andric 1585e8d8bef9SDimitry Andric // PowerPC64 prefers TOC indirection to avoid copy relocations. 1586e8d8bef9SDimitry Andric if (TT.isPPC64()) 15870b57cec5SDimitry Andric return false; 15880b57cec5SDimitry Andric 1589e8d8bef9SDimitry Andric if (CGOpts.DirectAccessExternalData) { 1590e8d8bef9SDimitry Andric // If -fdirect-access-external-data (default for -fno-pic), set dso_local 1591e8d8bef9SDimitry Andric // for non-thread-local variables. If the symbol is not defined in the 1592e8d8bef9SDimitry Andric // executable, a copy relocation will be needed at link time. dso_local is 1593e8d8bef9SDimitry Andric // excluded for thread-local variables because they generally don't support 1594e8d8bef9SDimitry Andric // copy relocations. 15950b57cec5SDimitry Andric if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV)) 1596e8d8bef9SDimitry Andric if (!Var->isThreadLocal()) 15970b57cec5SDimitry Andric return true; 15980b57cec5SDimitry Andric 1599e8d8bef9SDimitry Andric // -fno-pic sets dso_local on a function declaration to allow direct 1600e8d8bef9SDimitry Andric // accesses when taking its address (similar to a data symbol). If the 1601e8d8bef9SDimitry Andric // function is not defined in the executable, a canonical PLT entry will be 1602e8d8bef9SDimitry Andric // needed at link time. -fno-direct-access-external-data can avoid the 1603e8d8bef9SDimitry Andric // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as 1604e8d8bef9SDimitry Andric // it could just cause trouble without providing perceptible benefits. 16050b57cec5SDimitry Andric if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static) 16060b57cec5SDimitry Andric return true; 1607e8d8bef9SDimitry Andric } 1608e8d8bef9SDimitry Andric 1609e8d8bef9SDimitry Andric // If we can use copy relocations we can assume it is local. 16100b57cec5SDimitry Andric 16115ffd83dbSDimitry Andric // Otherwise don't assume it is local. 16120b57cec5SDimitry Andric return false; 16130b57cec5SDimitry Andric } 16140b57cec5SDimitry Andric 16150b57cec5SDimitry Andric void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const { 16160b57cec5SDimitry Andric GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV)); 16170b57cec5SDimitry Andric } 16180b57cec5SDimitry Andric 16190b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 16200b57cec5SDimitry Andric GlobalDecl GD) const { 16210b57cec5SDimitry Andric const auto *D = dyn_cast<NamedDecl>(GD.getDecl()); 16220b57cec5SDimitry Andric // C++ destructors have a few C++ ABI specific special cases. 16230b57cec5SDimitry Andric if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) { 16240b57cec5SDimitry Andric getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType()); 16250b57cec5SDimitry Andric return; 16260b57cec5SDimitry Andric } 16270b57cec5SDimitry Andric setDLLImportDLLExport(GV, D); 16280b57cec5SDimitry Andric } 16290b57cec5SDimitry Andric 16300b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 16310b57cec5SDimitry Andric const NamedDecl *D) const { 16320b57cec5SDimitry Andric if (D && D->isExternallyVisible()) { 16330b57cec5SDimitry Andric if (D->hasAttr<DLLImportAttr>()) 16340b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 163581ad6265SDimitry Andric else if ((D->hasAttr<DLLExportAttr>() || 163681ad6265SDimitry Andric shouldMapVisibilityToDLLExport(D)) && 163781ad6265SDimitry Andric !GV->isDeclarationForLinker()) 16380b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 16390b57cec5SDimitry Andric } 16400b57cec5SDimitry Andric } 16410b57cec5SDimitry Andric 16420b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 16430b57cec5SDimitry Andric GlobalDecl GD) const { 16440b57cec5SDimitry Andric setDLLImportDLLExport(GV, GD); 16450b57cec5SDimitry Andric setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl())); 16460b57cec5SDimitry Andric } 16470b57cec5SDimitry Andric 16480b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 16490b57cec5SDimitry Andric const NamedDecl *D) const { 16500b57cec5SDimitry Andric setDLLImportDLLExport(GV, D); 16510b57cec5SDimitry Andric setGVPropertiesAux(GV, D); 16520b57cec5SDimitry Andric } 16530b57cec5SDimitry Andric 16540b57cec5SDimitry Andric void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV, 16550b57cec5SDimitry Andric const NamedDecl *D) const { 16560b57cec5SDimitry Andric setGlobalVisibility(GV, D); 16570b57cec5SDimitry Andric setDSOLocal(GV); 16580b57cec5SDimitry Andric GV->setPartition(CodeGenOpts.SymbolPartition); 16590b57cec5SDimitry Andric } 16600b57cec5SDimitry Andric 16610b57cec5SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 16620b57cec5SDimitry Andric return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 16630b57cec5SDimitry Andric .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 16640b57cec5SDimitry Andric .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 16650b57cec5SDimitry Andric .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 16660b57cec5SDimitry Andric .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 16670b57cec5SDimitry Andric } 16680b57cec5SDimitry Andric 16695ffd83dbSDimitry Andric llvm::GlobalVariable::ThreadLocalMode 16705ffd83dbSDimitry Andric CodeGenModule::GetDefaultLLVMTLSModel() const { 16715ffd83dbSDimitry Andric switch (CodeGenOpts.getDefaultTLSModel()) { 16720b57cec5SDimitry Andric case CodeGenOptions::GeneralDynamicTLSModel: 16730b57cec5SDimitry Andric return llvm::GlobalVariable::GeneralDynamicTLSModel; 16740b57cec5SDimitry Andric case CodeGenOptions::LocalDynamicTLSModel: 16750b57cec5SDimitry Andric return llvm::GlobalVariable::LocalDynamicTLSModel; 16760b57cec5SDimitry Andric case CodeGenOptions::InitialExecTLSModel: 16770b57cec5SDimitry Andric return llvm::GlobalVariable::InitialExecTLSModel; 16780b57cec5SDimitry Andric case CodeGenOptions::LocalExecTLSModel: 16790b57cec5SDimitry Andric return llvm::GlobalVariable::LocalExecTLSModel; 16800b57cec5SDimitry Andric } 16810b57cec5SDimitry Andric llvm_unreachable("Invalid TLS model!"); 16820b57cec5SDimitry Andric } 16830b57cec5SDimitry Andric 16840b57cec5SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 16850b57cec5SDimitry Andric assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 16860b57cec5SDimitry Andric 16870b57cec5SDimitry Andric llvm::GlobalValue::ThreadLocalMode TLM; 16885ffd83dbSDimitry Andric TLM = GetDefaultLLVMTLSModel(); 16890b57cec5SDimitry Andric 16900b57cec5SDimitry Andric // Override the TLS model if it is explicitly specified. 16910b57cec5SDimitry Andric if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 16920b57cec5SDimitry Andric TLM = GetLLVMTLSModel(Attr->getModel()); 16930b57cec5SDimitry Andric } 16940b57cec5SDimitry Andric 16950b57cec5SDimitry Andric GV->setThreadLocalMode(TLM); 16960b57cec5SDimitry Andric } 16970b57cec5SDimitry Andric 16980b57cec5SDimitry Andric static std::string getCPUSpecificMangling(const CodeGenModule &CGM, 16990b57cec5SDimitry Andric StringRef Name) { 17000b57cec5SDimitry Andric const TargetInfo &Target = CGM.getTarget(); 17010b57cec5SDimitry Andric return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str(); 17020b57cec5SDimitry Andric } 17030b57cec5SDimitry Andric 17040b57cec5SDimitry Andric static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, 17050b57cec5SDimitry Andric const CPUSpecificAttr *Attr, 17060b57cec5SDimitry Andric unsigned CPUIndex, 17070b57cec5SDimitry Andric raw_ostream &Out) { 17080b57cec5SDimitry Andric // cpu_specific gets the current name, dispatch gets the resolver if IFunc is 17090b57cec5SDimitry Andric // supported. 17100b57cec5SDimitry Andric if (Attr) 17110b57cec5SDimitry Andric Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName()); 17120b57cec5SDimitry Andric else if (CGM.getTarget().supportsIFunc()) 17130b57cec5SDimitry Andric Out << ".resolver"; 17140b57cec5SDimitry Andric } 17150b57cec5SDimitry Andric 1716bdd1243dSDimitry Andric static void AppendTargetVersionMangling(const CodeGenModule &CGM, 1717bdd1243dSDimitry Andric const TargetVersionAttr *Attr, 1718bdd1243dSDimitry Andric raw_ostream &Out) { 1719*a58f00eaSDimitry Andric if (Attr->isDefaultVersion()) { 1720*a58f00eaSDimitry Andric Out << ".default"; 1721bdd1243dSDimitry Andric return; 1722*a58f00eaSDimitry Andric } 1723bdd1243dSDimitry Andric Out << "._"; 1724fe013be4SDimitry Andric const TargetInfo &TI = CGM.getTarget(); 1725bdd1243dSDimitry Andric llvm::SmallVector<StringRef, 8> Feats; 1726bdd1243dSDimitry Andric Attr->getFeatures(Feats); 1727fe013be4SDimitry Andric llvm::stable_sort(Feats, [&TI](const StringRef FeatL, const StringRef FeatR) { 1728fe013be4SDimitry Andric return TI.multiVersionSortPriority(FeatL) < 1729fe013be4SDimitry Andric TI.multiVersionSortPriority(FeatR); 1730fe013be4SDimitry Andric }); 1731bdd1243dSDimitry Andric for (const auto &Feat : Feats) { 1732bdd1243dSDimitry Andric Out << 'M'; 1733bdd1243dSDimitry Andric Out << Feat; 1734bdd1243dSDimitry Andric } 1735bdd1243dSDimitry Andric } 1736bdd1243dSDimitry Andric 17370b57cec5SDimitry Andric static void AppendTargetMangling(const CodeGenModule &CGM, 17380b57cec5SDimitry Andric const TargetAttr *Attr, raw_ostream &Out) { 17390b57cec5SDimitry Andric if (Attr->isDefaultVersion()) 17400b57cec5SDimitry Andric return; 17410b57cec5SDimitry Andric 17420b57cec5SDimitry Andric Out << '.'; 17430b57cec5SDimitry Andric const TargetInfo &Target = CGM.getTarget(); 1744bdd1243dSDimitry Andric ParsedTargetAttr Info = Target.parseTargetAttr(Attr->getFeaturesStr()); 1745bdd1243dSDimitry Andric llvm::sort(Info.Features, [&Target](StringRef LHS, StringRef RHS) { 17460b57cec5SDimitry Andric // Multiversioning doesn't allow "no-${feature}", so we can 17470b57cec5SDimitry Andric // only have "+" prefixes here. 1748c9157d92SDimitry Andric assert(LHS.starts_with("+") && RHS.starts_with("+") && 17490b57cec5SDimitry Andric "Features should always have a prefix."); 17500b57cec5SDimitry Andric return Target.multiVersionSortPriority(LHS.substr(1)) > 17510b57cec5SDimitry Andric Target.multiVersionSortPriority(RHS.substr(1)); 17520b57cec5SDimitry Andric }); 17530b57cec5SDimitry Andric 17540b57cec5SDimitry Andric bool IsFirst = true; 17550b57cec5SDimitry Andric 1756bdd1243dSDimitry Andric if (!Info.CPU.empty()) { 17570b57cec5SDimitry Andric IsFirst = false; 1758bdd1243dSDimitry Andric Out << "arch_" << Info.CPU; 17590b57cec5SDimitry Andric } 17600b57cec5SDimitry Andric 17610b57cec5SDimitry Andric for (StringRef Feat : Info.Features) { 17620b57cec5SDimitry Andric if (!IsFirst) 17630b57cec5SDimitry Andric Out << '_'; 17640b57cec5SDimitry Andric IsFirst = false; 17650b57cec5SDimitry Andric Out << Feat.substr(1); 17660b57cec5SDimitry Andric } 17670b57cec5SDimitry Andric } 17680b57cec5SDimitry Andric 1769fe6060f1SDimitry Andric // Returns true if GD is a function decl with internal linkage and 1770fe6060f1SDimitry Andric // needs a unique suffix after the mangled name. 1771fe6060f1SDimitry Andric static bool isUniqueInternalLinkageDecl(GlobalDecl GD, 1772fe6060f1SDimitry Andric CodeGenModule &CGM) { 1773fe6060f1SDimitry Andric const Decl *D = GD.getDecl(); 1774fe6060f1SDimitry Andric return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) && 1775fe6060f1SDimitry Andric (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage); 1776fe6060f1SDimitry Andric } 1777fe6060f1SDimitry Andric 17784824e7fdSDimitry Andric static void AppendTargetClonesMangling(const CodeGenModule &CGM, 17794824e7fdSDimitry Andric const TargetClonesAttr *Attr, 17804824e7fdSDimitry Andric unsigned VersionIndex, 17814824e7fdSDimitry Andric raw_ostream &Out) { 1782fe013be4SDimitry Andric const TargetInfo &TI = CGM.getTarget(); 1783fe013be4SDimitry Andric if (TI.getTriple().isAArch64()) { 1784bdd1243dSDimitry Andric StringRef FeatureStr = Attr->getFeatureStr(VersionIndex); 1785*a58f00eaSDimitry Andric if (FeatureStr == "default") { 1786*a58f00eaSDimitry Andric Out << ".default"; 1787bdd1243dSDimitry Andric return; 1788*a58f00eaSDimitry Andric } 1789bdd1243dSDimitry Andric Out << "._"; 1790bdd1243dSDimitry Andric SmallVector<StringRef, 8> Features; 1791bdd1243dSDimitry Andric FeatureStr.split(Features, "+"); 1792fe013be4SDimitry Andric llvm::stable_sort(Features, 1793fe013be4SDimitry Andric [&TI](const StringRef FeatL, const StringRef FeatR) { 1794fe013be4SDimitry Andric return TI.multiVersionSortPriority(FeatL) < 1795fe013be4SDimitry Andric TI.multiVersionSortPriority(FeatR); 1796fe013be4SDimitry Andric }); 1797bdd1243dSDimitry Andric for (auto &Feat : Features) { 1798bdd1243dSDimitry Andric Out << 'M'; 1799bdd1243dSDimitry Andric Out << Feat; 1800bdd1243dSDimitry Andric } 1801bdd1243dSDimitry Andric } else { 18024824e7fdSDimitry Andric Out << '.'; 18034824e7fdSDimitry Andric StringRef FeatureStr = Attr->getFeatureStr(VersionIndex); 1804c9157d92SDimitry Andric if (FeatureStr.starts_with("arch=")) 18054824e7fdSDimitry Andric Out << "arch_" << FeatureStr.substr(sizeof("arch=") - 1); 18064824e7fdSDimitry Andric else 18074824e7fdSDimitry Andric Out << FeatureStr; 18084824e7fdSDimitry Andric 18094824e7fdSDimitry Andric Out << '.' << Attr->getMangledIndex(VersionIndex); 18104824e7fdSDimitry Andric } 1811bdd1243dSDimitry Andric } 18124824e7fdSDimitry Andric 1813fe6060f1SDimitry Andric static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD, 18140b57cec5SDimitry Andric const NamedDecl *ND, 18150b57cec5SDimitry Andric bool OmitMultiVersionMangling = false) { 18160b57cec5SDimitry Andric SmallString<256> Buffer; 18170b57cec5SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 18180b57cec5SDimitry Andric MangleContext &MC = CGM.getCXXABI().getMangleContext(); 1819fe6060f1SDimitry Andric if (!CGM.getModuleNameHash().empty()) 1820fe6060f1SDimitry Andric MC.needsUniqueInternalLinkageNames(); 1821fe6060f1SDimitry Andric bool ShouldMangle = MC.shouldMangleDeclName(ND); 1822fe6060f1SDimitry Andric if (ShouldMangle) 18235ffd83dbSDimitry Andric MC.mangleName(GD.getWithDecl(ND), Out); 18245ffd83dbSDimitry Andric else { 18250b57cec5SDimitry Andric IdentifierInfo *II = ND->getIdentifier(); 18260b57cec5SDimitry Andric assert(II && "Attempt to mangle unnamed decl."); 18270b57cec5SDimitry Andric const auto *FD = dyn_cast<FunctionDecl>(ND); 18280b57cec5SDimitry Andric 18290b57cec5SDimitry Andric if (FD && 18300b57cec5SDimitry Andric FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { 1831c9157d92SDimitry Andric if (CGM.getLangOpts().RegCall4) 1832c9157d92SDimitry Andric Out << "__regcall4__" << II->getName(); 1833c9157d92SDimitry Andric else 18340b57cec5SDimitry Andric Out << "__regcall3__" << II->getName(); 18355ffd83dbSDimitry Andric } else if (FD && FD->hasAttr<CUDAGlobalAttr>() && 18365ffd83dbSDimitry Andric GD.getKernelReferenceKind() == KernelReferenceKind::Stub) { 18375ffd83dbSDimitry Andric Out << "__device_stub__" << II->getName(); 18380b57cec5SDimitry Andric } else { 18390b57cec5SDimitry Andric Out << II->getName(); 18400b57cec5SDimitry Andric } 18410b57cec5SDimitry Andric } 18420b57cec5SDimitry Andric 1843fe6060f1SDimitry Andric // Check if the module name hash should be appended for internal linkage 1844fe6060f1SDimitry Andric // symbols. This should come before multi-version target suffixes are 1845fe6060f1SDimitry Andric // appended. This is to keep the name and module hash suffix of the 1846fe6060f1SDimitry Andric // internal linkage function together. The unique suffix should only be 1847fe6060f1SDimitry Andric // added when name mangling is done to make sure that the final name can 1848fe6060f1SDimitry Andric // be properly demangled. For example, for C functions without prototypes, 1849fe6060f1SDimitry Andric // name mangling is not done and the unique suffix should not be appeneded 1850fe6060f1SDimitry Andric // then. 1851fe6060f1SDimitry Andric if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) { 1852fe6060f1SDimitry Andric assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames && 1853fe6060f1SDimitry Andric "Hash computed when not explicitly requested"); 1854fe6060f1SDimitry Andric Out << CGM.getModuleNameHash(); 1855fe6060f1SDimitry Andric } 1856fe6060f1SDimitry Andric 18570b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 18580b57cec5SDimitry Andric if (FD->isMultiVersion() && !OmitMultiVersionMangling) { 18590b57cec5SDimitry Andric switch (FD->getMultiVersionKind()) { 18600b57cec5SDimitry Andric case MultiVersionKind::CPUDispatch: 18610b57cec5SDimitry Andric case MultiVersionKind::CPUSpecific: 18620b57cec5SDimitry Andric AppendCPUSpecificCPUDispatchMangling(CGM, 18630b57cec5SDimitry Andric FD->getAttr<CPUSpecificAttr>(), 18640b57cec5SDimitry Andric GD.getMultiVersionIndex(), Out); 18650b57cec5SDimitry Andric break; 18660b57cec5SDimitry Andric case MultiVersionKind::Target: 18670b57cec5SDimitry Andric AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out); 18680b57cec5SDimitry Andric break; 1869bdd1243dSDimitry Andric case MultiVersionKind::TargetVersion: 1870bdd1243dSDimitry Andric AppendTargetVersionMangling(CGM, FD->getAttr<TargetVersionAttr>(), Out); 1871bdd1243dSDimitry Andric break; 18724824e7fdSDimitry Andric case MultiVersionKind::TargetClones: 18734824e7fdSDimitry Andric AppendTargetClonesMangling(CGM, FD->getAttr<TargetClonesAttr>(), 18744824e7fdSDimitry Andric GD.getMultiVersionIndex(), Out); 18754824e7fdSDimitry Andric break; 18760b57cec5SDimitry Andric case MultiVersionKind::None: 18770b57cec5SDimitry Andric llvm_unreachable("None multiversion type isn't valid here"); 18780b57cec5SDimitry Andric } 18790b57cec5SDimitry Andric } 18800b57cec5SDimitry Andric 1881fe6060f1SDimitry Andric // Make unique name for device side static file-scope variable for HIP. 188281ad6265SDimitry Andric if (CGM.getContext().shouldExternalize(ND) && 1883fe6060f1SDimitry Andric CGM.getLangOpts().GPURelocatableDeviceCode && 188481ad6265SDimitry Andric CGM.getLangOpts().CUDAIsDevice) 18852a66634dSDimitry Andric CGM.printPostfixForExternalizedDecl(Out, ND); 188681ad6265SDimitry Andric 18875ffd83dbSDimitry Andric return std::string(Out.str()); 18880b57cec5SDimitry Andric } 18890b57cec5SDimitry Andric 18900b57cec5SDimitry Andric void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD, 189104eeddc0SDimitry Andric const FunctionDecl *FD, 189204eeddc0SDimitry Andric StringRef &CurName) { 18930b57cec5SDimitry Andric if (!FD->isMultiVersion()) 18940b57cec5SDimitry Andric return; 18950b57cec5SDimitry Andric 18960b57cec5SDimitry Andric // Get the name of what this would be without the 'target' attribute. This 18970b57cec5SDimitry Andric // allows us to lookup the version that was emitted when this wasn't a 18980b57cec5SDimitry Andric // multiversion function. 18990b57cec5SDimitry Andric std::string NonTargetName = 19000b57cec5SDimitry Andric getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 19010b57cec5SDimitry Andric GlobalDecl OtherGD; 19020b57cec5SDimitry Andric if (lookupRepresentativeDecl(NonTargetName, OtherGD)) { 19030b57cec5SDimitry Andric assert(OtherGD.getCanonicalDecl() 19040b57cec5SDimitry Andric .getDecl() 19050b57cec5SDimitry Andric ->getAsFunction() 19060b57cec5SDimitry Andric ->isMultiVersion() && 19070b57cec5SDimitry Andric "Other GD should now be a multiversioned function"); 19080b57cec5SDimitry Andric // OtherFD is the version of this function that was mangled BEFORE 19090b57cec5SDimitry Andric // becoming a MultiVersion function. It potentially needs to be updated. 19100b57cec5SDimitry Andric const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl() 19110b57cec5SDimitry Andric .getDecl() 19120b57cec5SDimitry Andric ->getAsFunction() 19130b57cec5SDimitry Andric ->getMostRecentDecl(); 19140b57cec5SDimitry Andric std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD); 19150b57cec5SDimitry Andric // This is so that if the initial version was already the 'default' 19160b57cec5SDimitry Andric // version, we don't try to update it. 19170b57cec5SDimitry Andric if (OtherName != NonTargetName) { 19180b57cec5SDimitry Andric // Remove instead of erase, since others may have stored the StringRef 19190b57cec5SDimitry Andric // to this. 19200b57cec5SDimitry Andric const auto ExistingRecord = Manglings.find(NonTargetName); 19210b57cec5SDimitry Andric if (ExistingRecord != std::end(Manglings)) 19220b57cec5SDimitry Andric Manglings.remove(&(*ExistingRecord)); 19230b57cec5SDimitry Andric auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD)); 192404eeddc0SDimitry Andric StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] = 192504eeddc0SDimitry Andric Result.first->first(); 192604eeddc0SDimitry Andric // If this is the current decl is being created, make sure we update the name. 192704eeddc0SDimitry Andric if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl()) 192804eeddc0SDimitry Andric CurName = OtherNameRef; 19290b57cec5SDimitry Andric if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName)) 19300b57cec5SDimitry Andric Entry->setName(OtherName); 19310b57cec5SDimitry Andric } 19320b57cec5SDimitry Andric } 19330b57cec5SDimitry Andric } 19340b57cec5SDimitry Andric 19350b57cec5SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 19360b57cec5SDimitry Andric GlobalDecl CanonicalGD = GD.getCanonicalDecl(); 19370b57cec5SDimitry Andric 19380b57cec5SDimitry Andric // Some ABIs don't have constructor variants. Make sure that base and 19390b57cec5SDimitry Andric // complete constructors get mangled the same. 19400b57cec5SDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { 19410b57cec5SDimitry Andric if (!getTarget().getCXXABI().hasConstructorVariants()) { 19420b57cec5SDimitry Andric CXXCtorType OrigCtorType = GD.getCtorType(); 19430b57cec5SDimitry Andric assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); 19440b57cec5SDimitry Andric if (OrigCtorType == Ctor_Base) 19450b57cec5SDimitry Andric CanonicalGD = GlobalDecl(CD, Ctor_Complete); 19460b57cec5SDimitry Andric } 19470b57cec5SDimitry Andric } 19480b57cec5SDimitry Andric 1949fe6060f1SDimitry Andric // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a 1950fe6060f1SDimitry Andric // static device variable depends on whether the variable is referenced by 1951fe6060f1SDimitry Andric // a host or device host function. Therefore the mangled name cannot be 1952fe6060f1SDimitry Andric // cached. 195381ad6265SDimitry Andric if (!LangOpts.CUDAIsDevice || !getContext().mayExternalize(GD.getDecl())) { 19540b57cec5SDimitry Andric auto FoundName = MangledDeclNames.find(CanonicalGD); 19550b57cec5SDimitry Andric if (FoundName != MangledDeclNames.end()) 19560b57cec5SDimitry Andric return FoundName->second; 1957fe6060f1SDimitry Andric } 19580b57cec5SDimitry Andric 19590b57cec5SDimitry Andric // Keep the first result in the case of a mangling collision. 19600b57cec5SDimitry Andric const auto *ND = cast<NamedDecl>(GD.getDecl()); 19610b57cec5SDimitry Andric std::string MangledName = getMangledNameImpl(*this, GD, ND); 19620b57cec5SDimitry Andric 19635ffd83dbSDimitry Andric // Ensure either we have different ABIs between host and device compilations, 19645ffd83dbSDimitry Andric // says host compilation following MSVC ABI but device compilation follows 19655ffd83dbSDimitry Andric // Itanium C++ ABI or, if they follow the same ABI, kernel names after 19665ffd83dbSDimitry Andric // mangling should be the same after name stubbing. The later checking is 19675ffd83dbSDimitry Andric // very important as the device kernel name being mangled in host-compilation 19685ffd83dbSDimitry Andric // is used to resolve the device binaries to be executed. Inconsistent naming 19695ffd83dbSDimitry Andric // result in undefined behavior. Even though we cannot check that naming 19705ffd83dbSDimitry Andric // directly between host- and device-compilations, the host- and 19715ffd83dbSDimitry Andric // device-mangling in host compilation could help catching certain ones. 19725ffd83dbSDimitry Andric assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || 197381ad6265SDimitry Andric getContext().shouldExternalize(ND) || getLangOpts().CUDAIsDevice || 19745ffd83dbSDimitry Andric (getContext().getAuxTargetInfo() && 19755ffd83dbSDimitry Andric (getContext().getAuxTargetInfo()->getCXXABI() != 19765ffd83dbSDimitry Andric getContext().getTargetInfo().getCXXABI())) || 19775ffd83dbSDimitry Andric getCUDARuntime().getDeviceSideName(ND) == 19785ffd83dbSDimitry Andric getMangledNameImpl( 19795ffd83dbSDimitry Andric *this, 19805ffd83dbSDimitry Andric GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), 19815ffd83dbSDimitry Andric ND)); 19820b57cec5SDimitry Andric 19830b57cec5SDimitry Andric auto Result = Manglings.insert(std::make_pair(MangledName, GD)); 19840b57cec5SDimitry Andric return MangledDeclNames[CanonicalGD] = Result.first->first(); 19850b57cec5SDimitry Andric } 19860b57cec5SDimitry Andric 19870b57cec5SDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 19880b57cec5SDimitry Andric const BlockDecl *BD) { 19890b57cec5SDimitry Andric MangleContext &MangleCtx = getCXXABI().getMangleContext(); 19900b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 19910b57cec5SDimitry Andric 19920b57cec5SDimitry Andric SmallString<256> Buffer; 19930b57cec5SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 19940b57cec5SDimitry Andric if (!D) 19950b57cec5SDimitry Andric MangleCtx.mangleGlobalBlock(BD, 19960b57cec5SDimitry Andric dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 19970b57cec5SDimitry Andric else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 19980b57cec5SDimitry Andric MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 19990b57cec5SDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 20000b57cec5SDimitry Andric MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 20010b57cec5SDimitry Andric else 20020b57cec5SDimitry Andric MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 20030b57cec5SDimitry Andric 20040b57cec5SDimitry Andric auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 20050b57cec5SDimitry Andric return Result.first->first(); 20060b57cec5SDimitry Andric } 20070b57cec5SDimitry Andric 200881ad6265SDimitry Andric const GlobalDecl CodeGenModule::getMangledNameDecl(StringRef Name) { 200981ad6265SDimitry Andric auto it = MangledDeclNames.begin(); 201081ad6265SDimitry Andric while (it != MangledDeclNames.end()) { 201181ad6265SDimitry Andric if (it->second == Name) 201281ad6265SDimitry Andric return it->first; 201381ad6265SDimitry Andric it++; 201481ad6265SDimitry Andric } 201581ad6265SDimitry Andric return GlobalDecl(); 201681ad6265SDimitry Andric } 201781ad6265SDimitry Andric 20180b57cec5SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 20190b57cec5SDimitry Andric return getModule().getNamedValue(Name); 20200b57cec5SDimitry Andric } 20210b57cec5SDimitry Andric 20220b57cec5SDimitry Andric /// AddGlobalCtor - Add a function to the list that will be called before 20230b57cec5SDimitry Andric /// main() runs. 20240b57cec5SDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 2025bdd1243dSDimitry Andric unsigned LexOrder, 20260b57cec5SDimitry Andric llvm::Constant *AssociatedData) { 20270b57cec5SDimitry Andric // FIXME: Type coercion of void()* types. 2028bdd1243dSDimitry Andric GlobalCtors.push_back(Structor(Priority, LexOrder, Ctor, AssociatedData)); 20290b57cec5SDimitry Andric } 20300b57cec5SDimitry Andric 20310b57cec5SDimitry Andric /// AddGlobalDtor - Add a function to the list that will be called 20320b57cec5SDimitry Andric /// when the module is unloaded. 2033e8d8bef9SDimitry Andric void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority, 2034e8d8bef9SDimitry Andric bool IsDtorAttrFunc) { 2035e8d8bef9SDimitry Andric if (CodeGenOpts.RegisterGlobalDtorsWithAtExit && 2036e8d8bef9SDimitry Andric (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) { 20370b57cec5SDimitry Andric DtorsUsingAtExit[Priority].push_back(Dtor); 20380b57cec5SDimitry Andric return; 20390b57cec5SDimitry Andric } 20400b57cec5SDimitry Andric 20410b57cec5SDimitry Andric // FIXME: Type coercion of void()* types. 2042bdd1243dSDimitry Andric GlobalDtors.push_back(Structor(Priority, ~0U, Dtor, nullptr)); 20430b57cec5SDimitry Andric } 20440b57cec5SDimitry Andric 20450b57cec5SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { 20460b57cec5SDimitry Andric if (Fns.empty()) return; 20470b57cec5SDimitry Andric 20480b57cec5SDimitry Andric // Ctor function type is void()*. 20490b57cec5SDimitry Andric llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 20500b57cec5SDimitry Andric llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy, 20510b57cec5SDimitry Andric TheModule.getDataLayout().getProgramAddressSpace()); 20520b57cec5SDimitry Andric 20530b57cec5SDimitry Andric // Get the type of a ctor entry, { i32, void ()*, i8* }. 20540b57cec5SDimitry Andric llvm::StructType *CtorStructTy = llvm::StructType::get( 20550b57cec5SDimitry Andric Int32Ty, CtorPFTy, VoidPtrTy); 20560b57cec5SDimitry Andric 20570b57cec5SDimitry Andric // Construct the constructor and destructor arrays. 20580b57cec5SDimitry Andric ConstantInitBuilder builder(*this); 20590b57cec5SDimitry Andric auto ctors = builder.beginArray(CtorStructTy); 20600b57cec5SDimitry Andric for (const auto &I : Fns) { 20610b57cec5SDimitry Andric auto ctor = ctors.beginStruct(CtorStructTy); 20620b57cec5SDimitry Andric ctor.addInt(Int32Ty, I.Priority); 2063c9157d92SDimitry Andric ctor.add(I.Initializer); 20640b57cec5SDimitry Andric if (I.AssociatedData) 2065c9157d92SDimitry Andric ctor.add(I.AssociatedData); 20660b57cec5SDimitry Andric else 20670b57cec5SDimitry Andric ctor.addNullPointer(VoidPtrTy); 20680b57cec5SDimitry Andric ctor.finishAndAddTo(ctors); 20690b57cec5SDimitry Andric } 20700b57cec5SDimitry Andric 20710b57cec5SDimitry Andric auto list = 20720b57cec5SDimitry Andric ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(), 20730b57cec5SDimitry Andric /*constant*/ false, 20740b57cec5SDimitry Andric llvm::GlobalValue::AppendingLinkage); 20750b57cec5SDimitry Andric 20760b57cec5SDimitry Andric // The LTO linker doesn't seem to like it when we set an alignment 20770b57cec5SDimitry Andric // on appending variables. Take it off as a workaround. 2078bdd1243dSDimitry Andric list->setAlignment(std::nullopt); 20790b57cec5SDimitry Andric 20800b57cec5SDimitry Andric Fns.clear(); 20810b57cec5SDimitry Andric } 20820b57cec5SDimitry Andric 20830b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes 20840b57cec5SDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 20850b57cec5SDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 20860b57cec5SDimitry Andric 20870b57cec5SDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 20880b57cec5SDimitry Andric 20890b57cec5SDimitry Andric if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D)) 20900b57cec5SDimitry Andric return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType()); 20910b57cec5SDimitry Andric 2092271697daSDimitry Andric return getLLVMLinkageForDeclarator(D, Linkage); 20930b57cec5SDimitry Andric } 20940b57cec5SDimitry Andric 20950b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { 20960b57cec5SDimitry Andric llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 20970b57cec5SDimitry Andric if (!MDS) return nullptr; 20980b57cec5SDimitry Andric 20990b57cec5SDimitry Andric return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString())); 21000b57cec5SDimitry Andric } 21010b57cec5SDimitry Andric 2102bdd1243dSDimitry Andric llvm::ConstantInt *CodeGenModule::CreateKCFITypeId(QualType T) { 2103bdd1243dSDimitry Andric if (auto *FnType = T->getAs<FunctionProtoType>()) 2104bdd1243dSDimitry Andric T = getContext().getFunctionType( 2105bdd1243dSDimitry Andric FnType->getReturnType(), FnType->getParamTypes(), 2106bdd1243dSDimitry Andric FnType->getExtProtoInfo().withExceptionSpec(EST_None)); 2107bdd1243dSDimitry Andric 2108bdd1243dSDimitry Andric std::string OutName; 2109bdd1243dSDimitry Andric llvm::raw_string_ostream Out(OutName); 2110c9157d92SDimitry Andric getCXXABI().getMangleContext().mangleCanonicalTypeName( 2111fe013be4SDimitry Andric T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers); 2112fe013be4SDimitry Andric 2113fe013be4SDimitry Andric if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers) 2114fe013be4SDimitry Andric Out << ".normalized"; 2115bdd1243dSDimitry Andric 2116bdd1243dSDimitry Andric return llvm::ConstantInt::get(Int32Ty, 2117bdd1243dSDimitry Andric static_cast<uint32_t>(llvm::xxHash64(OutName))); 2118bdd1243dSDimitry Andric } 2119bdd1243dSDimitry Andric 21200b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD, 21210b57cec5SDimitry Andric const CGFunctionInfo &Info, 2122fe6060f1SDimitry Andric llvm::Function *F, bool IsThunk) { 21230b57cec5SDimitry Andric unsigned CallingConv; 21240b57cec5SDimitry Andric llvm::AttributeList PAL; 2125fe6060f1SDimitry Andric ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, 2126fe6060f1SDimitry Andric /*AttrOnCallSite=*/false, IsThunk); 21270b57cec5SDimitry Andric F->setAttributes(PAL); 21280b57cec5SDimitry Andric F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 21290b57cec5SDimitry Andric } 21300b57cec5SDimitry Andric 21310b57cec5SDimitry Andric static void removeImageAccessQualifier(std::string& TyName) { 21320b57cec5SDimitry Andric std::string ReadOnlyQual("__read_only"); 21330b57cec5SDimitry Andric std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual); 21340b57cec5SDimitry Andric if (ReadOnlyPos != std::string::npos) 21350b57cec5SDimitry Andric // "+ 1" for the space after access qualifier. 21360b57cec5SDimitry Andric TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1); 21370b57cec5SDimitry Andric else { 21380b57cec5SDimitry Andric std::string WriteOnlyQual("__write_only"); 21390b57cec5SDimitry Andric std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual); 21400b57cec5SDimitry Andric if (WriteOnlyPos != std::string::npos) 21410b57cec5SDimitry Andric TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1); 21420b57cec5SDimitry Andric else { 21430b57cec5SDimitry Andric std::string ReadWriteQual("__read_write"); 21440b57cec5SDimitry Andric std::string::size_type ReadWritePos = TyName.find(ReadWriteQual); 21450b57cec5SDimitry Andric if (ReadWritePos != std::string::npos) 21460b57cec5SDimitry Andric TyName.erase(ReadWritePos, ReadWriteQual.size() + 1); 21470b57cec5SDimitry Andric } 21480b57cec5SDimitry Andric } 21490b57cec5SDimitry Andric } 21500b57cec5SDimitry Andric 21510b57cec5SDimitry Andric // Returns the address space id that should be produced to the 21520b57cec5SDimitry Andric // kernel_arg_addr_space metadata. This is always fixed to the ids 21530b57cec5SDimitry Andric // as specified in the SPIR 2.0 specification in order to differentiate 21540b57cec5SDimitry Andric // for example in clGetKernelArgInfo() implementation between the address 21550b57cec5SDimitry Andric // spaces with targets without unique mapping to the OpenCL address spaces 21560b57cec5SDimitry Andric // (basically all single AS CPUs). 21570b57cec5SDimitry Andric static unsigned ArgInfoAddressSpace(LangAS AS) { 21580b57cec5SDimitry Andric switch (AS) { 2159e8d8bef9SDimitry Andric case LangAS::opencl_global: 2160e8d8bef9SDimitry Andric return 1; 2161e8d8bef9SDimitry Andric case LangAS::opencl_constant: 2162e8d8bef9SDimitry Andric return 2; 2163e8d8bef9SDimitry Andric case LangAS::opencl_local: 2164e8d8bef9SDimitry Andric return 3; 2165e8d8bef9SDimitry Andric case LangAS::opencl_generic: 2166e8d8bef9SDimitry Andric return 4; // Not in SPIR 2.0 specs. 2167e8d8bef9SDimitry Andric case LangAS::opencl_global_device: 2168e8d8bef9SDimitry Andric return 5; 2169e8d8bef9SDimitry Andric case LangAS::opencl_global_host: 2170e8d8bef9SDimitry Andric return 6; 21710b57cec5SDimitry Andric default: 21720b57cec5SDimitry Andric return 0; // Assume private. 21730b57cec5SDimitry Andric } 21740b57cec5SDimitry Andric } 21750b57cec5SDimitry Andric 217681ad6265SDimitry Andric void CodeGenModule::GenKernelArgMetadata(llvm::Function *Fn, 21770b57cec5SDimitry Andric const FunctionDecl *FD, 21780b57cec5SDimitry Andric CodeGenFunction *CGF) { 21790b57cec5SDimitry Andric assert(((FD && CGF) || (!FD && !CGF)) && 21800b57cec5SDimitry Andric "Incorrect use - FD and CGF should either be both null or not!"); 21810b57cec5SDimitry Andric // Create MDNodes that represent the kernel arg metadata. 21820b57cec5SDimitry Andric // Each MDNode is a list in the form of "key", N number of values which is 21830b57cec5SDimitry Andric // the same number of values as their are kernel arguments. 21840b57cec5SDimitry Andric 21850b57cec5SDimitry Andric const PrintingPolicy &Policy = Context.getPrintingPolicy(); 21860b57cec5SDimitry Andric 21870b57cec5SDimitry Andric // MDNode for the kernel argument address space qualifiers. 21880b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> addressQuals; 21890b57cec5SDimitry Andric 21900b57cec5SDimitry Andric // MDNode for the kernel argument access qualifiers (images only). 21910b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> accessQuals; 21920b57cec5SDimitry Andric 21930b57cec5SDimitry Andric // MDNode for the kernel argument type names. 21940b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> argTypeNames; 21950b57cec5SDimitry Andric 21960b57cec5SDimitry Andric // MDNode for the kernel argument base type names. 21970b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> argBaseTypeNames; 21980b57cec5SDimitry Andric 21990b57cec5SDimitry Andric // MDNode for the kernel argument type qualifiers. 22000b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> argTypeQuals; 22010b57cec5SDimitry Andric 22020b57cec5SDimitry Andric // MDNode for the kernel argument names. 22030b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> argNames; 22040b57cec5SDimitry Andric 22050b57cec5SDimitry Andric if (FD && CGF) 22060b57cec5SDimitry Andric for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { 22070b57cec5SDimitry Andric const ParmVarDecl *parm = FD->getParamDecl(i); 220881ad6265SDimitry Andric // Get argument name. 220981ad6265SDimitry Andric argNames.push_back(llvm::MDString::get(VMContext, parm->getName())); 221081ad6265SDimitry Andric 221181ad6265SDimitry Andric if (!getLangOpts().OpenCL) 221281ad6265SDimitry Andric continue; 22130b57cec5SDimitry Andric QualType ty = parm->getType(); 22140b57cec5SDimitry Andric std::string typeQuals; 22150b57cec5SDimitry Andric 2216fe6060f1SDimitry Andric // Get image and pipe access qualifier: 2217fe6060f1SDimitry Andric if (ty->isImageType() || ty->isPipeType()) { 2218fe6060f1SDimitry Andric const Decl *PDecl = parm; 2219bdd1243dSDimitry Andric if (const auto *TD = ty->getAs<TypedefType>()) 2220fe6060f1SDimitry Andric PDecl = TD->getDecl(); 2221fe6060f1SDimitry Andric const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>(); 2222fe6060f1SDimitry Andric if (A && A->isWriteOnly()) 2223fe6060f1SDimitry Andric accessQuals.push_back(llvm::MDString::get(VMContext, "write_only")); 2224fe6060f1SDimitry Andric else if (A && A->isReadWrite()) 2225fe6060f1SDimitry Andric accessQuals.push_back(llvm::MDString::get(VMContext, "read_write")); 2226fe6060f1SDimitry Andric else 2227fe6060f1SDimitry Andric accessQuals.push_back(llvm::MDString::get(VMContext, "read_only")); 2228fe6060f1SDimitry Andric } else 2229fe6060f1SDimitry Andric accessQuals.push_back(llvm::MDString::get(VMContext, "none")); 2230fe6060f1SDimitry Andric 2231fe6060f1SDimitry Andric auto getTypeSpelling = [&](QualType Ty) { 2232fe6060f1SDimitry Andric auto typeName = Ty.getUnqualifiedType().getAsString(Policy); 2233fe6060f1SDimitry Andric 2234fe6060f1SDimitry Andric if (Ty.isCanonical()) { 2235fe6060f1SDimitry Andric StringRef typeNameRef = typeName; 2236fe6060f1SDimitry Andric // Turn "unsigned type" to "utype" 2237fe6060f1SDimitry Andric if (typeNameRef.consume_front("unsigned ")) 2238fe6060f1SDimitry Andric return std::string("u") + typeNameRef.str(); 2239fe6060f1SDimitry Andric if (typeNameRef.consume_front("signed ")) 2240fe6060f1SDimitry Andric return typeNameRef.str(); 2241fe6060f1SDimitry Andric } 2242fe6060f1SDimitry Andric 2243fe6060f1SDimitry Andric return typeName; 2244fe6060f1SDimitry Andric }; 2245fe6060f1SDimitry Andric 22460b57cec5SDimitry Andric if (ty->isPointerType()) { 22470b57cec5SDimitry Andric QualType pointeeTy = ty->getPointeeType(); 22480b57cec5SDimitry Andric 22490b57cec5SDimitry Andric // Get address qualifier. 22500b57cec5SDimitry Andric addressQuals.push_back( 22510b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(CGF->Builder.getInt32( 22520b57cec5SDimitry Andric ArgInfoAddressSpace(pointeeTy.getAddressSpace())))); 22530b57cec5SDimitry Andric 22540b57cec5SDimitry Andric // Get argument type name. 2255fe6060f1SDimitry Andric std::string typeName = getTypeSpelling(pointeeTy) + "*"; 22560b57cec5SDimitry Andric std::string baseTypeName = 2257fe6060f1SDimitry Andric getTypeSpelling(pointeeTy.getCanonicalType()) + "*"; 2258fe6060f1SDimitry Andric argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 22590b57cec5SDimitry Andric argBaseTypeNames.push_back( 22600b57cec5SDimitry Andric llvm::MDString::get(VMContext, baseTypeName)); 22610b57cec5SDimitry Andric 22620b57cec5SDimitry Andric // Get argument type qualifiers: 22630b57cec5SDimitry Andric if (ty.isRestrictQualified()) 22640b57cec5SDimitry Andric typeQuals = "restrict"; 22650b57cec5SDimitry Andric if (pointeeTy.isConstQualified() || 22660b57cec5SDimitry Andric (pointeeTy.getAddressSpace() == LangAS::opencl_constant)) 22670b57cec5SDimitry Andric typeQuals += typeQuals.empty() ? "const" : " const"; 22680b57cec5SDimitry Andric if (pointeeTy.isVolatileQualified()) 22690b57cec5SDimitry Andric typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 22700b57cec5SDimitry Andric } else { 22710b57cec5SDimitry Andric uint32_t AddrSpc = 0; 22720b57cec5SDimitry Andric bool isPipe = ty->isPipeType(); 22730b57cec5SDimitry Andric if (ty->isImageType() || isPipe) 22740b57cec5SDimitry Andric AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global); 22750b57cec5SDimitry Andric 22760b57cec5SDimitry Andric addressQuals.push_back( 22770b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc))); 22780b57cec5SDimitry Andric 22790b57cec5SDimitry Andric // Get argument type name. 2280fe6060f1SDimitry Andric ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty; 2281fe6060f1SDimitry Andric std::string typeName = getTypeSpelling(ty); 2282fe6060f1SDimitry Andric std::string baseTypeName = getTypeSpelling(ty.getCanonicalType()); 22830b57cec5SDimitry Andric 22840b57cec5SDimitry Andric // Remove access qualifiers on images 22850b57cec5SDimitry Andric // (as they are inseparable from type in clang implementation, 22860b57cec5SDimitry Andric // but OpenCL spec provides a special query to get access qualifier 22870b57cec5SDimitry Andric // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER): 22880b57cec5SDimitry Andric if (ty->isImageType()) { 22890b57cec5SDimitry Andric removeImageAccessQualifier(typeName); 22900b57cec5SDimitry Andric removeImageAccessQualifier(baseTypeName); 22910b57cec5SDimitry Andric } 22920b57cec5SDimitry Andric 22930b57cec5SDimitry Andric argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 22940b57cec5SDimitry Andric argBaseTypeNames.push_back( 22950b57cec5SDimitry Andric llvm::MDString::get(VMContext, baseTypeName)); 22960b57cec5SDimitry Andric 22970b57cec5SDimitry Andric if (isPipe) 22980b57cec5SDimitry Andric typeQuals = "pipe"; 22990b57cec5SDimitry Andric } 23000b57cec5SDimitry Andric argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals)); 23010b57cec5SDimitry Andric } 23020b57cec5SDimitry Andric 230381ad6265SDimitry Andric if (getLangOpts().OpenCL) { 23040b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_addr_space", 23050b57cec5SDimitry Andric llvm::MDNode::get(VMContext, addressQuals)); 23060b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_access_qual", 23070b57cec5SDimitry Andric llvm::MDNode::get(VMContext, accessQuals)); 23080b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_type", 23090b57cec5SDimitry Andric llvm::MDNode::get(VMContext, argTypeNames)); 23100b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_base_type", 23110b57cec5SDimitry Andric llvm::MDNode::get(VMContext, argBaseTypeNames)); 23120b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_type_qual", 23130b57cec5SDimitry Andric llvm::MDNode::get(VMContext, argTypeQuals)); 231481ad6265SDimitry Andric } 231581ad6265SDimitry Andric if (getCodeGenOpts().EmitOpenCLArgMetadata || 231681ad6265SDimitry Andric getCodeGenOpts().HIPSaveKernelArgName) 23170b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_name", 23180b57cec5SDimitry Andric llvm::MDNode::get(VMContext, argNames)); 23190b57cec5SDimitry Andric } 23200b57cec5SDimitry Andric 23210b57cec5SDimitry Andric /// Determines whether the language options require us to model 23220b57cec5SDimitry Andric /// unwind exceptions. We treat -fexceptions as mandating this 23230b57cec5SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions 23240b57cec5SDimitry Andric /// enabled. This means, for example, that C with -fexceptions 23250b57cec5SDimitry Andric /// enables this. 23260b57cec5SDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) { 23270b57cec5SDimitry Andric // If exceptions are completely disabled, obviously this is false. 23280b57cec5SDimitry Andric if (!LangOpts.Exceptions) return false; 23290b57cec5SDimitry Andric 23300b57cec5SDimitry Andric // If C++ exceptions are enabled, this is true. 23310b57cec5SDimitry Andric if (LangOpts.CXXExceptions) return true; 23320b57cec5SDimitry Andric 23330b57cec5SDimitry Andric // If ObjC exceptions are enabled, this depends on the ABI. 23340b57cec5SDimitry Andric if (LangOpts.ObjCExceptions) { 23350b57cec5SDimitry Andric return LangOpts.ObjCRuntime.hasUnwindExceptions(); 23360b57cec5SDimitry Andric } 23370b57cec5SDimitry Andric 23380b57cec5SDimitry Andric return true; 23390b57cec5SDimitry Andric } 23400b57cec5SDimitry Andric 23410b57cec5SDimitry Andric static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, 23420b57cec5SDimitry Andric const CXXMethodDecl *MD) { 23430b57cec5SDimitry Andric // Check that the type metadata can ever actually be used by a call. 23440b57cec5SDimitry Andric if (!CGM.getCodeGenOpts().LTOUnit || 23450b57cec5SDimitry Andric !CGM.HasHiddenLTOVisibility(MD->getParent())) 23460b57cec5SDimitry Andric return false; 23470b57cec5SDimitry Andric 23480b57cec5SDimitry Andric // Only functions whose address can be taken with a member function pointer 23490b57cec5SDimitry Andric // need this sort of type metadata. 2350c9157d92SDimitry Andric return MD->isImplicitObjectMemberFunction() && !MD->isVirtual() && 2351c9157d92SDimitry Andric !isa<CXXConstructorDecl, CXXDestructorDecl>(MD); 23520b57cec5SDimitry Andric } 23530b57cec5SDimitry Andric 2354c9157d92SDimitry Andric SmallVector<const CXXRecordDecl *, 0> 23550b57cec5SDimitry Andric CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) { 23560b57cec5SDimitry Andric llvm::SetVector<const CXXRecordDecl *> MostBases; 23570b57cec5SDimitry Andric 23580b57cec5SDimitry Andric std::function<void (const CXXRecordDecl *)> CollectMostBases; 23590b57cec5SDimitry Andric CollectMostBases = [&](const CXXRecordDecl *RD) { 23600b57cec5SDimitry Andric if (RD->getNumBases() == 0) 23610b57cec5SDimitry Andric MostBases.insert(RD); 23620b57cec5SDimitry Andric for (const CXXBaseSpecifier &B : RD->bases()) 23630b57cec5SDimitry Andric CollectMostBases(B.getType()->getAsCXXRecordDecl()); 23640b57cec5SDimitry Andric }; 23650b57cec5SDimitry Andric CollectMostBases(RD); 23660b57cec5SDimitry Andric return MostBases.takeVector(); 23670b57cec5SDimitry Andric } 23680b57cec5SDimitry Andric 23690b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 23700b57cec5SDimitry Andric llvm::Function *F) { 237104eeddc0SDimitry Andric llvm::AttrBuilder B(F->getContext()); 23720b57cec5SDimitry Andric 2373bdd1243dSDimitry Andric if ((!D || !D->hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables) 237481ad6265SDimitry Andric B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables)); 23750b57cec5SDimitry Andric 23765ffd83dbSDimitry Andric if (CodeGenOpts.StackClashProtector) 23775ffd83dbSDimitry Andric B.addAttribute("probe-stack", "inline-asm"); 23785ffd83dbSDimitry Andric 2379c9157d92SDimitry Andric if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096) 2380c9157d92SDimitry Andric B.addAttribute("stack-probe-size", 2381c9157d92SDimitry Andric std::to_string(CodeGenOpts.StackProbeSize)); 2382c9157d92SDimitry Andric 23830b57cec5SDimitry Andric if (!hasUnwindExceptions(LangOpts)) 23840b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoUnwind); 23850b57cec5SDimitry Andric 2386bdd1243dSDimitry Andric if (D && D->hasAttr<NoStackProtectorAttr>()) 2387bdd1243dSDimitry Andric ; // Do nothing. 2388bdd1243dSDimitry Andric else if (D && D->hasAttr<StrictGuardStackCheckAttr>() && 2389c9157d92SDimitry Andric isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn)) 2390bdd1243dSDimitry Andric B.addAttribute(llvm::Attribute::StackProtectStrong); 2391c9157d92SDimitry Andric else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn)) 23920b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::StackProtect); 2393c9157d92SDimitry Andric else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPStrong)) 23940b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectStrong); 2395c9157d92SDimitry Andric else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPReq)) 23960b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectReq); 23970b57cec5SDimitry Andric 23980b57cec5SDimitry Andric if (!D) { 23990b57cec5SDimitry Andric // If we don't have a declaration to control inlining, the function isn't 24000b57cec5SDimitry Andric // explicitly marked as alwaysinline for semantic reasons, and inlining is 24010b57cec5SDimitry Andric // disabled, mark the function as noinline. 24020b57cec5SDimitry Andric if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 24030b57cec5SDimitry Andric CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) 24040b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 24050b57cec5SDimitry Andric 2406349cc55cSDimitry Andric F->addFnAttrs(B); 24070b57cec5SDimitry Andric return; 24080b57cec5SDimitry Andric } 24090b57cec5SDimitry Andric 2410c9157d92SDimitry Andric // Handle SME attributes that apply to function definitions, 2411c9157d92SDimitry Andric // rather than to function prototypes. 2412c9157d92SDimitry Andric if (D->hasAttr<ArmLocallyStreamingAttr>()) 2413c9157d92SDimitry Andric B.addAttribute("aarch64_pstate_sm_body"); 2414c9157d92SDimitry Andric 2415*a58f00eaSDimitry Andric if (auto *Attr = D->getAttr<ArmNewAttr>()) { 2416*a58f00eaSDimitry Andric if (Attr->isNewZA()) 2417c9157d92SDimitry Andric B.addAttribute("aarch64_pstate_za_new"); 2418*a58f00eaSDimitry Andric if (Attr->isNewZT0()) 2419*a58f00eaSDimitry Andric B.addAttribute("aarch64_new_zt0"); 2420*a58f00eaSDimitry Andric } 2421c9157d92SDimitry Andric 24220b57cec5SDimitry Andric // Track whether we need to add the optnone LLVM attribute, 24230b57cec5SDimitry Andric // starting with the default for this optimization level. 24240b57cec5SDimitry Andric bool ShouldAddOptNone = 24250b57cec5SDimitry Andric !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0; 24260b57cec5SDimitry Andric // We can't add optnone in the following cases, it won't pass the verifier. 24270b57cec5SDimitry Andric ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>(); 24280b57cec5SDimitry Andric ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>(); 24290b57cec5SDimitry Andric 2430480093f4SDimitry Andric // Add optnone, but do so only if the function isn't always_inline. 2431480093f4SDimitry Andric if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) && 2432480093f4SDimitry Andric !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 24330b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::OptimizeNone); 24340b57cec5SDimitry Andric 24350b57cec5SDimitry Andric // OptimizeNone implies noinline; we should not be inlining such functions. 24360b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 24370b57cec5SDimitry Andric 24380b57cec5SDimitry Andric // We still need to handle naked functions even though optnone subsumes 24390b57cec5SDimitry Andric // much of their semantics. 24400b57cec5SDimitry Andric if (D->hasAttr<NakedAttr>()) 24410b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::Naked); 24420b57cec5SDimitry Andric 24430b57cec5SDimitry Andric // OptimizeNone wins over OptimizeForSize and MinSize. 24440b57cec5SDimitry Andric F->removeFnAttr(llvm::Attribute::OptimizeForSize); 24450b57cec5SDimitry Andric F->removeFnAttr(llvm::Attribute::MinSize); 24460b57cec5SDimitry Andric } else if (D->hasAttr<NakedAttr>()) { 24470b57cec5SDimitry Andric // Naked implies noinline: we should not be inlining such functions. 24480b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::Naked); 24490b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 24500b57cec5SDimitry Andric } else if (D->hasAttr<NoDuplicateAttr>()) { 24510b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoDuplicate); 2452480093f4SDimitry Andric } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 2453480093f4SDimitry Andric // Add noinline if the function isn't always_inline. 24540b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 24550b57cec5SDimitry Andric } else if (D->hasAttr<AlwaysInlineAttr>() && 24560b57cec5SDimitry Andric !F->hasFnAttribute(llvm::Attribute::NoInline)) { 24570b57cec5SDimitry Andric // (noinline wins over always_inline, and we can't specify both in IR) 24580b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::AlwaysInline); 24590b57cec5SDimitry Andric } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { 24600b57cec5SDimitry Andric // If we're not inlining, then force everything that isn't always_inline to 24610b57cec5SDimitry Andric // carry an explicit noinline attribute. 24620b57cec5SDimitry Andric if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) 24630b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 24640b57cec5SDimitry Andric } else { 24650b57cec5SDimitry Andric // Otherwise, propagate the inline hint attribute and potentially use its 24660b57cec5SDimitry Andric // absence to mark things as noinline. 24670b57cec5SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) { 24680b57cec5SDimitry Andric // Search function and template pattern redeclarations for inline. 24690b57cec5SDimitry Andric auto CheckForInline = [](const FunctionDecl *FD) { 24700b57cec5SDimitry Andric auto CheckRedeclForInline = [](const FunctionDecl *Redecl) { 24710b57cec5SDimitry Andric return Redecl->isInlineSpecified(); 24720b57cec5SDimitry Andric }; 24730b57cec5SDimitry Andric if (any_of(FD->redecls(), CheckRedeclForInline)) 24740b57cec5SDimitry Andric return true; 24750b57cec5SDimitry Andric const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern(); 24760b57cec5SDimitry Andric if (!Pattern) 24770b57cec5SDimitry Andric return false; 24780b57cec5SDimitry Andric return any_of(Pattern->redecls(), CheckRedeclForInline); 24790b57cec5SDimitry Andric }; 24800b57cec5SDimitry Andric if (CheckForInline(FD)) { 24810b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::InlineHint); 24820b57cec5SDimitry Andric } else if (CodeGenOpts.getInlining() == 24830b57cec5SDimitry Andric CodeGenOptions::OnlyHintInlining && 24840b57cec5SDimitry Andric !FD->isInlined() && 24850b57cec5SDimitry Andric !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 24860b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 24870b57cec5SDimitry Andric } 24880b57cec5SDimitry Andric } 24890b57cec5SDimitry Andric } 24900b57cec5SDimitry Andric 24910b57cec5SDimitry Andric // Add other optimization related attributes if we are optimizing this 24920b57cec5SDimitry Andric // function. 24930b57cec5SDimitry Andric if (!D->hasAttr<OptimizeNoneAttr>()) { 24940b57cec5SDimitry Andric if (D->hasAttr<ColdAttr>()) { 24950b57cec5SDimitry Andric if (!ShouldAddOptNone) 24960b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::OptimizeForSize); 24970b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::Cold); 24980b57cec5SDimitry Andric } 2499e8d8bef9SDimitry Andric if (D->hasAttr<HotAttr>()) 2500e8d8bef9SDimitry Andric B.addAttribute(llvm::Attribute::Hot); 25010b57cec5SDimitry Andric if (D->hasAttr<MinSizeAttr>()) 25020b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::MinSize); 25030b57cec5SDimitry Andric } 25040b57cec5SDimitry Andric 2505349cc55cSDimitry Andric F->addFnAttrs(B); 25060b57cec5SDimitry Andric 25070b57cec5SDimitry Andric unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 25080b57cec5SDimitry Andric if (alignment) 2509a7dea167SDimitry Andric F->setAlignment(llvm::Align(alignment)); 25100b57cec5SDimitry Andric 25110b57cec5SDimitry Andric if (!D->hasAttr<AlignedAttr>()) 25120b57cec5SDimitry Andric if (LangOpts.FunctionAlignment) 2513a7dea167SDimitry Andric F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment)); 25140b57cec5SDimitry Andric 25150b57cec5SDimitry Andric // Some C++ ABIs require 2-byte alignment for member functions, in order to 25160b57cec5SDimitry Andric // reserve a bit for differentiating between virtual and non-virtual member 25170b57cec5SDimitry Andric // functions. If the current target's C++ ABI requires this and this is a 25180b57cec5SDimitry Andric // member function, set its alignment accordingly. 25190b57cec5SDimitry Andric if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 2520271697daSDimitry Andric if (isa<CXXMethodDecl>(D) && F->getPointerAlignment(getDataLayout()) < 2) 2521fe013be4SDimitry Andric F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne())); 25220b57cec5SDimitry Andric } 25230b57cec5SDimitry Andric 2524a7dea167SDimitry Andric // In the cross-dso CFI mode with canonical jump tables, we want !type 2525a7dea167SDimitry Andric // attributes on definitions only. 2526a7dea167SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso && 2527a7dea167SDimitry Andric CodeGenOpts.SanitizeCfiCanonicalJumpTables) { 2528a7dea167SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) { 2529a7dea167SDimitry Andric // Skip available_externally functions. They won't be codegen'ed in the 2530a7dea167SDimitry Andric // current module anyway. 2531a7dea167SDimitry Andric if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally) 25320b57cec5SDimitry Andric CreateFunctionTypeMetadataForIcall(FD, F); 2533a7dea167SDimitry Andric } 2534a7dea167SDimitry Andric } 25350b57cec5SDimitry Andric 25360b57cec5SDimitry Andric // Emit type metadata on member functions for member function pointer checks. 25370b57cec5SDimitry Andric // These are only ever necessary on definitions; we're guaranteed that the 25380b57cec5SDimitry Andric // definition will be present in the LTO unit as a result of LTO visibility. 25390b57cec5SDimitry Andric auto *MD = dyn_cast<CXXMethodDecl>(D); 25400b57cec5SDimitry Andric if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) { 25410b57cec5SDimitry Andric for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) { 25420b57cec5SDimitry Andric llvm::Metadata *Id = 25430b57cec5SDimitry Andric CreateMetadataIdentifierForType(Context.getMemberPointerType( 25440b57cec5SDimitry Andric MD->getType(), Context.getRecordType(Base).getTypePtr())); 25450b57cec5SDimitry Andric F->addTypeMetadata(0, Id); 25460b57cec5SDimitry Andric } 25470b57cec5SDimitry Andric } 25480b57cec5SDimitry Andric } 25490b57cec5SDimitry Andric 25500b57cec5SDimitry Andric void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) { 25510b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 2552349cc55cSDimitry Andric if (isa_and_nonnull<NamedDecl>(D)) 25530b57cec5SDimitry Andric setGVProperties(GV, GD); 25540b57cec5SDimitry Andric else 25550b57cec5SDimitry Andric GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 25560b57cec5SDimitry Andric 25570b57cec5SDimitry Andric if (D && D->hasAttr<UsedAttr>()) 2558fe6060f1SDimitry Andric addUsedOrCompilerUsedGlobal(GV); 25590b57cec5SDimitry Andric 2560fe013be4SDimitry Andric if (const auto *VD = dyn_cast_if_present<VarDecl>(D); 2561fe013be4SDimitry Andric VD && 2562fe013be4SDimitry Andric ((CodeGenOpts.KeepPersistentStorageVariables && 2563fe013be4SDimitry Andric (VD->getStorageDuration() == SD_Static || 2564fe013be4SDimitry Andric VD->getStorageDuration() == SD_Thread)) || 2565fe013be4SDimitry Andric (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static && 2566fe013be4SDimitry Andric VD->getType().isConstQualified()))) 2567fe6060f1SDimitry Andric addUsedOrCompilerUsedGlobal(GV); 25680b57cec5SDimitry Andric } 25690b57cec5SDimitry Andric 25700b57cec5SDimitry Andric bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD, 2571fe013be4SDimitry Andric llvm::AttrBuilder &Attrs, 2572fe013be4SDimitry Andric bool SetTargetFeatures) { 25730b57cec5SDimitry Andric // Add target-cpu and target-features attributes to functions. If 25740b57cec5SDimitry Andric // we have a decl for the function and it has a target attribute then 25750b57cec5SDimitry Andric // parse that and add it to the feature set. 25760b57cec5SDimitry Andric StringRef TargetCPU = getTarget().getTargetOpts().CPU; 2577e8d8bef9SDimitry Andric StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU; 25780b57cec5SDimitry Andric std::vector<std::string> Features; 25790b57cec5SDimitry Andric const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl()); 25800b57cec5SDimitry Andric FD = FD ? FD->getMostRecentDecl() : FD; 25810b57cec5SDimitry Andric const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr; 2582bdd1243dSDimitry Andric const auto *TV = FD ? FD->getAttr<TargetVersionAttr>() : nullptr; 2583bdd1243dSDimitry Andric assert((!TD || !TV) && "both target_version and target specified"); 25840b57cec5SDimitry Andric const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr; 25854824e7fdSDimitry Andric const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr; 25860b57cec5SDimitry Andric bool AddedAttr = false; 2587bdd1243dSDimitry Andric if (TD || TV || SD || TC) { 25880b57cec5SDimitry Andric llvm::StringMap<bool> FeatureMap; 2589480093f4SDimitry Andric getContext().getFunctionFeatureMap(FeatureMap, GD); 25900b57cec5SDimitry Andric 25910b57cec5SDimitry Andric // Produce the canonical string for this set of features. 25920b57cec5SDimitry Andric for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap) 25930b57cec5SDimitry Andric Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str()); 25940b57cec5SDimitry Andric 25950b57cec5SDimitry Andric // Now add the target-cpu and target-features to the function. 25960b57cec5SDimitry Andric // While we populated the feature map above, we still need to 25970b57cec5SDimitry Andric // get and parse the target attribute so we can get the cpu for 25980b57cec5SDimitry Andric // the function. 25990b57cec5SDimitry Andric if (TD) { 2600bdd1243dSDimitry Andric ParsedTargetAttr ParsedAttr = 2601bdd1243dSDimitry Andric Target.parseTargetAttr(TD->getFeaturesStr()); 2602bdd1243dSDimitry Andric if (!ParsedAttr.CPU.empty() && 2603bdd1243dSDimitry Andric getTarget().isValidCPUName(ParsedAttr.CPU)) { 2604bdd1243dSDimitry Andric TargetCPU = ParsedAttr.CPU; 2605e8d8bef9SDimitry Andric TuneCPU = ""; // Clear the tune CPU. 2606e8d8bef9SDimitry Andric } 2607e8d8bef9SDimitry Andric if (!ParsedAttr.Tune.empty() && 2608e8d8bef9SDimitry Andric getTarget().isValidCPUName(ParsedAttr.Tune)) 2609e8d8bef9SDimitry Andric TuneCPU = ParsedAttr.Tune; 26100b57cec5SDimitry Andric } 261181ad6265SDimitry Andric 261281ad6265SDimitry Andric if (SD) { 261381ad6265SDimitry Andric // Apply the given CPU name as the 'tune-cpu' so that the optimizer can 261481ad6265SDimitry Andric // favor this processor. 2615fe013be4SDimitry Andric TuneCPU = SD->getCPUName(GD.getMultiVersionIndex())->getName(); 261681ad6265SDimitry Andric } 26170b57cec5SDimitry Andric } else { 26180b57cec5SDimitry Andric // Otherwise just add the existing target cpu and target features to the 26190b57cec5SDimitry Andric // function. 26200b57cec5SDimitry Andric Features = getTarget().getTargetOpts().Features; 26210b57cec5SDimitry Andric } 26220b57cec5SDimitry Andric 2623e8d8bef9SDimitry Andric if (!TargetCPU.empty()) { 26240b57cec5SDimitry Andric Attrs.addAttribute("target-cpu", TargetCPU); 26250b57cec5SDimitry Andric AddedAttr = true; 26260b57cec5SDimitry Andric } 2627e8d8bef9SDimitry Andric if (!TuneCPU.empty()) { 2628e8d8bef9SDimitry Andric Attrs.addAttribute("tune-cpu", TuneCPU); 2629e8d8bef9SDimitry Andric AddedAttr = true; 2630e8d8bef9SDimitry Andric } 2631fe013be4SDimitry Andric if (!Features.empty() && SetTargetFeatures) { 2632fe013be4SDimitry Andric llvm::erase_if(Features, [&](const std::string& F) { 2633fe013be4SDimitry Andric return getTarget().isReadOnlyFeature(F.substr(1)); 2634fe013be4SDimitry Andric }); 26350b57cec5SDimitry Andric llvm::sort(Features); 26360b57cec5SDimitry Andric Attrs.addAttribute("target-features", llvm::join(Features, ",")); 26370b57cec5SDimitry Andric AddedAttr = true; 26380b57cec5SDimitry Andric } 26390b57cec5SDimitry Andric 26400b57cec5SDimitry Andric return AddedAttr; 26410b57cec5SDimitry Andric } 26420b57cec5SDimitry Andric 26430b57cec5SDimitry Andric void CodeGenModule::setNonAliasAttributes(GlobalDecl GD, 26440b57cec5SDimitry Andric llvm::GlobalObject *GO) { 26450b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 26460b57cec5SDimitry Andric SetCommonAttributes(GD, GO); 26470b57cec5SDimitry Andric 26480b57cec5SDimitry Andric if (D) { 26490b57cec5SDimitry Andric if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) { 2650fe6060f1SDimitry Andric if (D->hasAttr<RetainAttr>()) 2651fe6060f1SDimitry Andric addUsedGlobal(GV); 26520b57cec5SDimitry Andric if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) 26530b57cec5SDimitry Andric GV->addAttribute("bss-section", SA->getName()); 26540b57cec5SDimitry Andric if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) 26550b57cec5SDimitry Andric GV->addAttribute("data-section", SA->getName()); 26560b57cec5SDimitry Andric if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) 26570b57cec5SDimitry Andric GV->addAttribute("rodata-section", SA->getName()); 2658a7dea167SDimitry Andric if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>()) 2659a7dea167SDimitry Andric GV->addAttribute("relro-section", SA->getName()); 26600b57cec5SDimitry Andric } 26610b57cec5SDimitry Andric 26620b57cec5SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(GO)) { 2663fe6060f1SDimitry Andric if (D->hasAttr<RetainAttr>()) 2664fe6060f1SDimitry Andric addUsedGlobal(F); 26650b57cec5SDimitry Andric if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) 26660b57cec5SDimitry Andric if (!D->getAttr<SectionAttr>()) 26670b57cec5SDimitry Andric F->addFnAttr("implicit-section-name", SA->getName()); 26680b57cec5SDimitry Andric 266904eeddc0SDimitry Andric llvm::AttrBuilder Attrs(F->getContext()); 26700b57cec5SDimitry Andric if (GetCPUAndFeaturesAttributes(GD, Attrs)) { 26710b57cec5SDimitry Andric // We know that GetCPUAndFeaturesAttributes will always have the 26720b57cec5SDimitry Andric // newest set, since it has the newest possible FunctionDecl, so the 26730b57cec5SDimitry Andric // new ones should replace the old. 267404eeddc0SDimitry Andric llvm::AttributeMask RemoveAttrs; 2675e8d8bef9SDimitry Andric RemoveAttrs.addAttribute("target-cpu"); 2676e8d8bef9SDimitry Andric RemoveAttrs.addAttribute("target-features"); 2677e8d8bef9SDimitry Andric RemoveAttrs.addAttribute("tune-cpu"); 2678349cc55cSDimitry Andric F->removeFnAttrs(RemoveAttrs); 2679349cc55cSDimitry Andric F->addFnAttrs(Attrs); 26800b57cec5SDimitry Andric } 26810b57cec5SDimitry Andric } 26820b57cec5SDimitry Andric 26830b57cec5SDimitry Andric if (const auto *CSA = D->getAttr<CodeSegAttr>()) 26840b57cec5SDimitry Andric GO->setSection(CSA->getName()); 26850b57cec5SDimitry Andric else if (const auto *SA = D->getAttr<SectionAttr>()) 26860b57cec5SDimitry Andric GO->setSection(SA->getName()); 26870b57cec5SDimitry Andric } 26880b57cec5SDimitry Andric 26890b57cec5SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 26900b57cec5SDimitry Andric } 26910b57cec5SDimitry Andric 26920b57cec5SDimitry Andric void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD, 26930b57cec5SDimitry Andric llvm::Function *F, 26940b57cec5SDimitry Andric const CGFunctionInfo &FI) { 26950b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 2696fe6060f1SDimitry Andric SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false); 26970b57cec5SDimitry Andric SetLLVMFunctionAttributesForDefinition(D, F); 26980b57cec5SDimitry Andric 26990b57cec5SDimitry Andric F->setLinkage(llvm::Function::InternalLinkage); 27000b57cec5SDimitry Andric 27010b57cec5SDimitry Andric setNonAliasAttributes(GD, F); 27020b57cec5SDimitry Andric } 27030b57cec5SDimitry Andric 27040b57cec5SDimitry Andric static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) { 27050b57cec5SDimitry Andric // Set linkage and visibility in case we never see a definition. 27060b57cec5SDimitry Andric LinkageInfo LV = ND->getLinkageAndVisibility(); 27070b57cec5SDimitry Andric // Don't set internal linkage on declarations. 27080b57cec5SDimitry Andric // "extern_weak" is overloaded in LLVM; we probably should have 27090b57cec5SDimitry Andric // separate linkage types for this. 27100b57cec5SDimitry Andric if (isExternallyVisible(LV.getLinkage()) && 27110b57cec5SDimitry Andric (ND->hasAttr<WeakAttr>() || ND->isWeakImported())) 27120b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 27130b57cec5SDimitry Andric } 27140b57cec5SDimitry Andric 27150b57cec5SDimitry Andric void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, 27160b57cec5SDimitry Andric llvm::Function *F) { 27170b57cec5SDimitry Andric // Only if we are checking indirect calls. 27180b57cec5SDimitry Andric if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 27190b57cec5SDimitry Andric return; 27200b57cec5SDimitry Andric 27210b57cec5SDimitry Andric // Non-static class methods are handled via vtable or member function pointer 27220b57cec5SDimitry Andric // checks elsewhere. 27230b57cec5SDimitry Andric if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 27240b57cec5SDimitry Andric return; 27250b57cec5SDimitry Andric 27260b57cec5SDimitry Andric llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 27270b57cec5SDimitry Andric F->addTypeMetadata(0, MD); 27280b57cec5SDimitry Andric F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType())); 27290b57cec5SDimitry Andric 27300b57cec5SDimitry Andric // Emit a hash-based bit set entry for cross-DSO calls. 27310b57cec5SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 27320b57cec5SDimitry Andric if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 27330b57cec5SDimitry Andric F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 27340b57cec5SDimitry Andric } 27350b57cec5SDimitry Andric 2736bdd1243dSDimitry Andric void CodeGenModule::setKCFIType(const FunctionDecl *FD, llvm::Function *F) { 2737bdd1243dSDimitry Andric llvm::LLVMContext &Ctx = F->getContext(); 2738bdd1243dSDimitry Andric llvm::MDBuilder MDB(Ctx); 2739bdd1243dSDimitry Andric F->setMetadata(llvm::LLVMContext::MD_kcfi_type, 2740bdd1243dSDimitry Andric llvm::MDNode::get( 2741bdd1243dSDimitry Andric Ctx, MDB.createConstant(CreateKCFITypeId(FD->getType())))); 2742bdd1243dSDimitry Andric } 2743bdd1243dSDimitry Andric 2744bdd1243dSDimitry Andric static bool allowKCFIIdentifier(StringRef Name) { 2745bdd1243dSDimitry Andric // KCFI type identifier constants are only necessary for external assembly 2746bdd1243dSDimitry Andric // functions, which means it's safe to skip unusual names. Subset of 2747bdd1243dSDimitry Andric // MCAsmInfo::isAcceptableChar() and MCAsmInfoXCOFF::isAcceptableChar(). 2748bdd1243dSDimitry Andric return llvm::all_of(Name, [](const char &C) { 2749bdd1243dSDimitry Andric return llvm::isAlnum(C) || C == '_' || C == '.'; 2750bdd1243dSDimitry Andric }); 2751bdd1243dSDimitry Andric } 2752bdd1243dSDimitry Andric 2753bdd1243dSDimitry Andric void CodeGenModule::finalizeKCFITypes() { 2754bdd1243dSDimitry Andric llvm::Module &M = getModule(); 2755bdd1243dSDimitry Andric for (auto &F : M.functions()) { 2756bdd1243dSDimitry Andric // Remove KCFI type metadata from non-address-taken local functions. 2757bdd1243dSDimitry Andric bool AddressTaken = F.hasAddressTaken(); 2758bdd1243dSDimitry Andric if (!AddressTaken && F.hasLocalLinkage()) 2759bdd1243dSDimitry Andric F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type); 2760bdd1243dSDimitry Andric 2761bdd1243dSDimitry Andric // Generate a constant with the expected KCFI type identifier for all 2762bdd1243dSDimitry Andric // address-taken function declarations to support annotating indirectly 2763bdd1243dSDimitry Andric // called assembly functions. 2764bdd1243dSDimitry Andric if (!AddressTaken || !F.isDeclaration()) 2765bdd1243dSDimitry Andric continue; 2766bdd1243dSDimitry Andric 2767bdd1243dSDimitry Andric const llvm::ConstantInt *Type; 2768bdd1243dSDimitry Andric if (const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type)) 2769bdd1243dSDimitry Andric Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0)); 2770bdd1243dSDimitry Andric else 2771bdd1243dSDimitry Andric continue; 2772bdd1243dSDimitry Andric 2773bdd1243dSDimitry Andric StringRef Name = F.getName(); 2774bdd1243dSDimitry Andric if (!allowKCFIIdentifier(Name)) 2775bdd1243dSDimitry Andric continue; 2776bdd1243dSDimitry Andric 2777bdd1243dSDimitry Andric std::string Asm = (".weak __kcfi_typeid_" + Name + "\n.set __kcfi_typeid_" + 2778bdd1243dSDimitry Andric Name + ", " + Twine(Type->getZExtValue()) + "\n") 2779bdd1243dSDimitry Andric .str(); 2780bdd1243dSDimitry Andric M.appendModuleInlineAsm(Asm); 2781bdd1243dSDimitry Andric } 2782bdd1243dSDimitry Andric } 2783bdd1243dSDimitry Andric 27840b57cec5SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 27850b57cec5SDimitry Andric bool IsIncompleteFunction, 27860b57cec5SDimitry Andric bool IsThunk) { 27870b57cec5SDimitry Andric 27880b57cec5SDimitry Andric if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 27890b57cec5SDimitry Andric // If this is an intrinsic function, set the function's attributes 27900b57cec5SDimitry Andric // to the intrinsic's attributes. 27910b57cec5SDimitry Andric F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 27920b57cec5SDimitry Andric return; 27930b57cec5SDimitry Andric } 27940b57cec5SDimitry Andric 27950b57cec5SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 27960b57cec5SDimitry Andric 27970b57cec5SDimitry Andric if (!IsIncompleteFunction) 2798fe6060f1SDimitry Andric SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F, 2799fe6060f1SDimitry Andric IsThunk); 28000b57cec5SDimitry Andric 28010b57cec5SDimitry Andric // Add the Returned attribute for "this", except for iOS 5 and earlier 28020b57cec5SDimitry Andric // where substantial code, including the libstdc++ dylib, was compiled with 28030b57cec5SDimitry Andric // GCC and does not actually return "this". 28040b57cec5SDimitry Andric if (!IsThunk && getCXXABI().HasThisReturn(GD) && 28050b57cec5SDimitry Andric !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { 28060b57cec5SDimitry Andric assert(!F->arg_empty() && 28070b57cec5SDimitry Andric F->arg_begin()->getType() 28080b57cec5SDimitry Andric ->canLosslesslyBitCastTo(F->getReturnType()) && 28090b57cec5SDimitry Andric "unexpected this return"); 2810349cc55cSDimitry Andric F->addParamAttr(0, llvm::Attribute::Returned); 28110b57cec5SDimitry Andric } 28120b57cec5SDimitry Andric 28130b57cec5SDimitry Andric // Only a few attributes are set on declarations; these may later be 28140b57cec5SDimitry Andric // overridden by a definition. 28150b57cec5SDimitry Andric 28160b57cec5SDimitry Andric setLinkageForGV(F, FD); 28170b57cec5SDimitry Andric setGVProperties(F, FD); 28180b57cec5SDimitry Andric 28190b57cec5SDimitry Andric // Setup target-specific attributes. 28200b57cec5SDimitry Andric if (!IsIncompleteFunction && F->isDeclaration()) 28210b57cec5SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(FD, F, *this); 28220b57cec5SDimitry Andric 28230b57cec5SDimitry Andric if (const auto *CSA = FD->getAttr<CodeSegAttr>()) 28240b57cec5SDimitry Andric F->setSection(CSA->getName()); 28250b57cec5SDimitry Andric else if (const auto *SA = FD->getAttr<SectionAttr>()) 28260b57cec5SDimitry Andric F->setSection(SA->getName()); 28270b57cec5SDimitry Andric 2828349cc55cSDimitry Andric if (const auto *EA = FD->getAttr<ErrorAttr>()) { 2829349cc55cSDimitry Andric if (EA->isError()) 2830349cc55cSDimitry Andric F->addFnAttr("dontcall-error", EA->getUserDiagnostic()); 2831349cc55cSDimitry Andric else if (EA->isWarning()) 2832349cc55cSDimitry Andric F->addFnAttr("dontcall-warn", EA->getUserDiagnostic()); 2833349cc55cSDimitry Andric } 2834349cc55cSDimitry Andric 2835d65cd7a5SDimitry Andric // If we plan on emitting this inline builtin, we can't treat it as a builtin. 2836480093f4SDimitry Andric if (FD->isInlineBuiltinDeclaration()) { 2837d65cd7a5SDimitry Andric const FunctionDecl *FDBody; 2838d65cd7a5SDimitry Andric bool HasBody = FD->hasBody(FDBody); 2839d65cd7a5SDimitry Andric (void)HasBody; 2840d65cd7a5SDimitry Andric assert(HasBody && "Inline builtin declarations should always have an " 2841d65cd7a5SDimitry Andric "available body!"); 2842d65cd7a5SDimitry Andric if (shouldEmitFunction(FDBody)) 2843349cc55cSDimitry Andric F->addFnAttr(llvm::Attribute::NoBuiltin); 2844480093f4SDimitry Andric } 2845480093f4SDimitry Andric 28460b57cec5SDimitry Andric if (FD->isReplaceableGlobalAllocationFunction()) { 28470b57cec5SDimitry Andric // A replaceable global allocation function does not act like a builtin by 28480b57cec5SDimitry Andric // default, only if it is invoked by a new-expression or delete-expression. 2849349cc55cSDimitry Andric F->addFnAttr(llvm::Attribute::NoBuiltin); 28500b57cec5SDimitry Andric } 28510b57cec5SDimitry Andric 28520b57cec5SDimitry Andric if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 28530b57cec5SDimitry Andric F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 28540b57cec5SDimitry Andric else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 28550b57cec5SDimitry Andric if (MD->isVirtual()) 28560b57cec5SDimitry Andric F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 28570b57cec5SDimitry Andric 28580b57cec5SDimitry Andric // Don't emit entries for function declarations in the cross-DSO mode. This 2859a7dea167SDimitry Andric // is handled with better precision by the receiving DSO. But if jump tables 2860a7dea167SDimitry Andric // are non-canonical then we need type metadata in order to produce the local 2861a7dea167SDimitry Andric // jump table. 2862a7dea167SDimitry Andric if (!CodeGenOpts.SanitizeCfiCrossDso || 2863a7dea167SDimitry Andric !CodeGenOpts.SanitizeCfiCanonicalJumpTables) 28640b57cec5SDimitry Andric CreateFunctionTypeMetadataForIcall(FD, F); 28650b57cec5SDimitry Andric 2866bdd1243dSDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) 2867bdd1243dSDimitry Andric setKCFIType(FD, F); 2868bdd1243dSDimitry Andric 28690b57cec5SDimitry Andric if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) 28700b57cec5SDimitry Andric getOpenMPRuntime().emitDeclareSimdFunction(FD, F); 28710b57cec5SDimitry Andric 2872bdd1243dSDimitry Andric if (CodeGenOpts.InlineMaxStackSize != UINT_MAX) 2873bdd1243dSDimitry Andric F->addFnAttr("inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize)); 2874bdd1243dSDimitry Andric 28750b57cec5SDimitry Andric if (const auto *CB = FD->getAttr<CallbackAttr>()) { 28760b57cec5SDimitry Andric // Annotate the callback behavior as metadata: 28770b57cec5SDimitry Andric // - The callback callee (as argument number). 28780b57cec5SDimitry Andric // - The callback payloads (as argument numbers). 28790b57cec5SDimitry Andric llvm::LLVMContext &Ctx = F->getContext(); 28800b57cec5SDimitry Andric llvm::MDBuilder MDB(Ctx); 28810b57cec5SDimitry Andric 28820b57cec5SDimitry Andric // The payload indices are all but the first one in the encoding. The first 28830b57cec5SDimitry Andric // identifies the callback callee. 28840b57cec5SDimitry Andric int CalleeIdx = *CB->encoding_begin(); 28850b57cec5SDimitry Andric ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end()); 28860b57cec5SDimitry Andric F->addMetadata(llvm::LLVMContext::MD_callback, 28870b57cec5SDimitry Andric *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding( 28880b57cec5SDimitry Andric CalleeIdx, PayloadIndices, 28890b57cec5SDimitry Andric /* VarArgsArePassed */ false)})); 28900b57cec5SDimitry Andric } 28910b57cec5SDimitry Andric } 28920b57cec5SDimitry Andric 28930b57cec5SDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 2894e8d8bef9SDimitry Andric assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 28950b57cec5SDimitry Andric "Only globals with definition can force usage."); 28960b57cec5SDimitry Andric LLVMUsed.emplace_back(GV); 28970b57cec5SDimitry Andric } 28980b57cec5SDimitry Andric 28990b57cec5SDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 29000b57cec5SDimitry Andric assert(!GV->isDeclaration() && 29010b57cec5SDimitry Andric "Only globals with definition can force usage."); 29020b57cec5SDimitry Andric LLVMCompilerUsed.emplace_back(GV); 29030b57cec5SDimitry Andric } 29040b57cec5SDimitry Andric 2905fe6060f1SDimitry Andric void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) { 2906fe6060f1SDimitry Andric assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 2907fe6060f1SDimitry Andric "Only globals with definition can force usage."); 2908fe6060f1SDimitry Andric if (getTriple().isOSBinFormatELF()) 2909fe6060f1SDimitry Andric LLVMCompilerUsed.emplace_back(GV); 2910fe6060f1SDimitry Andric else 2911fe6060f1SDimitry Andric LLVMUsed.emplace_back(GV); 2912fe6060f1SDimitry Andric } 2913fe6060f1SDimitry Andric 29140b57cec5SDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name, 29150b57cec5SDimitry Andric std::vector<llvm::WeakTrackingVH> &List) { 29160b57cec5SDimitry Andric // Don't create llvm.used if there is no need. 29170b57cec5SDimitry Andric if (List.empty()) 29180b57cec5SDimitry Andric return; 29190b57cec5SDimitry Andric 29200b57cec5SDimitry Andric // Convert List to what ConstantArray needs. 29210b57cec5SDimitry Andric SmallVector<llvm::Constant*, 8> UsedArray; 29220b57cec5SDimitry Andric UsedArray.resize(List.size()); 29230b57cec5SDimitry Andric for (unsigned i = 0, e = List.size(); i != e; ++i) { 29240b57cec5SDimitry Andric UsedArray[i] = 29250b57cec5SDimitry Andric llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 29260b57cec5SDimitry Andric cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 29270b57cec5SDimitry Andric } 29280b57cec5SDimitry Andric 29290b57cec5SDimitry Andric if (UsedArray.empty()) 29300b57cec5SDimitry Andric return; 29310b57cec5SDimitry Andric llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 29320b57cec5SDimitry Andric 29330b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 29340b57cec5SDimitry Andric CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 29350b57cec5SDimitry Andric llvm::ConstantArray::get(ATy, UsedArray), Name); 29360b57cec5SDimitry Andric 29370b57cec5SDimitry Andric GV->setSection("llvm.metadata"); 29380b57cec5SDimitry Andric } 29390b57cec5SDimitry Andric 29400b57cec5SDimitry Andric void CodeGenModule::emitLLVMUsed() { 29410b57cec5SDimitry Andric emitUsed(*this, "llvm.used", LLVMUsed); 29420b57cec5SDimitry Andric emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 29430b57cec5SDimitry Andric } 29440b57cec5SDimitry Andric 29450b57cec5SDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 29460b57cec5SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 29470b57cec5SDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 29480b57cec5SDimitry Andric } 29490b57cec5SDimitry Andric 29500b57cec5SDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 29510b57cec5SDimitry Andric llvm::SmallString<32> Opt; 29520b57cec5SDimitry Andric getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 2953480093f4SDimitry Andric if (Opt.empty()) 2954480093f4SDimitry Andric return; 29550b57cec5SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 29560b57cec5SDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 29570b57cec5SDimitry Andric } 29580b57cec5SDimitry Andric 29590b57cec5SDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) { 29600b57cec5SDimitry Andric auto &C = getLLVMContext(); 29610b57cec5SDimitry Andric if (getTarget().getTriple().isOSBinFormatELF()) { 29620b57cec5SDimitry Andric ELFDependentLibraries.push_back( 29630b57cec5SDimitry Andric llvm::MDNode::get(C, llvm::MDString::get(C, Lib))); 29640b57cec5SDimitry Andric return; 29650b57cec5SDimitry Andric } 29660b57cec5SDimitry Andric 29670b57cec5SDimitry Andric llvm::SmallString<24> Opt; 29680b57cec5SDimitry Andric getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 29690b57cec5SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 29700b57cec5SDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts)); 29710b57cec5SDimitry Andric } 29720b57cec5SDimitry Andric 29730b57cec5SDimitry Andric /// Add link options implied by the given module, including modules 29740b57cec5SDimitry Andric /// it depends on, using a postorder walk. 29750b57cec5SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 29760b57cec5SDimitry Andric SmallVectorImpl<llvm::MDNode *> &Metadata, 29770b57cec5SDimitry Andric llvm::SmallPtrSet<Module *, 16> &Visited) { 29780b57cec5SDimitry Andric // Import this module's parent. 29790b57cec5SDimitry Andric if (Mod->Parent && Visited.insert(Mod->Parent).second) { 29800b57cec5SDimitry Andric addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 29810b57cec5SDimitry Andric } 29820b57cec5SDimitry Andric 29830b57cec5SDimitry Andric // Import this module's dependencies. 2984349cc55cSDimitry Andric for (Module *Import : llvm::reverse(Mod->Imports)) { 2985349cc55cSDimitry Andric if (Visited.insert(Import).second) 2986349cc55cSDimitry Andric addLinkOptionsPostorder(CGM, Import, Metadata, Visited); 29870b57cec5SDimitry Andric } 29880b57cec5SDimitry Andric 29890b57cec5SDimitry Andric // Add linker options to link against the libraries/frameworks 29900b57cec5SDimitry Andric // described by this module. 29910b57cec5SDimitry Andric llvm::LLVMContext &Context = CGM.getLLVMContext(); 29920b57cec5SDimitry Andric bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF(); 29930b57cec5SDimitry Andric 29940b57cec5SDimitry Andric // For modules that use export_as for linking, use that module 29950b57cec5SDimitry Andric // name instead. 29960b57cec5SDimitry Andric if (Mod->UseExportAsModuleLinkName) 29970b57cec5SDimitry Andric return; 29980b57cec5SDimitry Andric 2999349cc55cSDimitry Andric for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) { 30000b57cec5SDimitry Andric // Link against a framework. Frameworks are currently Darwin only, so we 30010b57cec5SDimitry Andric // don't to ask TargetCodeGenInfo for the spelling of the linker option. 3002349cc55cSDimitry Andric if (LL.IsFramework) { 3003349cc55cSDimitry Andric llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"), 3004349cc55cSDimitry Andric llvm::MDString::get(Context, LL.Library)}; 30050b57cec5SDimitry Andric 30060b57cec5SDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, Args)); 30070b57cec5SDimitry Andric continue; 30080b57cec5SDimitry Andric } 30090b57cec5SDimitry Andric 30100b57cec5SDimitry Andric // Link against a library. 30110b57cec5SDimitry Andric if (IsELF) { 30120b57cec5SDimitry Andric llvm::Metadata *Args[2] = { 30130b57cec5SDimitry Andric llvm::MDString::get(Context, "lib"), 3014349cc55cSDimitry Andric llvm::MDString::get(Context, LL.Library), 30150b57cec5SDimitry Andric }; 30160b57cec5SDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, Args)); 30170b57cec5SDimitry Andric } else { 30180b57cec5SDimitry Andric llvm::SmallString<24> Opt; 3019349cc55cSDimitry Andric CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt); 30200b57cec5SDimitry Andric auto *OptString = llvm::MDString::get(Context, Opt); 30210b57cec5SDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, OptString)); 30220b57cec5SDimitry Andric } 30230b57cec5SDimitry Andric } 30240b57cec5SDimitry Andric } 30250b57cec5SDimitry Andric 3026fcaf7f86SDimitry Andric void CodeGenModule::EmitModuleInitializers(clang::Module *Primary) { 3027c9157d92SDimitry Andric assert(Primary->isNamedModuleUnit() && 3028c9157d92SDimitry Andric "We should only emit module initializers for named modules."); 3029c9157d92SDimitry Andric 3030fcaf7f86SDimitry Andric // Emit the initializers in the order that sub-modules appear in the 3031fcaf7f86SDimitry Andric // source, first Global Module Fragments, if present. 3032fcaf7f86SDimitry Andric if (auto GMF = Primary->getGlobalModuleFragment()) { 3033fcaf7f86SDimitry Andric for (Decl *D : getContext().getModuleInitializers(GMF)) { 303461cfbce3SDimitry Andric if (isa<ImportDecl>(D)) 303561cfbce3SDimitry Andric continue; 303661cfbce3SDimitry Andric assert(isa<VarDecl>(D) && "GMF initializer decl is not a var?"); 3037fcaf7f86SDimitry Andric EmitTopLevelDecl(D); 3038fcaf7f86SDimitry Andric } 3039fcaf7f86SDimitry Andric } 3040fcaf7f86SDimitry Andric // Second any associated with the module, itself. 3041fcaf7f86SDimitry Andric for (Decl *D : getContext().getModuleInitializers(Primary)) { 3042fcaf7f86SDimitry Andric // Skip import decls, the inits for those are called explicitly. 304361cfbce3SDimitry Andric if (isa<ImportDecl>(D)) 3044fcaf7f86SDimitry Andric continue; 3045fcaf7f86SDimitry Andric EmitTopLevelDecl(D); 3046fcaf7f86SDimitry Andric } 3047fcaf7f86SDimitry Andric // Third any associated with the Privat eMOdule Fragment, if present. 3048fcaf7f86SDimitry Andric if (auto PMF = Primary->getPrivateModuleFragment()) { 3049fcaf7f86SDimitry Andric for (Decl *D : getContext().getModuleInitializers(PMF)) { 3050c9157d92SDimitry Andric // Skip import decls, the inits for those are called explicitly. 3051c9157d92SDimitry Andric if (isa<ImportDecl>(D)) 3052c9157d92SDimitry Andric continue; 305361cfbce3SDimitry Andric assert(isa<VarDecl>(D) && "PMF initializer decl is not a var?"); 3054fcaf7f86SDimitry Andric EmitTopLevelDecl(D); 3055fcaf7f86SDimitry Andric } 3056fcaf7f86SDimitry Andric } 3057fcaf7f86SDimitry Andric } 3058fcaf7f86SDimitry Andric 30590b57cec5SDimitry Andric void CodeGenModule::EmitModuleLinkOptions() { 30600b57cec5SDimitry Andric // Collect the set of all of the modules we want to visit to emit link 30610b57cec5SDimitry Andric // options, which is essentially the imported modules and all of their 30620b57cec5SDimitry Andric // non-explicit child modules. 30630b57cec5SDimitry Andric llvm::SetVector<clang::Module *> LinkModules; 30640b57cec5SDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 30650b57cec5SDimitry Andric SmallVector<clang::Module *, 16> Stack; 30660b57cec5SDimitry Andric 30670b57cec5SDimitry Andric // Seed the stack with imported modules. 30680b57cec5SDimitry Andric for (Module *M : ImportedModules) { 30690b57cec5SDimitry Andric // Do not add any link flags when an implementation TU of a module imports 30700b57cec5SDimitry Andric // a header of that same module. 30710b57cec5SDimitry Andric if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && 30720b57cec5SDimitry Andric !getLangOpts().isCompilingModule()) 30730b57cec5SDimitry Andric continue; 30740b57cec5SDimitry Andric if (Visited.insert(M).second) 30750b57cec5SDimitry Andric Stack.push_back(M); 30760b57cec5SDimitry Andric } 30770b57cec5SDimitry Andric 30780b57cec5SDimitry Andric // Find all of the modules to import, making a little effort to prune 30790b57cec5SDimitry Andric // non-leaf modules. 30800b57cec5SDimitry Andric while (!Stack.empty()) { 30810b57cec5SDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 30820b57cec5SDimitry Andric 30830b57cec5SDimitry Andric bool AnyChildren = false; 30840b57cec5SDimitry Andric 30850b57cec5SDimitry Andric // Visit the submodules of this module. 30860b57cec5SDimitry Andric for (const auto &SM : Mod->submodules()) { 30870b57cec5SDimitry Andric // Skip explicit children; they need to be explicitly imported to be 30880b57cec5SDimitry Andric // linked against. 30890b57cec5SDimitry Andric if (SM->IsExplicit) 30900b57cec5SDimitry Andric continue; 30910b57cec5SDimitry Andric 30920b57cec5SDimitry Andric if (Visited.insert(SM).second) { 30930b57cec5SDimitry Andric Stack.push_back(SM); 30940b57cec5SDimitry Andric AnyChildren = true; 30950b57cec5SDimitry Andric } 30960b57cec5SDimitry Andric } 30970b57cec5SDimitry Andric 30980b57cec5SDimitry Andric // We didn't find any children, so add this module to the list of 30990b57cec5SDimitry Andric // modules to link against. 31000b57cec5SDimitry Andric if (!AnyChildren) { 31010b57cec5SDimitry Andric LinkModules.insert(Mod); 31020b57cec5SDimitry Andric } 31030b57cec5SDimitry Andric } 31040b57cec5SDimitry Andric 31050b57cec5SDimitry Andric // Add link options for all of the imported modules in reverse topological 31060b57cec5SDimitry Andric // order. We don't do anything to try to order import link flags with respect 31070b57cec5SDimitry Andric // to linker options inserted by things like #pragma comment(). 31080b57cec5SDimitry Andric SmallVector<llvm::MDNode *, 16> MetadataArgs; 31090b57cec5SDimitry Andric Visited.clear(); 31100b57cec5SDimitry Andric for (Module *M : LinkModules) 31110b57cec5SDimitry Andric if (Visited.insert(M).second) 31120b57cec5SDimitry Andric addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 31130b57cec5SDimitry Andric std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 31140b57cec5SDimitry Andric LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 31150b57cec5SDimitry Andric 31160b57cec5SDimitry Andric // Add the linker options metadata flag. 31170b57cec5SDimitry Andric auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options"); 31180b57cec5SDimitry Andric for (auto *MD : LinkerOptionsMetadata) 31190b57cec5SDimitry Andric NMD->addOperand(MD); 31200b57cec5SDimitry Andric } 31210b57cec5SDimitry Andric 31220b57cec5SDimitry Andric void CodeGenModule::EmitDeferred() { 31230b57cec5SDimitry Andric // Emit deferred declare target declarations. 31240b57cec5SDimitry Andric if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 31250b57cec5SDimitry Andric getOpenMPRuntime().emitDeferredTargetDecls(); 31260b57cec5SDimitry Andric 31270b57cec5SDimitry Andric // Emit code for any potentially referenced deferred decls. Since a 31280b57cec5SDimitry Andric // previously unused static decl may become used during the generation of code 31290b57cec5SDimitry Andric // for a static function, iterate until no changes are made. 31300b57cec5SDimitry Andric 31310b57cec5SDimitry Andric if (!DeferredVTables.empty()) { 31320b57cec5SDimitry Andric EmitDeferredVTables(); 31330b57cec5SDimitry Andric 31340b57cec5SDimitry Andric // Emitting a vtable doesn't directly cause more vtables to 31350b57cec5SDimitry Andric // become deferred, although it can cause functions to be 31360b57cec5SDimitry Andric // emitted that then need those vtables. 31370b57cec5SDimitry Andric assert(DeferredVTables.empty()); 31380b57cec5SDimitry Andric } 31390b57cec5SDimitry Andric 3140e8d8bef9SDimitry Andric // Emit CUDA/HIP static device variables referenced by host code only. 3141fe6060f1SDimitry Andric // Note we should not clear CUDADeviceVarODRUsedByHost since it is still 3142fe6060f1SDimitry Andric // needed for further handling. 3143fe6060f1SDimitry Andric if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) 314481ad6265SDimitry Andric llvm::append_range(DeferredDeclsToEmit, 314581ad6265SDimitry Andric getContext().CUDADeviceVarODRUsedByHost); 3146e8d8bef9SDimitry Andric 31470b57cec5SDimitry Andric // Stop if we're out of both deferred vtables and deferred declarations. 31480b57cec5SDimitry Andric if (DeferredDeclsToEmit.empty()) 31490b57cec5SDimitry Andric return; 31500b57cec5SDimitry Andric 31510b57cec5SDimitry Andric // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 31520b57cec5SDimitry Andric // work, it will not interfere with this. 31530b57cec5SDimitry Andric std::vector<GlobalDecl> CurDeclsToEmit; 31540b57cec5SDimitry Andric CurDeclsToEmit.swap(DeferredDeclsToEmit); 31550b57cec5SDimitry Andric 31560b57cec5SDimitry Andric for (GlobalDecl &D : CurDeclsToEmit) { 31570b57cec5SDimitry Andric // We should call GetAddrOfGlobal with IsForDefinition set to true in order 31580b57cec5SDimitry Andric // to get GlobalValue with exactly the type we need, not something that 31590b57cec5SDimitry Andric // might had been created for another decl with the same mangled name but 31600b57cec5SDimitry Andric // different type. 31610b57cec5SDimitry Andric llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 31620b57cec5SDimitry Andric GetAddrOfGlobal(D, ForDefinition)); 31630b57cec5SDimitry Andric 31640b57cec5SDimitry Andric // In case of different address spaces, we may still get a cast, even with 31650b57cec5SDimitry Andric // IsForDefinition equal to true. Query mangled names table to get 31660b57cec5SDimitry Andric // GlobalValue. 31670b57cec5SDimitry Andric if (!GV) 31680b57cec5SDimitry Andric GV = GetGlobalValue(getMangledName(D)); 31690b57cec5SDimitry Andric 31700b57cec5SDimitry Andric // Make sure GetGlobalValue returned non-null. 31710b57cec5SDimitry Andric assert(GV); 31720b57cec5SDimitry Andric 31730b57cec5SDimitry Andric // Check to see if we've already emitted this. This is necessary 31740b57cec5SDimitry Andric // for a couple of reasons: first, decls can end up in the 31750b57cec5SDimitry Andric // deferred-decls queue multiple times, and second, decls can end 31760b57cec5SDimitry Andric // up with definitions in unusual ways (e.g. by an extern inline 31770b57cec5SDimitry Andric // function acquiring a strong function redefinition). Just 31780b57cec5SDimitry Andric // ignore these cases. 31790b57cec5SDimitry Andric if (!GV->isDeclaration()) 31800b57cec5SDimitry Andric continue; 31810b57cec5SDimitry Andric 3182a7dea167SDimitry Andric // If this is OpenMP, check if it is legal to emit this global normally. 3183a7dea167SDimitry Andric if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D)) 3184a7dea167SDimitry Andric continue; 3185a7dea167SDimitry Andric 31860b57cec5SDimitry Andric // Otherwise, emit the definition and move on to the next one. 31870b57cec5SDimitry Andric EmitGlobalDefinition(D, GV); 31880b57cec5SDimitry Andric 31890b57cec5SDimitry Andric // If we found out that we need to emit more decls, do that recursively. 31900b57cec5SDimitry Andric // This has the advantage that the decls are emitted in a DFS and related 31910b57cec5SDimitry Andric // ones are close together, which is convenient for testing. 31920b57cec5SDimitry Andric if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 31930b57cec5SDimitry Andric EmitDeferred(); 31940b57cec5SDimitry Andric assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 31950b57cec5SDimitry Andric } 31960b57cec5SDimitry Andric } 31970b57cec5SDimitry Andric } 31980b57cec5SDimitry Andric 31990b57cec5SDimitry Andric void CodeGenModule::EmitVTablesOpportunistically() { 32000b57cec5SDimitry Andric // Try to emit external vtables as available_externally if they have emitted 32010b57cec5SDimitry Andric // all inlined virtual functions. It runs after EmitDeferred() and therefore 32020b57cec5SDimitry Andric // is not allowed to create new references to things that need to be emitted 32030b57cec5SDimitry Andric // lazily. Note that it also uses fact that we eagerly emitting RTTI. 32040b57cec5SDimitry Andric 32050b57cec5SDimitry Andric assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) 32060b57cec5SDimitry Andric && "Only emit opportunistic vtables with optimizations"); 32070b57cec5SDimitry Andric 32080b57cec5SDimitry Andric for (const CXXRecordDecl *RD : OpportunisticVTables) { 32090b57cec5SDimitry Andric assert(getVTables().isVTableExternal(RD) && 32100b57cec5SDimitry Andric "This queue should only contain external vtables"); 32110b57cec5SDimitry Andric if (getCXXABI().canSpeculativelyEmitVTable(RD)) 32120b57cec5SDimitry Andric VTables.GenerateClassData(RD); 32130b57cec5SDimitry Andric } 32140b57cec5SDimitry Andric OpportunisticVTables.clear(); 32150b57cec5SDimitry Andric } 32160b57cec5SDimitry Andric 32170b57cec5SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() { 3218c9157d92SDimitry Andric for (const auto& [MangledName, VD] : DeferredAnnotations) { 3219c9157d92SDimitry Andric llvm::GlobalValue *GV = GetGlobalValue(MangledName); 3220c9157d92SDimitry Andric if (GV) 3221c9157d92SDimitry Andric AddGlobalAnnotations(VD, GV); 3222c9157d92SDimitry Andric } 3223c9157d92SDimitry Andric DeferredAnnotations.clear(); 3224c9157d92SDimitry Andric 32250b57cec5SDimitry Andric if (Annotations.empty()) 32260b57cec5SDimitry Andric return; 32270b57cec5SDimitry Andric 32280b57cec5SDimitry Andric // Create a new global variable for the ConstantStruct in the Module. 32290b57cec5SDimitry Andric llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 32300b57cec5SDimitry Andric Annotations[0]->getType(), Annotations.size()), Annotations); 32310b57cec5SDimitry Andric auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 32320b57cec5SDimitry Andric llvm::GlobalValue::AppendingLinkage, 32330b57cec5SDimitry Andric Array, "llvm.global.annotations"); 32340b57cec5SDimitry Andric gv->setSection(AnnotationSection); 32350b57cec5SDimitry Andric } 32360b57cec5SDimitry Andric 32370b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 32380b57cec5SDimitry Andric llvm::Constant *&AStr = AnnotationStrings[Str]; 32390b57cec5SDimitry Andric if (AStr) 32400b57cec5SDimitry Andric return AStr; 32410b57cec5SDimitry Andric 32420b57cec5SDimitry Andric // Not found yet, create a new global. 32430b57cec5SDimitry Andric llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 3244bdd1243dSDimitry Andric auto *gv = new llvm::GlobalVariable( 3245bdd1243dSDimitry Andric getModule(), s->getType(), true, llvm::GlobalValue::PrivateLinkage, s, 3246bdd1243dSDimitry Andric ".str", nullptr, llvm::GlobalValue::NotThreadLocal, 3247bdd1243dSDimitry Andric ConstGlobalsPtrTy->getAddressSpace()); 32480b57cec5SDimitry Andric gv->setSection(AnnotationSection); 32490b57cec5SDimitry Andric gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 32500b57cec5SDimitry Andric AStr = gv; 32510b57cec5SDimitry Andric return gv; 32520b57cec5SDimitry Andric } 32530b57cec5SDimitry Andric 32540b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 32550b57cec5SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 32560b57cec5SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(Loc); 32570b57cec5SDimitry Andric if (PLoc.isValid()) 32580b57cec5SDimitry Andric return EmitAnnotationString(PLoc.getFilename()); 32590b57cec5SDimitry Andric return EmitAnnotationString(SM.getBufferName(Loc)); 32600b57cec5SDimitry Andric } 32610b57cec5SDimitry Andric 32620b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 32630b57cec5SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 32640b57cec5SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(L); 32650b57cec5SDimitry Andric unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 32660b57cec5SDimitry Andric SM.getExpansionLineNumber(L); 32670b57cec5SDimitry Andric return llvm::ConstantInt::get(Int32Ty, LineNo); 32680b57cec5SDimitry Andric } 32690b57cec5SDimitry Andric 3270e8d8bef9SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) { 3271e8d8bef9SDimitry Andric ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()}; 3272e8d8bef9SDimitry Andric if (Exprs.empty()) 3273bdd1243dSDimitry Andric return llvm::ConstantPointerNull::get(ConstGlobalsPtrTy); 3274e8d8bef9SDimitry Andric 3275e8d8bef9SDimitry Andric llvm::FoldingSetNodeID ID; 3276e8d8bef9SDimitry Andric for (Expr *E : Exprs) { 3277e8d8bef9SDimitry Andric ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult()); 3278e8d8bef9SDimitry Andric } 3279e8d8bef9SDimitry Andric llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()]; 3280e8d8bef9SDimitry Andric if (Lookup) 3281e8d8bef9SDimitry Andric return Lookup; 3282e8d8bef9SDimitry Andric 3283e8d8bef9SDimitry Andric llvm::SmallVector<llvm::Constant *, 4> LLVMArgs; 3284e8d8bef9SDimitry Andric LLVMArgs.reserve(Exprs.size()); 3285e8d8bef9SDimitry Andric ConstantEmitter ConstEmiter(*this); 3286e8d8bef9SDimitry Andric llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) { 3287e8d8bef9SDimitry Andric const auto *CE = cast<clang::ConstantExpr>(E); 3288e8d8bef9SDimitry Andric return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(), 3289e8d8bef9SDimitry Andric CE->getType()); 3290e8d8bef9SDimitry Andric }); 3291e8d8bef9SDimitry Andric auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs); 3292e8d8bef9SDimitry Andric auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true, 3293e8d8bef9SDimitry Andric llvm::GlobalValue::PrivateLinkage, Struct, 3294e8d8bef9SDimitry Andric ".args"); 3295e8d8bef9SDimitry Andric GV->setSection(AnnotationSection); 3296e8d8bef9SDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3297e8d8bef9SDimitry Andric 3298c9157d92SDimitry Andric Lookup = GV; 3299c9157d92SDimitry Andric return GV; 3300e8d8bef9SDimitry Andric } 3301e8d8bef9SDimitry Andric 33020b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 33030b57cec5SDimitry Andric const AnnotateAttr *AA, 33040b57cec5SDimitry Andric SourceLocation L) { 33050b57cec5SDimitry Andric // Get the globals for file name, annotation, and the line number. 33060b57cec5SDimitry Andric llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 33070b57cec5SDimitry Andric *UnitGV = EmitAnnotationUnit(L), 3308e8d8bef9SDimitry Andric *LineNoCst = EmitAnnotationLineNo(L), 3309e8d8bef9SDimitry Andric *Args = EmitAnnotationArgs(AA); 33100b57cec5SDimitry Andric 3311349cc55cSDimitry Andric llvm::Constant *GVInGlobalsAS = GV; 3312349cc55cSDimitry Andric if (GV->getAddressSpace() != 3313349cc55cSDimitry Andric getDataLayout().getDefaultGlobalsAddressSpace()) { 3314349cc55cSDimitry Andric GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast( 3315c9157d92SDimitry Andric GV, 3316c9157d92SDimitry Andric llvm::PointerType::get( 3317c9157d92SDimitry Andric GV->getContext(), getDataLayout().getDefaultGlobalsAddressSpace())); 3318480093f4SDimitry Andric } 3319480093f4SDimitry Andric 33200b57cec5SDimitry Andric // Create the ConstantStruct for the global annotation. 3321e8d8bef9SDimitry Andric llvm::Constant *Fields[] = { 3322c9157d92SDimitry Andric GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args, 33230b57cec5SDimitry Andric }; 33240b57cec5SDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 33250b57cec5SDimitry Andric } 33260b57cec5SDimitry Andric 33270b57cec5SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 33280b57cec5SDimitry Andric llvm::GlobalValue *GV) { 33290b57cec5SDimitry Andric assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 33300b57cec5SDimitry Andric // Get the struct elements for these annotations. 33310b57cec5SDimitry Andric for (const auto *I : D->specific_attrs<AnnotateAttr>()) 33320b57cec5SDimitry Andric Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 33330b57cec5SDimitry Andric } 33340b57cec5SDimitry Andric 3335fe6060f1SDimitry Andric bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, 33360b57cec5SDimitry Andric SourceLocation Loc) const { 3337fe6060f1SDimitry Andric const auto &NoSanitizeL = getContext().getNoSanitizeList(); 3338fe6060f1SDimitry Andric // NoSanitize by function name. 3339fe6060f1SDimitry Andric if (NoSanitizeL.containsFunction(Kind, Fn->getName())) 33400b57cec5SDimitry Andric return true; 3341fcaf7f86SDimitry Andric // NoSanitize by location. Check "mainfile" prefix. 3342fcaf7f86SDimitry Andric auto &SM = Context.getSourceManager(); 3343c9157d92SDimitry Andric FileEntryRef MainFile = *SM.getFileEntryRefForID(SM.getMainFileID()); 3344fcaf7f86SDimitry Andric if (NoSanitizeL.containsMainFile(Kind, MainFile.getName())) 3345fcaf7f86SDimitry Andric return true; 3346fcaf7f86SDimitry Andric 3347fcaf7f86SDimitry Andric // Check "src" prefix. 33480b57cec5SDimitry Andric if (Loc.isValid()) 3349fe6060f1SDimitry Andric return NoSanitizeL.containsLocation(Kind, Loc); 33500b57cec5SDimitry Andric // If location is unknown, this may be a compiler-generated function. Assume 33510b57cec5SDimitry Andric // it's located in the main file. 3352fcaf7f86SDimitry Andric return NoSanitizeL.containsFile(Kind, MainFile.getName()); 33530b57cec5SDimitry Andric } 33540b57cec5SDimitry Andric 335581ad6265SDimitry Andric bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, 335681ad6265SDimitry Andric llvm::GlobalVariable *GV, 33570b57cec5SDimitry Andric SourceLocation Loc, QualType Ty, 33580b57cec5SDimitry Andric StringRef Category) const { 3359fe6060f1SDimitry Andric const auto &NoSanitizeL = getContext().getNoSanitizeList(); 336081ad6265SDimitry Andric if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category)) 33610b57cec5SDimitry Andric return true; 3362fcaf7f86SDimitry Andric auto &SM = Context.getSourceManager(); 3363fcaf7f86SDimitry Andric if (NoSanitizeL.containsMainFile( 3364c9157d92SDimitry Andric Kind, SM.getFileEntryRefForID(SM.getMainFileID())->getName(), 3365c9157d92SDimitry Andric Category)) 3366fcaf7f86SDimitry Andric return true; 336781ad6265SDimitry Andric if (NoSanitizeL.containsLocation(Kind, Loc, Category)) 33680b57cec5SDimitry Andric return true; 3369fcaf7f86SDimitry Andric 33700b57cec5SDimitry Andric // Check global type. 33710b57cec5SDimitry Andric if (!Ty.isNull()) { 33720b57cec5SDimitry Andric // Drill down the array types: if global variable of a fixed type is 3373fe6060f1SDimitry Andric // not sanitized, we also don't instrument arrays of them. 33740b57cec5SDimitry Andric while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 33750b57cec5SDimitry Andric Ty = AT->getElementType(); 33760b57cec5SDimitry Andric Ty = Ty.getCanonicalType().getUnqualifiedType(); 3377fe6060f1SDimitry Andric // Only record types (classes, structs etc.) are ignored. 33780b57cec5SDimitry Andric if (Ty->isRecordType()) { 33790b57cec5SDimitry Andric std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 338081ad6265SDimitry Andric if (NoSanitizeL.containsType(Kind, TypeStr, Category)) 33810b57cec5SDimitry Andric return true; 33820b57cec5SDimitry Andric } 33830b57cec5SDimitry Andric } 33840b57cec5SDimitry Andric return false; 33850b57cec5SDimitry Andric } 33860b57cec5SDimitry Andric 33870b57cec5SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 33880b57cec5SDimitry Andric StringRef Category) const { 33890b57cec5SDimitry Andric const auto &XRayFilter = getContext().getXRayFilter(); 33900b57cec5SDimitry Andric using ImbueAttr = XRayFunctionFilter::ImbueAttribute; 33910b57cec5SDimitry Andric auto Attr = ImbueAttr::NONE; 33920b57cec5SDimitry Andric if (Loc.isValid()) 33930b57cec5SDimitry Andric Attr = XRayFilter.shouldImbueLocation(Loc, Category); 33940b57cec5SDimitry Andric if (Attr == ImbueAttr::NONE) 33950b57cec5SDimitry Andric Attr = XRayFilter.shouldImbueFunction(Fn->getName()); 33960b57cec5SDimitry Andric switch (Attr) { 33970b57cec5SDimitry Andric case ImbueAttr::NONE: 33980b57cec5SDimitry Andric return false; 33990b57cec5SDimitry Andric case ImbueAttr::ALWAYS: 34000b57cec5SDimitry Andric Fn->addFnAttr("function-instrument", "xray-always"); 34010b57cec5SDimitry Andric break; 34020b57cec5SDimitry Andric case ImbueAttr::ALWAYS_ARG1: 34030b57cec5SDimitry Andric Fn->addFnAttr("function-instrument", "xray-always"); 34040b57cec5SDimitry Andric Fn->addFnAttr("xray-log-args", "1"); 34050b57cec5SDimitry Andric break; 34060b57cec5SDimitry Andric case ImbueAttr::NEVER: 34070b57cec5SDimitry Andric Fn->addFnAttr("function-instrument", "xray-never"); 34080b57cec5SDimitry Andric break; 34090b57cec5SDimitry Andric } 34100b57cec5SDimitry Andric return true; 34110b57cec5SDimitry Andric } 34120b57cec5SDimitry Andric 3413bdd1243dSDimitry Andric ProfileList::ExclusionType 3414bdd1243dSDimitry Andric CodeGenModule::isFunctionBlockedByProfileList(llvm::Function *Fn, 3415e8d8bef9SDimitry Andric SourceLocation Loc) const { 3416e8d8bef9SDimitry Andric const auto &ProfileList = getContext().getProfileList(); 3417e8d8bef9SDimitry Andric // If the profile list is empty, then instrument everything. 3418e8d8bef9SDimitry Andric if (ProfileList.isEmpty()) 3419bdd1243dSDimitry Andric return ProfileList::Allow; 3420e8d8bef9SDimitry Andric CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr(); 3421e8d8bef9SDimitry Andric // First, check the function name. 3422bdd1243dSDimitry Andric if (auto V = ProfileList.isFunctionExcluded(Fn->getName(), Kind)) 3423e8d8bef9SDimitry Andric return *V; 3424e8d8bef9SDimitry Andric // Next, check the source location. 3425bdd1243dSDimitry Andric if (Loc.isValid()) 3426bdd1243dSDimitry Andric if (auto V = ProfileList.isLocationExcluded(Loc, Kind)) 3427e8d8bef9SDimitry Andric return *V; 3428e8d8bef9SDimitry Andric // If location is unknown, this may be a compiler-generated function. Assume 3429e8d8bef9SDimitry Andric // it's located in the main file. 3430e8d8bef9SDimitry Andric auto &SM = Context.getSourceManager(); 3431c9157d92SDimitry Andric if (auto MainFile = SM.getFileEntryRefForID(SM.getMainFileID())) 3432bdd1243dSDimitry Andric if (auto V = ProfileList.isFileExcluded(MainFile->getName(), Kind)) 3433e8d8bef9SDimitry Andric return *V; 3434bdd1243dSDimitry Andric return ProfileList.getDefault(Kind); 3435e8d8bef9SDimitry Andric } 3436e8d8bef9SDimitry Andric 3437bdd1243dSDimitry Andric ProfileList::ExclusionType 3438bdd1243dSDimitry Andric CodeGenModule::isFunctionBlockedFromProfileInstr(llvm::Function *Fn, 3439bdd1243dSDimitry Andric SourceLocation Loc) const { 3440bdd1243dSDimitry Andric auto V = isFunctionBlockedByProfileList(Fn, Loc); 3441bdd1243dSDimitry Andric if (V != ProfileList::Allow) 3442bdd1243dSDimitry Andric return V; 3443fcaf7f86SDimitry Andric 3444fcaf7f86SDimitry Andric auto NumGroups = getCodeGenOpts().ProfileTotalFunctionGroups; 3445fcaf7f86SDimitry Andric if (NumGroups > 1) { 3446fcaf7f86SDimitry Andric auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups; 3447fcaf7f86SDimitry Andric if (Group != getCodeGenOpts().ProfileSelectedFunctionGroup) 3448bdd1243dSDimitry Andric return ProfileList::Skip; 3449fcaf7f86SDimitry Andric } 3450bdd1243dSDimitry Andric return ProfileList::Allow; 3451fcaf7f86SDimitry Andric } 3452fcaf7f86SDimitry Andric 34530b57cec5SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 34540b57cec5SDimitry Andric // Never defer when EmitAllDecls is specified. 34550b57cec5SDimitry Andric if (LangOpts.EmitAllDecls) 34560b57cec5SDimitry Andric return true; 34570b57cec5SDimitry Andric 34580b57cec5SDimitry Andric const auto *VD = dyn_cast<VarDecl>(Global); 3459fe013be4SDimitry Andric if (VD && 3460fe013be4SDimitry Andric ((CodeGenOpts.KeepPersistentStorageVariables && 3461fe013be4SDimitry Andric (VD->getStorageDuration() == SD_Static || 3462fe013be4SDimitry Andric VD->getStorageDuration() == SD_Thread)) || 3463fe013be4SDimitry Andric (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static && 3464fe013be4SDimitry Andric VD->getType().isConstQualified()))) 34650b57cec5SDimitry Andric return true; 34660b57cec5SDimitry Andric 34670b57cec5SDimitry Andric return getContext().DeclMustBeEmitted(Global); 34680b57cec5SDimitry Andric } 34690b57cec5SDimitry Andric 34700b57cec5SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 3471fe6060f1SDimitry Andric // In OpenMP 5.0 variables and function may be marked as 3472fe6060f1SDimitry Andric // device_type(host/nohost) and we should not emit them eagerly unless we sure 3473fe6060f1SDimitry Andric // that they must be emitted on the host/device. To be sure we need to have 3474fe6060f1SDimitry Andric // seen a declare target with an explicit mentioning of the function, we know 3475fe6060f1SDimitry Andric // we have if the level of the declare target attribute is -1. Note that we 3476fe6060f1SDimitry Andric // check somewhere else if we should emit this at all. 3477fe6060f1SDimitry Andric if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) { 3478bdd1243dSDimitry Andric std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr = 3479fe6060f1SDimitry Andric OMPDeclareTargetDeclAttr::getActiveAttr(Global); 3480fe6060f1SDimitry Andric if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1) 3481fe6060f1SDimitry Andric return false; 3482fe6060f1SDimitry Andric } 3483fe6060f1SDimitry Andric 3484a7dea167SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 34850b57cec5SDimitry Andric if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 34860b57cec5SDimitry Andric // Implicit template instantiations may change linkage if they are later 34870b57cec5SDimitry Andric // explicitly instantiated, so they should not be emitted eagerly. 34880b57cec5SDimitry Andric return false; 3489a7dea167SDimitry Andric } 3490fcaf7f86SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(Global)) { 34910b57cec5SDimitry Andric if (Context.getInlineVariableDefinitionKind(VD) == 34920b57cec5SDimitry Andric ASTContext::InlineVariableDefinitionKind::WeakUnknown) 34930b57cec5SDimitry Andric // A definition of an inline constexpr static data member may change 34940b57cec5SDimitry Andric // linkage later if it's redeclared outside the class. 34950b57cec5SDimitry Andric return false; 3496fcaf7f86SDimitry Andric if (CXX20ModuleInits && VD->getOwningModule() && 3497fcaf7f86SDimitry Andric !VD->getOwningModule()->isModuleMapModule()) { 3498fcaf7f86SDimitry Andric // For CXX20, module-owned initializers need to be deferred, since it is 3499fcaf7f86SDimitry Andric // not known at this point if they will be run for the current module or 3500fcaf7f86SDimitry Andric // as part of the initializer for an imported one. 3501fcaf7f86SDimitry Andric return false; 3502fcaf7f86SDimitry Andric } 3503fcaf7f86SDimitry Andric } 35040b57cec5SDimitry Andric // If OpenMP is enabled and threadprivates must be generated like TLS, delay 35050b57cec5SDimitry Andric // codegen for global variables, because they may be marked as threadprivate. 35060b57cec5SDimitry Andric if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 35070b57cec5SDimitry Andric getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) && 3508c9157d92SDimitry Andric !Global->getType().isConstantStorage(getContext(), false, false) && 35090b57cec5SDimitry Andric !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global)) 35100b57cec5SDimitry Andric return false; 35110b57cec5SDimitry Andric 35120b57cec5SDimitry Andric return true; 35130b57cec5SDimitry Andric } 35140b57cec5SDimitry Andric 35155ffd83dbSDimitry Andric ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) { 35165ffd83dbSDimitry Andric StringRef Name = getMangledName(GD); 35170b57cec5SDimitry Andric 35180b57cec5SDimitry Andric // The UUID descriptor should be pointer aligned. 35190b57cec5SDimitry Andric CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 35200b57cec5SDimitry Andric 35210b57cec5SDimitry Andric // Look for an existing global. 35220b57cec5SDimitry Andric if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 35230eae32dcSDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 35240b57cec5SDimitry Andric 35255ffd83dbSDimitry Andric ConstantEmitter Emitter(*this); 35265ffd83dbSDimitry Andric llvm::Constant *Init; 35275ffd83dbSDimitry Andric 35285ffd83dbSDimitry Andric APValue &V = GD->getAsAPValue(); 35295ffd83dbSDimitry Andric if (!V.isAbsent()) { 35305ffd83dbSDimitry Andric // If possible, emit the APValue version of the initializer. In particular, 35315ffd83dbSDimitry Andric // this gets the type of the constant right. 35325ffd83dbSDimitry Andric Init = Emitter.emitForInitializer( 35335ffd83dbSDimitry Andric GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType()); 35345ffd83dbSDimitry Andric } else { 35355ffd83dbSDimitry Andric // As a fallback, directly construct the constant. 35365ffd83dbSDimitry Andric // FIXME: This may get padding wrong under esoteric struct layout rules. 35375ffd83dbSDimitry Andric // MSVC appears to create a complete type 'struct __s_GUID' that it 35385ffd83dbSDimitry Andric // presumably uses to represent these constants. 35395ffd83dbSDimitry Andric MSGuidDecl::Parts Parts = GD->getParts(); 35405ffd83dbSDimitry Andric llvm::Constant *Fields[4] = { 35415ffd83dbSDimitry Andric llvm::ConstantInt::get(Int32Ty, Parts.Part1), 35425ffd83dbSDimitry Andric llvm::ConstantInt::get(Int16Ty, Parts.Part2), 35435ffd83dbSDimitry Andric llvm::ConstantInt::get(Int16Ty, Parts.Part3), 35445ffd83dbSDimitry Andric llvm::ConstantDataArray::getRaw( 35455ffd83dbSDimitry Andric StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8, 35465ffd83dbSDimitry Andric Int8Ty)}; 35475ffd83dbSDimitry Andric Init = llvm::ConstantStruct::getAnon(Fields); 35485ffd83dbSDimitry Andric } 35490b57cec5SDimitry Andric 35500b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 35510b57cec5SDimitry Andric getModule(), Init->getType(), 35520b57cec5SDimitry Andric /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 35530b57cec5SDimitry Andric if (supportsCOMDAT()) 35540b57cec5SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 35550b57cec5SDimitry Andric setDSOLocal(GV); 35565ffd83dbSDimitry Andric 35575ffd83dbSDimitry Andric if (!V.isAbsent()) { 35585ffd83dbSDimitry Andric Emitter.finalize(GV); 35590eae32dcSDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 35605ffd83dbSDimitry Andric } 35610eae32dcSDimitry Andric 35620eae32dcSDimitry Andric llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType()); 3563c9157d92SDimitry Andric return ConstantAddress(GV, Ty, Alignment); 35640b57cec5SDimitry Andric } 35650b57cec5SDimitry Andric 356681ad6265SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUnnamedGlobalConstantDecl( 356781ad6265SDimitry Andric const UnnamedGlobalConstantDecl *GCD) { 356881ad6265SDimitry Andric CharUnits Alignment = getContext().getTypeAlignInChars(GCD->getType()); 356981ad6265SDimitry Andric 357081ad6265SDimitry Andric llvm::GlobalVariable **Entry = nullptr; 357181ad6265SDimitry Andric Entry = &UnnamedGlobalConstantDeclMap[GCD]; 357281ad6265SDimitry Andric if (*Entry) 357381ad6265SDimitry Andric return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment); 357481ad6265SDimitry Andric 357581ad6265SDimitry Andric ConstantEmitter Emitter(*this); 357681ad6265SDimitry Andric llvm::Constant *Init; 357781ad6265SDimitry Andric 357881ad6265SDimitry Andric const APValue &V = GCD->getValue(); 357981ad6265SDimitry Andric 358081ad6265SDimitry Andric assert(!V.isAbsent()); 358181ad6265SDimitry Andric Init = Emitter.emitForInitializer(V, GCD->getType().getAddressSpace(), 358281ad6265SDimitry Andric GCD->getType()); 358381ad6265SDimitry Andric 358481ad6265SDimitry Andric auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(), 358581ad6265SDimitry Andric /*isConstant=*/true, 358681ad6265SDimitry Andric llvm::GlobalValue::PrivateLinkage, Init, 358781ad6265SDimitry Andric ".constant"); 358881ad6265SDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 358981ad6265SDimitry Andric GV->setAlignment(Alignment.getAsAlign()); 359081ad6265SDimitry Andric 359181ad6265SDimitry Andric Emitter.finalize(GV); 359281ad6265SDimitry Andric 359381ad6265SDimitry Andric *Entry = GV; 359481ad6265SDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 359581ad6265SDimitry Andric } 359681ad6265SDimitry Andric 3597e8d8bef9SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject( 3598e8d8bef9SDimitry Andric const TemplateParamObjectDecl *TPO) { 3599e8d8bef9SDimitry Andric StringRef Name = getMangledName(TPO); 3600e8d8bef9SDimitry Andric CharUnits Alignment = getNaturalTypeAlignment(TPO->getType()); 3601e8d8bef9SDimitry Andric 3602e8d8bef9SDimitry Andric if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 36030eae32dcSDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 3604e8d8bef9SDimitry Andric 3605e8d8bef9SDimitry Andric ConstantEmitter Emitter(*this); 3606e8d8bef9SDimitry Andric llvm::Constant *Init = Emitter.emitForInitializer( 3607e8d8bef9SDimitry Andric TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType()); 3608e8d8bef9SDimitry Andric 3609e8d8bef9SDimitry Andric if (!Init) { 3610e8d8bef9SDimitry Andric ErrorUnsupported(TPO, "template parameter object"); 3611e8d8bef9SDimitry Andric return ConstantAddress::invalid(); 3612e8d8bef9SDimitry Andric } 3613e8d8bef9SDimitry Andric 3614fe013be4SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 3615fe013be4SDimitry Andric isExternallyVisible(TPO->getLinkageAndVisibility().getLinkage()) 3616fe013be4SDimitry Andric ? llvm::GlobalValue::LinkOnceODRLinkage 3617fe013be4SDimitry Andric : llvm::GlobalValue::InternalLinkage; 3618fe013be4SDimitry Andric auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(), 3619fe013be4SDimitry Andric /*isConstant=*/true, Linkage, Init, Name); 3620fe013be4SDimitry Andric setGVProperties(GV, TPO); 3621e8d8bef9SDimitry Andric if (supportsCOMDAT()) 3622e8d8bef9SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3623e8d8bef9SDimitry Andric Emitter.finalize(GV); 3624e8d8bef9SDimitry Andric 36250eae32dcSDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 3626e8d8bef9SDimitry Andric } 3627e8d8bef9SDimitry Andric 36280b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 36290b57cec5SDimitry Andric const AliasAttr *AA = VD->getAttr<AliasAttr>(); 36300b57cec5SDimitry Andric assert(AA && "No alias?"); 36310b57cec5SDimitry Andric 36320b57cec5SDimitry Andric CharUnits Alignment = getContext().getDeclAlign(VD); 36330b57cec5SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 36340b57cec5SDimitry Andric 36350b57cec5SDimitry Andric // See if there is already something with the target's name in the module. 36360b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 3637c9157d92SDimitry Andric if (Entry) 3638c9157d92SDimitry Andric return ConstantAddress(Entry, DeclTy, Alignment); 36390b57cec5SDimitry Andric 36400b57cec5SDimitry Andric llvm::Constant *Aliasee; 36410b57cec5SDimitry Andric if (isa<llvm::FunctionType>(DeclTy)) 36420b57cec5SDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 36430b57cec5SDimitry Andric GlobalDecl(cast<FunctionDecl>(VD)), 36440b57cec5SDimitry Andric /*ForVTable=*/false); 36450b57cec5SDimitry Andric else 3646349cc55cSDimitry Andric Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 3647349cc55cSDimitry Andric nullptr); 36480b57cec5SDimitry Andric 36490b57cec5SDimitry Andric auto *F = cast<llvm::GlobalValue>(Aliasee); 36500b57cec5SDimitry Andric F->setLinkage(llvm::Function::ExternalWeakLinkage); 36510b57cec5SDimitry Andric WeakRefReferences.insert(F); 36520b57cec5SDimitry Andric 36530eae32dcSDimitry Andric return ConstantAddress(Aliasee, DeclTy, Alignment); 36540b57cec5SDimitry Andric } 36550b57cec5SDimitry Andric 3656c9157d92SDimitry Andric template <typename AttrT> static bool hasImplicitAttr(const ValueDecl *D) { 3657c9157d92SDimitry Andric if (!D) 3658c9157d92SDimitry Andric return false; 3659c9157d92SDimitry Andric if (auto *A = D->getAttr<AttrT>()) 3660c9157d92SDimitry Andric return A->isImplicit(); 3661c9157d92SDimitry Andric return D->isImplicit(); 3662c9157d92SDimitry Andric } 3663c9157d92SDimitry Andric 36640b57cec5SDimitry Andric void CodeGenModule::EmitGlobal(GlobalDecl GD) { 36650b57cec5SDimitry Andric const auto *Global = cast<ValueDecl>(GD.getDecl()); 36660b57cec5SDimitry Andric 36670b57cec5SDimitry Andric // Weak references don't produce any output by themselves. 36680b57cec5SDimitry Andric if (Global->hasAttr<WeakRefAttr>()) 36690b57cec5SDimitry Andric return; 36700b57cec5SDimitry Andric 36710b57cec5SDimitry Andric // If this is an alias definition (which otherwise looks like a declaration) 36720b57cec5SDimitry Andric // emit it now. 36730b57cec5SDimitry Andric if (Global->hasAttr<AliasAttr>()) 36740b57cec5SDimitry Andric return EmitAliasDefinition(GD); 36750b57cec5SDimitry Andric 36760b57cec5SDimitry Andric // IFunc like an alias whose value is resolved at runtime by calling resolver. 36770b57cec5SDimitry Andric if (Global->hasAttr<IFuncAttr>()) 36780b57cec5SDimitry Andric return emitIFuncDefinition(GD); 36790b57cec5SDimitry Andric 36800b57cec5SDimitry Andric // If this is a cpu_dispatch multiversion function, emit the resolver. 36810b57cec5SDimitry Andric if (Global->hasAttr<CPUDispatchAttr>()) 36820b57cec5SDimitry Andric return emitCPUDispatchDefinition(GD); 36830b57cec5SDimitry Andric 36840b57cec5SDimitry Andric // If this is CUDA, be selective about which declarations we emit. 3685c9157d92SDimitry Andric // Non-constexpr non-lambda implicit host device functions are not emitted 3686c9157d92SDimitry Andric // unless they are used on device side. 36870b57cec5SDimitry Andric if (LangOpts.CUDA) { 36880b57cec5SDimitry Andric if (LangOpts.CUDAIsDevice) { 3689c9157d92SDimitry Andric const auto *FD = dyn_cast<FunctionDecl>(Global); 3690c9157d92SDimitry Andric if ((!Global->hasAttr<CUDADeviceAttr>() || 3691c9157d92SDimitry Andric (LangOpts.OffloadImplicitHostDeviceTemplates && FD && 3692c9157d92SDimitry Andric hasImplicitAttr<CUDAHostAttr>(FD) && 3693c9157d92SDimitry Andric hasImplicitAttr<CUDADeviceAttr>(FD) && !FD->isConstexpr() && 3694c9157d92SDimitry Andric !isLambdaCallOperator(FD) && 3695c9157d92SDimitry Andric !getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) && 36960b57cec5SDimitry Andric !Global->hasAttr<CUDAGlobalAttr>() && 36970b57cec5SDimitry Andric !Global->hasAttr<CUDAConstantAttr>() && 36980b57cec5SDimitry Andric !Global->hasAttr<CUDASharedAttr>() && 36995ffd83dbSDimitry Andric !Global->getType()->isCUDADeviceBuiltinSurfaceType() && 3700c9157d92SDimitry Andric !Global->getType()->isCUDADeviceBuiltinTextureType() && 3701c9157d92SDimitry Andric !(LangOpts.HIPStdPar && isa<FunctionDecl>(Global) && 3702c9157d92SDimitry Andric !Global->hasAttr<CUDAHostAttr>())) 37030b57cec5SDimitry Andric return; 37040b57cec5SDimitry Andric } else { 37050b57cec5SDimitry Andric // We need to emit host-side 'shadows' for all global 37060b57cec5SDimitry Andric // device-side variables because the CUDA runtime needs their 37070b57cec5SDimitry Andric // size and host-side address in order to provide access to 37080b57cec5SDimitry Andric // their device-side incarnations. 37090b57cec5SDimitry Andric 37100b57cec5SDimitry Andric // So device-only functions are the only things we skip. 37110b57cec5SDimitry Andric if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 37120b57cec5SDimitry Andric Global->hasAttr<CUDADeviceAttr>()) 37130b57cec5SDimitry Andric return; 37140b57cec5SDimitry Andric 37150b57cec5SDimitry Andric assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 37160b57cec5SDimitry Andric "Expected Variable or Function"); 37170b57cec5SDimitry Andric } 37180b57cec5SDimitry Andric } 37190b57cec5SDimitry Andric 37200b57cec5SDimitry Andric if (LangOpts.OpenMP) { 3721a7dea167SDimitry Andric // If this is OpenMP, check if it is legal to emit this global normally. 37220b57cec5SDimitry Andric if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 37230b57cec5SDimitry Andric return; 37240b57cec5SDimitry Andric if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 37250b57cec5SDimitry Andric if (MustBeEmitted(Global)) 37260b57cec5SDimitry Andric EmitOMPDeclareReduction(DRD); 37270b57cec5SDimitry Andric return; 3728fe013be4SDimitry Andric } 3729fe013be4SDimitry Andric if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) { 37300b57cec5SDimitry Andric if (MustBeEmitted(Global)) 37310b57cec5SDimitry Andric EmitOMPDeclareMapper(DMD); 37320b57cec5SDimitry Andric return; 37330b57cec5SDimitry Andric } 37340b57cec5SDimitry Andric } 37350b57cec5SDimitry Andric 37360b57cec5SDimitry Andric // Ignore declarations, they will be emitted on their first use. 37370b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 3738c9157d92SDimitry Andric // Update deferred annotations with the latest declaration if the function 3739c9157d92SDimitry Andric // function was already used or defined. 3740c9157d92SDimitry Andric if (FD->hasAttr<AnnotateAttr>()) { 3741c9157d92SDimitry Andric StringRef MangledName = getMangledName(GD); 3742c9157d92SDimitry Andric if (GetGlobalValue(MangledName)) 3743c9157d92SDimitry Andric DeferredAnnotations[MangledName] = FD; 3744c9157d92SDimitry Andric } 3745c9157d92SDimitry Andric 37460b57cec5SDimitry Andric // Forward declarations are emitted lazily on first use. 37470b57cec5SDimitry Andric if (!FD->doesThisDeclarationHaveABody()) { 37480b57cec5SDimitry Andric if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 37490b57cec5SDimitry Andric return; 37500b57cec5SDimitry Andric 37510b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 37520b57cec5SDimitry Andric 37530b57cec5SDimitry Andric // Compute the function info and LLVM type. 37540b57cec5SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 37550b57cec5SDimitry Andric llvm::Type *Ty = getTypes().GetFunctionType(FI); 37560b57cec5SDimitry Andric 37570b57cec5SDimitry Andric GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 37580b57cec5SDimitry Andric /*DontDefer=*/false); 37590b57cec5SDimitry Andric return; 37600b57cec5SDimitry Andric } 37610b57cec5SDimitry Andric } else { 37620b57cec5SDimitry Andric const auto *VD = cast<VarDecl>(Global); 37630b57cec5SDimitry Andric assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 37640b57cec5SDimitry Andric if (VD->isThisDeclarationADefinition() != VarDecl::Definition && 37650b57cec5SDimitry Andric !Context.isMSStaticDataMemberInlineDefinition(VD)) { 37660b57cec5SDimitry Andric if (LangOpts.OpenMP) { 37670b57cec5SDimitry Andric // Emit declaration of the must-be-emitted declare target variable. 3768bdd1243dSDimitry Andric if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 37690b57cec5SDimitry Andric OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 3770271697daSDimitry Andric 3771271697daSDimitry Andric // If this variable has external storage and doesn't require special 3772271697daSDimitry Andric // link handling we defer to its canonical definition. 3773271697daSDimitry Andric if (VD->hasExternalStorage() && 3774271697daSDimitry Andric Res != OMPDeclareTargetDeclAttr::MT_Link) 3775271697daSDimitry Andric return; 3776271697daSDimitry Andric 37770b57cec5SDimitry Andric bool UnifiedMemoryEnabled = 37780b57cec5SDimitry Andric getOpenMPRuntime().hasRequiresUnifiedSharedMemory(); 3779bdd1243dSDimitry Andric if ((*Res == OMPDeclareTargetDeclAttr::MT_To || 3780bdd1243dSDimitry Andric *Res == OMPDeclareTargetDeclAttr::MT_Enter) && 37810b57cec5SDimitry Andric !UnifiedMemoryEnabled) { 37820b57cec5SDimitry Andric (void)GetAddrOfGlobalVar(VD); 37830b57cec5SDimitry Andric } else { 37840b57cec5SDimitry Andric assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) || 3785bdd1243dSDimitry Andric ((*Res == OMPDeclareTargetDeclAttr::MT_To || 3786bdd1243dSDimitry Andric *Res == OMPDeclareTargetDeclAttr::MT_Enter) && 37870b57cec5SDimitry Andric UnifiedMemoryEnabled)) && 37880b57cec5SDimitry Andric "Link clause or to clause with unified memory expected."); 37890b57cec5SDimitry Andric (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD); 37900b57cec5SDimitry Andric } 37910b57cec5SDimitry Andric 37920b57cec5SDimitry Andric return; 37930b57cec5SDimitry Andric } 37940b57cec5SDimitry Andric } 37950b57cec5SDimitry Andric // If this declaration may have caused an inline variable definition to 37960b57cec5SDimitry Andric // change linkage, make sure that it's emitted. 37970b57cec5SDimitry Andric if (Context.getInlineVariableDefinitionKind(VD) == 37980b57cec5SDimitry Andric ASTContext::InlineVariableDefinitionKind::Strong) 37990b57cec5SDimitry Andric GetAddrOfGlobalVar(VD); 38000b57cec5SDimitry Andric return; 38010b57cec5SDimitry Andric } 38020b57cec5SDimitry Andric } 38030b57cec5SDimitry Andric 38040b57cec5SDimitry Andric // Defer code generation to first use when possible, e.g. if this is an inline 38050b57cec5SDimitry Andric // function. If the global must always be emitted, do it eagerly if possible 38060b57cec5SDimitry Andric // to benefit from cache locality. 38070b57cec5SDimitry Andric if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 38080b57cec5SDimitry Andric // Emit the definition if it can't be deferred. 38090b57cec5SDimitry Andric EmitGlobalDefinition(GD); 3810271697daSDimitry Andric addEmittedDeferredDecl(GD); 38110b57cec5SDimitry Andric return; 38120b57cec5SDimitry Andric } 38130b57cec5SDimitry Andric 38140b57cec5SDimitry Andric // If we're deferring emission of a C++ variable with an 38150b57cec5SDimitry Andric // initializer, remember the order in which it appeared in the file. 38160b57cec5SDimitry Andric if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 38170b57cec5SDimitry Andric cast<VarDecl>(Global)->hasInit()) { 38180b57cec5SDimitry Andric DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 38190b57cec5SDimitry Andric CXXGlobalInits.push_back(nullptr); 38200b57cec5SDimitry Andric } 38210b57cec5SDimitry Andric 38220b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 38230b57cec5SDimitry Andric if (GetGlobalValue(MangledName) != nullptr) { 38240b57cec5SDimitry Andric // The value has already been used and should therefore be emitted. 38250b57cec5SDimitry Andric addDeferredDeclToEmit(GD); 38260b57cec5SDimitry Andric } else if (MustBeEmitted(Global)) { 38270b57cec5SDimitry Andric // The value must be emitted, but cannot be emitted eagerly. 38280b57cec5SDimitry Andric assert(!MayBeEmittedEagerly(Global)); 38290b57cec5SDimitry Andric addDeferredDeclToEmit(GD); 38300b57cec5SDimitry Andric } else { 38310b57cec5SDimitry Andric // Otherwise, remember that we saw a deferred decl with this name. The 38320b57cec5SDimitry Andric // first use of the mangled name will cause it to move into 38330b57cec5SDimitry Andric // DeferredDeclsToEmit. 38340b57cec5SDimitry Andric DeferredDecls[MangledName] = GD; 38350b57cec5SDimitry Andric } 38360b57cec5SDimitry Andric } 38370b57cec5SDimitry Andric 38380b57cec5SDimitry Andric // Check if T is a class type with a destructor that's not dllimport. 38390b57cec5SDimitry Andric static bool HasNonDllImportDtor(QualType T) { 38400b57cec5SDimitry Andric if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) 38410b57cec5SDimitry Andric if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 38420b57cec5SDimitry Andric if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) 38430b57cec5SDimitry Andric return true; 38440b57cec5SDimitry Andric 38450b57cec5SDimitry Andric return false; 38460b57cec5SDimitry Andric } 38470b57cec5SDimitry Andric 38480b57cec5SDimitry Andric namespace { 38490b57cec5SDimitry Andric struct FunctionIsDirectlyRecursive 38500b57cec5SDimitry Andric : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> { 38510b57cec5SDimitry Andric const StringRef Name; 38520b57cec5SDimitry Andric const Builtin::Context &BI; 38530b57cec5SDimitry Andric FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) 38540b57cec5SDimitry Andric : Name(N), BI(C) {} 38550b57cec5SDimitry Andric 38560b57cec5SDimitry Andric bool VisitCallExpr(const CallExpr *E) { 38570b57cec5SDimitry Andric const FunctionDecl *FD = E->getDirectCallee(); 38580b57cec5SDimitry Andric if (!FD) 38590b57cec5SDimitry Andric return false; 38600b57cec5SDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 38610b57cec5SDimitry Andric if (Attr && Name == Attr->getLabel()) 38620b57cec5SDimitry Andric return true; 38630b57cec5SDimitry Andric unsigned BuiltinID = FD->getBuiltinID(); 38640b57cec5SDimitry Andric if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 38650b57cec5SDimitry Andric return false; 38660b57cec5SDimitry Andric StringRef BuiltinName = BI.getName(BuiltinID); 3867c9157d92SDimitry Andric if (BuiltinName.starts_with("__builtin_") && 38680b57cec5SDimitry Andric Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 38690b57cec5SDimitry Andric return true; 38700b57cec5SDimitry Andric } 38710b57cec5SDimitry Andric return false; 38720b57cec5SDimitry Andric } 38730b57cec5SDimitry Andric 38740b57cec5SDimitry Andric bool VisitStmt(const Stmt *S) { 38750b57cec5SDimitry Andric for (const Stmt *Child : S->children()) 38760b57cec5SDimitry Andric if (Child && this->Visit(Child)) 38770b57cec5SDimitry Andric return true; 38780b57cec5SDimitry Andric return false; 38790b57cec5SDimitry Andric } 38800b57cec5SDimitry Andric }; 38810b57cec5SDimitry Andric 38820b57cec5SDimitry Andric // Make sure we're not referencing non-imported vars or functions. 38830b57cec5SDimitry Andric struct DLLImportFunctionVisitor 38840b57cec5SDimitry Andric : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 38850b57cec5SDimitry Andric bool SafeToInline = true; 38860b57cec5SDimitry Andric 38870b57cec5SDimitry Andric bool shouldVisitImplicitCode() const { return true; } 38880b57cec5SDimitry Andric 38890b57cec5SDimitry Andric bool VisitVarDecl(VarDecl *VD) { 38900b57cec5SDimitry Andric if (VD->getTLSKind()) { 38910b57cec5SDimitry Andric // A thread-local variable cannot be imported. 38920b57cec5SDimitry Andric SafeToInline = false; 38930b57cec5SDimitry Andric return SafeToInline; 38940b57cec5SDimitry Andric } 38950b57cec5SDimitry Andric 38960b57cec5SDimitry Andric // A variable definition might imply a destructor call. 38970b57cec5SDimitry Andric if (VD->isThisDeclarationADefinition()) 38980b57cec5SDimitry Andric SafeToInline = !HasNonDllImportDtor(VD->getType()); 38990b57cec5SDimitry Andric 39000b57cec5SDimitry Andric return SafeToInline; 39010b57cec5SDimitry Andric } 39020b57cec5SDimitry Andric 39030b57cec5SDimitry Andric bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 39040b57cec5SDimitry Andric if (const auto *D = E->getTemporary()->getDestructor()) 39050b57cec5SDimitry Andric SafeToInline = D->hasAttr<DLLImportAttr>(); 39060b57cec5SDimitry Andric return SafeToInline; 39070b57cec5SDimitry Andric } 39080b57cec5SDimitry Andric 39090b57cec5SDimitry Andric bool VisitDeclRefExpr(DeclRefExpr *E) { 39100b57cec5SDimitry Andric ValueDecl *VD = E->getDecl(); 39110b57cec5SDimitry Andric if (isa<FunctionDecl>(VD)) 39120b57cec5SDimitry Andric SafeToInline = VD->hasAttr<DLLImportAttr>(); 39130b57cec5SDimitry Andric else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 39140b57cec5SDimitry Andric SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 39150b57cec5SDimitry Andric return SafeToInline; 39160b57cec5SDimitry Andric } 39170b57cec5SDimitry Andric 39180b57cec5SDimitry Andric bool VisitCXXConstructExpr(CXXConstructExpr *E) { 39190b57cec5SDimitry Andric SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); 39200b57cec5SDimitry Andric return SafeToInline; 39210b57cec5SDimitry Andric } 39220b57cec5SDimitry Andric 39230b57cec5SDimitry Andric bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 39240b57cec5SDimitry Andric CXXMethodDecl *M = E->getMethodDecl(); 39250b57cec5SDimitry Andric if (!M) { 39260b57cec5SDimitry Andric // Call through a pointer to member function. This is safe to inline. 39270b57cec5SDimitry Andric SafeToInline = true; 39280b57cec5SDimitry Andric } else { 39290b57cec5SDimitry Andric SafeToInline = M->hasAttr<DLLImportAttr>(); 39300b57cec5SDimitry Andric } 39310b57cec5SDimitry Andric return SafeToInline; 39320b57cec5SDimitry Andric } 39330b57cec5SDimitry Andric 39340b57cec5SDimitry Andric bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 39350b57cec5SDimitry Andric SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 39360b57cec5SDimitry Andric return SafeToInline; 39370b57cec5SDimitry Andric } 39380b57cec5SDimitry Andric 39390b57cec5SDimitry Andric bool VisitCXXNewExpr(CXXNewExpr *E) { 39400b57cec5SDimitry Andric SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 39410b57cec5SDimitry Andric return SafeToInline; 39420b57cec5SDimitry Andric } 39430b57cec5SDimitry Andric }; 39440b57cec5SDimitry Andric } 39450b57cec5SDimitry Andric 39460b57cec5SDimitry Andric // isTriviallyRecursive - Check if this function calls another 39470b57cec5SDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin, 39480b57cec5SDimitry Andric // ends up pointing to itself. 39490b57cec5SDimitry Andric bool 39500b57cec5SDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 39510b57cec5SDimitry Andric StringRef Name; 39520b57cec5SDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 39530b57cec5SDimitry Andric // asm labels are a special kind of mangling we have to support. 39540b57cec5SDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 39550b57cec5SDimitry Andric if (!Attr) 39560b57cec5SDimitry Andric return false; 39570b57cec5SDimitry Andric Name = Attr->getLabel(); 39580b57cec5SDimitry Andric } else { 39590b57cec5SDimitry Andric Name = FD->getName(); 39600b57cec5SDimitry Andric } 39610b57cec5SDimitry Andric 39620b57cec5SDimitry Andric FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 39630b57cec5SDimitry Andric const Stmt *Body = FD->getBody(); 39640b57cec5SDimitry Andric return Body ? Walker.Visit(Body) : false; 39650b57cec5SDimitry Andric } 39660b57cec5SDimitry Andric 39670b57cec5SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 39680b57cec5SDimitry Andric if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 39690b57cec5SDimitry Andric return true; 3970c9157d92SDimitry Andric 39710b57cec5SDimitry Andric const auto *F = cast<FunctionDecl>(GD.getDecl()); 39720b57cec5SDimitry Andric if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 39730b57cec5SDimitry Andric return false; 39740b57cec5SDimitry Andric 3975c9157d92SDimitry Andric // We don't import function bodies from other named module units since that 3976c9157d92SDimitry Andric // behavior may break ABI compatibility of the current unit. 3977c9157d92SDimitry Andric if (const Module *M = F->getOwningModule(); 3978c9157d92SDimitry Andric M && M->getTopLevelModule()->isNamedModule() && 3979c9157d92SDimitry Andric getContext().getCurrentNamedModule() != M->getTopLevelModule() && 3980c9157d92SDimitry Andric !F->hasAttr<AlwaysInlineAttr>()) 3981c9157d92SDimitry Andric return false; 3982c9157d92SDimitry Andric 3983c9157d92SDimitry Andric if (F->hasAttr<NoInlineAttr>()) 3984c9157d92SDimitry Andric return false; 3985c9157d92SDimitry Andric 3986fe6060f1SDimitry Andric if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) { 39870b57cec5SDimitry Andric // Check whether it would be safe to inline this dllimport function. 39880b57cec5SDimitry Andric DLLImportFunctionVisitor Visitor; 39890b57cec5SDimitry Andric Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 39900b57cec5SDimitry Andric if (!Visitor.SafeToInline) 39910b57cec5SDimitry Andric return false; 39920b57cec5SDimitry Andric 39930b57cec5SDimitry Andric if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { 39940b57cec5SDimitry Andric // Implicit destructor invocations aren't captured in the AST, so the 39950b57cec5SDimitry Andric // check above can't see them. Check for them manually here. 39960b57cec5SDimitry Andric for (const Decl *Member : Dtor->getParent()->decls()) 39970b57cec5SDimitry Andric if (isa<FieldDecl>(Member)) 39980b57cec5SDimitry Andric if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) 39990b57cec5SDimitry Andric return false; 40000b57cec5SDimitry Andric for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) 40010b57cec5SDimitry Andric if (HasNonDllImportDtor(B.getType())) 40020b57cec5SDimitry Andric return false; 40030b57cec5SDimitry Andric } 40040b57cec5SDimitry Andric } 40050b57cec5SDimitry Andric 4006349cc55cSDimitry Andric // Inline builtins declaration must be emitted. They often are fortified 4007349cc55cSDimitry Andric // functions. 4008349cc55cSDimitry Andric if (F->isInlineBuiltinDeclaration()) 4009349cc55cSDimitry Andric return true; 4010349cc55cSDimitry Andric 40110b57cec5SDimitry Andric // PR9614. Avoid cases where the source code is lying to us. An available 40120b57cec5SDimitry Andric // externally function should have an equivalent function somewhere else, 40135ffd83dbSDimitry Andric // but a function that calls itself through asm label/`__builtin_` trickery is 40145ffd83dbSDimitry Andric // clearly not equivalent to the real implementation. 40150b57cec5SDimitry Andric // This happens in glibc's btowc and in some configure checks. 40160b57cec5SDimitry Andric return !isTriviallyRecursive(F); 40170b57cec5SDimitry Andric } 40180b57cec5SDimitry Andric 40190b57cec5SDimitry Andric bool CodeGenModule::shouldOpportunisticallyEmitVTables() { 40200b57cec5SDimitry Andric return CodeGenOpts.OptimizationLevel > 0; 40210b57cec5SDimitry Andric } 40220b57cec5SDimitry Andric 40230b57cec5SDimitry Andric void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD, 40240b57cec5SDimitry Andric llvm::GlobalValue *GV) { 40250b57cec5SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 40260b57cec5SDimitry Andric 40270b57cec5SDimitry Andric if (FD->isCPUSpecificMultiVersion()) { 40280b57cec5SDimitry Andric auto *Spec = FD->getAttr<CPUSpecificAttr>(); 40290b57cec5SDimitry Andric for (unsigned I = 0; I < Spec->cpus_size(); ++I) 40300b57cec5SDimitry Andric EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); 40314824e7fdSDimitry Andric } else if (FD->isTargetClonesMultiVersion()) { 40324824e7fdSDimitry Andric auto *Clone = FD->getAttr<TargetClonesAttr>(); 40334824e7fdSDimitry Andric for (unsigned I = 0; I < Clone->featuresStrs_size(); ++I) 40344824e7fdSDimitry Andric if (Clone->isFirstOfVersion(I)) 40354824e7fdSDimitry Andric EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); 403681ad6265SDimitry Andric // Ensure that the resolver function is also emitted. 403781ad6265SDimitry Andric GetOrCreateMultiVersionResolver(GD); 4038*a58f00eaSDimitry Andric } else if (FD->hasAttr<TargetVersionAttr>()) { 4039*a58f00eaSDimitry Andric GetOrCreateMultiVersionResolver(GD); 40400b57cec5SDimitry Andric } else 40410b57cec5SDimitry Andric EmitGlobalFunctionDefinition(GD, GV); 40420b57cec5SDimitry Andric } 40430b57cec5SDimitry Andric 40440b57cec5SDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 40450b57cec5SDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 40460b57cec5SDimitry Andric 40470b57cec5SDimitry Andric PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 40480b57cec5SDimitry Andric Context.getSourceManager(), 40490b57cec5SDimitry Andric "Generating code for declaration"); 40500b57cec5SDimitry Andric 40510b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 40520b57cec5SDimitry Andric // At -O0, don't generate IR for functions with available_externally 40530b57cec5SDimitry Andric // linkage. 40540b57cec5SDimitry Andric if (!shouldEmitFunction(GD)) 40550b57cec5SDimitry Andric return; 40560b57cec5SDimitry Andric 40570b57cec5SDimitry Andric llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() { 40580b57cec5SDimitry Andric std::string Name; 40590b57cec5SDimitry Andric llvm::raw_string_ostream OS(Name); 40600b57cec5SDimitry Andric FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(), 40610b57cec5SDimitry Andric /*Qualified=*/true); 40620b57cec5SDimitry Andric return Name; 40630b57cec5SDimitry Andric }); 40640b57cec5SDimitry Andric 40650b57cec5SDimitry Andric if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 40660b57cec5SDimitry Andric // Make sure to emit the definition(s) before we emit the thunks. 40670b57cec5SDimitry Andric // This is necessary for the generation of certain thunks. 40680b57cec5SDimitry Andric if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method)) 40690b57cec5SDimitry Andric ABI->emitCXXStructor(GD); 40700b57cec5SDimitry Andric else if (FD->isMultiVersion()) 40710b57cec5SDimitry Andric EmitMultiVersionFunctionDefinition(GD, GV); 40720b57cec5SDimitry Andric else 40730b57cec5SDimitry Andric EmitGlobalFunctionDefinition(GD, GV); 40740b57cec5SDimitry Andric 40750b57cec5SDimitry Andric if (Method->isVirtual()) 40760b57cec5SDimitry Andric getVTables().EmitThunks(GD); 40770b57cec5SDimitry Andric 40780b57cec5SDimitry Andric return; 40790b57cec5SDimitry Andric } 40800b57cec5SDimitry Andric 40810b57cec5SDimitry Andric if (FD->isMultiVersion()) 40820b57cec5SDimitry Andric return EmitMultiVersionFunctionDefinition(GD, GV); 40830b57cec5SDimitry Andric return EmitGlobalFunctionDefinition(GD, GV); 40840b57cec5SDimitry Andric } 40850b57cec5SDimitry Andric 40860b57cec5SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 40870b57cec5SDimitry Andric return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 40880b57cec5SDimitry Andric 40890b57cec5SDimitry Andric llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 40900b57cec5SDimitry Andric } 40910b57cec5SDimitry Andric 40920b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 40930b57cec5SDimitry Andric llvm::Function *NewFn); 40940b57cec5SDimitry Andric 40950b57cec5SDimitry Andric static unsigned 40960b57cec5SDimitry Andric TargetMVPriority(const TargetInfo &TI, 40970b57cec5SDimitry Andric const CodeGenFunction::MultiVersionResolverOption &RO) { 40980b57cec5SDimitry Andric unsigned Priority = 0; 4099bdd1243dSDimitry Andric unsigned NumFeatures = 0; 4100bdd1243dSDimitry Andric for (StringRef Feat : RO.Conditions.Features) { 41010b57cec5SDimitry Andric Priority = std::max(Priority, TI.multiVersionSortPriority(Feat)); 4102bdd1243dSDimitry Andric NumFeatures++; 4103bdd1243dSDimitry Andric } 41040b57cec5SDimitry Andric 41050b57cec5SDimitry Andric if (!RO.Conditions.Architecture.empty()) 41060b57cec5SDimitry Andric Priority = std::max( 41070b57cec5SDimitry Andric Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture)); 4108bdd1243dSDimitry Andric 4109bdd1243dSDimitry Andric Priority += TI.multiVersionFeatureCost() * NumFeatures; 4110bdd1243dSDimitry Andric 41110b57cec5SDimitry Andric return Priority; 41120b57cec5SDimitry Andric } 41130b57cec5SDimitry Andric 4114349cc55cSDimitry Andric // Multiversion functions should be at most 'WeakODRLinkage' so that a different 4115349cc55cSDimitry Andric // TU can forward declare the function without causing problems. Particularly 4116349cc55cSDimitry Andric // in the cases of CPUDispatch, this causes issues. This also makes sure we 4117349cc55cSDimitry Andric // work with internal linkage functions, so that the same function name can be 4118349cc55cSDimitry Andric // used with internal linkage in multiple TUs. 4119349cc55cSDimitry Andric llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM, 4120349cc55cSDimitry Andric GlobalDecl GD) { 4121349cc55cSDimitry Andric const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 4122c9157d92SDimitry Andric if (FD->getFormalLinkage() == Linkage::Internal) 4123349cc55cSDimitry Andric return llvm::GlobalValue::InternalLinkage; 4124349cc55cSDimitry Andric return llvm::GlobalValue::WeakODRLinkage; 4125349cc55cSDimitry Andric } 4126349cc55cSDimitry Andric 41270b57cec5SDimitry Andric void CodeGenModule::emitMultiVersionFunctions() { 4128fe6060f1SDimitry Andric std::vector<GlobalDecl> MVFuncsToEmit; 4129fe6060f1SDimitry Andric MultiVersionFuncs.swap(MVFuncsToEmit); 4130fe6060f1SDimitry Andric for (GlobalDecl GD : MVFuncsToEmit) { 413181ad6265SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 413281ad6265SDimitry Andric assert(FD && "Expected a FunctionDecl"); 413381ad6265SDimitry Andric 41340b57cec5SDimitry Andric SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 413581ad6265SDimitry Andric if (FD->isTargetMultiVersion()) { 41360b57cec5SDimitry Andric getContext().forEachMultiversionedFunctionVersion( 41370b57cec5SDimitry Andric FD, [this, &GD, &Options](const FunctionDecl *CurFD) { 41380b57cec5SDimitry Andric GlobalDecl CurGD{ 41390b57cec5SDimitry Andric (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)}; 41400b57cec5SDimitry Andric StringRef MangledName = getMangledName(CurGD); 41410b57cec5SDimitry Andric llvm::Constant *Func = GetGlobalValue(MangledName); 41420b57cec5SDimitry Andric if (!Func) { 41430b57cec5SDimitry Andric if (CurFD->isDefined()) { 41440b57cec5SDimitry Andric EmitGlobalFunctionDefinition(CurGD, nullptr); 41450b57cec5SDimitry Andric Func = GetGlobalValue(MangledName); 41460b57cec5SDimitry Andric } else { 41470b57cec5SDimitry Andric const CGFunctionInfo &FI = 41480b57cec5SDimitry Andric getTypes().arrangeGlobalDeclaration(GD); 41490b57cec5SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 41500b57cec5SDimitry Andric Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, 41510b57cec5SDimitry Andric /*DontDefer=*/false, ForDefinition); 41520b57cec5SDimitry Andric } 41530b57cec5SDimitry Andric assert(Func && "This should have just been created"); 41540b57cec5SDimitry Andric } 4155bdd1243dSDimitry Andric if (CurFD->getMultiVersionKind() == MultiVersionKind::Target) { 41560b57cec5SDimitry Andric const auto *TA = CurFD->getAttr<TargetAttr>(); 41570b57cec5SDimitry Andric llvm::SmallVector<StringRef, 8> Feats; 41580b57cec5SDimitry Andric TA->getAddedFeatures(Feats); 41590b57cec5SDimitry Andric Options.emplace_back(cast<llvm::Function>(Func), 41600b57cec5SDimitry Andric TA->getArchitecture(), Feats); 4161bdd1243dSDimitry Andric } else { 4162bdd1243dSDimitry Andric const auto *TVA = CurFD->getAttr<TargetVersionAttr>(); 4163bdd1243dSDimitry Andric llvm::SmallVector<StringRef, 8> Feats; 4164bdd1243dSDimitry Andric TVA->getFeatures(Feats); 4165bdd1243dSDimitry Andric Options.emplace_back(cast<llvm::Function>(Func), 4166bdd1243dSDimitry Andric /*Architecture*/ "", Feats); 4167bdd1243dSDimitry Andric } 41680b57cec5SDimitry Andric }); 416981ad6265SDimitry Andric } else if (FD->isTargetClonesMultiVersion()) { 417081ad6265SDimitry Andric const auto *TC = FD->getAttr<TargetClonesAttr>(); 417181ad6265SDimitry Andric for (unsigned VersionIndex = 0; VersionIndex < TC->featuresStrs_size(); 417281ad6265SDimitry Andric ++VersionIndex) { 417381ad6265SDimitry Andric if (!TC->isFirstOfVersion(VersionIndex)) 417481ad6265SDimitry Andric continue; 417581ad6265SDimitry Andric GlobalDecl CurGD{(FD->isDefined() ? FD->getDefinition() : FD), 417681ad6265SDimitry Andric VersionIndex}; 417781ad6265SDimitry Andric StringRef Version = TC->getFeatureStr(VersionIndex); 417881ad6265SDimitry Andric StringRef MangledName = getMangledName(CurGD); 417981ad6265SDimitry Andric llvm::Constant *Func = GetGlobalValue(MangledName); 418081ad6265SDimitry Andric if (!Func) { 418181ad6265SDimitry Andric if (FD->isDefined()) { 418281ad6265SDimitry Andric EmitGlobalFunctionDefinition(CurGD, nullptr); 418381ad6265SDimitry Andric Func = GetGlobalValue(MangledName); 4184a7dea167SDimitry Andric } else { 418581ad6265SDimitry Andric const CGFunctionInfo &FI = 418681ad6265SDimitry Andric getTypes().arrangeGlobalDeclaration(CurGD); 418781ad6265SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 418881ad6265SDimitry Andric Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, 418981ad6265SDimitry Andric /*DontDefer=*/false, ForDefinition); 4190a7dea167SDimitry Andric } 419181ad6265SDimitry Andric assert(Func && "This should have just been created"); 419281ad6265SDimitry Andric } 419381ad6265SDimitry Andric 419481ad6265SDimitry Andric StringRef Architecture; 419581ad6265SDimitry Andric llvm::SmallVector<StringRef, 1> Feature; 419681ad6265SDimitry Andric 4197bdd1243dSDimitry Andric if (getTarget().getTriple().isAArch64()) { 4198bdd1243dSDimitry Andric if (Version != "default") { 4199bdd1243dSDimitry Andric llvm::SmallVector<StringRef, 8> VerFeats; 4200bdd1243dSDimitry Andric Version.split(VerFeats, "+"); 4201bdd1243dSDimitry Andric for (auto &CurFeat : VerFeats) 4202bdd1243dSDimitry Andric Feature.push_back(CurFeat.trim()); 4203bdd1243dSDimitry Andric } 4204bdd1243dSDimitry Andric } else { 4205c9157d92SDimitry Andric if (Version.starts_with("arch=")) 420681ad6265SDimitry Andric Architecture = Version.drop_front(sizeof("arch=") - 1); 420781ad6265SDimitry Andric else if (Version != "default") 420881ad6265SDimitry Andric Feature.push_back(Version); 4209bdd1243dSDimitry Andric } 421081ad6265SDimitry Andric 421181ad6265SDimitry Andric Options.emplace_back(cast<llvm::Function>(Func), Architecture, Feature); 421281ad6265SDimitry Andric } 421381ad6265SDimitry Andric } else { 421481ad6265SDimitry Andric assert(0 && "Expected a target or target_clones multiversion function"); 421581ad6265SDimitry Andric continue; 421681ad6265SDimitry Andric } 421781ad6265SDimitry Andric 421881ad6265SDimitry Andric llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD); 4219c9157d92SDimitry Andric if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) { 422081ad6265SDimitry Andric ResolverConstant = IFunc->getResolver(); 4221*a58f00eaSDimitry Andric if (FD->isTargetClonesMultiVersion()) { 4222c9157d92SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 4223c9157d92SDimitry Andric llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI); 4224c9157d92SDimitry Andric std::string MangledName = getMangledNameImpl( 4225c9157d92SDimitry Andric *this, GD, FD, /*OmitMultiVersionMangling=*/true); 4226c9157d92SDimitry Andric // In prior versions of Clang, the mangling for ifuncs incorrectly 4227c9157d92SDimitry Andric // included an .ifunc suffix. This alias is generated for backward 4228c9157d92SDimitry Andric // compatibility. It is deprecated, and may be removed in the future. 4229c9157d92SDimitry Andric auto *Alias = llvm::GlobalAlias::create( 4230c9157d92SDimitry Andric DeclTy, 0, getMultiversionLinkage(*this, GD), 4231c9157d92SDimitry Andric MangledName + ".ifunc", IFunc, &getModule()); 4232c9157d92SDimitry Andric SetCommonAttributes(FD, Alias); 4233c9157d92SDimitry Andric } 4234c9157d92SDimitry Andric } 423581ad6265SDimitry Andric llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant); 423681ad6265SDimitry Andric 423781ad6265SDimitry Andric ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD)); 42380b57cec5SDimitry Andric 4239c9157d92SDimitry Andric if (!ResolverFunc->hasLocalLinkage() && supportsCOMDAT()) 42400b57cec5SDimitry Andric ResolverFunc->setComdat( 42410b57cec5SDimitry Andric getModule().getOrInsertComdat(ResolverFunc->getName())); 42420b57cec5SDimitry Andric 424381ad6265SDimitry Andric const TargetInfo &TI = getTarget(); 42440b57cec5SDimitry Andric llvm::stable_sort( 42450b57cec5SDimitry Andric Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS, 42460b57cec5SDimitry Andric const CodeGenFunction::MultiVersionResolverOption &RHS) { 42470b57cec5SDimitry Andric return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS); 42480b57cec5SDimitry Andric }); 42490b57cec5SDimitry Andric CodeGenFunction CGF(*this); 42500b57cec5SDimitry Andric CGF.EmitMultiVersionResolver(ResolverFunc, Options); 42510b57cec5SDimitry Andric } 4252fe6060f1SDimitry Andric 4253fe6060f1SDimitry Andric // Ensure that any additions to the deferred decls list caused by emitting a 4254fe6060f1SDimitry Andric // variant are emitted. This can happen when the variant itself is inline and 4255fe6060f1SDimitry Andric // calls a function without linkage. 4256fe6060f1SDimitry Andric if (!MVFuncsToEmit.empty()) 4257fe6060f1SDimitry Andric EmitDeferred(); 4258fe6060f1SDimitry Andric 4259fe6060f1SDimitry Andric // Ensure that any additions to the multiversion funcs list from either the 4260fe6060f1SDimitry Andric // deferred decls or the multiversion functions themselves are emitted. 4261fe6060f1SDimitry Andric if (!MultiVersionFuncs.empty()) 4262fe6060f1SDimitry Andric emitMultiVersionFunctions(); 42630b57cec5SDimitry Andric } 42640b57cec5SDimitry Andric 42650b57cec5SDimitry Andric void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) { 42660b57cec5SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 42670b57cec5SDimitry Andric assert(FD && "Not a FunctionDecl?"); 426804eeddc0SDimitry Andric assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?"); 42690b57cec5SDimitry Andric const auto *DD = FD->getAttr<CPUDispatchAttr>(); 42700b57cec5SDimitry Andric assert(DD && "Not a cpu_dispatch Function?"); 42710b57cec5SDimitry Andric 427281ad6265SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 427381ad6265SDimitry Andric llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI); 42740b57cec5SDimitry Andric 42750b57cec5SDimitry Andric StringRef ResolverName = getMangledName(GD); 427604eeddc0SDimitry Andric UpdateMultiVersionNames(GD, FD, ResolverName); 42770b57cec5SDimitry Andric 42780b57cec5SDimitry Andric llvm::Type *ResolverType; 42790b57cec5SDimitry Andric GlobalDecl ResolverGD; 428004eeddc0SDimitry Andric if (getTarget().supportsIFunc()) { 42810b57cec5SDimitry Andric ResolverType = llvm::FunctionType::get( 42820b57cec5SDimitry Andric llvm::PointerType::get(DeclTy, 4283bdd1243dSDimitry Andric getTypes().getTargetAddressSpace(FD->getType())), 42840b57cec5SDimitry Andric false); 428504eeddc0SDimitry Andric } 42860b57cec5SDimitry Andric else { 42870b57cec5SDimitry Andric ResolverType = DeclTy; 42880b57cec5SDimitry Andric ResolverGD = GD; 42890b57cec5SDimitry Andric } 42900b57cec5SDimitry Andric 42910b57cec5SDimitry Andric auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction( 42920b57cec5SDimitry Andric ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false)); 4293349cc55cSDimitry Andric ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD)); 4294a7dea167SDimitry Andric if (supportsCOMDAT()) 4295a7dea167SDimitry Andric ResolverFunc->setComdat( 4296a7dea167SDimitry Andric getModule().getOrInsertComdat(ResolverFunc->getName())); 42970b57cec5SDimitry Andric 42980b57cec5SDimitry Andric SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 42990b57cec5SDimitry Andric const TargetInfo &Target = getTarget(); 43000b57cec5SDimitry Andric unsigned Index = 0; 43010b57cec5SDimitry Andric for (const IdentifierInfo *II : DD->cpus()) { 43020b57cec5SDimitry Andric // Get the name of the target function so we can look it up/create it. 43030b57cec5SDimitry Andric std::string MangledName = getMangledNameImpl(*this, GD, FD, true) + 43040b57cec5SDimitry Andric getCPUSpecificMangling(*this, II->getName()); 43050b57cec5SDimitry Andric 43060b57cec5SDimitry Andric llvm::Constant *Func = GetGlobalValue(MangledName); 43070b57cec5SDimitry Andric 43080b57cec5SDimitry Andric if (!Func) { 43090b57cec5SDimitry Andric GlobalDecl ExistingDecl = Manglings.lookup(MangledName); 43100b57cec5SDimitry Andric if (ExistingDecl.getDecl() && 43110b57cec5SDimitry Andric ExistingDecl.getDecl()->getAsFunction()->isDefined()) { 43120b57cec5SDimitry Andric EmitGlobalFunctionDefinition(ExistingDecl, nullptr); 43130b57cec5SDimitry Andric Func = GetGlobalValue(MangledName); 43140b57cec5SDimitry Andric } else { 43150b57cec5SDimitry Andric if (!ExistingDecl.getDecl()) 43160b57cec5SDimitry Andric ExistingDecl = GD.getWithMultiVersionIndex(Index); 43170b57cec5SDimitry Andric 43180b57cec5SDimitry Andric Func = GetOrCreateLLVMFunction( 43190b57cec5SDimitry Andric MangledName, DeclTy, ExistingDecl, 43200b57cec5SDimitry Andric /*ForVTable=*/false, /*DontDefer=*/true, 43210b57cec5SDimitry Andric /*IsThunk=*/false, llvm::AttributeList(), ForDefinition); 43220b57cec5SDimitry Andric } 43230b57cec5SDimitry Andric } 43240b57cec5SDimitry Andric 43250b57cec5SDimitry Andric llvm::SmallVector<StringRef, 32> Features; 43260b57cec5SDimitry Andric Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features); 43270b57cec5SDimitry Andric llvm::transform(Features, Features.begin(), 43280b57cec5SDimitry Andric [](StringRef Str) { return Str.substr(1); }); 4329349cc55cSDimitry Andric llvm::erase_if(Features, [&Target](StringRef Feat) { 43300b57cec5SDimitry Andric return !Target.validateCpuSupports(Feat); 4331349cc55cSDimitry Andric }); 43320b57cec5SDimitry Andric Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features); 43330b57cec5SDimitry Andric ++Index; 43340b57cec5SDimitry Andric } 43350b57cec5SDimitry Andric 4336fe6060f1SDimitry Andric llvm::stable_sort( 43370b57cec5SDimitry Andric Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS, 43380b57cec5SDimitry Andric const CodeGenFunction::MultiVersionResolverOption &RHS) { 4339349cc55cSDimitry Andric return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) > 4340349cc55cSDimitry Andric llvm::X86::getCpuSupportsMask(RHS.Conditions.Features); 43410b57cec5SDimitry Andric }); 43420b57cec5SDimitry Andric 43430b57cec5SDimitry Andric // If the list contains multiple 'default' versions, such as when it contains 43440b57cec5SDimitry Andric // 'pentium' and 'generic', don't emit the call to the generic one (since we 43450b57cec5SDimitry Andric // always run on at least a 'pentium'). We do this by deleting the 'least 43460b57cec5SDimitry Andric // advanced' (read, lowest mangling letter). 43470b57cec5SDimitry Andric while (Options.size() > 1 && 4348c9157d92SDimitry Andric llvm::all_of(llvm::X86::getCpuSupportsMask( 4349c9157d92SDimitry Andric (Options.end() - 2)->Conditions.Features), 4350c9157d92SDimitry Andric [](auto X) { return X == 0; })) { 43510b57cec5SDimitry Andric StringRef LHSName = (Options.end() - 2)->Function->getName(); 43520b57cec5SDimitry Andric StringRef RHSName = (Options.end() - 1)->Function->getName(); 43530b57cec5SDimitry Andric if (LHSName.compare(RHSName) < 0) 43540b57cec5SDimitry Andric Options.erase(Options.end() - 2); 43550b57cec5SDimitry Andric else 43560b57cec5SDimitry Andric Options.erase(Options.end() - 1); 43570b57cec5SDimitry Andric } 43580b57cec5SDimitry Andric 43590b57cec5SDimitry Andric CodeGenFunction CGF(*this); 43600b57cec5SDimitry Andric CGF.EmitMultiVersionResolver(ResolverFunc, Options); 4361a7dea167SDimitry Andric 4362a7dea167SDimitry Andric if (getTarget().supportsIFunc()) { 436381ad6265SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = getMultiversionLinkage(*this, GD); 436481ad6265SDimitry Andric auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD)); 436581ad6265SDimitry Andric 436681ad6265SDimitry Andric // Fix up function declarations that were created for cpu_specific before 436781ad6265SDimitry Andric // cpu_dispatch was known 436881ad6265SDimitry Andric if (!isa<llvm::GlobalIFunc>(IFunc)) { 436981ad6265SDimitry Andric assert(cast<llvm::Function>(IFunc)->isDeclaration()); 437081ad6265SDimitry Andric auto *GI = llvm::GlobalIFunc::create(DeclTy, 0, Linkage, "", ResolverFunc, 437181ad6265SDimitry Andric &getModule()); 437281ad6265SDimitry Andric GI->takeName(IFunc); 437381ad6265SDimitry Andric IFunc->replaceAllUsesWith(GI); 437481ad6265SDimitry Andric IFunc->eraseFromParent(); 437581ad6265SDimitry Andric IFunc = GI; 437681ad6265SDimitry Andric } 437781ad6265SDimitry Andric 4378a7dea167SDimitry Andric std::string AliasName = getMangledNameImpl( 4379a7dea167SDimitry Andric *this, GD, FD, /*OmitMultiVersionMangling=*/true); 4380a7dea167SDimitry Andric llvm::Constant *AliasFunc = GetGlobalValue(AliasName); 4381a7dea167SDimitry Andric if (!AliasFunc) { 438281ad6265SDimitry Andric auto *GA = llvm::GlobalAlias::create(DeclTy, 0, Linkage, AliasName, IFunc, 438381ad6265SDimitry Andric &getModule()); 4384a7dea167SDimitry Andric SetCommonAttributes(GD, GA); 4385a7dea167SDimitry Andric } 4386a7dea167SDimitry Andric } 43870b57cec5SDimitry Andric } 43880b57cec5SDimitry Andric 43890b57cec5SDimitry Andric /// If a dispatcher for the specified mangled name is not in the module, create 43900b57cec5SDimitry Andric /// and return an llvm Function with the specified type. 439181ad6265SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) { 439281ad6265SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 439381ad6265SDimitry Andric assert(FD && "Not a FunctionDecl?"); 439481ad6265SDimitry Andric 43950b57cec5SDimitry Andric std::string MangledName = 43960b57cec5SDimitry Andric getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 43970b57cec5SDimitry Andric 43980b57cec5SDimitry Andric // Holds the name of the resolver, in ifunc mode this is the ifunc (which has 43990b57cec5SDimitry Andric // a separate resolver). 44000b57cec5SDimitry Andric std::string ResolverName = MangledName; 4401c9157d92SDimitry Andric if (getTarget().supportsIFunc()) { 4402*a58f00eaSDimitry Andric if (!FD->isTargetClonesMultiVersion()) 44030b57cec5SDimitry Andric ResolverName += ".ifunc"; 4404c9157d92SDimitry Andric } else if (FD->isTargetMultiVersion()) { 44050b57cec5SDimitry Andric ResolverName += ".resolver"; 4406c9157d92SDimitry Andric } 44070b57cec5SDimitry Andric 440881ad6265SDimitry Andric // If the resolver has already been created, just return it. 44090b57cec5SDimitry Andric if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName)) 44100b57cec5SDimitry Andric return ResolverGV; 44110b57cec5SDimitry Andric 441281ad6265SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 441381ad6265SDimitry Andric llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI); 44140b57cec5SDimitry Andric 441581ad6265SDimitry Andric // The resolver needs to be created. For target and target_clones, defer 441681ad6265SDimitry Andric // creation until the end of the TU. 441781ad6265SDimitry Andric if (FD->isTargetMultiVersion() || FD->isTargetClonesMultiVersion()) 441881ad6265SDimitry Andric MultiVersionFuncs.push_back(GD); 441981ad6265SDimitry Andric 442081ad6265SDimitry Andric // For cpu_specific, don't create an ifunc yet because we don't know if the 442181ad6265SDimitry Andric // cpu_dispatch will be emitted in this translation unit. 442281ad6265SDimitry Andric if (getTarget().supportsIFunc() && !FD->isCPUSpecificMultiVersion()) { 44230b57cec5SDimitry Andric llvm::Type *ResolverType = llvm::FunctionType::get( 4424bdd1243dSDimitry Andric llvm::PointerType::get(DeclTy, 4425bdd1243dSDimitry Andric getTypes().getTargetAddressSpace(FD->getType())), 44260b57cec5SDimitry Andric false); 44270b57cec5SDimitry Andric llvm::Constant *Resolver = GetOrCreateLLVMFunction( 44280b57cec5SDimitry Andric MangledName + ".resolver", ResolverType, GlobalDecl{}, 44290b57cec5SDimitry Andric /*ForVTable=*/false); 4430349cc55cSDimitry Andric llvm::GlobalIFunc *GIF = 4431349cc55cSDimitry Andric llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD), 4432349cc55cSDimitry Andric "", Resolver, &getModule()); 44330b57cec5SDimitry Andric GIF->setName(ResolverName); 44340b57cec5SDimitry Andric SetCommonAttributes(FD, GIF); 44350b57cec5SDimitry Andric 44360b57cec5SDimitry Andric return GIF; 44370b57cec5SDimitry Andric } 44380b57cec5SDimitry Andric 44390b57cec5SDimitry Andric llvm::Constant *Resolver = GetOrCreateLLVMFunction( 44400b57cec5SDimitry Andric ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false); 44410b57cec5SDimitry Andric assert(isa<llvm::GlobalValue>(Resolver) && 44420b57cec5SDimitry Andric "Resolver should be created for the first time"); 44430b57cec5SDimitry Andric SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver)); 44440b57cec5SDimitry Andric return Resolver; 44450b57cec5SDimitry Andric } 44460b57cec5SDimitry Andric 44470b57cec5SDimitry Andric /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 44480b57cec5SDimitry Andric /// module, create and return an llvm Function with the specified type. If there 44490b57cec5SDimitry Andric /// is something in the module with the specified name, return it potentially 44500b57cec5SDimitry Andric /// bitcasted to the right type. 44510b57cec5SDimitry Andric /// 44520b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this. This is used 44530b57cec5SDimitry Andric /// to set the attributes on the function when it is first created. 44540b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( 44550b57cec5SDimitry Andric StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, 44560b57cec5SDimitry Andric bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, 44570b57cec5SDimitry Andric ForDefinition_t IsForDefinition) { 44580b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 44590b57cec5SDimitry Andric 44600b57cec5SDimitry Andric // Any attempts to use a MultiVersion function should result in retrieving 44610b57cec5SDimitry Andric // the iFunc instead. Name Mangling will handle the rest of the changes. 44620b57cec5SDimitry Andric if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) { 44630b57cec5SDimitry Andric // For the device mark the function as one that should be emitted. 4464fe013be4SDimitry Andric if (getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime && 44650b57cec5SDimitry Andric !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() && 44660b57cec5SDimitry Andric !DontDefer && !IsForDefinition) { 44670b57cec5SDimitry Andric if (const FunctionDecl *FDDef = FD->getDefinition()) { 44680b57cec5SDimitry Andric GlobalDecl GDDef; 44690b57cec5SDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef)) 44700b57cec5SDimitry Andric GDDef = GlobalDecl(CD, GD.getCtorType()); 44710b57cec5SDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef)) 44720b57cec5SDimitry Andric GDDef = GlobalDecl(DD, GD.getDtorType()); 44730b57cec5SDimitry Andric else 44740b57cec5SDimitry Andric GDDef = GlobalDecl(FDDef); 44750b57cec5SDimitry Andric EmitGlobal(GDDef); 44760b57cec5SDimitry Andric } 44770b57cec5SDimitry Andric } 44780b57cec5SDimitry Andric 44790b57cec5SDimitry Andric if (FD->isMultiVersion()) { 448004eeddc0SDimitry Andric UpdateMultiVersionNames(GD, FD, MangledName); 44810b57cec5SDimitry Andric if (!IsForDefinition) 448281ad6265SDimitry Andric return GetOrCreateMultiVersionResolver(GD); 44830b57cec5SDimitry Andric } 44840b57cec5SDimitry Andric } 44850b57cec5SDimitry Andric 44860b57cec5SDimitry Andric // Lookup the entry, lazily creating it if necessary. 44870b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 44880b57cec5SDimitry Andric if (Entry) { 44890b57cec5SDimitry Andric if (WeakRefReferences.erase(Entry)) { 44900b57cec5SDimitry Andric const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 44910b57cec5SDimitry Andric if (FD && !FD->hasAttr<WeakAttr>()) 44920b57cec5SDimitry Andric Entry->setLinkage(llvm::Function::ExternalLinkage); 44930b57cec5SDimitry Andric } 44940b57cec5SDimitry Andric 44950b57cec5SDimitry Andric // Handle dropped DLL attributes. 449681ad6265SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() && 449781ad6265SDimitry Andric !shouldMapVisibilityToDLLExport(cast_or_null<NamedDecl>(D))) { 44980b57cec5SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 44990b57cec5SDimitry Andric setDSOLocal(Entry); 45000b57cec5SDimitry Andric } 45010b57cec5SDimitry Andric 45020b57cec5SDimitry Andric // If there are two attempts to define the same mangled name, issue an 45030b57cec5SDimitry Andric // error. 45040b57cec5SDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 45050b57cec5SDimitry Andric GlobalDecl OtherGD; 45060b57cec5SDimitry Andric // Check that GD is not yet in DiagnosedConflictingDefinitions is required 45070b57cec5SDimitry Andric // to make sure that we issue an error only once. 45080b57cec5SDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 45090b57cec5SDimitry Andric (GD.getCanonicalDecl().getDecl() != 45100b57cec5SDimitry Andric OtherGD.getCanonicalDecl().getDecl()) && 45110b57cec5SDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 45120b57cec5SDimitry Andric getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 45130b57cec5SDimitry Andric << MangledName; 45140b57cec5SDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 45150b57cec5SDimitry Andric diag::note_previous_definition); 45160b57cec5SDimitry Andric } 45170b57cec5SDimitry Andric } 45180b57cec5SDimitry Andric 45190b57cec5SDimitry Andric if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 45205ffd83dbSDimitry Andric (Entry->getValueType() == Ty)) { 45210b57cec5SDimitry Andric return Entry; 45220b57cec5SDimitry Andric } 45230b57cec5SDimitry Andric 45240b57cec5SDimitry Andric // Make sure the result is of the correct type. 45250b57cec5SDimitry Andric // (If function is requested for a definition, we always need to create a new 45260b57cec5SDimitry Andric // function, not just return a bitcast.) 45270b57cec5SDimitry Andric if (!IsForDefinition) 4528c9157d92SDimitry Andric return Entry; 45290b57cec5SDimitry Andric } 45300b57cec5SDimitry Andric 45310b57cec5SDimitry Andric // This function doesn't have a complete type (for example, the return 45320b57cec5SDimitry Andric // type is an incomplete struct). Use a fake type instead, and make 45330b57cec5SDimitry Andric // sure not to try to set attributes. 45340b57cec5SDimitry Andric bool IsIncompleteFunction = false; 45350b57cec5SDimitry Andric 45360b57cec5SDimitry Andric llvm::FunctionType *FTy; 45370b57cec5SDimitry Andric if (isa<llvm::FunctionType>(Ty)) { 45380b57cec5SDimitry Andric FTy = cast<llvm::FunctionType>(Ty); 45390b57cec5SDimitry Andric } else { 45400b57cec5SDimitry Andric FTy = llvm::FunctionType::get(VoidTy, false); 45410b57cec5SDimitry Andric IsIncompleteFunction = true; 45420b57cec5SDimitry Andric } 45430b57cec5SDimitry Andric 45440b57cec5SDimitry Andric llvm::Function *F = 45450b57cec5SDimitry Andric llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 45460b57cec5SDimitry Andric Entry ? StringRef() : MangledName, &getModule()); 45470b57cec5SDimitry Andric 4548c9157d92SDimitry Andric // Store the declaration associated with this function so it is potentially 4549c9157d92SDimitry Andric // updated by further declarations or definitions and emitted at the end. 4550c9157d92SDimitry Andric if (D && D->hasAttr<AnnotateAttr>()) 4551c9157d92SDimitry Andric DeferredAnnotations[MangledName] = cast<ValueDecl>(D); 4552c9157d92SDimitry Andric 45530b57cec5SDimitry Andric // If we already created a function with the same mangled name (but different 45540b57cec5SDimitry Andric // type) before, take its name and add it to the list of functions to be 45550b57cec5SDimitry Andric // replaced with F at the end of CodeGen. 45560b57cec5SDimitry Andric // 45570b57cec5SDimitry Andric // This happens if there is a prototype for a function (e.g. "int f()") and 45580b57cec5SDimitry Andric // then a definition of a different type (e.g. "int f(int x)"). 45590b57cec5SDimitry Andric if (Entry) { 45600b57cec5SDimitry Andric F->takeName(Entry); 45610b57cec5SDimitry Andric 45620b57cec5SDimitry Andric // This might be an implementation of a function without a prototype, in 45630b57cec5SDimitry Andric // which case, try to do special replacement of calls which match the new 45640b57cec5SDimitry Andric // prototype. The really key thing here is that we also potentially drop 45650b57cec5SDimitry Andric // arguments from the call site so as to make a direct call, which makes the 45660b57cec5SDimitry Andric // inliner happier and suppresses a number of optimizer warnings (!) about 45670b57cec5SDimitry Andric // dropping arguments. 45680b57cec5SDimitry Andric if (!Entry->use_empty()) { 45690b57cec5SDimitry Andric ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 45700b57cec5SDimitry Andric Entry->removeDeadConstantUsers(); 45710b57cec5SDimitry Andric } 45720b57cec5SDimitry Andric 4573c9157d92SDimitry Andric addGlobalValReplacement(Entry, F); 45740b57cec5SDimitry Andric } 45750b57cec5SDimitry Andric 45760b57cec5SDimitry Andric assert(F->getName() == MangledName && "name was uniqued!"); 45770b57cec5SDimitry Andric if (D) 45780b57cec5SDimitry Andric SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 4579349cc55cSDimitry Andric if (ExtraAttrs.hasFnAttrs()) { 458004eeddc0SDimitry Andric llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs()); 4581349cc55cSDimitry Andric F->addFnAttrs(B); 45820b57cec5SDimitry Andric } 45830b57cec5SDimitry Andric 45840b57cec5SDimitry Andric if (!DontDefer) { 45850b57cec5SDimitry Andric // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 45860b57cec5SDimitry Andric // each other bottoming out with the base dtor. Therefore we emit non-base 45870b57cec5SDimitry Andric // dtors on usage, even if there is no dtor definition in the TU. 4588bdd1243dSDimitry Andric if (isa_and_nonnull<CXXDestructorDecl>(D) && 45890b57cec5SDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 45900b57cec5SDimitry Andric GD.getDtorType())) 45910b57cec5SDimitry Andric addDeferredDeclToEmit(GD); 45920b57cec5SDimitry Andric 45930b57cec5SDimitry Andric // This is the first use or definition of a mangled name. If there is a 45940b57cec5SDimitry Andric // deferred decl with this name, remember that we need to emit it at the end 45950b57cec5SDimitry Andric // of the file. 45960b57cec5SDimitry Andric auto DDI = DeferredDecls.find(MangledName); 45970b57cec5SDimitry Andric if (DDI != DeferredDecls.end()) { 45980b57cec5SDimitry Andric // Move the potentially referenced deferred decl to the 45990b57cec5SDimitry Andric // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 46000b57cec5SDimitry Andric // don't need it anymore). 46010b57cec5SDimitry Andric addDeferredDeclToEmit(DDI->second); 46020b57cec5SDimitry Andric DeferredDecls.erase(DDI); 46030b57cec5SDimitry Andric 46040b57cec5SDimitry Andric // Otherwise, there are cases we have to worry about where we're 46050b57cec5SDimitry Andric // using a declaration for which we must emit a definition but where 46060b57cec5SDimitry Andric // we might not find a top-level definition: 46070b57cec5SDimitry Andric // - member functions defined inline in their classes 46080b57cec5SDimitry Andric // - friend functions defined inline in some class 46090b57cec5SDimitry Andric // - special member functions with implicit definitions 46100b57cec5SDimitry Andric // If we ever change our AST traversal to walk into class methods, 46110b57cec5SDimitry Andric // this will be unnecessary. 46120b57cec5SDimitry Andric // 46130b57cec5SDimitry Andric // We also don't emit a definition for a function if it's going to be an 46140b57cec5SDimitry Andric // entry in a vtable, unless it's already marked as used. 46150b57cec5SDimitry Andric } else if (getLangOpts().CPlusPlus && D) { 46160b57cec5SDimitry Andric // Look for a declaration that's lexically in a record. 46170b57cec5SDimitry Andric for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 46180b57cec5SDimitry Andric FD = FD->getPreviousDecl()) { 46190b57cec5SDimitry Andric if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 46200b57cec5SDimitry Andric if (FD->doesThisDeclarationHaveABody()) { 46210b57cec5SDimitry Andric addDeferredDeclToEmit(GD.getWithDecl(FD)); 46220b57cec5SDimitry Andric break; 46230b57cec5SDimitry Andric } 46240b57cec5SDimitry Andric } 46250b57cec5SDimitry Andric } 46260b57cec5SDimitry Andric } 46270b57cec5SDimitry Andric } 46280b57cec5SDimitry Andric 46290b57cec5SDimitry Andric // Make sure the result is of the requested type. 46300b57cec5SDimitry Andric if (!IsIncompleteFunction) { 46315ffd83dbSDimitry Andric assert(F->getFunctionType() == Ty); 46320b57cec5SDimitry Andric return F; 46330b57cec5SDimitry Andric } 46340b57cec5SDimitry Andric 4635c9157d92SDimitry Andric return F; 46360b57cec5SDimitry Andric } 46370b57cec5SDimitry Andric 46380b57cec5SDimitry Andric /// GetAddrOfFunction - Return the address of the given function. If Ty is 46390b57cec5SDimitry Andric /// non-null, then this function will use the specified type if it has to 46400b57cec5SDimitry Andric /// create it (this occurs when we see a definition of the function). 4641fe013be4SDimitry Andric llvm::Constant * 4642fe013be4SDimitry Andric CodeGenModule::GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty, bool ForVTable, 46430b57cec5SDimitry Andric bool DontDefer, 46440b57cec5SDimitry Andric ForDefinition_t IsForDefinition) { 46450b57cec5SDimitry Andric // If there was no specific requested type, just convert it now. 46460b57cec5SDimitry Andric if (!Ty) { 46470b57cec5SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 46480b57cec5SDimitry Andric Ty = getTypes().ConvertType(FD->getType()); 46490b57cec5SDimitry Andric } 46500b57cec5SDimitry Andric 46510b57cec5SDimitry Andric // Devirtualized destructor calls may come through here instead of via 46520b57cec5SDimitry Andric // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead 46530b57cec5SDimitry Andric // of the complete destructor when necessary. 46540b57cec5SDimitry Andric if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) { 46550b57cec5SDimitry Andric if (getTarget().getCXXABI().isMicrosoft() && 46560b57cec5SDimitry Andric GD.getDtorType() == Dtor_Complete && 46570b57cec5SDimitry Andric DD->getParent()->getNumVBases() == 0) 46580b57cec5SDimitry Andric GD = GlobalDecl(DD, Dtor_Base); 46590b57cec5SDimitry Andric } 46600b57cec5SDimitry Andric 46610b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 4662fe6060f1SDimitry Andric auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 46630b57cec5SDimitry Andric /*IsThunk=*/false, llvm::AttributeList(), 46640b57cec5SDimitry Andric IsForDefinition); 4665fe6060f1SDimitry Andric // Returns kernel handle for HIP kernel stub function. 4666fe6060f1SDimitry Andric if (LangOpts.CUDA && !LangOpts.CUDAIsDevice && 4667fe6060f1SDimitry Andric cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) { 4668fe6060f1SDimitry Andric auto *Handle = getCUDARuntime().getKernelHandle( 4669fe6060f1SDimitry Andric cast<llvm::Function>(F->stripPointerCasts()), GD); 4670fe6060f1SDimitry Andric if (IsForDefinition) 4671fe6060f1SDimitry Andric return F; 4672c9157d92SDimitry Andric return Handle; 4673fe6060f1SDimitry Andric } 4674fe6060f1SDimitry Andric return F; 46750b57cec5SDimitry Andric } 46760b57cec5SDimitry Andric 46770eae32dcSDimitry Andric llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) { 46780eae32dcSDimitry Andric llvm::GlobalValue *F = 46790eae32dcSDimitry Andric cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts()); 46800eae32dcSDimitry Andric 4681c9157d92SDimitry Andric return llvm::NoCFIValue::get(F); 46820eae32dcSDimitry Andric } 46830eae32dcSDimitry Andric 46840b57cec5SDimitry Andric static const FunctionDecl * 46850b57cec5SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { 46860b57cec5SDimitry Andric TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 46870b57cec5SDimitry Andric DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 46880b57cec5SDimitry Andric 46890b57cec5SDimitry Andric IdentifierInfo &CII = C.Idents.get(Name); 4690fe6060f1SDimitry Andric for (const auto *Result : DC->lookup(&CII)) 4691fe6060f1SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 46920b57cec5SDimitry Andric return FD; 46930b57cec5SDimitry Andric 46940b57cec5SDimitry Andric if (!C.getLangOpts().CPlusPlus) 46950b57cec5SDimitry Andric return nullptr; 46960b57cec5SDimitry Andric 46970b57cec5SDimitry Andric // Demangle the premangled name from getTerminateFn() 46980b57cec5SDimitry Andric IdentifierInfo &CXXII = 46990b57cec5SDimitry Andric (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ") 47000b57cec5SDimitry Andric ? C.Idents.get("terminate") 47010b57cec5SDimitry Andric : C.Idents.get(Name); 47020b57cec5SDimitry Andric 47030b57cec5SDimitry Andric for (const auto &N : {"__cxxabiv1", "std"}) { 47040b57cec5SDimitry Andric IdentifierInfo &NS = C.Idents.get(N); 4705fe6060f1SDimitry Andric for (const auto *Result : DC->lookup(&NS)) { 4706fe6060f1SDimitry Andric const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); 4707fe6060f1SDimitry Andric if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result)) 4708fe6060f1SDimitry Andric for (const auto *Result : LSD->lookup(&NS)) 47090b57cec5SDimitry Andric if ((ND = dyn_cast<NamespaceDecl>(Result))) 47100b57cec5SDimitry Andric break; 47110b57cec5SDimitry Andric 47120b57cec5SDimitry Andric if (ND) 4713fe6060f1SDimitry Andric for (const auto *Result : ND->lookup(&CXXII)) 47140b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 47150b57cec5SDimitry Andric return FD; 47160b57cec5SDimitry Andric } 47170b57cec5SDimitry Andric } 47180b57cec5SDimitry Andric 47190b57cec5SDimitry Andric return nullptr; 47200b57cec5SDimitry Andric } 47210b57cec5SDimitry Andric 47220b57cec5SDimitry Andric /// CreateRuntimeFunction - Create a new runtime function with the specified 47230b57cec5SDimitry Andric /// type and name. 47240b57cec5SDimitry Andric llvm::FunctionCallee 47250b57cec5SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, 4726480093f4SDimitry Andric llvm::AttributeList ExtraAttrs, bool Local, 4727480093f4SDimitry Andric bool AssumeConvergent) { 4728480093f4SDimitry Andric if (AssumeConvergent) { 4729480093f4SDimitry Andric ExtraAttrs = 4730349cc55cSDimitry Andric ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent); 4731480093f4SDimitry Andric } 4732480093f4SDimitry Andric 47330b57cec5SDimitry Andric llvm::Constant *C = 47340b57cec5SDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 47350b57cec5SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, 47360b57cec5SDimitry Andric ExtraAttrs); 47370b57cec5SDimitry Andric 47380b57cec5SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) { 47390b57cec5SDimitry Andric if (F->empty()) { 47400b57cec5SDimitry Andric F->setCallingConv(getRuntimeCC()); 47410b57cec5SDimitry Andric 47420b57cec5SDimitry Andric // In Windows Itanium environments, try to mark runtime functions 47430b57cec5SDimitry Andric // dllimport. For Mingw and MSVC, don't. We don't really know if the user 47440b57cec5SDimitry Andric // will link their standard library statically or dynamically. Marking 47450b57cec5SDimitry Andric // functions imported when they are not imported can cause linker errors 47460b57cec5SDimitry Andric // and warnings. 47470b57cec5SDimitry Andric if (!Local && getTriple().isWindowsItaniumEnvironment() && 47480b57cec5SDimitry Andric !getCodeGenOpts().LTOVisibilityPublicStd) { 47490b57cec5SDimitry Andric const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); 47500b57cec5SDimitry Andric if (!FD || FD->hasAttr<DLLImportAttr>()) { 47510b57cec5SDimitry Andric F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 47520b57cec5SDimitry Andric F->setLinkage(llvm::GlobalValue::ExternalLinkage); 47530b57cec5SDimitry Andric } 47540b57cec5SDimitry Andric } 47550b57cec5SDimitry Andric setDSOLocal(F); 47560b57cec5SDimitry Andric } 47570b57cec5SDimitry Andric } 47580b57cec5SDimitry Andric 47590b57cec5SDimitry Andric return {FTy, C}; 47600b57cec5SDimitry Andric } 47610b57cec5SDimitry Andric 47620b57cec5SDimitry Andric /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 4763fe6060f1SDimitry Andric /// create and return an llvm GlobalVariable with the specified type and address 4764fe6060f1SDimitry Andric /// space. If there is something in the module with the specified name, return 4765fe6060f1SDimitry Andric /// it potentially bitcasted to the right type. 47660b57cec5SDimitry Andric /// 47670b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this. This is used 47680b57cec5SDimitry Andric /// to set the attributes on the global when it is first created. 47690b57cec5SDimitry Andric /// 47700b57cec5SDimitry Andric /// If IsForDefinition is true, it is guaranteed that an actual global with 47710b57cec5SDimitry Andric /// type Ty will be returned, not conversion of a variable with the same 47720b57cec5SDimitry Andric /// mangled name but some other type. 47730b57cec5SDimitry Andric llvm::Constant * 4774fe6060f1SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, 4775349cc55cSDimitry Andric LangAS AddrSpace, const VarDecl *D, 47760b57cec5SDimitry Andric ForDefinition_t IsForDefinition) { 47770b57cec5SDimitry Andric // Lookup the entry, lazily creating it if necessary. 47780b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4779349cc55cSDimitry Andric unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace); 47800b57cec5SDimitry Andric if (Entry) { 47810b57cec5SDimitry Andric if (WeakRefReferences.erase(Entry)) { 47820b57cec5SDimitry Andric if (D && !D->hasAttr<WeakAttr>()) 47830b57cec5SDimitry Andric Entry->setLinkage(llvm::Function::ExternalLinkage); 47840b57cec5SDimitry Andric } 47850b57cec5SDimitry Andric 47860b57cec5SDimitry Andric // Handle dropped DLL attributes. 478781ad6265SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() && 478881ad6265SDimitry Andric !shouldMapVisibilityToDLLExport(D)) 47890b57cec5SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 47900b57cec5SDimitry Andric 47910b57cec5SDimitry Andric if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D) 47920b57cec5SDimitry Andric getOpenMPRuntime().registerTargetGlobalVariable(D, Entry); 47930b57cec5SDimitry Andric 4794349cc55cSDimitry Andric if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS) 47950b57cec5SDimitry Andric return Entry; 47960b57cec5SDimitry Andric 47970b57cec5SDimitry Andric // If there are two attempts to define the same mangled name, issue an 47980b57cec5SDimitry Andric // error. 47990b57cec5SDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 48000b57cec5SDimitry Andric GlobalDecl OtherGD; 48010b57cec5SDimitry Andric const VarDecl *OtherD; 48020b57cec5SDimitry Andric 48030b57cec5SDimitry Andric // Check that D is not yet in DiagnosedConflictingDefinitions is required 48040b57cec5SDimitry Andric // to make sure that we issue an error only once. 48050b57cec5SDimitry Andric if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 48060b57cec5SDimitry Andric (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 48070b57cec5SDimitry Andric (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 48080b57cec5SDimitry Andric OtherD->hasInit() && 48090b57cec5SDimitry Andric DiagnosedConflictingDefinitions.insert(D).second) { 48100b57cec5SDimitry Andric getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 48110b57cec5SDimitry Andric << MangledName; 48120b57cec5SDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 48130b57cec5SDimitry Andric diag::note_previous_definition); 48140b57cec5SDimitry Andric } 48150b57cec5SDimitry Andric } 48160b57cec5SDimitry Andric 48170b57cec5SDimitry Andric // Make sure the result is of the correct type. 4818c9157d92SDimitry Andric if (Entry->getType()->getAddressSpace() != TargetAS) 4819c9157d92SDimitry Andric return llvm::ConstantExpr::getAddrSpaceCast( 4820c9157d92SDimitry Andric Entry, llvm::PointerType::get(Ty->getContext(), TargetAS)); 48210b57cec5SDimitry Andric 48220b57cec5SDimitry Andric // (If global is requested for a definition, we always need to create a new 48230b57cec5SDimitry Andric // global, not just return a bitcast.) 48240b57cec5SDimitry Andric if (!IsForDefinition) 4825c9157d92SDimitry Andric return Entry; 48260b57cec5SDimitry Andric } 48270b57cec5SDimitry Andric 4828fe6060f1SDimitry Andric auto DAddrSpace = GetGlobalVarAddressSpace(D); 48290b57cec5SDimitry Andric 48300b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 4831fe6060f1SDimitry Andric getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr, 4832fe6060f1SDimitry Andric MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal, 4833349cc55cSDimitry Andric getContext().getTargetAddressSpace(DAddrSpace)); 48340b57cec5SDimitry Andric 48350b57cec5SDimitry Andric // If we already created a global with the same mangled name (but different 48360b57cec5SDimitry Andric // type) before, take its name and remove it from its parent. 48370b57cec5SDimitry Andric if (Entry) { 48380b57cec5SDimitry Andric GV->takeName(Entry); 48390b57cec5SDimitry Andric 48400b57cec5SDimitry Andric if (!Entry->use_empty()) { 4841c9157d92SDimitry Andric Entry->replaceAllUsesWith(GV); 48420b57cec5SDimitry Andric } 48430b57cec5SDimitry Andric 48440b57cec5SDimitry Andric Entry->eraseFromParent(); 48450b57cec5SDimitry Andric } 48460b57cec5SDimitry Andric 48470b57cec5SDimitry Andric // This is the first use or definition of a mangled name. If there is a 48480b57cec5SDimitry Andric // deferred decl with this name, remember that we need to emit it at the end 48490b57cec5SDimitry Andric // of the file. 48500b57cec5SDimitry Andric auto DDI = DeferredDecls.find(MangledName); 48510b57cec5SDimitry Andric if (DDI != DeferredDecls.end()) { 48520b57cec5SDimitry Andric // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 48530b57cec5SDimitry Andric // list, and remove it from DeferredDecls (since we don't need it anymore). 48540b57cec5SDimitry Andric addDeferredDeclToEmit(DDI->second); 48550b57cec5SDimitry Andric DeferredDecls.erase(DDI); 48560b57cec5SDimitry Andric } 48570b57cec5SDimitry Andric 48580b57cec5SDimitry Andric // Handle things which are present even on external declarations. 48590b57cec5SDimitry Andric if (D) { 48600b57cec5SDimitry Andric if (LangOpts.OpenMP && !LangOpts.OpenMPSimd) 48610b57cec5SDimitry Andric getOpenMPRuntime().registerTargetGlobalVariable(D, GV); 48620b57cec5SDimitry Andric 48630b57cec5SDimitry Andric // FIXME: This code is overly simple and should be merged with other global 48640b57cec5SDimitry Andric // handling. 4865c9157d92SDimitry Andric GV->setConstant(D->getType().isConstantStorage(getContext(), false, false)); 48660b57cec5SDimitry Andric 4867a7dea167SDimitry Andric GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); 48680b57cec5SDimitry Andric 48690b57cec5SDimitry Andric setLinkageForGV(GV, D); 48700b57cec5SDimitry Andric 48710b57cec5SDimitry Andric if (D->getTLSKind()) { 48720b57cec5SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 48730b57cec5SDimitry Andric CXXThreadLocals.push_back(D); 48740b57cec5SDimitry Andric setTLSMode(GV, *D); 48750b57cec5SDimitry Andric } 48760b57cec5SDimitry Andric 48770b57cec5SDimitry Andric setGVProperties(GV, D); 48780b57cec5SDimitry Andric 48790b57cec5SDimitry Andric // If required by the ABI, treat declarations of static data members with 48800b57cec5SDimitry Andric // inline initializers as definitions. 48810b57cec5SDimitry Andric if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 48820b57cec5SDimitry Andric EmitGlobalVarDefinition(D); 48830b57cec5SDimitry Andric } 48840b57cec5SDimitry Andric 48850b57cec5SDimitry Andric // Emit section information for extern variables. 48860b57cec5SDimitry Andric if (D->hasExternalStorage()) { 48870b57cec5SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 48880b57cec5SDimitry Andric GV->setSection(SA->getName()); 48890b57cec5SDimitry Andric } 48900b57cec5SDimitry Andric 48910b57cec5SDimitry Andric // Handle XCore specific ABI requirements. 48920b57cec5SDimitry Andric if (getTriple().getArch() == llvm::Triple::xcore && 48930b57cec5SDimitry Andric D->getLanguageLinkage() == CLanguageLinkage && 48940b57cec5SDimitry Andric D->getType().isConstant(Context) && 48950b57cec5SDimitry Andric isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 48960b57cec5SDimitry Andric GV->setSection(".cp.rodata"); 48970b57cec5SDimitry Andric 4898cdc20ff6SDimitry Andric // Handle code model attribute 4899cdc20ff6SDimitry Andric if (const auto *CMA = D->getAttr<CodeModelAttr>()) 4900cdc20ff6SDimitry Andric GV->setCodeModel(CMA->getModel()); 4901cdc20ff6SDimitry Andric 49020b57cec5SDimitry Andric // Check if we a have a const declaration with an initializer, we may be 49030b57cec5SDimitry Andric // able to emit it as available_externally to expose it's value to the 49040b57cec5SDimitry Andric // optimizer. 49050b57cec5SDimitry Andric if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() && 49060b57cec5SDimitry Andric D->getType().isConstQualified() && !GV->hasInitializer() && 49070b57cec5SDimitry Andric !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) { 49080b57cec5SDimitry Andric const auto *Record = 49090b57cec5SDimitry Andric Context.getBaseElementType(D->getType())->getAsCXXRecordDecl(); 49100b57cec5SDimitry Andric bool HasMutableFields = Record && Record->hasMutableFields(); 49110b57cec5SDimitry Andric if (!HasMutableFields) { 49120b57cec5SDimitry Andric const VarDecl *InitDecl; 49130b57cec5SDimitry Andric const Expr *InitExpr = D->getAnyInitializer(InitDecl); 49140b57cec5SDimitry Andric if (InitExpr) { 49150b57cec5SDimitry Andric ConstantEmitter emitter(*this); 49160b57cec5SDimitry Andric llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl); 49170b57cec5SDimitry Andric if (Init) { 49180b57cec5SDimitry Andric auto *InitType = Init->getType(); 49195ffd83dbSDimitry Andric if (GV->getValueType() != InitType) { 49200b57cec5SDimitry Andric // The type of the initializer does not match the definition. 49210b57cec5SDimitry Andric // This happens when an initializer has a different type from 49220b57cec5SDimitry Andric // the type of the global (because of padding at the end of a 49230b57cec5SDimitry Andric // structure for instance). 49240b57cec5SDimitry Andric GV->setName(StringRef()); 49250b57cec5SDimitry Andric // Make a new global with the correct type, this is now guaranteed 49260b57cec5SDimitry Andric // to work. 49270b57cec5SDimitry Andric auto *NewGV = cast<llvm::GlobalVariable>( 4928a7dea167SDimitry Andric GetAddrOfGlobalVar(D, InitType, IsForDefinition) 4929a7dea167SDimitry Andric ->stripPointerCasts()); 49300b57cec5SDimitry Andric 49310b57cec5SDimitry Andric // Erase the old global, since it is no longer used. 49320b57cec5SDimitry Andric GV->eraseFromParent(); 49330b57cec5SDimitry Andric GV = NewGV; 49340b57cec5SDimitry Andric } else { 49350b57cec5SDimitry Andric GV->setInitializer(Init); 49360b57cec5SDimitry Andric GV->setConstant(true); 49370b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 49380b57cec5SDimitry Andric } 49390b57cec5SDimitry Andric emitter.finalize(GV); 49400b57cec5SDimitry Andric } 49410b57cec5SDimitry Andric } 49420b57cec5SDimitry Andric } 49430b57cec5SDimitry Andric } 49440b57cec5SDimitry Andric } 49450b57cec5SDimitry Andric 4946fe013be4SDimitry Andric if (D && 4947fe013be4SDimitry Andric D->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly) { 4948480093f4SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(D, GV, *this); 4949fe6060f1SDimitry Andric // External HIP managed variables needed to be recorded for transformation 4950fe6060f1SDimitry Andric // in both device and host compilations. 4951fe6060f1SDimitry Andric if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() && 4952fe6060f1SDimitry Andric D->hasExternalStorage()) 4953fe6060f1SDimitry Andric getCUDARuntime().handleVarRegistration(D, *GV); 4954fe6060f1SDimitry Andric } 4955480093f4SDimitry Andric 4956753f127fSDimitry Andric if (D) 4957753f127fSDimitry Andric SanitizerMD->reportGlobal(GV, *D); 4958753f127fSDimitry Andric 49590b57cec5SDimitry Andric LangAS ExpectedAS = 49600b57cec5SDimitry Andric D ? D->getType().getAddressSpace() 49610b57cec5SDimitry Andric : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default); 4962349cc55cSDimitry Andric assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS); 4963fe6060f1SDimitry Andric if (DAddrSpace != ExpectedAS) { 4964fe6060f1SDimitry Andric return getTargetCodeGenInfo().performAddrSpaceCast( 4965c9157d92SDimitry Andric *this, GV, DAddrSpace, ExpectedAS, 4966c9157d92SDimitry Andric llvm::PointerType::get(getLLVMContext(), TargetAS)); 4967fe6060f1SDimitry Andric } 49680b57cec5SDimitry Andric 49690b57cec5SDimitry Andric return GV; 49700b57cec5SDimitry Andric } 49710b57cec5SDimitry Andric 49720b57cec5SDimitry Andric llvm::Constant * 49735ffd83dbSDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) { 49740b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 49755ffd83dbSDimitry Andric 49760b57cec5SDimitry Andric if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 49770b57cec5SDimitry Andric return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr, 49780b57cec5SDimitry Andric /*DontDefer=*/false, IsForDefinition); 49795ffd83dbSDimitry Andric 49805ffd83dbSDimitry Andric if (isa<CXXMethodDecl>(D)) { 49815ffd83dbSDimitry Andric auto FInfo = 49825ffd83dbSDimitry Andric &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D)); 49830b57cec5SDimitry Andric auto Ty = getTypes().GetFunctionType(*FInfo); 49840b57cec5SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 49850b57cec5SDimitry Andric IsForDefinition); 49865ffd83dbSDimitry Andric } 49875ffd83dbSDimitry Andric 49885ffd83dbSDimitry Andric if (isa<FunctionDecl>(D)) { 49890b57cec5SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 49900b57cec5SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 49910b57cec5SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 49920b57cec5SDimitry Andric IsForDefinition); 49935ffd83dbSDimitry Andric } 49945ffd83dbSDimitry Andric 49955ffd83dbSDimitry Andric return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition); 49960b57cec5SDimitry Andric } 49970b57cec5SDimitry Andric 49980b57cec5SDimitry Andric llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable( 49990b57cec5SDimitry Andric StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, 5000bdd1243dSDimitry Andric llvm::Align Alignment) { 50010b57cec5SDimitry Andric llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 50020b57cec5SDimitry Andric llvm::GlobalVariable *OldGV = nullptr; 50030b57cec5SDimitry Andric 50040b57cec5SDimitry Andric if (GV) { 50050b57cec5SDimitry Andric // Check if the variable has the right type. 50065ffd83dbSDimitry Andric if (GV->getValueType() == Ty) 50070b57cec5SDimitry Andric return GV; 50080b57cec5SDimitry Andric 50090b57cec5SDimitry Andric // Because C++ name mangling, the only way we can end up with an already 50100b57cec5SDimitry Andric // existing global with the same name is if it has been declared extern "C". 50110b57cec5SDimitry Andric assert(GV->isDeclaration() && "Declaration has wrong type!"); 50120b57cec5SDimitry Andric OldGV = GV; 50130b57cec5SDimitry Andric } 50140b57cec5SDimitry Andric 50150b57cec5SDimitry Andric // Create a new variable. 50160b57cec5SDimitry Andric GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 50170b57cec5SDimitry Andric Linkage, nullptr, Name); 50180b57cec5SDimitry Andric 50190b57cec5SDimitry Andric if (OldGV) { 50200b57cec5SDimitry Andric // Replace occurrences of the old variable if needed. 50210b57cec5SDimitry Andric GV->takeName(OldGV); 50220b57cec5SDimitry Andric 50230b57cec5SDimitry Andric if (!OldGV->use_empty()) { 5024c9157d92SDimitry Andric OldGV->replaceAllUsesWith(GV); 50250b57cec5SDimitry Andric } 50260b57cec5SDimitry Andric 50270b57cec5SDimitry Andric OldGV->eraseFromParent(); 50280b57cec5SDimitry Andric } 50290b57cec5SDimitry Andric 50300b57cec5SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker() && 50310b57cec5SDimitry Andric !GV->hasAvailableExternallyLinkage()) 50320b57cec5SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 50330b57cec5SDimitry Andric 5034bdd1243dSDimitry Andric GV->setAlignment(Alignment); 50350b57cec5SDimitry Andric 50360b57cec5SDimitry Andric return GV; 50370b57cec5SDimitry Andric } 50380b57cec5SDimitry Andric 50390b57cec5SDimitry Andric /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 50400b57cec5SDimitry Andric /// given global variable. If Ty is non-null and if the global doesn't exist, 50410b57cec5SDimitry Andric /// then it will be created with the specified type instead of whatever the 50420b57cec5SDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guaranteed 50430b57cec5SDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a 50440b57cec5SDimitry Andric /// variable with the same mangled name but some other type. 50450b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 50460b57cec5SDimitry Andric llvm::Type *Ty, 50470b57cec5SDimitry Andric ForDefinition_t IsForDefinition) { 50480b57cec5SDimitry Andric assert(D->hasGlobalStorage() && "Not a global variable"); 50490b57cec5SDimitry Andric QualType ASTTy = D->getType(); 50500b57cec5SDimitry Andric if (!Ty) 50510b57cec5SDimitry Andric Ty = getTypes().ConvertTypeForMem(ASTTy); 50520b57cec5SDimitry Andric 50530b57cec5SDimitry Andric StringRef MangledName = getMangledName(D); 5054349cc55cSDimitry Andric return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D, 5055fe6060f1SDimitry Andric IsForDefinition); 50560b57cec5SDimitry Andric } 50570b57cec5SDimitry Andric 50580b57cec5SDimitry Andric /// CreateRuntimeVariable - Create a new runtime global variable with the 50590b57cec5SDimitry Andric /// specified type and name. 50600b57cec5SDimitry Andric llvm::Constant * 50610b57cec5SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 50620b57cec5SDimitry Andric StringRef Name) { 5063349cc55cSDimitry Andric LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global 5064349cc55cSDimitry Andric : LangAS::Default; 5065fe6060f1SDimitry Andric auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr); 50660b57cec5SDimitry Andric setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts())); 50670b57cec5SDimitry Andric return Ret; 50680b57cec5SDimitry Andric } 50690b57cec5SDimitry Andric 50700b57cec5SDimitry Andric void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 50710b57cec5SDimitry Andric assert(!D->getInit() && "Cannot emit definite definitions here!"); 50720b57cec5SDimitry Andric 50730b57cec5SDimitry Andric StringRef MangledName = getMangledName(D); 50740b57cec5SDimitry Andric llvm::GlobalValue *GV = GetGlobalValue(MangledName); 50750b57cec5SDimitry Andric 50760b57cec5SDimitry Andric // We already have a definition, not declaration, with the same mangled name. 50770b57cec5SDimitry Andric // Emitting of declaration is not required (and actually overwrites emitted 50780b57cec5SDimitry Andric // definition). 50790b57cec5SDimitry Andric if (GV && !GV->isDeclaration()) 50800b57cec5SDimitry Andric return; 50810b57cec5SDimitry Andric 50820b57cec5SDimitry Andric // If we have not seen a reference to this variable yet, place it into the 50830b57cec5SDimitry Andric // deferred declarations table to be emitted if needed later. 50840b57cec5SDimitry Andric if (!MustBeEmitted(D) && !GV) { 50850b57cec5SDimitry Andric DeferredDecls[MangledName] = D; 50860b57cec5SDimitry Andric return; 50870b57cec5SDimitry Andric } 50880b57cec5SDimitry Andric 50890b57cec5SDimitry Andric // The tentative definition is the only definition. 50900b57cec5SDimitry Andric EmitGlobalVarDefinition(D); 50910b57cec5SDimitry Andric } 50920b57cec5SDimitry Andric 5093480093f4SDimitry Andric void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) { 5094480093f4SDimitry Andric EmitExternalVarDeclaration(D); 5095480093f4SDimitry Andric } 5096480093f4SDimitry Andric 50970b57cec5SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 50980b57cec5SDimitry Andric return Context.toCharUnitsFromBits( 50990b57cec5SDimitry Andric getDataLayout().getTypeStoreSizeInBits(Ty)); 51000b57cec5SDimitry Andric } 51010b57cec5SDimitry Andric 51020b57cec5SDimitry Andric LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { 51030b57cec5SDimitry Andric if (LangOpts.OpenCL) { 5104349cc55cSDimitry Andric LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global; 5105349cc55cSDimitry Andric assert(AS == LangAS::opencl_global || 5106349cc55cSDimitry Andric AS == LangAS::opencl_global_device || 5107349cc55cSDimitry Andric AS == LangAS::opencl_global_host || 5108349cc55cSDimitry Andric AS == LangAS::opencl_constant || 5109349cc55cSDimitry Andric AS == LangAS::opencl_local || 5110349cc55cSDimitry Andric AS >= LangAS::FirstTargetAddressSpace); 5111349cc55cSDimitry Andric return AS; 51120b57cec5SDimitry Andric } 51130b57cec5SDimitry Andric 5114fe6060f1SDimitry Andric if (LangOpts.SYCLIsDevice && 5115fe6060f1SDimitry Andric (!D || D->getType().getAddressSpace() == LangAS::Default)) 5116fe6060f1SDimitry Andric return LangAS::sycl_global; 5117fe6060f1SDimitry Andric 51180b57cec5SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { 5119fe013be4SDimitry Andric if (D) { 5120fe013be4SDimitry Andric if (D->hasAttr<CUDAConstantAttr>()) 51210b57cec5SDimitry Andric return LangAS::cuda_constant; 5122fe013be4SDimitry Andric if (D->hasAttr<CUDASharedAttr>()) 51230b57cec5SDimitry Andric return LangAS::cuda_shared; 5124fe013be4SDimitry Andric if (D->hasAttr<CUDADeviceAttr>()) 51250b57cec5SDimitry Andric return LangAS::cuda_device; 5126fe013be4SDimitry Andric if (D->getType().isConstQualified()) 51270b57cec5SDimitry Andric return LangAS::cuda_constant; 5128fe013be4SDimitry Andric } 51290b57cec5SDimitry Andric return LangAS::cuda_device; 51300b57cec5SDimitry Andric } 51310b57cec5SDimitry Andric 51320b57cec5SDimitry Andric if (LangOpts.OpenMP) { 51330b57cec5SDimitry Andric LangAS AS; 51340b57cec5SDimitry Andric if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS)) 51350b57cec5SDimitry Andric return AS; 51360b57cec5SDimitry Andric } 51370b57cec5SDimitry Andric return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D); 51380b57cec5SDimitry Andric } 51390b57cec5SDimitry Andric 5140fe6060f1SDimitry Andric LangAS CodeGenModule::GetGlobalConstantAddressSpace() const { 51410b57cec5SDimitry Andric // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 51420b57cec5SDimitry Andric if (LangOpts.OpenCL) 51430b57cec5SDimitry Andric return LangAS::opencl_constant; 5144fe6060f1SDimitry Andric if (LangOpts.SYCLIsDevice) 5145fe6060f1SDimitry Andric return LangAS::sycl_global; 5146d56accc7SDimitry Andric if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV()) 5147d56accc7SDimitry Andric // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V) 5148d56accc7SDimitry Andric // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up 5149d56accc7SDimitry Andric // with OpVariable instructions with Generic storage class which is not 5150d56accc7SDimitry Andric // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V 5151d56accc7SDimitry Andric // UniformConstant storage class is not viable as pointers to it may not be 5152d56accc7SDimitry Andric // casted to Generic pointers which are used to model HIP's "flat" pointers. 5153d56accc7SDimitry Andric return LangAS::cuda_device; 51540b57cec5SDimitry Andric if (auto AS = getTarget().getConstantAddressSpace()) 515581ad6265SDimitry Andric return *AS; 51560b57cec5SDimitry Andric return LangAS::Default; 51570b57cec5SDimitry Andric } 51580b57cec5SDimitry Andric 51590b57cec5SDimitry Andric // In address space agnostic languages, string literals are in default address 51600b57cec5SDimitry Andric // space in AST. However, certain targets (e.g. amdgcn) request them to be 51610b57cec5SDimitry Andric // emitted in constant address space in LLVM IR. To be consistent with other 51620b57cec5SDimitry Andric // parts of AST, string literal global variables in constant address space 51630b57cec5SDimitry Andric // need to be casted to default address space before being put into address 51640b57cec5SDimitry Andric // map and referenced by other part of CodeGen. 51650b57cec5SDimitry Andric // In OpenCL, string literals are in constant address space in AST, therefore 51660b57cec5SDimitry Andric // they should not be casted to default address space. 51670b57cec5SDimitry Andric static llvm::Constant * 51680b57cec5SDimitry Andric castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, 51690b57cec5SDimitry Andric llvm::GlobalVariable *GV) { 51700b57cec5SDimitry Andric llvm::Constant *Cast = GV; 51710b57cec5SDimitry Andric if (!CGM.getLangOpts().OpenCL) { 5172fe6060f1SDimitry Andric auto AS = CGM.GetGlobalConstantAddressSpace(); 51730b57cec5SDimitry Andric if (AS != LangAS::Default) 51740b57cec5SDimitry Andric Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast( 5175fe6060f1SDimitry Andric CGM, GV, AS, LangAS::Default, 5176c9157d92SDimitry Andric llvm::PointerType::get( 5177c9157d92SDimitry Andric CGM.getLLVMContext(), 51780b57cec5SDimitry Andric CGM.getContext().getTargetAddressSpace(LangAS::Default))); 51790b57cec5SDimitry Andric } 51800b57cec5SDimitry Andric return Cast; 51810b57cec5SDimitry Andric } 51820b57cec5SDimitry Andric 51830b57cec5SDimitry Andric template<typename SomeDecl> 51840b57cec5SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 51850b57cec5SDimitry Andric llvm::GlobalValue *GV) { 51860b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus) 51870b57cec5SDimitry Andric return; 51880b57cec5SDimitry Andric 51890b57cec5SDimitry Andric // Must have 'used' attribute, or else inline assembly can't rely on 51900b57cec5SDimitry Andric // the name existing. 51910b57cec5SDimitry Andric if (!D->template hasAttr<UsedAttr>()) 51920b57cec5SDimitry Andric return; 51930b57cec5SDimitry Andric 51940b57cec5SDimitry Andric // Must have internal linkage and an ordinary name. 5195c9157d92SDimitry Andric if (!D->getIdentifier() || D->getFormalLinkage() != Linkage::Internal) 51960b57cec5SDimitry Andric return; 51970b57cec5SDimitry Andric 51980b57cec5SDimitry Andric // Must be in an extern "C" context. Entities declared directly within 51990b57cec5SDimitry Andric // a record are not extern "C" even if the record is in such a context. 52000b57cec5SDimitry Andric const SomeDecl *First = D->getFirstDecl(); 52010b57cec5SDimitry Andric if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 52020b57cec5SDimitry Andric return; 52030b57cec5SDimitry Andric 52040b57cec5SDimitry Andric // OK, this is an internal linkage entity inside an extern "C" linkage 52050b57cec5SDimitry Andric // specification. Make a note of that so we can give it the "expected" 52060b57cec5SDimitry Andric // mangled name if nothing else is using that name. 52070b57cec5SDimitry Andric std::pair<StaticExternCMap::iterator, bool> R = 52080b57cec5SDimitry Andric StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 52090b57cec5SDimitry Andric 52100b57cec5SDimitry Andric // If we have multiple internal linkage entities with the same name 52110b57cec5SDimitry Andric // in extern "C" regions, none of them gets that name. 52120b57cec5SDimitry Andric if (!R.second) 52130b57cec5SDimitry Andric R.first->second = nullptr; 52140b57cec5SDimitry Andric } 52150b57cec5SDimitry Andric 52160b57cec5SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 52170b57cec5SDimitry Andric if (!CGM.supportsCOMDAT()) 52180b57cec5SDimitry Andric return false; 52190b57cec5SDimitry Andric 52200b57cec5SDimitry Andric if (D.hasAttr<SelectAnyAttr>()) 52210b57cec5SDimitry Andric return true; 52220b57cec5SDimitry Andric 52230b57cec5SDimitry Andric GVALinkage Linkage; 52240b57cec5SDimitry Andric if (auto *VD = dyn_cast<VarDecl>(&D)) 52250b57cec5SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 52260b57cec5SDimitry Andric else 52270b57cec5SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 52280b57cec5SDimitry Andric 52290b57cec5SDimitry Andric switch (Linkage) { 52300b57cec5SDimitry Andric case GVA_Internal: 52310b57cec5SDimitry Andric case GVA_AvailableExternally: 52320b57cec5SDimitry Andric case GVA_StrongExternal: 52330b57cec5SDimitry Andric return false; 52340b57cec5SDimitry Andric case GVA_DiscardableODR: 52350b57cec5SDimitry Andric case GVA_StrongODR: 52360b57cec5SDimitry Andric return true; 52370b57cec5SDimitry Andric } 52380b57cec5SDimitry Andric llvm_unreachable("No such linkage"); 52390b57cec5SDimitry Andric } 52400b57cec5SDimitry Andric 5241fe013be4SDimitry Andric bool CodeGenModule::supportsCOMDAT() const { 5242fe013be4SDimitry Andric return getTriple().supportsCOMDAT(); 5243fe013be4SDimitry Andric } 5244fe013be4SDimitry Andric 52450b57cec5SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 52460b57cec5SDimitry Andric llvm::GlobalObject &GO) { 52470b57cec5SDimitry Andric if (!shouldBeInCOMDAT(*this, D)) 52480b57cec5SDimitry Andric return; 52490b57cec5SDimitry Andric GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 52500b57cec5SDimitry Andric } 52510b57cec5SDimitry Andric 52520b57cec5SDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition. 52530b57cec5SDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 52540b57cec5SDimitry Andric bool IsTentative) { 52550b57cec5SDimitry Andric // OpenCL global variables of sampler type are translated to function calls, 52560b57cec5SDimitry Andric // therefore no need to be translated. 52570b57cec5SDimitry Andric QualType ASTTy = D->getType(); 52580b57cec5SDimitry Andric if (getLangOpts().OpenCL && ASTTy->isSamplerT()) 52590b57cec5SDimitry Andric return; 52600b57cec5SDimitry Andric 52610b57cec5SDimitry Andric // If this is OpenMP device, check if it is legal to emit this global 52620b57cec5SDimitry Andric // normally. 5263fe013be4SDimitry Andric if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime && 52640b57cec5SDimitry Andric OpenMPRuntime->emitTargetGlobalVariable(D)) 52650b57cec5SDimitry Andric return; 52660b57cec5SDimitry Andric 5267fe6060f1SDimitry Andric llvm::TrackingVH<llvm::Constant> Init; 52680b57cec5SDimitry Andric bool NeedsGlobalCtor = false; 5269bdd1243dSDimitry Andric // Whether the definition of the variable is available externally. 5270bdd1243dSDimitry Andric // If yes, we shouldn't emit the GloablCtor and GlobalDtor for the variable 5271bdd1243dSDimitry Andric // since this is the job for its original source. 5272bdd1243dSDimitry Andric bool IsDefinitionAvailableExternally = 5273bdd1243dSDimitry Andric getContext().GetGVALinkageForVariable(D) == GVA_AvailableExternally; 5274a7dea167SDimitry Andric bool NeedsGlobalDtor = 5275bdd1243dSDimitry Andric !IsDefinitionAvailableExternally && 5276a7dea167SDimitry Andric D->needsDestruction(getContext()) == QualType::DK_cxx_destructor; 52770b57cec5SDimitry Andric 52780b57cec5SDimitry Andric const VarDecl *InitDecl; 52790b57cec5SDimitry Andric const Expr *InitExpr = D->getAnyInitializer(InitDecl); 52800b57cec5SDimitry Andric 5281bdd1243dSDimitry Andric std::optional<ConstantEmitter> emitter; 52820b57cec5SDimitry Andric 52830b57cec5SDimitry Andric // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 52840b57cec5SDimitry Andric // as part of their declaration." Sema has already checked for 52850b57cec5SDimitry Andric // error cases, so we just need to set Init to UndefValue. 52860b57cec5SDimitry Andric bool IsCUDASharedVar = 52870b57cec5SDimitry Andric getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>(); 52880b57cec5SDimitry Andric // Shadows of initialized device-side global variables are also left 52890b57cec5SDimitry Andric // undefined. 5290fe6060f1SDimitry Andric // Managed Variables should be initialized on both host side and device side. 52910b57cec5SDimitry Andric bool IsCUDAShadowVar = 5292e8d8bef9SDimitry Andric !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 52930b57cec5SDimitry Andric (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() || 52940b57cec5SDimitry Andric D->hasAttr<CUDASharedAttr>()); 52955ffd83dbSDimitry Andric bool IsCUDADeviceShadowVar = 5296fe6060f1SDimitry Andric getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 52975ffd83dbSDimitry Andric (D->getType()->isCUDADeviceBuiltinSurfaceType() || 5298fe6060f1SDimitry Andric D->getType()->isCUDADeviceBuiltinTextureType()); 52990b57cec5SDimitry Andric if (getLangOpts().CUDA && 53005ffd83dbSDimitry Andric (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) 5301fe6060f1SDimitry Andric Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 53025ffd83dbSDimitry Andric else if (D->hasAttr<LoaderUninitializedAttr>()) 5303fe6060f1SDimitry Andric Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 53040b57cec5SDimitry Andric else if (!InitExpr) { 53050b57cec5SDimitry Andric // This is a tentative definition; tentative definitions are 53060b57cec5SDimitry Andric // implicitly initialized with { 0 }. 53070b57cec5SDimitry Andric // 53080b57cec5SDimitry Andric // Note that tentative definitions are only emitted at the end of 53090b57cec5SDimitry Andric // a translation unit, so they should never have incomplete 53100b57cec5SDimitry Andric // type. In addition, EmitTentativeDefinition makes sure that we 53110b57cec5SDimitry Andric // never attempt to emit a tentative definition if a real one 53120b57cec5SDimitry Andric // exists. A use may still exists, however, so we still may need 53130b57cec5SDimitry Andric // to do a RAUW. 53140b57cec5SDimitry Andric assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 53150b57cec5SDimitry Andric Init = EmitNullConstant(D->getType()); 53160b57cec5SDimitry Andric } else { 53170b57cec5SDimitry Andric initializedGlobalDecl = GlobalDecl(D); 53180b57cec5SDimitry Andric emitter.emplace(*this); 5319fe6060f1SDimitry Andric llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl); 5320fe6060f1SDimitry Andric if (!Initializer) { 53210b57cec5SDimitry Andric QualType T = InitExpr->getType(); 53220b57cec5SDimitry Andric if (D->getType()->isReferenceType()) 53230b57cec5SDimitry Andric T = D->getType(); 53240b57cec5SDimitry Andric 53250b57cec5SDimitry Andric if (getLangOpts().CPlusPlus) { 532681ad6265SDimitry Andric if (InitDecl->hasFlexibleArrayInit(getContext())) 532781ad6265SDimitry Andric ErrorUnsupported(D, "flexible array initializer"); 53280b57cec5SDimitry Andric Init = EmitNullConstant(T); 5329bdd1243dSDimitry Andric 5330bdd1243dSDimitry Andric if (!IsDefinitionAvailableExternally) 53310b57cec5SDimitry Andric NeedsGlobalCtor = true; 53320b57cec5SDimitry Andric } else { 53330b57cec5SDimitry Andric ErrorUnsupported(D, "static initializer"); 53340b57cec5SDimitry Andric Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 53350b57cec5SDimitry Andric } 53360b57cec5SDimitry Andric } else { 5337fe6060f1SDimitry Andric Init = Initializer; 53380b57cec5SDimitry Andric // We don't need an initializer, so remove the entry for the delayed 53390b57cec5SDimitry Andric // initializer position (just in case this entry was delayed) if we 53400b57cec5SDimitry Andric // also don't need to register a destructor. 53410b57cec5SDimitry Andric if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 53420b57cec5SDimitry Andric DelayedCXXInitPosition.erase(D); 534381ad6265SDimitry Andric 534481ad6265SDimitry Andric #ifndef NDEBUG 534581ad6265SDimitry Andric CharUnits VarSize = getContext().getTypeSizeInChars(ASTTy) + 534681ad6265SDimitry Andric InitDecl->getFlexibleArrayInitChars(getContext()); 534781ad6265SDimitry Andric CharUnits CstSize = CharUnits::fromQuantity( 534881ad6265SDimitry Andric getDataLayout().getTypeAllocSize(Init->getType())); 534981ad6265SDimitry Andric assert(VarSize == CstSize && "Emitted constant has unexpected size"); 535081ad6265SDimitry Andric #endif 53510b57cec5SDimitry Andric } 53520b57cec5SDimitry Andric } 53530b57cec5SDimitry Andric 53540b57cec5SDimitry Andric llvm::Type* InitType = Init->getType(); 53550b57cec5SDimitry Andric llvm::Constant *Entry = 53560b57cec5SDimitry Andric GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); 53570b57cec5SDimitry Andric 5358a7dea167SDimitry Andric // Strip off pointer casts if we got them. 5359a7dea167SDimitry Andric Entry = Entry->stripPointerCasts(); 53600b57cec5SDimitry Andric 53610b57cec5SDimitry Andric // Entry is now either a Function or GlobalVariable. 53620b57cec5SDimitry Andric auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 53630b57cec5SDimitry Andric 53640b57cec5SDimitry Andric // We have a definition after a declaration with the wrong type. 53650b57cec5SDimitry Andric // We must make a new GlobalVariable* and update everything that used OldGV 53660b57cec5SDimitry Andric // (a declaration or tentative definition) with the new GlobalVariable* 53670b57cec5SDimitry Andric // (which will be a definition). 53680b57cec5SDimitry Andric // 53690b57cec5SDimitry Andric // This happens if there is a prototype for a global (e.g. 53700b57cec5SDimitry Andric // "extern int x[];") and then a definition of a different type (e.g. 53710b57cec5SDimitry Andric // "int x[10];"). This also happens when an initializer has a different type 53720b57cec5SDimitry Andric // from the type of the global (this happens with unions). 53735ffd83dbSDimitry Andric if (!GV || GV->getValueType() != InitType || 53740b57cec5SDimitry Andric GV->getType()->getAddressSpace() != 53750b57cec5SDimitry Andric getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) { 53760b57cec5SDimitry Andric 53770b57cec5SDimitry Andric // Move the old entry aside so that we'll create a new one. 53780b57cec5SDimitry Andric Entry->setName(StringRef()); 53790b57cec5SDimitry Andric 53800b57cec5SDimitry Andric // Make a new global with the correct type, this is now guaranteed to work. 53810b57cec5SDimitry Andric GV = cast<llvm::GlobalVariable>( 5382a7dea167SDimitry Andric GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)) 5383a7dea167SDimitry Andric ->stripPointerCasts()); 53840b57cec5SDimitry Andric 53850b57cec5SDimitry Andric // Replace all uses of the old global with the new global 53860b57cec5SDimitry Andric llvm::Constant *NewPtrForOldDecl = 5387fe6060f1SDimitry Andric llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, 5388fe6060f1SDimitry Andric Entry->getType()); 53890b57cec5SDimitry Andric Entry->replaceAllUsesWith(NewPtrForOldDecl); 53900b57cec5SDimitry Andric 53910b57cec5SDimitry Andric // Erase the old global, since it is no longer used. 53920b57cec5SDimitry Andric cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 53930b57cec5SDimitry Andric } 53940b57cec5SDimitry Andric 53950b57cec5SDimitry Andric MaybeHandleStaticInExternC(D, GV); 53960b57cec5SDimitry Andric 53970b57cec5SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 53980b57cec5SDimitry Andric AddGlobalAnnotations(D, GV); 53990b57cec5SDimitry Andric 54000b57cec5SDimitry Andric // Set the llvm linkage type as appropriate. 5401271697daSDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(D); 54020b57cec5SDimitry Andric 54030b57cec5SDimitry Andric // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 54040b57cec5SDimitry Andric // the device. [...]" 54050b57cec5SDimitry Andric // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 54060b57cec5SDimitry Andric // __device__, declares a variable that: [...] 54070b57cec5SDimitry Andric // Is accessible from all the threads within the grid and from the host 54080b57cec5SDimitry Andric // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 54090b57cec5SDimitry Andric // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 5410fe013be4SDimitry Andric if (LangOpts.CUDA) { 54110b57cec5SDimitry Andric if (LangOpts.CUDAIsDevice) { 54120b57cec5SDimitry Andric if (Linkage != llvm::GlobalValue::InternalLinkage && 5413349cc55cSDimitry Andric (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 5414349cc55cSDimitry Andric D->getType()->isCUDADeviceBuiltinSurfaceType() || 5415349cc55cSDimitry Andric D->getType()->isCUDADeviceBuiltinTextureType())) 54160b57cec5SDimitry Andric GV->setExternallyInitialized(true); 54170b57cec5SDimitry Andric } else { 5418fe6060f1SDimitry Andric getCUDARuntime().internalizeDeviceSideVar(D, Linkage); 54195ffd83dbSDimitry Andric } 5420fe6060f1SDimitry Andric getCUDARuntime().handleVarRegistration(D, *GV); 54210b57cec5SDimitry Andric } 54220b57cec5SDimitry Andric 54230b57cec5SDimitry Andric GV->setInitializer(Init); 54245ffd83dbSDimitry Andric if (emitter) 54255ffd83dbSDimitry Andric emitter->finalize(GV); 54260b57cec5SDimitry Andric 54270b57cec5SDimitry Andric // If it is safe to mark the global 'constant', do so now. 54280b57cec5SDimitry Andric GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 5429c9157d92SDimitry Andric D->getType().isConstantStorage(getContext(), true, true)); 54300b57cec5SDimitry Andric 54310b57cec5SDimitry Andric // If it is in a read-only section, mark it 'constant'. 54320b57cec5SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 54330b57cec5SDimitry Andric const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 54340b57cec5SDimitry Andric if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 54350b57cec5SDimitry Andric GV->setConstant(true); 54360b57cec5SDimitry Andric } 54370b57cec5SDimitry Andric 543881ad6265SDimitry Andric CharUnits AlignVal = getContext().getDeclAlign(D); 543981ad6265SDimitry Andric // Check for alignment specifed in an 'omp allocate' directive. 5440bdd1243dSDimitry Andric if (std::optional<CharUnits> AlignValFromAllocate = 544181ad6265SDimitry Andric getOMPAllocateAlignment(D)) 544281ad6265SDimitry Andric AlignVal = *AlignValFromAllocate; 544381ad6265SDimitry Andric GV->setAlignment(AlignVal.getAsAlign()); 54440b57cec5SDimitry Andric 54455ffd83dbSDimitry Andric // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper 54465ffd83dbSDimitry Andric // function is only defined alongside the variable, not also alongside 54475ffd83dbSDimitry Andric // callers. Normally, all accesses to a thread_local go through the 54485ffd83dbSDimitry Andric // thread-wrapper in order to ensure initialization has occurred, underlying 54495ffd83dbSDimitry Andric // variable will never be used other than the thread-wrapper, so it can be 54505ffd83dbSDimitry Andric // converted to internal linkage. 54515ffd83dbSDimitry Andric // 54525ffd83dbSDimitry Andric // However, if the variable has the 'constinit' attribute, it _can_ be 54535ffd83dbSDimitry Andric // referenced directly, without calling the thread-wrapper, so the linkage 54545ffd83dbSDimitry Andric // must not be changed. 54555ffd83dbSDimitry Andric // 54565ffd83dbSDimitry Andric // Additionally, if the variable isn't plain external linkage, e.g. if it's 54575ffd83dbSDimitry Andric // weak or linkonce, the de-duplication semantics are important to preserve, 54585ffd83dbSDimitry Andric // so we don't change the linkage. 54595ffd83dbSDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic && 54605ffd83dbSDimitry Andric Linkage == llvm::GlobalValue::ExternalLinkage && 54610b57cec5SDimitry Andric Context.getTargetInfo().getTriple().isOSDarwin() && 54625ffd83dbSDimitry Andric !D->hasAttr<ConstInitAttr>()) 54630b57cec5SDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 54640b57cec5SDimitry Andric 54650b57cec5SDimitry Andric GV->setLinkage(Linkage); 54660b57cec5SDimitry Andric if (D->hasAttr<DLLImportAttr>()) 54670b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 54680b57cec5SDimitry Andric else if (D->hasAttr<DLLExportAttr>()) 54690b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 54700b57cec5SDimitry Andric else 54710b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 54720b57cec5SDimitry Andric 54730b57cec5SDimitry Andric if (Linkage == llvm::GlobalVariable::CommonLinkage) { 54740b57cec5SDimitry Andric // common vars aren't constant even if declared const. 54750b57cec5SDimitry Andric GV->setConstant(false); 54760b57cec5SDimitry Andric // Tentative definition of global variables may be initialized with 54770b57cec5SDimitry Andric // non-zero null pointers. In this case they should have weak linkage 54780b57cec5SDimitry Andric // since common linkage must have zero initializer and must not have 54790b57cec5SDimitry Andric // explicit section therefore cannot have non-zero initial value. 54800b57cec5SDimitry Andric if (!GV->getInitializer()->isNullValue()) 54810b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 54820b57cec5SDimitry Andric } 54830b57cec5SDimitry Andric 54840b57cec5SDimitry Andric setNonAliasAttributes(D, GV); 54850b57cec5SDimitry Andric 54860b57cec5SDimitry Andric if (D->getTLSKind() && !GV->isThreadLocal()) { 54870b57cec5SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 54880b57cec5SDimitry Andric CXXThreadLocals.push_back(D); 54890b57cec5SDimitry Andric setTLSMode(GV, *D); 54900b57cec5SDimitry Andric } 54910b57cec5SDimitry Andric 54920b57cec5SDimitry Andric maybeSetTrivialComdat(*D, *GV); 54930b57cec5SDimitry Andric 54940b57cec5SDimitry Andric // Emit the initializer function if necessary. 54950b57cec5SDimitry Andric if (NeedsGlobalCtor || NeedsGlobalDtor) 54960b57cec5SDimitry Andric EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 54970b57cec5SDimitry Andric 549881ad6265SDimitry Andric SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor); 54990b57cec5SDimitry Andric 55000b57cec5SDimitry Andric // Emit global variable debug information. 55010b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 5502480093f4SDimitry Andric if (getCodeGenOpts().hasReducedDebugInfo()) 55030b57cec5SDimitry Andric DI->EmitGlobalVariable(GV, D); 55040b57cec5SDimitry Andric } 55050b57cec5SDimitry Andric 5506480093f4SDimitry Andric void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) { 5507480093f4SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 5508480093f4SDimitry Andric if (getCodeGenOpts().hasReducedDebugInfo()) { 5509480093f4SDimitry Andric QualType ASTTy = D->getType(); 5510480093f4SDimitry Andric llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType()); 5511349cc55cSDimitry Andric llvm::Constant *GV = 5512349cc55cSDimitry Andric GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D); 5513480093f4SDimitry Andric DI->EmitExternalVariable( 5514480093f4SDimitry Andric cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D); 5515480093f4SDimitry Andric } 5516480093f4SDimitry Andric } 5517480093f4SDimitry Andric 55180b57cec5SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context, 55190b57cec5SDimitry Andric CodeGenModule &CGM, const VarDecl *D, 55200b57cec5SDimitry Andric bool NoCommon) { 55210b57cec5SDimitry Andric // Don't give variables common linkage if -fno-common was specified unless it 55220b57cec5SDimitry Andric // was overridden by a NoCommon attribute. 55230b57cec5SDimitry Andric if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 55240b57cec5SDimitry Andric return true; 55250b57cec5SDimitry Andric 55260b57cec5SDimitry Andric // C11 6.9.2/2: 55270b57cec5SDimitry Andric // A declaration of an identifier for an object that has file scope without 55280b57cec5SDimitry Andric // an initializer, and without a storage-class specifier or with the 55290b57cec5SDimitry Andric // storage-class specifier static, constitutes a tentative definition. 55300b57cec5SDimitry Andric if (D->getInit() || D->hasExternalStorage()) 55310b57cec5SDimitry Andric return true; 55320b57cec5SDimitry Andric 55330b57cec5SDimitry Andric // A variable cannot be both common and exist in a section. 55340b57cec5SDimitry Andric if (D->hasAttr<SectionAttr>()) 55350b57cec5SDimitry Andric return true; 55360b57cec5SDimitry Andric 55370b57cec5SDimitry Andric // A variable cannot be both common and exist in a section. 55380b57cec5SDimitry Andric // We don't try to determine which is the right section in the front-end. 55390b57cec5SDimitry Andric // If no specialized section name is applicable, it will resort to default. 55400b57cec5SDimitry Andric if (D->hasAttr<PragmaClangBSSSectionAttr>() || 55410b57cec5SDimitry Andric D->hasAttr<PragmaClangDataSectionAttr>() || 5542a7dea167SDimitry Andric D->hasAttr<PragmaClangRelroSectionAttr>() || 55430b57cec5SDimitry Andric D->hasAttr<PragmaClangRodataSectionAttr>()) 55440b57cec5SDimitry Andric return true; 55450b57cec5SDimitry Andric 55460b57cec5SDimitry Andric // Thread local vars aren't considered common linkage. 55470b57cec5SDimitry Andric if (D->getTLSKind()) 55480b57cec5SDimitry Andric return true; 55490b57cec5SDimitry Andric 55500b57cec5SDimitry Andric // Tentative definitions marked with WeakImportAttr are true definitions. 55510b57cec5SDimitry Andric if (D->hasAttr<WeakImportAttr>()) 55520b57cec5SDimitry Andric return true; 55530b57cec5SDimitry Andric 55540b57cec5SDimitry Andric // A variable cannot be both common and exist in a comdat. 55550b57cec5SDimitry Andric if (shouldBeInCOMDAT(CGM, *D)) 55560b57cec5SDimitry Andric return true; 55570b57cec5SDimitry Andric 55580b57cec5SDimitry Andric // Declarations with a required alignment do not have common linkage in MSVC 55590b57cec5SDimitry Andric // mode. 55600b57cec5SDimitry Andric if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 55610b57cec5SDimitry Andric if (D->hasAttr<AlignedAttr>()) 55620b57cec5SDimitry Andric return true; 55630b57cec5SDimitry Andric QualType VarType = D->getType(); 55640b57cec5SDimitry Andric if (Context.isAlignmentRequired(VarType)) 55650b57cec5SDimitry Andric return true; 55660b57cec5SDimitry Andric 55670b57cec5SDimitry Andric if (const auto *RT = VarType->getAs<RecordType>()) { 55680b57cec5SDimitry Andric const RecordDecl *RD = RT->getDecl(); 55690b57cec5SDimitry Andric for (const FieldDecl *FD : RD->fields()) { 55700b57cec5SDimitry Andric if (FD->isBitField()) 55710b57cec5SDimitry Andric continue; 55720b57cec5SDimitry Andric if (FD->hasAttr<AlignedAttr>()) 55730b57cec5SDimitry Andric return true; 55740b57cec5SDimitry Andric if (Context.isAlignmentRequired(FD->getType())) 55750b57cec5SDimitry Andric return true; 55760b57cec5SDimitry Andric } 55770b57cec5SDimitry Andric } 55780b57cec5SDimitry Andric } 55790b57cec5SDimitry Andric 55800b57cec5SDimitry Andric // Microsoft's link.exe doesn't support alignments greater than 32 bytes for 55810b57cec5SDimitry Andric // common symbols, so symbols with greater alignment requirements cannot be 55820b57cec5SDimitry Andric // common. 55830b57cec5SDimitry Andric // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two 55840b57cec5SDimitry Andric // alignments for common symbols via the aligncomm directive, so this 55850b57cec5SDimitry Andric // restriction only applies to MSVC environments. 55860b57cec5SDimitry Andric if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() && 55870b57cec5SDimitry Andric Context.getTypeAlignIfKnown(D->getType()) > 55880b57cec5SDimitry Andric Context.toBits(CharUnits::fromQuantity(32))) 55890b57cec5SDimitry Andric return true; 55900b57cec5SDimitry Andric 55910b57cec5SDimitry Andric return false; 55920b57cec5SDimitry Andric } 55930b57cec5SDimitry Andric 5594271697daSDimitry Andric llvm::GlobalValue::LinkageTypes 5595271697daSDimitry Andric CodeGenModule::getLLVMLinkageForDeclarator(const DeclaratorDecl *D, 5596271697daSDimitry Andric GVALinkage Linkage) { 55970b57cec5SDimitry Andric if (Linkage == GVA_Internal) 55980b57cec5SDimitry Andric return llvm::Function::InternalLinkage; 55990b57cec5SDimitry Andric 560081ad6265SDimitry Andric if (D->hasAttr<WeakAttr>()) 56010b57cec5SDimitry Andric return llvm::GlobalVariable::WeakAnyLinkage; 56020b57cec5SDimitry Andric 56030b57cec5SDimitry Andric if (const auto *FD = D->getAsFunction()) 56040b57cec5SDimitry Andric if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally) 56050b57cec5SDimitry Andric return llvm::GlobalVariable::LinkOnceAnyLinkage; 56060b57cec5SDimitry Andric 56070b57cec5SDimitry Andric // We are guaranteed to have a strong definition somewhere else, 56080b57cec5SDimitry Andric // so we can use available_externally linkage. 56090b57cec5SDimitry Andric if (Linkage == GVA_AvailableExternally) 56100b57cec5SDimitry Andric return llvm::GlobalValue::AvailableExternallyLinkage; 56110b57cec5SDimitry Andric 56120b57cec5SDimitry Andric // Note that Apple's kernel linker doesn't support symbol 56130b57cec5SDimitry Andric // coalescing, so we need to avoid linkonce and weak linkages there. 56140b57cec5SDimitry Andric // Normally, this means we just map to internal, but for explicit 56150b57cec5SDimitry Andric // instantiations we'll map to external. 56160b57cec5SDimitry Andric 56170b57cec5SDimitry Andric // In C++, the compiler has to emit a definition in every translation unit 56180b57cec5SDimitry Andric // that references the function. We should use linkonce_odr because 56190b57cec5SDimitry Andric // a) if all references in this translation unit are optimized away, we 56200b57cec5SDimitry Andric // don't need to codegen it. b) if the function persists, it needs to be 56210b57cec5SDimitry Andric // merged with other definitions. c) C++ has the ODR, so we know the 56220b57cec5SDimitry Andric // definition is dependable. 56230b57cec5SDimitry Andric if (Linkage == GVA_DiscardableODR) 56240b57cec5SDimitry Andric return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 56250b57cec5SDimitry Andric : llvm::Function::InternalLinkage; 56260b57cec5SDimitry Andric 56270b57cec5SDimitry Andric // An explicit instantiation of a template has weak linkage, since 56280b57cec5SDimitry Andric // explicit instantiations can occur in multiple translation units 56290b57cec5SDimitry Andric // and must all be equivalent. However, we are not allowed to 56300b57cec5SDimitry Andric // throw away these explicit instantiations. 56310b57cec5SDimitry Andric // 5632e8d8bef9SDimitry Andric // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU, 56330b57cec5SDimitry Andric // so say that CUDA templates are either external (for kernels) or internal. 5634e8d8bef9SDimitry Andric // This lets llvm perform aggressive inter-procedural optimizations. For 5635e8d8bef9SDimitry Andric // -fgpu-rdc case, device function calls across multiple TU's are allowed, 5636e8d8bef9SDimitry Andric // therefore we need to follow the normal linkage paradigm. 56370b57cec5SDimitry Andric if (Linkage == GVA_StrongODR) { 5638e8d8bef9SDimitry Andric if (getLangOpts().AppleKext) 56390b57cec5SDimitry Andric return llvm::Function::ExternalLinkage; 5640e8d8bef9SDimitry Andric if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 5641e8d8bef9SDimitry Andric !getLangOpts().GPURelocatableDeviceCode) 56420b57cec5SDimitry Andric return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage 56430b57cec5SDimitry Andric : llvm::Function::InternalLinkage; 56440b57cec5SDimitry Andric return llvm::Function::WeakODRLinkage; 56450b57cec5SDimitry Andric } 56460b57cec5SDimitry Andric 56470b57cec5SDimitry Andric // C++ doesn't have tentative definitions and thus cannot have common 56480b57cec5SDimitry Andric // linkage. 56490b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 56500b57cec5SDimitry Andric !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 56510b57cec5SDimitry Andric CodeGenOpts.NoCommon)) 56520b57cec5SDimitry Andric return llvm::GlobalVariable::CommonLinkage; 56530b57cec5SDimitry Andric 56540b57cec5SDimitry Andric // selectany symbols are externally visible, so use weak instead of 56550b57cec5SDimitry Andric // linkonce. MSVC optimizes away references to const selectany globals, so 56560b57cec5SDimitry Andric // all definitions should be the same and ODR linkage should be used. 56570b57cec5SDimitry Andric // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 56580b57cec5SDimitry Andric if (D->hasAttr<SelectAnyAttr>()) 56590b57cec5SDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 56600b57cec5SDimitry Andric 56610b57cec5SDimitry Andric // Otherwise, we have strong external linkage. 56620b57cec5SDimitry Andric assert(Linkage == GVA_StrongExternal); 56630b57cec5SDimitry Andric return llvm::GlobalVariable::ExternalLinkage; 56640b57cec5SDimitry Andric } 56650b57cec5SDimitry Andric 5666271697daSDimitry Andric llvm::GlobalValue::LinkageTypes 5667271697daSDimitry Andric CodeGenModule::getLLVMLinkageVarDefinition(const VarDecl *VD) { 56680b57cec5SDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 5669271697daSDimitry Andric return getLLVMLinkageForDeclarator(VD, Linkage); 56700b57cec5SDimitry Andric } 56710b57cec5SDimitry Andric 56720b57cec5SDimitry Andric /// Replace the uses of a function that was declared with a non-proto type. 56730b57cec5SDimitry Andric /// We want to silently drop extra arguments from call sites 56740b57cec5SDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 56750b57cec5SDimitry Andric llvm::Function *newFn) { 56760b57cec5SDimitry Andric // Fast path. 56770b57cec5SDimitry Andric if (old->use_empty()) return; 56780b57cec5SDimitry Andric 56790b57cec5SDimitry Andric llvm::Type *newRetTy = newFn->getReturnType(); 56800b57cec5SDimitry Andric SmallVector<llvm::Value*, 4> newArgs; 56810b57cec5SDimitry Andric 56820b57cec5SDimitry Andric for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 56830b57cec5SDimitry Andric ui != ue; ) { 56840b57cec5SDimitry Andric llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 56850b57cec5SDimitry Andric llvm::User *user = use->getUser(); 56860b57cec5SDimitry Andric 56870b57cec5SDimitry Andric // Recognize and replace uses of bitcasts. Most calls to 56880b57cec5SDimitry Andric // unprototyped functions will use bitcasts. 56890b57cec5SDimitry Andric if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 56900b57cec5SDimitry Andric if (bitcast->getOpcode() == llvm::Instruction::BitCast) 56910b57cec5SDimitry Andric replaceUsesOfNonProtoConstant(bitcast, newFn); 56920b57cec5SDimitry Andric continue; 56930b57cec5SDimitry Andric } 56940b57cec5SDimitry Andric 56950b57cec5SDimitry Andric // Recognize calls to the function. 56960b57cec5SDimitry Andric llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user); 56970b57cec5SDimitry Andric if (!callSite) continue; 56980b57cec5SDimitry Andric if (!callSite->isCallee(&*use)) 56990b57cec5SDimitry Andric continue; 57000b57cec5SDimitry Andric 57010b57cec5SDimitry Andric // If the return types don't match exactly, then we can't 57020b57cec5SDimitry Andric // transform this call unless it's dead. 57030b57cec5SDimitry Andric if (callSite->getType() != newRetTy && !callSite->use_empty()) 57040b57cec5SDimitry Andric continue; 57050b57cec5SDimitry Andric 57060b57cec5SDimitry Andric // Get the call site's attribute list. 57070b57cec5SDimitry Andric SmallVector<llvm::AttributeSet, 8> newArgAttrs; 57080b57cec5SDimitry Andric llvm::AttributeList oldAttrs = callSite->getAttributes(); 57090b57cec5SDimitry Andric 57100b57cec5SDimitry Andric // If the function was passed too few arguments, don't transform. 57110b57cec5SDimitry Andric unsigned newNumArgs = newFn->arg_size(); 57120b57cec5SDimitry Andric if (callSite->arg_size() < newNumArgs) 57130b57cec5SDimitry Andric continue; 57140b57cec5SDimitry Andric 57150b57cec5SDimitry Andric // If extra arguments were passed, we silently drop them. 57160b57cec5SDimitry Andric // If any of the types mismatch, we don't transform. 57170b57cec5SDimitry Andric unsigned argNo = 0; 57180b57cec5SDimitry Andric bool dontTransform = false; 57190b57cec5SDimitry Andric for (llvm::Argument &A : newFn->args()) { 57200b57cec5SDimitry Andric if (callSite->getArgOperand(argNo)->getType() != A.getType()) { 57210b57cec5SDimitry Andric dontTransform = true; 57220b57cec5SDimitry Andric break; 57230b57cec5SDimitry Andric } 57240b57cec5SDimitry Andric 57250b57cec5SDimitry Andric // Add any parameter attributes. 5726349cc55cSDimitry Andric newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo)); 57270b57cec5SDimitry Andric argNo++; 57280b57cec5SDimitry Andric } 57290b57cec5SDimitry Andric if (dontTransform) 57300b57cec5SDimitry Andric continue; 57310b57cec5SDimitry Andric 57320b57cec5SDimitry Andric // Okay, we can transform this. Create the new call instruction and copy 57330b57cec5SDimitry Andric // over the required information. 57340b57cec5SDimitry Andric newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo); 57350b57cec5SDimitry Andric 57360b57cec5SDimitry Andric // Copy over any operand bundles. 5737fe6060f1SDimitry Andric SmallVector<llvm::OperandBundleDef, 1> newBundles; 57380b57cec5SDimitry Andric callSite->getOperandBundlesAsDefs(newBundles); 57390b57cec5SDimitry Andric 57400b57cec5SDimitry Andric llvm::CallBase *newCall; 5741349cc55cSDimitry Andric if (isa<llvm::CallInst>(callSite)) { 57420b57cec5SDimitry Andric newCall = 57430b57cec5SDimitry Andric llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite); 57440b57cec5SDimitry Andric } else { 57450b57cec5SDimitry Andric auto *oldInvoke = cast<llvm::InvokeInst>(callSite); 57460b57cec5SDimitry Andric newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(), 57470b57cec5SDimitry Andric oldInvoke->getUnwindDest(), newArgs, 57480b57cec5SDimitry Andric newBundles, "", callSite); 57490b57cec5SDimitry Andric } 57500b57cec5SDimitry Andric newArgs.clear(); // for the next iteration 57510b57cec5SDimitry Andric 57520b57cec5SDimitry Andric if (!newCall->getType()->isVoidTy()) 57530b57cec5SDimitry Andric newCall->takeName(callSite); 5754349cc55cSDimitry Andric newCall->setAttributes( 5755349cc55cSDimitry Andric llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(), 5756349cc55cSDimitry Andric oldAttrs.getRetAttrs(), newArgAttrs)); 57570b57cec5SDimitry Andric newCall->setCallingConv(callSite->getCallingConv()); 57580b57cec5SDimitry Andric 57590b57cec5SDimitry Andric // Finally, remove the old call, replacing any uses with the new one. 57600b57cec5SDimitry Andric if (!callSite->use_empty()) 57610b57cec5SDimitry Andric callSite->replaceAllUsesWith(newCall); 57620b57cec5SDimitry Andric 57630b57cec5SDimitry Andric // Copy debug location attached to CI. 57640b57cec5SDimitry Andric if (callSite->getDebugLoc()) 57650b57cec5SDimitry Andric newCall->setDebugLoc(callSite->getDebugLoc()); 57660b57cec5SDimitry Andric 57670b57cec5SDimitry Andric callSite->eraseFromParent(); 57680b57cec5SDimitry Andric } 57690b57cec5SDimitry Andric } 57700b57cec5SDimitry Andric 57710b57cec5SDimitry Andric /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 57720b57cec5SDimitry Andric /// implement a function with no prototype, e.g. "int foo() {}". If there are 57730b57cec5SDimitry Andric /// existing call uses of the old function in the module, this adjusts them to 57740b57cec5SDimitry Andric /// call the new function directly. 57750b57cec5SDimitry Andric /// 57760b57cec5SDimitry Andric /// This is not just a cleanup: the always_inline pass requires direct calls to 57770b57cec5SDimitry Andric /// functions to be able to inline them. If there is a bitcast in the way, it 57780b57cec5SDimitry Andric /// won't inline them. Instcombine normally deletes these calls, but it isn't 57790b57cec5SDimitry Andric /// run at -O0. 57800b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 57810b57cec5SDimitry Andric llvm::Function *NewFn) { 57820b57cec5SDimitry Andric // If we're redefining a global as a function, don't transform it. 57830b57cec5SDimitry Andric if (!isa<llvm::Function>(Old)) return; 57840b57cec5SDimitry Andric 57850b57cec5SDimitry Andric replaceUsesOfNonProtoConstant(Old, NewFn); 57860b57cec5SDimitry Andric } 57870b57cec5SDimitry Andric 57880b57cec5SDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 57890b57cec5SDimitry Andric auto DK = VD->isThisDeclarationADefinition(); 57900b57cec5SDimitry Andric if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) 57910b57cec5SDimitry Andric return; 57920b57cec5SDimitry Andric 57930b57cec5SDimitry Andric TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 57940b57cec5SDimitry Andric // If we have a definition, this might be a deferred decl. If the 57950b57cec5SDimitry Andric // instantiation is explicit, make sure we emit it at the end. 57960b57cec5SDimitry Andric if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 57970b57cec5SDimitry Andric GetAddrOfGlobalVar(VD); 57980b57cec5SDimitry Andric 57990b57cec5SDimitry Andric EmitTopLevelDecl(VD); 58000b57cec5SDimitry Andric } 58010b57cec5SDimitry Andric 58020b57cec5SDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 58030b57cec5SDimitry Andric llvm::GlobalValue *GV) { 58040b57cec5SDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 58050b57cec5SDimitry Andric 58060b57cec5SDimitry Andric // Compute the function info and LLVM type. 58070b57cec5SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 58080b57cec5SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 58090b57cec5SDimitry Andric 58100b57cec5SDimitry Andric // Get or create the prototype for the function. 58115ffd83dbSDimitry Andric if (!GV || (GV->getValueType() != Ty)) 58120b57cec5SDimitry Andric GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 58130b57cec5SDimitry Andric /*DontDefer=*/true, 58140b57cec5SDimitry Andric ForDefinition)); 58150b57cec5SDimitry Andric 58160b57cec5SDimitry Andric // Already emitted. 58170b57cec5SDimitry Andric if (!GV->isDeclaration()) 58180b57cec5SDimitry Andric return; 58190b57cec5SDimitry Andric 58200b57cec5SDimitry Andric // We need to set linkage and visibility on the function before 58210b57cec5SDimitry Andric // generating code for it because various parts of IR generation 58220b57cec5SDimitry Andric // want to propagate this information down (e.g. to local static 58230b57cec5SDimitry Andric // declarations). 58240b57cec5SDimitry Andric auto *Fn = cast<llvm::Function>(GV); 58250b57cec5SDimitry Andric setFunctionLinkage(GD, Fn); 58260b57cec5SDimitry Andric 58270b57cec5SDimitry Andric // FIXME: this is redundant with part of setFunctionDefinitionAttributes 58280b57cec5SDimitry Andric setGVProperties(Fn, GD); 58290b57cec5SDimitry Andric 58300b57cec5SDimitry Andric MaybeHandleStaticInExternC(D, Fn); 58310b57cec5SDimitry Andric 58320b57cec5SDimitry Andric maybeSetTrivialComdat(*D, *Fn); 58330b57cec5SDimitry Andric 58345ffd83dbSDimitry Andric CodeGenFunction(*this).GenerateCode(GD, Fn, FI); 58350b57cec5SDimitry Andric 58360b57cec5SDimitry Andric setNonAliasAttributes(GD, Fn); 58370b57cec5SDimitry Andric SetLLVMFunctionAttributesForDefinition(D, Fn); 58380b57cec5SDimitry Andric 58390b57cec5SDimitry Andric if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 58400b57cec5SDimitry Andric AddGlobalCtor(Fn, CA->getPriority()); 58410b57cec5SDimitry Andric if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 5842e8d8bef9SDimitry Andric AddGlobalDtor(Fn, DA->getPriority(), true); 5843c9157d92SDimitry Andric if (getLangOpts().OpenMP && D->hasAttr<OMPDeclareTargetDeclAttr>()) 5844c9157d92SDimitry Andric getOpenMPRuntime().emitDeclareTargetFunction(D, GV); 58450b57cec5SDimitry Andric } 58460b57cec5SDimitry Andric 58470b57cec5SDimitry Andric void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 58480b57cec5SDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 58490b57cec5SDimitry Andric const AliasAttr *AA = D->getAttr<AliasAttr>(); 58500b57cec5SDimitry Andric assert(AA && "Not an alias?"); 58510b57cec5SDimitry Andric 58520b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 58530b57cec5SDimitry Andric 58540b57cec5SDimitry Andric if (AA->getAliasee() == MangledName) { 58550b57cec5SDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 58560b57cec5SDimitry Andric return; 58570b57cec5SDimitry Andric } 58580b57cec5SDimitry Andric 58590b57cec5SDimitry Andric // If there is a definition in the module, then it wins over the alias. 58600b57cec5SDimitry Andric // This is dubious, but allow it to be safe. Just ignore the alias. 58610b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 58620b57cec5SDimitry Andric if (Entry && !Entry->isDeclaration()) 58630b57cec5SDimitry Andric return; 58640b57cec5SDimitry Andric 58650b57cec5SDimitry Andric Aliases.push_back(GD); 58660b57cec5SDimitry Andric 58670b57cec5SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 58680b57cec5SDimitry Andric 58690b57cec5SDimitry Andric // Create a reference to the named value. This ensures that it is emitted 58700b57cec5SDimitry Andric // if a deferred decl. 58710b57cec5SDimitry Andric llvm::Constant *Aliasee; 58720b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes LT; 58730b57cec5SDimitry Andric if (isa<llvm::FunctionType>(DeclTy)) { 58740b57cec5SDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 58750b57cec5SDimitry Andric /*ForVTable=*/false); 58760b57cec5SDimitry Andric LT = getFunctionLinkage(GD); 58770b57cec5SDimitry Andric } else { 5878349cc55cSDimitry Andric Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 58790b57cec5SDimitry Andric /*D=*/nullptr); 5880e8d8bef9SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl())) 5881271697daSDimitry Andric LT = getLLVMLinkageVarDefinition(VD); 5882e8d8bef9SDimitry Andric else 5883e8d8bef9SDimitry Andric LT = getFunctionLinkage(GD); 58840b57cec5SDimitry Andric } 58850b57cec5SDimitry Andric 58860b57cec5SDimitry Andric // Create the new alias itself, but don't set a name yet. 58875ffd83dbSDimitry Andric unsigned AS = Aliasee->getType()->getPointerAddressSpace(); 58880b57cec5SDimitry Andric auto *GA = 58895ffd83dbSDimitry Andric llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule()); 58900b57cec5SDimitry Andric 58910b57cec5SDimitry Andric if (Entry) { 58920b57cec5SDimitry Andric if (GA->getAliasee() == Entry) { 58930b57cec5SDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 58940b57cec5SDimitry Andric return; 58950b57cec5SDimitry Andric } 58960b57cec5SDimitry Andric 58970b57cec5SDimitry Andric assert(Entry->isDeclaration()); 58980b57cec5SDimitry Andric 58990b57cec5SDimitry Andric // If there is a declaration in the module, then we had an extern followed 59000b57cec5SDimitry Andric // by the alias, as in: 59010b57cec5SDimitry Andric // extern int test6(); 59020b57cec5SDimitry Andric // ... 59030b57cec5SDimitry Andric // int test6() __attribute__((alias("test7"))); 59040b57cec5SDimitry Andric // 59050b57cec5SDimitry Andric // Remove it and replace uses of it with the alias. 59060b57cec5SDimitry Andric GA->takeName(Entry); 59070b57cec5SDimitry Andric 5908c9157d92SDimitry Andric Entry->replaceAllUsesWith(GA); 59090b57cec5SDimitry Andric Entry->eraseFromParent(); 59100b57cec5SDimitry Andric } else { 59110b57cec5SDimitry Andric GA->setName(MangledName); 59120b57cec5SDimitry Andric } 59130b57cec5SDimitry Andric 59140b57cec5SDimitry Andric // Set attributes which are particular to an alias; this is a 59150b57cec5SDimitry Andric // specialization of the attributes which may be set on a global 59160b57cec5SDimitry Andric // variable/function. 59170b57cec5SDimitry Andric if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 59180b57cec5SDimitry Andric D->isWeakImported()) { 59190b57cec5SDimitry Andric GA->setLinkage(llvm::Function::WeakAnyLinkage); 59200b57cec5SDimitry Andric } 59210b57cec5SDimitry Andric 59220b57cec5SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 59230b57cec5SDimitry Andric if (VD->getTLSKind()) 59240b57cec5SDimitry Andric setTLSMode(GA, *VD); 59250b57cec5SDimitry Andric 59260b57cec5SDimitry Andric SetCommonAttributes(GD, GA); 592781ad6265SDimitry Andric 592881ad6265SDimitry Andric // Emit global alias debug information. 592981ad6265SDimitry Andric if (isa<VarDecl>(D)) 593081ad6265SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 5931bdd1243dSDimitry Andric DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD); 59320b57cec5SDimitry Andric } 59330b57cec5SDimitry Andric 59340b57cec5SDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 59350b57cec5SDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 59360b57cec5SDimitry Andric const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 59370b57cec5SDimitry Andric assert(IFA && "Not an ifunc?"); 59380b57cec5SDimitry Andric 59390b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 59400b57cec5SDimitry Andric 59410b57cec5SDimitry Andric if (IFA->getResolver() == MangledName) { 59420b57cec5SDimitry Andric Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 59430b57cec5SDimitry Andric return; 59440b57cec5SDimitry Andric } 59450b57cec5SDimitry Andric 59460b57cec5SDimitry Andric // Report an error if some definition overrides ifunc. 59470b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 59480b57cec5SDimitry Andric if (Entry && !Entry->isDeclaration()) { 59490b57cec5SDimitry Andric GlobalDecl OtherGD; 59500b57cec5SDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 59510b57cec5SDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 59520b57cec5SDimitry Andric Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name) 59530b57cec5SDimitry Andric << MangledName; 59540b57cec5SDimitry Andric Diags.Report(OtherGD.getDecl()->getLocation(), 59550b57cec5SDimitry Andric diag::note_previous_definition); 59560b57cec5SDimitry Andric } 59570b57cec5SDimitry Andric return; 59580b57cec5SDimitry Andric } 59590b57cec5SDimitry Andric 59600b57cec5SDimitry Andric Aliases.push_back(GD); 59610b57cec5SDimitry Andric 59620b57cec5SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 5963349cc55cSDimitry Andric llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy); 59640b57cec5SDimitry Andric llvm::Constant *Resolver = 5965349cc55cSDimitry Andric GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {}, 59660b57cec5SDimitry Andric /*ForVTable=*/false); 59670b57cec5SDimitry Andric llvm::GlobalIFunc *GIF = 59680b57cec5SDimitry Andric llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 59690b57cec5SDimitry Andric "", Resolver, &getModule()); 59700b57cec5SDimitry Andric if (Entry) { 59710b57cec5SDimitry Andric if (GIF->getResolver() == Entry) { 59720b57cec5SDimitry Andric Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 59730b57cec5SDimitry Andric return; 59740b57cec5SDimitry Andric } 59750b57cec5SDimitry Andric assert(Entry->isDeclaration()); 59760b57cec5SDimitry Andric 59770b57cec5SDimitry Andric // If there is a declaration in the module, then we had an extern followed 59780b57cec5SDimitry Andric // by the ifunc, as in: 59790b57cec5SDimitry Andric // extern int test(); 59800b57cec5SDimitry Andric // ... 59810b57cec5SDimitry Andric // int test() __attribute__((ifunc("resolver"))); 59820b57cec5SDimitry Andric // 59830b57cec5SDimitry Andric // Remove it and replace uses of it with the ifunc. 59840b57cec5SDimitry Andric GIF->takeName(Entry); 59850b57cec5SDimitry Andric 5986c9157d92SDimitry Andric Entry->replaceAllUsesWith(GIF); 59870b57cec5SDimitry Andric Entry->eraseFromParent(); 59880b57cec5SDimitry Andric } else 59890b57cec5SDimitry Andric GIF->setName(MangledName); 5990c9157d92SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(Resolver)) { 5991c9157d92SDimitry Andric F->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation); 5992c9157d92SDimitry Andric } 59930b57cec5SDimitry Andric SetCommonAttributes(GD, GIF); 59940b57cec5SDimitry Andric } 59950b57cec5SDimitry Andric 59960b57cec5SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 59970b57cec5SDimitry Andric ArrayRef<llvm::Type*> Tys) { 59980b57cec5SDimitry Andric return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 59990b57cec5SDimitry Andric Tys); 60000b57cec5SDimitry Andric } 60010b57cec5SDimitry Andric 60020b57cec5SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> & 60030b57cec5SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 60040b57cec5SDimitry Andric const StringLiteral *Literal, bool TargetIsLSB, 60050b57cec5SDimitry Andric bool &IsUTF16, unsigned &StringLength) { 60060b57cec5SDimitry Andric StringRef String = Literal->getString(); 60070b57cec5SDimitry Andric unsigned NumBytes = String.size(); 60080b57cec5SDimitry Andric 60090b57cec5SDimitry Andric // Check for simple case. 60100b57cec5SDimitry Andric if (!Literal->containsNonAsciiOrNull()) { 60110b57cec5SDimitry Andric StringLength = NumBytes; 60120b57cec5SDimitry Andric return *Map.insert(std::make_pair(String, nullptr)).first; 60130b57cec5SDimitry Andric } 60140b57cec5SDimitry Andric 60150b57cec5SDimitry Andric // Otherwise, convert the UTF8 literals into a string of shorts. 60160b57cec5SDimitry Andric IsUTF16 = true; 60170b57cec5SDimitry Andric 60180b57cec5SDimitry Andric SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 60190b57cec5SDimitry Andric const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 60200b57cec5SDimitry Andric llvm::UTF16 *ToPtr = &ToBuf[0]; 60210b57cec5SDimitry Andric 60220b57cec5SDimitry Andric (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 60230b57cec5SDimitry Andric ToPtr + NumBytes, llvm::strictConversion); 60240b57cec5SDimitry Andric 60250b57cec5SDimitry Andric // ConvertUTF8toUTF16 returns the length in ToPtr. 60260b57cec5SDimitry Andric StringLength = ToPtr - &ToBuf[0]; 60270b57cec5SDimitry Andric 60280b57cec5SDimitry Andric // Add an explicit null. 60290b57cec5SDimitry Andric *ToPtr = 0; 60300b57cec5SDimitry Andric return *Map.insert(std::make_pair( 60310b57cec5SDimitry Andric StringRef(reinterpret_cast<const char *>(ToBuf.data()), 60320b57cec5SDimitry Andric (StringLength + 1) * 2), 60330b57cec5SDimitry Andric nullptr)).first; 60340b57cec5SDimitry Andric } 60350b57cec5SDimitry Andric 60360b57cec5SDimitry Andric ConstantAddress 60370b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 60380b57cec5SDimitry Andric unsigned StringLength = 0; 60390b57cec5SDimitry Andric bool isUTF16 = false; 60400b57cec5SDimitry Andric llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 60410b57cec5SDimitry Andric GetConstantCFStringEntry(CFConstantStringMap, Literal, 60420b57cec5SDimitry Andric getDataLayout().isLittleEndian(), isUTF16, 60430b57cec5SDimitry Andric StringLength); 60440b57cec5SDimitry Andric 60450b57cec5SDimitry Andric if (auto *C = Entry.second) 60460eae32dcSDimitry Andric return ConstantAddress( 60470eae32dcSDimitry Andric C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment())); 60480b57cec5SDimitry Andric 60490b57cec5SDimitry Andric llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 60500b57cec5SDimitry Andric llvm::Constant *Zeros[] = { Zero, Zero }; 60510b57cec5SDimitry Andric 60520b57cec5SDimitry Andric const ASTContext &Context = getContext(); 60530b57cec5SDimitry Andric const llvm::Triple &Triple = getTriple(); 60540b57cec5SDimitry Andric 60550b57cec5SDimitry Andric const auto CFRuntime = getLangOpts().CFRuntime; 60560b57cec5SDimitry Andric const bool IsSwiftABI = 60570b57cec5SDimitry Andric static_cast<unsigned>(CFRuntime) >= 60580b57cec5SDimitry Andric static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift); 60590b57cec5SDimitry Andric const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1; 60600b57cec5SDimitry Andric 60610b57cec5SDimitry Andric // If we don't already have it, get __CFConstantStringClassReference. 60620b57cec5SDimitry Andric if (!CFConstantStringClassRef) { 60630b57cec5SDimitry Andric const char *CFConstantStringClassName = "__CFConstantStringClassReference"; 60640b57cec5SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 60650b57cec5SDimitry Andric Ty = llvm::ArrayType::get(Ty, 0); 60660b57cec5SDimitry Andric 60670b57cec5SDimitry Andric switch (CFRuntime) { 60680b57cec5SDimitry Andric default: break; 6069bdd1243dSDimitry Andric case LangOptions::CoreFoundationABI::Swift: [[fallthrough]]; 60700b57cec5SDimitry Andric case LangOptions::CoreFoundationABI::Swift5_0: 60710b57cec5SDimitry Andric CFConstantStringClassName = 60720b57cec5SDimitry Andric Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN" 60730b57cec5SDimitry Andric : "$s10Foundation19_NSCFConstantStringCN"; 60740b57cec5SDimitry Andric Ty = IntPtrTy; 60750b57cec5SDimitry Andric break; 60760b57cec5SDimitry Andric case LangOptions::CoreFoundationABI::Swift4_2: 60770b57cec5SDimitry Andric CFConstantStringClassName = 60780b57cec5SDimitry Andric Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN" 60790b57cec5SDimitry Andric : "$S10Foundation19_NSCFConstantStringCN"; 60800b57cec5SDimitry Andric Ty = IntPtrTy; 60810b57cec5SDimitry Andric break; 60820b57cec5SDimitry Andric case LangOptions::CoreFoundationABI::Swift4_1: 60830b57cec5SDimitry Andric CFConstantStringClassName = 60840b57cec5SDimitry Andric Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN" 60850b57cec5SDimitry Andric : "__T010Foundation19_NSCFConstantStringCN"; 60860b57cec5SDimitry Andric Ty = IntPtrTy; 60870b57cec5SDimitry Andric break; 60880b57cec5SDimitry Andric } 60890b57cec5SDimitry Andric 60900b57cec5SDimitry Andric llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName); 60910b57cec5SDimitry Andric 60920b57cec5SDimitry Andric if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) { 60930b57cec5SDimitry Andric llvm::GlobalValue *GV = nullptr; 60940b57cec5SDimitry Andric 60950b57cec5SDimitry Andric if ((GV = dyn_cast<llvm::GlobalValue>(C))) { 60960b57cec5SDimitry Andric IdentifierInfo &II = Context.Idents.get(GV->getName()); 60970b57cec5SDimitry Andric TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl(); 60980b57cec5SDimitry Andric DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 60990b57cec5SDimitry Andric 61000b57cec5SDimitry Andric const VarDecl *VD = nullptr; 6101fe6060f1SDimitry Andric for (const auto *Result : DC->lookup(&II)) 61020b57cec5SDimitry Andric if ((VD = dyn_cast<VarDecl>(Result))) 61030b57cec5SDimitry Andric break; 61040b57cec5SDimitry Andric 61050b57cec5SDimitry Andric if (Triple.isOSBinFormatELF()) { 61060b57cec5SDimitry Andric if (!VD) 61070b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 61080b57cec5SDimitry Andric } else { 61090b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 61100b57cec5SDimitry Andric if (!VD || !VD->hasAttr<DLLExportAttr>()) 61110b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 61120b57cec5SDimitry Andric else 61130b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 61140b57cec5SDimitry Andric } 61150b57cec5SDimitry Andric 61160b57cec5SDimitry Andric setDSOLocal(GV); 61170b57cec5SDimitry Andric } 61180b57cec5SDimitry Andric } 61190b57cec5SDimitry Andric 61200b57cec5SDimitry Andric // Decay array -> ptr 61210b57cec5SDimitry Andric CFConstantStringClassRef = 61220b57cec5SDimitry Andric IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) 61230b57cec5SDimitry Andric : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros); 61240b57cec5SDimitry Andric } 61250b57cec5SDimitry Andric 61260b57cec5SDimitry Andric QualType CFTy = Context.getCFConstantStringType(); 61270b57cec5SDimitry Andric 61280b57cec5SDimitry Andric auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 61290b57cec5SDimitry Andric 61300b57cec5SDimitry Andric ConstantInitBuilder Builder(*this); 61310b57cec5SDimitry Andric auto Fields = Builder.beginStruct(STy); 61320b57cec5SDimitry Andric 61330b57cec5SDimitry Andric // Class pointer. 613481ad6265SDimitry Andric Fields.add(cast<llvm::Constant>(CFConstantStringClassRef)); 61350b57cec5SDimitry Andric 61360b57cec5SDimitry Andric // Flags. 61370b57cec5SDimitry Andric if (IsSwiftABI) { 61380b57cec5SDimitry Andric Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01); 61390b57cec5SDimitry Andric Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8); 61400b57cec5SDimitry Andric } else { 61410b57cec5SDimitry Andric Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); 61420b57cec5SDimitry Andric } 61430b57cec5SDimitry Andric 61440b57cec5SDimitry Andric // String pointer. 61450b57cec5SDimitry Andric llvm::Constant *C = nullptr; 61460b57cec5SDimitry Andric if (isUTF16) { 6147bdd1243dSDimitry Andric auto Arr = llvm::ArrayRef( 61480b57cec5SDimitry Andric reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 61490b57cec5SDimitry Andric Entry.first().size() / 2); 61500b57cec5SDimitry Andric C = llvm::ConstantDataArray::get(VMContext, Arr); 61510b57cec5SDimitry Andric } else { 61520b57cec5SDimitry Andric C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 61530b57cec5SDimitry Andric } 61540b57cec5SDimitry Andric 61550b57cec5SDimitry Andric // Note: -fwritable-strings doesn't make the backing store strings of 6156c9157d92SDimitry Andric // CFStrings writable. 61570b57cec5SDimitry Andric auto *GV = 61580b57cec5SDimitry Andric new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 61590b57cec5SDimitry Andric llvm::GlobalValue::PrivateLinkage, C, ".str"); 61600b57cec5SDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 61610b57cec5SDimitry Andric // Don't enforce the target's minimum global alignment, since the only use 61620b57cec5SDimitry Andric // of the string is via this class initializer. 61630b57cec5SDimitry Andric CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy) 61640b57cec5SDimitry Andric : Context.getTypeAlignInChars(Context.CharTy); 6165a7dea167SDimitry Andric GV->setAlignment(Align.getAsAlign()); 61660b57cec5SDimitry Andric 61670b57cec5SDimitry Andric // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 61680b57cec5SDimitry Andric // Without it LLVM can merge the string with a non unnamed_addr one during 61690b57cec5SDimitry Andric // LTO. Doing that changes the section it ends in, which surprises ld64. 61700b57cec5SDimitry Andric if (Triple.isOSBinFormatMachO()) 61710b57cec5SDimitry Andric GV->setSection(isUTF16 ? "__TEXT,__ustring" 61720b57cec5SDimitry Andric : "__TEXT,__cstring,cstring_literals"); 61730b57cec5SDimitry Andric // Make sure the literal ends up in .rodata to allow for safe ICF and for 61740b57cec5SDimitry Andric // the static linker to adjust permissions to read-only later on. 61750b57cec5SDimitry Andric else if (Triple.isOSBinFormatELF()) 61760b57cec5SDimitry Andric GV->setSection(".rodata"); 61770b57cec5SDimitry Andric 61780b57cec5SDimitry Andric // String. 61790b57cec5SDimitry Andric llvm::Constant *Str = 61800b57cec5SDimitry Andric llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 61810b57cec5SDimitry Andric 61820b57cec5SDimitry Andric Fields.add(Str); 61830b57cec5SDimitry Andric 61840b57cec5SDimitry Andric // String length. 61850b57cec5SDimitry Andric llvm::IntegerType *LengthTy = 61860b57cec5SDimitry Andric llvm::IntegerType::get(getModule().getContext(), 61870b57cec5SDimitry Andric Context.getTargetInfo().getLongWidth()); 61880b57cec5SDimitry Andric if (IsSwiftABI) { 61890b57cec5SDimitry Andric if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 61900b57cec5SDimitry Andric CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 61910b57cec5SDimitry Andric LengthTy = Int32Ty; 61920b57cec5SDimitry Andric else 61930b57cec5SDimitry Andric LengthTy = IntPtrTy; 61940b57cec5SDimitry Andric } 61950b57cec5SDimitry Andric Fields.addInt(LengthTy, StringLength); 61960b57cec5SDimitry Andric 6197a7dea167SDimitry Andric // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is 6198a7dea167SDimitry Andric // properly aligned on 32-bit platforms. 6199a7dea167SDimitry Andric CharUnits Alignment = 6200a7dea167SDimitry Andric IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign(); 62010b57cec5SDimitry Andric 62020b57cec5SDimitry Andric // The struct. 62030b57cec5SDimitry Andric GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, 62040b57cec5SDimitry Andric /*isConstant=*/false, 62050b57cec5SDimitry Andric llvm::GlobalVariable::PrivateLinkage); 62060b57cec5SDimitry Andric GV->addAttribute("objc_arc_inert"); 62070b57cec5SDimitry Andric switch (Triple.getObjectFormat()) { 62080b57cec5SDimitry Andric case llvm::Triple::UnknownObjectFormat: 62090b57cec5SDimitry Andric llvm_unreachable("unknown file format"); 621081ad6265SDimitry Andric case llvm::Triple::DXContainer: 6211e8d8bef9SDimitry Andric case llvm::Triple::GOFF: 621281ad6265SDimitry Andric case llvm::Triple::SPIRV: 62130b57cec5SDimitry Andric case llvm::Triple::XCOFF: 621481ad6265SDimitry Andric llvm_unreachable("unimplemented"); 62150b57cec5SDimitry Andric case llvm::Triple::COFF: 62160b57cec5SDimitry Andric case llvm::Triple::ELF: 62170b57cec5SDimitry Andric case llvm::Triple::Wasm: 62180b57cec5SDimitry Andric GV->setSection("cfstring"); 62190b57cec5SDimitry Andric break; 62200b57cec5SDimitry Andric case llvm::Triple::MachO: 62210b57cec5SDimitry Andric GV->setSection("__DATA,__cfstring"); 62220b57cec5SDimitry Andric break; 62230b57cec5SDimitry Andric } 62240b57cec5SDimitry Andric Entry.second = GV; 62250b57cec5SDimitry Andric 62260eae32dcSDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 62270b57cec5SDimitry Andric } 62280b57cec5SDimitry Andric 62290b57cec5SDimitry Andric bool CodeGenModule::getExpressionLocationsEnabled() const { 62300b57cec5SDimitry Andric return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo; 62310b57cec5SDimitry Andric } 62320b57cec5SDimitry Andric 62330b57cec5SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() { 62340b57cec5SDimitry Andric if (ObjCFastEnumerationStateType.isNull()) { 62350b57cec5SDimitry Andric RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 62360b57cec5SDimitry Andric D->startDefinition(); 62370b57cec5SDimitry Andric 62380b57cec5SDimitry Andric QualType FieldTypes[] = { 6239c9157d92SDimitry Andric Context.UnsignedLongTy, Context.getPointerType(Context.getObjCIdType()), 62400b57cec5SDimitry Andric Context.getPointerType(Context.UnsignedLongTy), 6241c9157d92SDimitry Andric Context.getConstantArrayType(Context.UnsignedLongTy, llvm::APInt(32, 5), 6242c9157d92SDimitry Andric nullptr, ArraySizeModifier::Normal, 0)}; 62430b57cec5SDimitry Andric 62440b57cec5SDimitry Andric for (size_t i = 0; i < 4; ++i) { 62450b57cec5SDimitry Andric FieldDecl *Field = FieldDecl::Create(Context, 62460b57cec5SDimitry Andric D, 62470b57cec5SDimitry Andric SourceLocation(), 62480b57cec5SDimitry Andric SourceLocation(), nullptr, 62490b57cec5SDimitry Andric FieldTypes[i], /*TInfo=*/nullptr, 62500b57cec5SDimitry Andric /*BitWidth=*/nullptr, 62510b57cec5SDimitry Andric /*Mutable=*/false, 62520b57cec5SDimitry Andric ICIS_NoInit); 62530b57cec5SDimitry Andric Field->setAccess(AS_public); 62540b57cec5SDimitry Andric D->addDecl(Field); 62550b57cec5SDimitry Andric } 62560b57cec5SDimitry Andric 62570b57cec5SDimitry Andric D->completeDefinition(); 62580b57cec5SDimitry Andric ObjCFastEnumerationStateType = Context.getTagDeclType(D); 62590b57cec5SDimitry Andric } 62600b57cec5SDimitry Andric 62610b57cec5SDimitry Andric return ObjCFastEnumerationStateType; 62620b57cec5SDimitry Andric } 62630b57cec5SDimitry Andric 62640b57cec5SDimitry Andric llvm::Constant * 62650b57cec5SDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 62660b57cec5SDimitry Andric assert(!E->getType()->isPointerType() && "Strings are always arrays"); 62670b57cec5SDimitry Andric 62680b57cec5SDimitry Andric // Don't emit it as the address of the string, emit the string data itself 62690b57cec5SDimitry Andric // as an inline array. 62700b57cec5SDimitry Andric if (E->getCharByteWidth() == 1) { 62710b57cec5SDimitry Andric SmallString<64> Str(E->getString()); 62720b57cec5SDimitry Andric 62730b57cec5SDimitry Andric // Resize the string to the right size, which is indicated by its type. 62740b57cec5SDimitry Andric const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 6275fe013be4SDimitry Andric assert(CAT && "String literal not of constant array type!"); 62760b57cec5SDimitry Andric Str.resize(CAT->getSize().getZExtValue()); 62770b57cec5SDimitry Andric return llvm::ConstantDataArray::getString(VMContext, Str, false); 62780b57cec5SDimitry Andric } 62790b57cec5SDimitry Andric 62800b57cec5SDimitry Andric auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 62810b57cec5SDimitry Andric llvm::Type *ElemTy = AType->getElementType(); 62820b57cec5SDimitry Andric unsigned NumElements = AType->getNumElements(); 62830b57cec5SDimitry Andric 62840b57cec5SDimitry Andric // Wide strings have either 2-byte or 4-byte elements. 62850b57cec5SDimitry Andric if (ElemTy->getPrimitiveSizeInBits() == 16) { 62860b57cec5SDimitry Andric SmallVector<uint16_t, 32> Elements; 62870b57cec5SDimitry Andric Elements.reserve(NumElements); 62880b57cec5SDimitry Andric 62890b57cec5SDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 62900b57cec5SDimitry Andric Elements.push_back(E->getCodeUnit(i)); 62910b57cec5SDimitry Andric Elements.resize(NumElements); 62920b57cec5SDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 62930b57cec5SDimitry Andric } 62940b57cec5SDimitry Andric 62950b57cec5SDimitry Andric assert(ElemTy->getPrimitiveSizeInBits() == 32); 62960b57cec5SDimitry Andric SmallVector<uint32_t, 32> Elements; 62970b57cec5SDimitry Andric Elements.reserve(NumElements); 62980b57cec5SDimitry Andric 62990b57cec5SDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 63000b57cec5SDimitry Andric Elements.push_back(E->getCodeUnit(i)); 63010b57cec5SDimitry Andric Elements.resize(NumElements); 63020b57cec5SDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 63030b57cec5SDimitry Andric } 63040b57cec5SDimitry Andric 63050b57cec5SDimitry Andric static llvm::GlobalVariable * 63060b57cec5SDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 63070b57cec5SDimitry Andric CodeGenModule &CGM, StringRef GlobalName, 63080b57cec5SDimitry Andric CharUnits Alignment) { 63090b57cec5SDimitry Andric unsigned AddrSpace = CGM.getContext().getTargetAddressSpace( 6310fe6060f1SDimitry Andric CGM.GetGlobalConstantAddressSpace()); 63110b57cec5SDimitry Andric 63120b57cec5SDimitry Andric llvm::Module &M = CGM.getModule(); 63130b57cec5SDimitry Andric // Create a global variable for this string 63140b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 63150b57cec5SDimitry Andric M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 63160b57cec5SDimitry Andric nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 6317a7dea167SDimitry Andric GV->setAlignment(Alignment.getAsAlign()); 63180b57cec5SDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 63190b57cec5SDimitry Andric if (GV->isWeakForLinker()) { 63200b57cec5SDimitry Andric assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 63210b57cec5SDimitry Andric GV->setComdat(M.getOrInsertComdat(GV->getName())); 63220b57cec5SDimitry Andric } 63230b57cec5SDimitry Andric CGM.setDSOLocal(GV); 63240b57cec5SDimitry Andric 63250b57cec5SDimitry Andric return GV; 63260b57cec5SDimitry Andric } 63270b57cec5SDimitry Andric 63280b57cec5SDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 63290b57cec5SDimitry Andric /// constant array for the given string literal. 63300b57cec5SDimitry Andric ConstantAddress 63310b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 63320b57cec5SDimitry Andric StringRef Name) { 63330b57cec5SDimitry Andric CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 63340b57cec5SDimitry Andric 63350b57cec5SDimitry Andric llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 63360b57cec5SDimitry Andric llvm::GlobalVariable **Entry = nullptr; 63370b57cec5SDimitry Andric if (!LangOpts.WritableStrings) { 63380b57cec5SDimitry Andric Entry = &ConstantStringMap[C]; 63390b57cec5SDimitry Andric if (auto GV = *Entry) { 6340349cc55cSDimitry Andric if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 6341a7dea167SDimitry Andric GV->setAlignment(Alignment.getAsAlign()); 63420b57cec5SDimitry Andric return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 63430eae32dcSDimitry Andric GV->getValueType(), Alignment); 63440b57cec5SDimitry Andric } 63450b57cec5SDimitry Andric } 63460b57cec5SDimitry Andric 63470b57cec5SDimitry Andric SmallString<256> MangledNameBuffer; 63480b57cec5SDimitry Andric StringRef GlobalVariableName; 63490b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes LT; 63500b57cec5SDimitry Andric 63510b57cec5SDimitry Andric // Mangle the string literal if that's how the ABI merges duplicate strings. 63520b57cec5SDimitry Andric // Don't do it if they are writable, since we don't want writes in one TU to 63530b57cec5SDimitry Andric // affect strings in another. 63540b57cec5SDimitry Andric if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) && 63550b57cec5SDimitry Andric !LangOpts.WritableStrings) { 63560b57cec5SDimitry Andric llvm::raw_svector_ostream Out(MangledNameBuffer); 63570b57cec5SDimitry Andric getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 63580b57cec5SDimitry Andric LT = llvm::GlobalValue::LinkOnceODRLinkage; 63590b57cec5SDimitry Andric GlobalVariableName = MangledNameBuffer; 63600b57cec5SDimitry Andric } else { 63610b57cec5SDimitry Andric LT = llvm::GlobalValue::PrivateLinkage; 63620b57cec5SDimitry Andric GlobalVariableName = Name; 63630b57cec5SDimitry Andric } 63640b57cec5SDimitry Andric 63650b57cec5SDimitry Andric auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 636681ad6265SDimitry Andric 636781ad6265SDimitry Andric CGDebugInfo *DI = getModuleDebugInfo(); 636881ad6265SDimitry Andric if (DI && getCodeGenOpts().hasReducedDebugInfo()) 636981ad6265SDimitry Andric DI->AddStringLiteralDebugInfo(GV, S); 637081ad6265SDimitry Andric 63710b57cec5SDimitry Andric if (Entry) 63720b57cec5SDimitry Andric *Entry = GV; 63730b57cec5SDimitry Andric 637481ad6265SDimitry Andric SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0), "<string literal>"); 63750b57cec5SDimitry Andric 63760b57cec5SDimitry Andric return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 63770eae32dcSDimitry Andric GV->getValueType(), Alignment); 63780b57cec5SDimitry Andric } 63790b57cec5SDimitry Andric 63800b57cec5SDimitry Andric /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 63810b57cec5SDimitry Andric /// array for the given ObjCEncodeExpr node. 63820b57cec5SDimitry Andric ConstantAddress 63830b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 63840b57cec5SDimitry Andric std::string Str; 63850b57cec5SDimitry Andric getContext().getObjCEncodingForType(E->getEncodedType(), Str); 63860b57cec5SDimitry Andric 63870b57cec5SDimitry Andric return GetAddrOfConstantCString(Str); 63880b57cec5SDimitry Andric } 63890b57cec5SDimitry Andric 63900b57cec5SDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing 63910b57cec5SDimitry Andric /// the literal and a terminating '\0' character. 63920b57cec5SDimitry Andric /// The result has pointer to array type. 63930b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString( 63940b57cec5SDimitry Andric const std::string &Str, const char *GlobalName) { 63950b57cec5SDimitry Andric StringRef StrWithNull(Str.c_str(), Str.size() + 1); 63960b57cec5SDimitry Andric CharUnits Alignment = 63970b57cec5SDimitry Andric getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 63980b57cec5SDimitry Andric 63990b57cec5SDimitry Andric llvm::Constant *C = 64000b57cec5SDimitry Andric llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 64010b57cec5SDimitry Andric 64020b57cec5SDimitry Andric // Don't share any string literals if strings aren't constant. 64030b57cec5SDimitry Andric llvm::GlobalVariable **Entry = nullptr; 64040b57cec5SDimitry Andric if (!LangOpts.WritableStrings) { 64050b57cec5SDimitry Andric Entry = &ConstantStringMap[C]; 64060b57cec5SDimitry Andric if (auto GV = *Entry) { 6407349cc55cSDimitry Andric if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 6408a7dea167SDimitry Andric GV->setAlignment(Alignment.getAsAlign()); 64090b57cec5SDimitry Andric return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 64100eae32dcSDimitry Andric GV->getValueType(), Alignment); 64110b57cec5SDimitry Andric } 64120b57cec5SDimitry Andric } 64130b57cec5SDimitry Andric 64140b57cec5SDimitry Andric // Get the default prefix if a name wasn't specified. 64150b57cec5SDimitry Andric if (!GlobalName) 64160b57cec5SDimitry Andric GlobalName = ".str"; 64170b57cec5SDimitry Andric // Create a global variable for this. 64180b57cec5SDimitry Andric auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 64190b57cec5SDimitry Andric GlobalName, Alignment); 64200b57cec5SDimitry Andric if (Entry) 64210b57cec5SDimitry Andric *Entry = GV; 64220b57cec5SDimitry Andric 64230b57cec5SDimitry Andric return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 64240eae32dcSDimitry Andric GV->getValueType(), Alignment); 64250b57cec5SDimitry Andric } 64260b57cec5SDimitry Andric 64270b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 64280b57cec5SDimitry Andric const MaterializeTemporaryExpr *E, const Expr *Init) { 64290b57cec5SDimitry Andric assert((E->getStorageDuration() == SD_Static || 64300b57cec5SDimitry Andric E->getStorageDuration() == SD_Thread) && "not a global temporary"); 64310b57cec5SDimitry Andric const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 64320b57cec5SDimitry Andric 64330b57cec5SDimitry Andric // If we're not materializing a subobject of the temporary, keep the 64340b57cec5SDimitry Andric // cv-qualifiers from the type of the MaterializeTemporaryExpr. 64350b57cec5SDimitry Andric QualType MaterializedType = Init->getType(); 6436480093f4SDimitry Andric if (Init == E->getSubExpr()) 64370b57cec5SDimitry Andric MaterializedType = E->getType(); 64380b57cec5SDimitry Andric 64390b57cec5SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 64400b57cec5SDimitry Andric 6441fe6060f1SDimitry Andric auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr}); 6442fe6060f1SDimitry Andric if (!InsertResult.second) { 6443fe6060f1SDimitry Andric // We've seen this before: either we already created it or we're in the 6444fe6060f1SDimitry Andric // process of doing so. 6445fe6060f1SDimitry Andric if (!InsertResult.first->second) { 6446fe6060f1SDimitry Andric // We recursively re-entered this function, probably during emission of 6447fe6060f1SDimitry Andric // the initializer. Create a placeholder. We'll clean this up in the 6448fe6060f1SDimitry Andric // outer call, at the end of this function. 6449fe6060f1SDimitry Andric llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType); 6450fe6060f1SDimitry Andric InsertResult.first->second = new llvm::GlobalVariable( 6451fe6060f1SDimitry Andric getModule(), Type, false, llvm::GlobalVariable::InternalLinkage, 6452fe6060f1SDimitry Andric nullptr); 6453fe6060f1SDimitry Andric } 645481ad6265SDimitry Andric return ConstantAddress(InsertResult.first->second, 645581ad6265SDimitry Andric llvm::cast<llvm::GlobalVariable>( 645681ad6265SDimitry Andric InsertResult.first->second->stripPointerCasts()) 645781ad6265SDimitry Andric ->getValueType(), 645881ad6265SDimitry Andric Align); 6459fe6060f1SDimitry Andric } 64600b57cec5SDimitry Andric 64610b57cec5SDimitry Andric // FIXME: If an externally-visible declaration extends multiple temporaries, 64620b57cec5SDimitry Andric // we need to give each temporary the same name in every translation unit (and 64630b57cec5SDimitry Andric // we also need to make the temporaries externally-visible). 64640b57cec5SDimitry Andric SmallString<256> Name; 64650b57cec5SDimitry Andric llvm::raw_svector_ostream Out(Name); 64660b57cec5SDimitry Andric getCXXABI().getMangleContext().mangleReferenceTemporary( 64670b57cec5SDimitry Andric VD, E->getManglingNumber(), Out); 64680b57cec5SDimitry Andric 64690b57cec5SDimitry Andric APValue *Value = nullptr; 6470c9157d92SDimitry Andric if (E->getStorageDuration() == SD_Static && VD->evaluateValue()) { 6471a7dea167SDimitry Andric // If the initializer of the extending declaration is a constant 6472a7dea167SDimitry Andric // initializer, we should have a cached constant initializer for this 6473a7dea167SDimitry Andric // temporary. Note that this might have a different value from the value 6474a7dea167SDimitry Andric // computed by evaluating the initializer if the surrounding constant 6475a7dea167SDimitry Andric // expression modifies the temporary. 6476480093f4SDimitry Andric Value = E->getOrCreateValue(false); 64770b57cec5SDimitry Andric } 64780b57cec5SDimitry Andric 64790b57cec5SDimitry Andric // Try evaluating it now, it might have a constant initializer. 64800b57cec5SDimitry Andric Expr::EvalResult EvalResult; 64810b57cec5SDimitry Andric if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 64820b57cec5SDimitry Andric !EvalResult.hasSideEffects()) 64830b57cec5SDimitry Andric Value = &EvalResult.Val; 64840b57cec5SDimitry Andric 6485c9157d92SDimitry Andric LangAS AddrSpace = GetGlobalVarAddressSpace(VD); 64860b57cec5SDimitry Andric 6487bdd1243dSDimitry Andric std::optional<ConstantEmitter> emitter; 64880b57cec5SDimitry Andric llvm::Constant *InitialValue = nullptr; 64890b57cec5SDimitry Andric bool Constant = false; 64900b57cec5SDimitry Andric llvm::Type *Type; 64910b57cec5SDimitry Andric if (Value) { 64920b57cec5SDimitry Andric // The temporary has a constant initializer, use it. 64930b57cec5SDimitry Andric emitter.emplace(*this); 64940b57cec5SDimitry Andric InitialValue = emitter->emitForInitializer(*Value, AddrSpace, 64950b57cec5SDimitry Andric MaterializedType); 6496c9157d92SDimitry Andric Constant = 6497c9157d92SDimitry Andric MaterializedType.isConstantStorage(getContext(), /*ExcludeCtor*/ Value, 6498fe013be4SDimitry Andric /*ExcludeDtor*/ false); 64990b57cec5SDimitry Andric Type = InitialValue->getType(); 65000b57cec5SDimitry Andric } else { 65010b57cec5SDimitry Andric // No initializer, the initialization will be provided when we 65020b57cec5SDimitry Andric // initialize the declaration which performed lifetime extension. 65030b57cec5SDimitry Andric Type = getTypes().ConvertTypeForMem(MaterializedType); 65040b57cec5SDimitry Andric } 65050b57cec5SDimitry Andric 65060b57cec5SDimitry Andric // Create a global variable for this lifetime-extended temporary. 6507271697daSDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(VD); 65080b57cec5SDimitry Andric if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 65090b57cec5SDimitry Andric const VarDecl *InitVD; 65100b57cec5SDimitry Andric if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 65110b57cec5SDimitry Andric isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 65120b57cec5SDimitry Andric // Temporaries defined inside a class get linkonce_odr linkage because the 65130b57cec5SDimitry Andric // class can be defined in multiple translation units. 65140b57cec5SDimitry Andric Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 65150b57cec5SDimitry Andric } else { 65160b57cec5SDimitry Andric // There is no need for this temporary to have external linkage if the 65170b57cec5SDimitry Andric // VarDecl has external linkage. 65180b57cec5SDimitry Andric Linkage = llvm::GlobalVariable::InternalLinkage; 65190b57cec5SDimitry Andric } 65200b57cec5SDimitry Andric } 65210b57cec5SDimitry Andric auto TargetAS = getContext().getTargetAddressSpace(AddrSpace); 65220b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 65230b57cec5SDimitry Andric getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 65240b57cec5SDimitry Andric /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); 65250b57cec5SDimitry Andric if (emitter) emitter->finalize(GV); 6526bdd1243dSDimitry Andric // Don't assign dllimport or dllexport to local linkage globals. 6527bdd1243dSDimitry Andric if (!llvm::GlobalValue::isLocalLinkage(Linkage)) { 65280b57cec5SDimitry Andric setGVProperties(GV, VD); 652981ad6265SDimitry Andric if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass) 653081ad6265SDimitry Andric // The reference temporary should never be dllexport. 653181ad6265SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 6532bdd1243dSDimitry Andric } 6533a7dea167SDimitry Andric GV->setAlignment(Align.getAsAlign()); 65340b57cec5SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker()) 65350b57cec5SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 65360b57cec5SDimitry Andric if (VD->getTLSKind()) 65370b57cec5SDimitry Andric setTLSMode(GV, *VD); 65380b57cec5SDimitry Andric llvm::Constant *CV = GV; 65390b57cec5SDimitry Andric if (AddrSpace != LangAS::Default) 65400b57cec5SDimitry Andric CV = getTargetCodeGenInfo().performAddrSpaceCast( 65410b57cec5SDimitry Andric *this, GV, AddrSpace, LangAS::Default, 6542c9157d92SDimitry Andric llvm::PointerType::get( 6543c9157d92SDimitry Andric getLLVMContext(), 65440b57cec5SDimitry Andric getContext().getTargetAddressSpace(LangAS::Default))); 6545fe6060f1SDimitry Andric 6546fe6060f1SDimitry Andric // Update the map with the new temporary. If we created a placeholder above, 6547fe6060f1SDimitry Andric // replace it with the new global now. 6548fe6060f1SDimitry Andric llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E]; 6549fe6060f1SDimitry Andric if (Entry) { 6550c9157d92SDimitry Andric Entry->replaceAllUsesWith(CV); 6551fe6060f1SDimitry Andric llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent(); 6552fe6060f1SDimitry Andric } 6553fe6060f1SDimitry Andric Entry = CV; 6554fe6060f1SDimitry Andric 65550eae32dcSDimitry Andric return ConstantAddress(CV, Type, Align); 65560b57cec5SDimitry Andric } 65570b57cec5SDimitry Andric 65580b57cec5SDimitry Andric /// EmitObjCPropertyImplementations - Emit information for synthesized 65590b57cec5SDimitry Andric /// properties for an implementation. 65600b57cec5SDimitry Andric void CodeGenModule::EmitObjCPropertyImplementations(const 65610b57cec5SDimitry Andric ObjCImplementationDecl *D) { 65620b57cec5SDimitry Andric for (const auto *PID : D->property_impls()) { 65630b57cec5SDimitry Andric // Dynamic is just for type-checking. 65640b57cec5SDimitry Andric if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 65650b57cec5SDimitry Andric ObjCPropertyDecl *PD = PID->getPropertyDecl(); 65660b57cec5SDimitry Andric 65670b57cec5SDimitry Andric // Determine which methods need to be implemented, some may have 65680b57cec5SDimitry Andric // been overridden. Note that ::isPropertyAccessor is not the method 65690b57cec5SDimitry Andric // we want, that just indicates if the decl came from a 65700b57cec5SDimitry Andric // property. What we want to know is if the method is defined in 65710b57cec5SDimitry Andric // this implementation. 6572480093f4SDimitry Andric auto *Getter = PID->getGetterMethodDecl(); 6573480093f4SDimitry Andric if (!Getter || Getter->isSynthesizedAccessorStub()) 65740b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCGetter( 65750b57cec5SDimitry Andric const_cast<ObjCImplementationDecl *>(D), PID); 6576480093f4SDimitry Andric auto *Setter = PID->getSetterMethodDecl(); 6577480093f4SDimitry Andric if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub())) 65780b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCSetter( 65790b57cec5SDimitry Andric const_cast<ObjCImplementationDecl *>(D), PID); 65800b57cec5SDimitry Andric } 65810b57cec5SDimitry Andric } 65820b57cec5SDimitry Andric } 65830b57cec5SDimitry Andric 65840b57cec5SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) { 65850b57cec5SDimitry Andric const ObjCInterfaceDecl *iface = impl->getClassInterface(); 65860b57cec5SDimitry Andric for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 65870b57cec5SDimitry Andric ivar; ivar = ivar->getNextIvar()) 65880b57cec5SDimitry Andric if (ivar->getType().isDestructedType()) 65890b57cec5SDimitry Andric return true; 65900b57cec5SDimitry Andric 65910b57cec5SDimitry Andric return false; 65920b57cec5SDimitry Andric } 65930b57cec5SDimitry Andric 65940b57cec5SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM, 65950b57cec5SDimitry Andric ObjCImplementationDecl *D) { 65960b57cec5SDimitry Andric CodeGenFunction CGF(CGM); 65970b57cec5SDimitry Andric for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 65980b57cec5SDimitry Andric E = D->init_end(); B != E; ++B) { 65990b57cec5SDimitry Andric CXXCtorInitializer *CtorInitExp = *B; 66000b57cec5SDimitry Andric Expr *Init = CtorInitExp->getInit(); 66010b57cec5SDimitry Andric if (!CGF.isTrivialInitializer(Init)) 66020b57cec5SDimitry Andric return false; 66030b57cec5SDimitry Andric } 66040b57cec5SDimitry Andric return true; 66050b57cec5SDimitry Andric } 66060b57cec5SDimitry Andric 66070b57cec5SDimitry Andric /// EmitObjCIvarInitializations - Emit information for ivar initialization 66080b57cec5SDimitry Andric /// for an implementation. 66090b57cec5SDimitry Andric void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 66100b57cec5SDimitry Andric // We might need a .cxx_destruct even if we don't have any ivar initializers. 66110b57cec5SDimitry Andric if (needsDestructMethod(D)) { 66120b57cec5SDimitry Andric IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 66130b57cec5SDimitry Andric Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 6614480093f4SDimitry Andric ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create( 6615480093f4SDimitry Andric getContext(), D->getLocation(), D->getLocation(), cxxSelector, 6616480093f4SDimitry Andric getContext().VoidTy, nullptr, D, 66170b57cec5SDimitry Andric /*isInstance=*/true, /*isVariadic=*/false, 6618480093f4SDimitry Andric /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 6619480093f4SDimitry Andric /*isImplicitlyDeclared=*/true, 6620c9157d92SDimitry Andric /*isDefined=*/false, ObjCImplementationControl::Required); 66210b57cec5SDimitry Andric D->addInstanceMethod(DTORMethod); 66220b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 66230b57cec5SDimitry Andric D->setHasDestructors(true); 66240b57cec5SDimitry Andric } 66250b57cec5SDimitry Andric 66260b57cec5SDimitry Andric // If the implementation doesn't have any ivar initializers, we don't need 66270b57cec5SDimitry Andric // a .cxx_construct. 66280b57cec5SDimitry Andric if (D->getNumIvarInitializers() == 0 || 66290b57cec5SDimitry Andric AllTrivialInitializers(*this, D)) 66300b57cec5SDimitry Andric return; 66310b57cec5SDimitry Andric 66320b57cec5SDimitry Andric IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 66330b57cec5SDimitry Andric Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 66340b57cec5SDimitry Andric // The constructor returns 'self'. 6635480093f4SDimitry Andric ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create( 6636480093f4SDimitry Andric getContext(), D->getLocation(), D->getLocation(), cxxSelector, 6637480093f4SDimitry Andric getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true, 66380b57cec5SDimitry Andric /*isVariadic=*/false, 6639480093f4SDimitry Andric /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 66400b57cec5SDimitry Andric /*isImplicitlyDeclared=*/true, 6641c9157d92SDimitry Andric /*isDefined=*/false, ObjCImplementationControl::Required); 66420b57cec5SDimitry Andric D->addInstanceMethod(CTORMethod); 66430b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 66440b57cec5SDimitry Andric D->setHasNonZeroConstructors(true); 66450b57cec5SDimitry Andric } 66460b57cec5SDimitry Andric 66470b57cec5SDimitry Andric // EmitLinkageSpec - Emit all declarations in a linkage spec. 66480b57cec5SDimitry Andric void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 6649c9157d92SDimitry Andric if (LSD->getLanguage() != LinkageSpecLanguageIDs::C && 6650c9157d92SDimitry Andric LSD->getLanguage() != LinkageSpecLanguageIDs::CXX) { 66510b57cec5SDimitry Andric ErrorUnsupported(LSD, "linkage spec"); 66520b57cec5SDimitry Andric return; 66530b57cec5SDimitry Andric } 66540b57cec5SDimitry Andric 66550b57cec5SDimitry Andric EmitDeclContext(LSD); 66560b57cec5SDimitry Andric } 66570b57cec5SDimitry Andric 6658bdd1243dSDimitry Andric void CodeGenModule::EmitTopLevelStmt(const TopLevelStmtDecl *D) { 6659fe013be4SDimitry Andric // Device code should not be at top level. 6660fe013be4SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 6661fe013be4SDimitry Andric return; 6662fe013be4SDimitry Andric 6663bdd1243dSDimitry Andric std::unique_ptr<CodeGenFunction> &CurCGF = 6664bdd1243dSDimitry Andric GlobalTopLevelStmtBlockInFlight.first; 6665bdd1243dSDimitry Andric 6666bdd1243dSDimitry Andric // We emitted a top-level stmt but after it there is initialization. 6667bdd1243dSDimitry Andric // Stop squashing the top-level stmts into a single function. 6668bdd1243dSDimitry Andric if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) { 6669bdd1243dSDimitry Andric CurCGF->FinishFunction(D->getEndLoc()); 6670bdd1243dSDimitry Andric CurCGF = nullptr; 6671bdd1243dSDimitry Andric } 6672bdd1243dSDimitry Andric 6673bdd1243dSDimitry Andric if (!CurCGF) { 6674bdd1243dSDimitry Andric // void __stmts__N(void) 6675bdd1243dSDimitry Andric // FIXME: Ask the ABI name mangler to pick a name. 6676bdd1243dSDimitry Andric std::string Name = "__stmts__" + llvm::utostr(CXXGlobalInits.size()); 6677bdd1243dSDimitry Andric FunctionArgList Args; 6678bdd1243dSDimitry Andric QualType RetTy = getContext().VoidTy; 6679bdd1243dSDimitry Andric const CGFunctionInfo &FnInfo = 6680bdd1243dSDimitry Andric getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args); 6681bdd1243dSDimitry Andric llvm::FunctionType *FnTy = getTypes().GetFunctionType(FnInfo); 6682bdd1243dSDimitry Andric llvm::Function *Fn = llvm::Function::Create( 6683bdd1243dSDimitry Andric FnTy, llvm::GlobalValue::InternalLinkage, Name, &getModule()); 6684bdd1243dSDimitry Andric 6685bdd1243dSDimitry Andric CurCGF.reset(new CodeGenFunction(*this)); 6686bdd1243dSDimitry Andric GlobalTopLevelStmtBlockInFlight.second = D; 6687bdd1243dSDimitry Andric CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args, 6688bdd1243dSDimitry Andric D->getBeginLoc(), D->getBeginLoc()); 6689bdd1243dSDimitry Andric CXXGlobalInits.push_back(Fn); 6690bdd1243dSDimitry Andric } 6691bdd1243dSDimitry Andric 6692bdd1243dSDimitry Andric CurCGF->EmitStmt(D->getStmt()); 6693bdd1243dSDimitry Andric } 6694bdd1243dSDimitry Andric 66950b57cec5SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) { 66960b57cec5SDimitry Andric for (auto *I : DC->decls()) { 66970b57cec5SDimitry Andric // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope 66980b57cec5SDimitry Andric // are themselves considered "top-level", so EmitTopLevelDecl on an 66990b57cec5SDimitry Andric // ObjCImplDecl does not recursively visit them. We need to do that in 67000b57cec5SDimitry Andric // case they're nested inside another construct (LinkageSpecDecl / 67010b57cec5SDimitry Andric // ExportDecl) that does stop them from being considered "top-level". 67020b57cec5SDimitry Andric if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 67030b57cec5SDimitry Andric for (auto *M : OID->methods()) 67040b57cec5SDimitry Andric EmitTopLevelDecl(M); 67050b57cec5SDimitry Andric } 67060b57cec5SDimitry Andric 67070b57cec5SDimitry Andric EmitTopLevelDecl(I); 67080b57cec5SDimitry Andric } 67090b57cec5SDimitry Andric } 67100b57cec5SDimitry Andric 67110b57cec5SDimitry Andric /// EmitTopLevelDecl - Emit code for a single top level declaration. 67120b57cec5SDimitry Andric void CodeGenModule::EmitTopLevelDecl(Decl *D) { 67130b57cec5SDimitry Andric // Ignore dependent declarations. 67140b57cec5SDimitry Andric if (D->isTemplated()) 67150b57cec5SDimitry Andric return; 67160b57cec5SDimitry Andric 67175ffd83dbSDimitry Andric // Consteval function shouldn't be emitted. 6718fe013be4SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D); FD && FD->isImmediateFunction()) 67195ffd83dbSDimitry Andric return; 67205ffd83dbSDimitry Andric 67210b57cec5SDimitry Andric switch (D->getKind()) { 67220b57cec5SDimitry Andric case Decl::CXXConversion: 67230b57cec5SDimitry Andric case Decl::CXXMethod: 67240b57cec5SDimitry Andric case Decl::Function: 67250b57cec5SDimitry Andric EmitGlobal(cast<FunctionDecl>(D)); 67260b57cec5SDimitry Andric // Always provide some coverage mapping 67270b57cec5SDimitry Andric // even for the functions that aren't emitted. 67280b57cec5SDimitry Andric AddDeferredUnusedCoverageMapping(D); 67290b57cec5SDimitry Andric break; 67300b57cec5SDimitry Andric 67310b57cec5SDimitry Andric case Decl::CXXDeductionGuide: 67320b57cec5SDimitry Andric // Function-like, but does not result in code emission. 67330b57cec5SDimitry Andric break; 67340b57cec5SDimitry Andric 67350b57cec5SDimitry Andric case Decl::Var: 67360b57cec5SDimitry Andric case Decl::Decomposition: 67370b57cec5SDimitry Andric case Decl::VarTemplateSpecialization: 67380b57cec5SDimitry Andric EmitGlobal(cast<VarDecl>(D)); 67390b57cec5SDimitry Andric if (auto *DD = dyn_cast<DecompositionDecl>(D)) 67400b57cec5SDimitry Andric for (auto *B : DD->bindings()) 67410b57cec5SDimitry Andric if (auto *HD = B->getHoldingVar()) 67420b57cec5SDimitry Andric EmitGlobal(HD); 67430b57cec5SDimitry Andric break; 67440b57cec5SDimitry Andric 67450b57cec5SDimitry Andric // Indirect fields from global anonymous structs and unions can be 67460b57cec5SDimitry Andric // ignored; only the actual variable requires IR gen support. 67470b57cec5SDimitry Andric case Decl::IndirectField: 67480b57cec5SDimitry Andric break; 67490b57cec5SDimitry Andric 67500b57cec5SDimitry Andric // C++ Decls 67510b57cec5SDimitry Andric case Decl::Namespace: 67520b57cec5SDimitry Andric EmitDeclContext(cast<NamespaceDecl>(D)); 67530b57cec5SDimitry Andric break; 67540b57cec5SDimitry Andric case Decl::ClassTemplateSpecialization: { 67550b57cec5SDimitry Andric const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 67565ffd83dbSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 67575ffd83dbSDimitry Andric if (Spec->getSpecializationKind() == 67585ffd83dbSDimitry Andric TSK_ExplicitInstantiationDefinition && 67590b57cec5SDimitry Andric Spec->hasDefinition()) 67605ffd83dbSDimitry Andric DI->completeTemplateDefinition(*Spec); 6761bdd1243dSDimitry Andric } [[fallthrough]]; 6762e8d8bef9SDimitry Andric case Decl::CXXRecord: { 6763e8d8bef9SDimitry Andric CXXRecordDecl *CRD = cast<CXXRecordDecl>(D); 6764e8d8bef9SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) { 6765e8d8bef9SDimitry Andric if (CRD->hasDefinition()) 6766e8d8bef9SDimitry Andric DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 67670b57cec5SDimitry Andric if (auto *ES = D->getASTContext().getExternalSource()) 67680b57cec5SDimitry Andric if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) 6769e8d8bef9SDimitry Andric DI->completeUnusedClass(*CRD); 6770e8d8bef9SDimitry Andric } 67710b57cec5SDimitry Andric // Emit any static data members, they may be definitions. 6772e8d8bef9SDimitry Andric for (auto *I : CRD->decls()) 67730b57cec5SDimitry Andric if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) 67740b57cec5SDimitry Andric EmitTopLevelDecl(I); 67750b57cec5SDimitry Andric break; 6776e8d8bef9SDimitry Andric } 67770b57cec5SDimitry Andric // No code generation needed. 67780b57cec5SDimitry Andric case Decl::UsingShadow: 67790b57cec5SDimitry Andric case Decl::ClassTemplate: 67800b57cec5SDimitry Andric case Decl::VarTemplate: 67810b57cec5SDimitry Andric case Decl::Concept: 67820b57cec5SDimitry Andric case Decl::VarTemplatePartialSpecialization: 67830b57cec5SDimitry Andric case Decl::FunctionTemplate: 67840b57cec5SDimitry Andric case Decl::TypeAliasTemplate: 67850b57cec5SDimitry Andric case Decl::Block: 67860b57cec5SDimitry Andric case Decl::Empty: 67870b57cec5SDimitry Andric case Decl::Binding: 67880b57cec5SDimitry Andric break; 67890b57cec5SDimitry Andric case Decl::Using: // using X; [C++] 67900b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 67910b57cec5SDimitry Andric DI->EmitUsingDecl(cast<UsingDecl>(*D)); 67925ffd83dbSDimitry Andric break; 6793fe6060f1SDimitry Andric case Decl::UsingEnum: // using enum X; [C++] 6794fe6060f1SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6795fe6060f1SDimitry Andric DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D)); 6796fe6060f1SDimitry Andric break; 67970b57cec5SDimitry Andric case Decl::NamespaceAlias: 67980b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 67990b57cec5SDimitry Andric DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 68005ffd83dbSDimitry Andric break; 68010b57cec5SDimitry Andric case Decl::UsingDirective: // using namespace X; [C++] 68020b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 68030b57cec5SDimitry Andric DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 68045ffd83dbSDimitry Andric break; 68050b57cec5SDimitry Andric case Decl::CXXConstructor: 68060b57cec5SDimitry Andric getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 68070b57cec5SDimitry Andric break; 68080b57cec5SDimitry Andric case Decl::CXXDestructor: 68090b57cec5SDimitry Andric getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 68100b57cec5SDimitry Andric break; 68110b57cec5SDimitry Andric 68120b57cec5SDimitry Andric case Decl::StaticAssert: 68130b57cec5SDimitry Andric // Nothing to do. 68140b57cec5SDimitry Andric break; 68150b57cec5SDimitry Andric 68160b57cec5SDimitry Andric // Objective-C Decls 68170b57cec5SDimitry Andric 68180b57cec5SDimitry Andric // Forward declarations, no (immediate) code generation. 68190b57cec5SDimitry Andric case Decl::ObjCInterface: 68200b57cec5SDimitry Andric case Decl::ObjCCategory: 68210b57cec5SDimitry Andric break; 68220b57cec5SDimitry Andric 68230b57cec5SDimitry Andric case Decl::ObjCProtocol: { 68240b57cec5SDimitry Andric auto *Proto = cast<ObjCProtocolDecl>(D); 68250b57cec5SDimitry Andric if (Proto->isThisDeclarationADefinition()) 68260b57cec5SDimitry Andric ObjCRuntime->GenerateProtocol(Proto); 68270b57cec5SDimitry Andric break; 68280b57cec5SDimitry Andric } 68290b57cec5SDimitry Andric 68300b57cec5SDimitry Andric case Decl::ObjCCategoryImpl: 68310b57cec5SDimitry Andric // Categories have properties but don't support synthesize so we 68320b57cec5SDimitry Andric // can ignore them here. 68330b57cec5SDimitry Andric ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 68340b57cec5SDimitry Andric break; 68350b57cec5SDimitry Andric 68360b57cec5SDimitry Andric case Decl::ObjCImplementation: { 68370b57cec5SDimitry Andric auto *OMD = cast<ObjCImplementationDecl>(D); 68380b57cec5SDimitry Andric EmitObjCPropertyImplementations(OMD); 68390b57cec5SDimitry Andric EmitObjCIvarInitializations(OMD); 68400b57cec5SDimitry Andric ObjCRuntime->GenerateClass(OMD); 68410b57cec5SDimitry Andric // Emit global variable debug information. 68420b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6843480093f4SDimitry Andric if (getCodeGenOpts().hasReducedDebugInfo()) 68440b57cec5SDimitry Andric DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 68450b57cec5SDimitry Andric OMD->getClassInterface()), OMD->getLocation()); 68460b57cec5SDimitry Andric break; 68470b57cec5SDimitry Andric } 68480b57cec5SDimitry Andric case Decl::ObjCMethod: { 68490b57cec5SDimitry Andric auto *OMD = cast<ObjCMethodDecl>(D); 68500b57cec5SDimitry Andric // If this is not a prototype, emit the body. 68510b57cec5SDimitry Andric if (OMD->getBody()) 68520b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCMethod(OMD); 68530b57cec5SDimitry Andric break; 68540b57cec5SDimitry Andric } 68550b57cec5SDimitry Andric case Decl::ObjCCompatibleAlias: 68560b57cec5SDimitry Andric ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 68570b57cec5SDimitry Andric break; 68580b57cec5SDimitry Andric 68590b57cec5SDimitry Andric case Decl::PragmaComment: { 68600b57cec5SDimitry Andric const auto *PCD = cast<PragmaCommentDecl>(D); 68610b57cec5SDimitry Andric switch (PCD->getCommentKind()) { 68620b57cec5SDimitry Andric case PCK_Unknown: 68630b57cec5SDimitry Andric llvm_unreachable("unexpected pragma comment kind"); 68640b57cec5SDimitry Andric case PCK_Linker: 68650b57cec5SDimitry Andric AppendLinkerOptions(PCD->getArg()); 68660b57cec5SDimitry Andric break; 68670b57cec5SDimitry Andric case PCK_Lib: 68680b57cec5SDimitry Andric AddDependentLib(PCD->getArg()); 68690b57cec5SDimitry Andric break; 68700b57cec5SDimitry Andric case PCK_Compiler: 68710b57cec5SDimitry Andric case PCK_ExeStr: 68720b57cec5SDimitry Andric case PCK_User: 68730b57cec5SDimitry Andric break; // We ignore all of these. 68740b57cec5SDimitry Andric } 68750b57cec5SDimitry Andric break; 68760b57cec5SDimitry Andric } 68770b57cec5SDimitry Andric 68780b57cec5SDimitry Andric case Decl::PragmaDetectMismatch: { 68790b57cec5SDimitry Andric const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 68800b57cec5SDimitry Andric AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 68810b57cec5SDimitry Andric break; 68820b57cec5SDimitry Andric } 68830b57cec5SDimitry Andric 68840b57cec5SDimitry Andric case Decl::LinkageSpec: 68850b57cec5SDimitry Andric EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 68860b57cec5SDimitry Andric break; 68870b57cec5SDimitry Andric 68880b57cec5SDimitry Andric case Decl::FileScopeAsm: { 68890b57cec5SDimitry Andric // File-scope asm is ignored during device-side CUDA compilation. 68900b57cec5SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 68910b57cec5SDimitry Andric break; 68920b57cec5SDimitry Andric // File-scope asm is ignored during device-side OpenMP compilation. 6893fe013be4SDimitry Andric if (LangOpts.OpenMPIsTargetDevice) 68940b57cec5SDimitry Andric break; 6895fe6060f1SDimitry Andric // File-scope asm is ignored during device-side SYCL compilation. 6896fe6060f1SDimitry Andric if (LangOpts.SYCLIsDevice) 6897fe6060f1SDimitry Andric break; 68980b57cec5SDimitry Andric auto *AD = cast<FileScopeAsmDecl>(D); 68990b57cec5SDimitry Andric getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 69000b57cec5SDimitry Andric break; 69010b57cec5SDimitry Andric } 69020b57cec5SDimitry Andric 6903bdd1243dSDimitry Andric case Decl::TopLevelStmt: 6904bdd1243dSDimitry Andric EmitTopLevelStmt(cast<TopLevelStmtDecl>(D)); 6905bdd1243dSDimitry Andric break; 6906bdd1243dSDimitry Andric 69070b57cec5SDimitry Andric case Decl::Import: { 69080b57cec5SDimitry Andric auto *Import = cast<ImportDecl>(D); 69090b57cec5SDimitry Andric 69100b57cec5SDimitry Andric // If we've already imported this module, we're done. 69110b57cec5SDimitry Andric if (!ImportedModules.insert(Import->getImportedModule())) 69120b57cec5SDimitry Andric break; 69130b57cec5SDimitry Andric 69140b57cec5SDimitry Andric // Emit debug information for direct imports. 69150b57cec5SDimitry Andric if (!Import->getImportedOwningModule()) { 69160b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 69170b57cec5SDimitry Andric DI->EmitImportDecl(*Import); 69180b57cec5SDimitry Andric } 69190b57cec5SDimitry Andric 6920fcaf7f86SDimitry Andric // For C++ standard modules we are done - we will call the module 6921fcaf7f86SDimitry Andric // initializer for imported modules, and that will likewise call those for 6922fcaf7f86SDimitry Andric // any imports it has. 6923fcaf7f86SDimitry Andric if (CXX20ModuleInits && Import->getImportedOwningModule() && 6924fcaf7f86SDimitry Andric !Import->getImportedOwningModule()->isModuleMapModule()) 6925fcaf7f86SDimitry Andric break; 6926fcaf7f86SDimitry Andric 6927fcaf7f86SDimitry Andric // For clang C++ module map modules the initializers for sub-modules are 6928fcaf7f86SDimitry Andric // emitted here. 6929fcaf7f86SDimitry Andric 69300b57cec5SDimitry Andric // Find all of the submodules and emit the module initializers. 69310b57cec5SDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 69320b57cec5SDimitry Andric SmallVector<clang::Module *, 16> Stack; 69330b57cec5SDimitry Andric Visited.insert(Import->getImportedModule()); 69340b57cec5SDimitry Andric Stack.push_back(Import->getImportedModule()); 69350b57cec5SDimitry Andric 69360b57cec5SDimitry Andric while (!Stack.empty()) { 69370b57cec5SDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 69380b57cec5SDimitry Andric if (!EmittedModuleInitializers.insert(Mod).second) 69390b57cec5SDimitry Andric continue; 69400b57cec5SDimitry Andric 69410b57cec5SDimitry Andric for (auto *D : Context.getModuleInitializers(Mod)) 69420b57cec5SDimitry Andric EmitTopLevelDecl(D); 69430b57cec5SDimitry Andric 69440b57cec5SDimitry Andric // Visit the submodules of this module. 6945fe013be4SDimitry Andric for (auto *Submodule : Mod->submodules()) { 69460b57cec5SDimitry Andric // Skip explicit children; they need to be explicitly imported to emit 69470b57cec5SDimitry Andric // the initializers. 6948fe013be4SDimitry Andric if (Submodule->IsExplicit) 69490b57cec5SDimitry Andric continue; 69500b57cec5SDimitry Andric 6951fe013be4SDimitry Andric if (Visited.insert(Submodule).second) 6952fe013be4SDimitry Andric Stack.push_back(Submodule); 69530b57cec5SDimitry Andric } 69540b57cec5SDimitry Andric } 69550b57cec5SDimitry Andric break; 69560b57cec5SDimitry Andric } 69570b57cec5SDimitry Andric 69580b57cec5SDimitry Andric case Decl::Export: 69590b57cec5SDimitry Andric EmitDeclContext(cast<ExportDecl>(D)); 69600b57cec5SDimitry Andric break; 69610b57cec5SDimitry Andric 69620b57cec5SDimitry Andric case Decl::OMPThreadPrivate: 69630b57cec5SDimitry Andric EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 69640b57cec5SDimitry Andric break; 69650b57cec5SDimitry Andric 69660b57cec5SDimitry Andric case Decl::OMPAllocate: 6967fe6060f1SDimitry Andric EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D)); 69680b57cec5SDimitry Andric break; 69690b57cec5SDimitry Andric 69700b57cec5SDimitry Andric case Decl::OMPDeclareReduction: 69710b57cec5SDimitry Andric EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 69720b57cec5SDimitry Andric break; 69730b57cec5SDimitry Andric 69740b57cec5SDimitry Andric case Decl::OMPDeclareMapper: 69750b57cec5SDimitry Andric EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D)); 69760b57cec5SDimitry Andric break; 69770b57cec5SDimitry Andric 69780b57cec5SDimitry Andric case Decl::OMPRequires: 69790b57cec5SDimitry Andric EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D)); 69800b57cec5SDimitry Andric break; 69810b57cec5SDimitry Andric 6982e8d8bef9SDimitry Andric case Decl::Typedef: 6983e8d8bef9SDimitry Andric case Decl::TypeAlias: // using foo = bar; [C++11] 6984e8d8bef9SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6985e8d8bef9SDimitry Andric DI->EmitAndRetainType( 6986e8d8bef9SDimitry Andric getContext().getTypedefType(cast<TypedefNameDecl>(D))); 6987e8d8bef9SDimitry Andric break; 6988e8d8bef9SDimitry Andric 6989e8d8bef9SDimitry Andric case Decl::Record: 6990e8d8bef9SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6991e8d8bef9SDimitry Andric if (cast<RecordDecl>(D)->getDefinition()) 6992e8d8bef9SDimitry Andric DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 6993e8d8bef9SDimitry Andric break; 6994e8d8bef9SDimitry Andric 6995e8d8bef9SDimitry Andric case Decl::Enum: 6996e8d8bef9SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6997e8d8bef9SDimitry Andric if (cast<EnumDecl>(D)->getDefinition()) 6998e8d8bef9SDimitry Andric DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D))); 6999e8d8bef9SDimitry Andric break; 7000e8d8bef9SDimitry Andric 7001bdd1243dSDimitry Andric case Decl::HLSLBuffer: 7002bdd1243dSDimitry Andric getHLSLRuntime().addBuffer(cast<HLSLBufferDecl>(D)); 7003bdd1243dSDimitry Andric break; 7004bdd1243dSDimitry Andric 70050b57cec5SDimitry Andric default: 70060b57cec5SDimitry Andric // Make sure we handled everything we should, every other kind is a 70070b57cec5SDimitry Andric // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 70080b57cec5SDimitry Andric // function. Need to recode Decl::Kind to do that easily. 70090b57cec5SDimitry Andric assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 70100b57cec5SDimitry Andric break; 70110b57cec5SDimitry Andric } 70120b57cec5SDimitry Andric } 70130b57cec5SDimitry Andric 70140b57cec5SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 70150b57cec5SDimitry Andric // Do we need to generate coverage mapping? 70160b57cec5SDimitry Andric if (!CodeGenOpts.CoverageMapping) 70170b57cec5SDimitry Andric return; 70180b57cec5SDimitry Andric switch (D->getKind()) { 70190b57cec5SDimitry Andric case Decl::CXXConversion: 70200b57cec5SDimitry Andric case Decl::CXXMethod: 70210b57cec5SDimitry Andric case Decl::Function: 70220b57cec5SDimitry Andric case Decl::ObjCMethod: 70230b57cec5SDimitry Andric case Decl::CXXConstructor: 70240b57cec5SDimitry Andric case Decl::CXXDestructor: { 70250b57cec5SDimitry Andric if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 70265ffd83dbSDimitry Andric break; 70270b57cec5SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 70280b57cec5SDimitry Andric if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc())) 70295ffd83dbSDimitry Andric break; 7030c9157d92SDimitry Andric DeferredEmptyCoverageMappingDecls.try_emplace(D, true); 70310b57cec5SDimitry Andric break; 70320b57cec5SDimitry Andric } 70330b57cec5SDimitry Andric default: 70340b57cec5SDimitry Andric break; 70350b57cec5SDimitry Andric }; 70360b57cec5SDimitry Andric } 70370b57cec5SDimitry Andric 70380b57cec5SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 70390b57cec5SDimitry Andric // Do we need to generate coverage mapping? 70400b57cec5SDimitry Andric if (!CodeGenOpts.CoverageMapping) 70410b57cec5SDimitry Andric return; 70420b57cec5SDimitry Andric if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 70430b57cec5SDimitry Andric if (Fn->isTemplateInstantiation()) 70440b57cec5SDimitry Andric ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 70450b57cec5SDimitry Andric } 7046c9157d92SDimitry Andric DeferredEmptyCoverageMappingDecls.insert_or_assign(D, false); 70470b57cec5SDimitry Andric } 70480b57cec5SDimitry Andric 70490b57cec5SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 70500b57cec5SDimitry Andric // We call takeVector() here to avoid use-after-free. 70510b57cec5SDimitry Andric // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because 70520b57cec5SDimitry Andric // we deserialize function bodies to emit coverage info for them, and that 70530b57cec5SDimitry Andric // deserializes more declarations. How should we handle that case? 70540b57cec5SDimitry Andric for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) { 70550b57cec5SDimitry Andric if (!Entry.second) 70560b57cec5SDimitry Andric continue; 70570b57cec5SDimitry Andric const Decl *D = Entry.first; 70580b57cec5SDimitry Andric switch (D->getKind()) { 70590b57cec5SDimitry Andric case Decl::CXXConversion: 70600b57cec5SDimitry Andric case Decl::CXXMethod: 70610b57cec5SDimitry Andric case Decl::Function: 70620b57cec5SDimitry Andric case Decl::ObjCMethod: { 70630b57cec5SDimitry Andric CodeGenPGO PGO(*this); 70640b57cec5SDimitry Andric GlobalDecl GD(cast<FunctionDecl>(D)); 70650b57cec5SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 70660b57cec5SDimitry Andric getFunctionLinkage(GD)); 70670b57cec5SDimitry Andric break; 70680b57cec5SDimitry Andric } 70690b57cec5SDimitry Andric case Decl::CXXConstructor: { 70700b57cec5SDimitry Andric CodeGenPGO PGO(*this); 70710b57cec5SDimitry Andric GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 70720b57cec5SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 70730b57cec5SDimitry Andric getFunctionLinkage(GD)); 70740b57cec5SDimitry Andric break; 70750b57cec5SDimitry Andric } 70760b57cec5SDimitry Andric case Decl::CXXDestructor: { 70770b57cec5SDimitry Andric CodeGenPGO PGO(*this); 70780b57cec5SDimitry Andric GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 70790b57cec5SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 70800b57cec5SDimitry Andric getFunctionLinkage(GD)); 70810b57cec5SDimitry Andric break; 70820b57cec5SDimitry Andric } 70830b57cec5SDimitry Andric default: 70840b57cec5SDimitry Andric break; 70850b57cec5SDimitry Andric }; 70860b57cec5SDimitry Andric } 70870b57cec5SDimitry Andric } 70880b57cec5SDimitry Andric 70895ffd83dbSDimitry Andric void CodeGenModule::EmitMainVoidAlias() { 70905ffd83dbSDimitry Andric // In order to transition away from "__original_main" gracefully, emit an 70915ffd83dbSDimitry Andric // alias for "main" in the no-argument case so that libc can detect when 70925ffd83dbSDimitry Andric // new-style no-argument main is in used. 70935ffd83dbSDimitry Andric if (llvm::Function *F = getModule().getFunction("main")) { 70945ffd83dbSDimitry Andric if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() && 709581ad6265SDimitry Andric F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) { 709681ad6265SDimitry Andric auto *GA = llvm::GlobalAlias::create("__main_void", F); 709781ad6265SDimitry Andric GA->setVisibility(llvm::GlobalValue::HiddenVisibility); 709881ad6265SDimitry Andric } 70995ffd83dbSDimitry Andric } 71005ffd83dbSDimitry Andric } 71015ffd83dbSDimitry Andric 71020b57cec5SDimitry Andric /// Turns the given pointer into a constant. 71030b57cec5SDimitry Andric static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 71040b57cec5SDimitry Andric const void *Ptr) { 71050b57cec5SDimitry Andric uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 71060b57cec5SDimitry Andric llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 71070b57cec5SDimitry Andric return llvm::ConstantInt::get(i64, PtrInt); 71080b57cec5SDimitry Andric } 71090b57cec5SDimitry Andric 71100b57cec5SDimitry Andric static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 71110b57cec5SDimitry Andric llvm::NamedMDNode *&GlobalMetadata, 71120b57cec5SDimitry Andric GlobalDecl D, 71130b57cec5SDimitry Andric llvm::GlobalValue *Addr) { 71140b57cec5SDimitry Andric if (!GlobalMetadata) 71150b57cec5SDimitry Andric GlobalMetadata = 71160b57cec5SDimitry Andric CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 71170b57cec5SDimitry Andric 71180b57cec5SDimitry Andric // TODO: should we report variant information for ctors/dtors? 71190b57cec5SDimitry Andric llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 71200b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(GetPointerConstant( 71210b57cec5SDimitry Andric CGM.getLLVMContext(), D.getDecl()))}; 71220b57cec5SDimitry Andric GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 71230b57cec5SDimitry Andric } 71240b57cec5SDimitry Andric 712581ad6265SDimitry Andric bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem, 712681ad6265SDimitry Andric llvm::GlobalValue *CppFunc) { 712781ad6265SDimitry Andric // Store the list of ifuncs we need to replace uses in. 712881ad6265SDimitry Andric llvm::SmallVector<llvm::GlobalIFunc *> IFuncs; 712981ad6265SDimitry Andric // List of ConstantExprs that we should be able to delete when we're done 713081ad6265SDimitry Andric // here. 713181ad6265SDimitry Andric llvm::SmallVector<llvm::ConstantExpr *> CEs; 713281ad6265SDimitry Andric 713381ad6265SDimitry Andric // It isn't valid to replace the extern-C ifuncs if all we find is itself! 713481ad6265SDimitry Andric if (Elem == CppFunc) 713581ad6265SDimitry Andric return false; 713681ad6265SDimitry Andric 713781ad6265SDimitry Andric // First make sure that all users of this are ifuncs (or ifuncs via a 713881ad6265SDimitry Andric // bitcast), and collect the list of ifuncs and CEs so we can work on them 713981ad6265SDimitry Andric // later. 714081ad6265SDimitry Andric for (llvm::User *User : Elem->users()) { 714181ad6265SDimitry Andric // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an 714281ad6265SDimitry Andric // ifunc directly. In any other case, just give up, as we don't know what we 714381ad6265SDimitry Andric // could break by changing those. 714481ad6265SDimitry Andric if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) { 714581ad6265SDimitry Andric if (ConstExpr->getOpcode() != llvm::Instruction::BitCast) 714681ad6265SDimitry Andric return false; 714781ad6265SDimitry Andric 714881ad6265SDimitry Andric for (llvm::User *CEUser : ConstExpr->users()) { 714981ad6265SDimitry Andric if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) { 715081ad6265SDimitry Andric IFuncs.push_back(IFunc); 715181ad6265SDimitry Andric } else { 715281ad6265SDimitry Andric return false; 715381ad6265SDimitry Andric } 715481ad6265SDimitry Andric } 715581ad6265SDimitry Andric CEs.push_back(ConstExpr); 715681ad6265SDimitry Andric } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) { 715781ad6265SDimitry Andric IFuncs.push_back(IFunc); 715881ad6265SDimitry Andric } else { 715981ad6265SDimitry Andric // This user is one we don't know how to handle, so fail redirection. This 716081ad6265SDimitry Andric // will result in an ifunc retaining a resolver name that will ultimately 716181ad6265SDimitry Andric // fail to be resolved to a defined function. 716281ad6265SDimitry Andric return false; 716381ad6265SDimitry Andric } 716481ad6265SDimitry Andric } 716581ad6265SDimitry Andric 716681ad6265SDimitry Andric // Now we know this is a valid case where we can do this alias replacement, we 716781ad6265SDimitry Andric // need to remove all of the references to Elem (and the bitcasts!) so we can 716881ad6265SDimitry Andric // delete it. 716981ad6265SDimitry Andric for (llvm::GlobalIFunc *IFunc : IFuncs) 717081ad6265SDimitry Andric IFunc->setResolver(nullptr); 717181ad6265SDimitry Andric for (llvm::ConstantExpr *ConstExpr : CEs) 717281ad6265SDimitry Andric ConstExpr->destroyConstant(); 717381ad6265SDimitry Andric 717481ad6265SDimitry Andric // We should now be out of uses for the 'old' version of this function, so we 717581ad6265SDimitry Andric // can erase it as well. 717681ad6265SDimitry Andric Elem->eraseFromParent(); 717781ad6265SDimitry Andric 717881ad6265SDimitry Andric for (llvm::GlobalIFunc *IFunc : IFuncs) { 717981ad6265SDimitry Andric // The type of the resolver is always just a function-type that returns the 718081ad6265SDimitry Andric // type of the IFunc, so create that here. If the type of the actual 718181ad6265SDimitry Andric // resolver doesn't match, it just gets bitcast to the right thing. 718281ad6265SDimitry Andric auto *ResolverTy = 718381ad6265SDimitry Andric llvm::FunctionType::get(IFunc->getType(), /*isVarArg*/ false); 718481ad6265SDimitry Andric llvm::Constant *Resolver = GetOrCreateLLVMFunction( 718581ad6265SDimitry Andric CppFunc->getName(), ResolverTy, {}, /*ForVTable*/ false); 718681ad6265SDimitry Andric IFunc->setResolver(Resolver); 718781ad6265SDimitry Andric } 718881ad6265SDimitry Andric return true; 718981ad6265SDimitry Andric } 719081ad6265SDimitry Andric 71910b57cec5SDimitry Andric /// For each function which is declared within an extern "C" region and marked 71920b57cec5SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled 71930b57cec5SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer 71940b57cec5SDimitry Andric /// to such functions with an unmangled name from inline assembly within the 71950b57cec5SDimitry Andric /// same translation unit. 71960b57cec5SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() { 71970b57cec5SDimitry Andric if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases()) 71980b57cec5SDimitry Andric return; 71990b57cec5SDimitry Andric for (auto &I : StaticExternCValues) { 72000b57cec5SDimitry Andric IdentifierInfo *Name = I.first; 72010b57cec5SDimitry Andric llvm::GlobalValue *Val = I.second; 720281ad6265SDimitry Andric 720381ad6265SDimitry Andric // If Val is null, that implies there were multiple declarations that each 720481ad6265SDimitry Andric // had a claim to the unmangled name. In this case, generation of the alias 720581ad6265SDimitry Andric // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC. 720681ad6265SDimitry Andric if (!Val) 720781ad6265SDimitry Andric break; 720881ad6265SDimitry Andric 720981ad6265SDimitry Andric llvm::GlobalValue *ExistingElem = 721081ad6265SDimitry Andric getModule().getNamedValue(Name->getName()); 721181ad6265SDimitry Andric 721281ad6265SDimitry Andric // If there is either not something already by this name, or we were able to 721381ad6265SDimitry Andric // replace all uses from IFuncs, create the alias. 721481ad6265SDimitry Andric if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val)) 7215fe6060f1SDimitry Andric addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 72160b57cec5SDimitry Andric } 72170b57cec5SDimitry Andric } 72180b57cec5SDimitry Andric 72190b57cec5SDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 72200b57cec5SDimitry Andric GlobalDecl &Result) const { 72210b57cec5SDimitry Andric auto Res = Manglings.find(MangledName); 72220b57cec5SDimitry Andric if (Res == Manglings.end()) 72230b57cec5SDimitry Andric return false; 72240b57cec5SDimitry Andric Result = Res->getValue(); 72250b57cec5SDimitry Andric return true; 72260b57cec5SDimitry Andric } 72270b57cec5SDimitry Andric 72280b57cec5SDimitry Andric /// Emits metadata nodes associating all the global values in the 72290b57cec5SDimitry Andric /// current module with the Decls they came from. This is useful for 72300b57cec5SDimitry Andric /// projects using IR gen as a subroutine. 72310b57cec5SDimitry Andric /// 72320b57cec5SDimitry Andric /// Since there's currently no way to associate an MDNode directly 72330b57cec5SDimitry Andric /// with an llvm::GlobalValue, we create a global named metadata 72340b57cec5SDimitry Andric /// with the name 'clang.global.decl.ptrs'. 72350b57cec5SDimitry Andric void CodeGenModule::EmitDeclMetadata() { 72360b57cec5SDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 72370b57cec5SDimitry Andric 72380b57cec5SDimitry Andric for (auto &I : MangledDeclNames) { 72390b57cec5SDimitry Andric llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 72400b57cec5SDimitry Andric // Some mangled names don't necessarily have an associated GlobalValue 72410b57cec5SDimitry Andric // in this module, e.g. if we mangled it for DebugInfo. 72420b57cec5SDimitry Andric if (Addr) 72430b57cec5SDimitry Andric EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 72440b57cec5SDimitry Andric } 72450b57cec5SDimitry Andric } 72460b57cec5SDimitry Andric 72470b57cec5SDimitry Andric /// Emits metadata nodes for all the local variables in the current 72480b57cec5SDimitry Andric /// function. 72490b57cec5SDimitry Andric void CodeGenFunction::EmitDeclMetadata() { 72500b57cec5SDimitry Andric if (LocalDeclMap.empty()) return; 72510b57cec5SDimitry Andric 72520b57cec5SDimitry Andric llvm::LLVMContext &Context = getLLVMContext(); 72530b57cec5SDimitry Andric 72540b57cec5SDimitry Andric // Find the unique metadata ID for this name. 72550b57cec5SDimitry Andric unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 72560b57cec5SDimitry Andric 72570b57cec5SDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 72580b57cec5SDimitry Andric 72590b57cec5SDimitry Andric for (auto &I : LocalDeclMap) { 72600b57cec5SDimitry Andric const Decl *D = I.first; 72610b57cec5SDimitry Andric llvm::Value *Addr = I.second.getPointer(); 72620b57cec5SDimitry Andric if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 72630b57cec5SDimitry Andric llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 72640b57cec5SDimitry Andric Alloca->setMetadata( 72650b57cec5SDimitry Andric DeclPtrKind, llvm::MDNode::get( 72660b57cec5SDimitry Andric Context, llvm::ValueAsMetadata::getConstant(DAddr))); 72670b57cec5SDimitry Andric } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 72680b57cec5SDimitry Andric GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 72690b57cec5SDimitry Andric EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 72700b57cec5SDimitry Andric } 72710b57cec5SDimitry Andric } 72720b57cec5SDimitry Andric } 72730b57cec5SDimitry Andric 72740b57cec5SDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() { 72750b57cec5SDimitry Andric llvm::NamedMDNode *IdentMetadata = 72760b57cec5SDimitry Andric TheModule.getOrInsertNamedMetadata("llvm.ident"); 72770b57cec5SDimitry Andric std::string Version = getClangFullVersion(); 72780b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 72790b57cec5SDimitry Andric 72800b57cec5SDimitry Andric llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 72810b57cec5SDimitry Andric IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 72820b57cec5SDimitry Andric } 72830b57cec5SDimitry Andric 72840b57cec5SDimitry Andric void CodeGenModule::EmitCommandLineMetadata() { 72850b57cec5SDimitry Andric llvm::NamedMDNode *CommandLineMetadata = 72860b57cec5SDimitry Andric TheModule.getOrInsertNamedMetadata("llvm.commandline"); 72870b57cec5SDimitry Andric std::string CommandLine = getCodeGenOpts().RecordCommandLine; 72880b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 72890b57cec5SDimitry Andric 72900b57cec5SDimitry Andric llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)}; 72910b57cec5SDimitry Andric CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode)); 72920b57cec5SDimitry Andric } 72930b57cec5SDimitry Andric 72940b57cec5SDimitry Andric void CodeGenModule::EmitCoverageFile() { 72950b57cec5SDimitry Andric llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); 72960b57cec5SDimitry Andric if (!CUNode) 72970b57cec5SDimitry Andric return; 72980b57cec5SDimitry Andric 72990b57cec5SDimitry Andric llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 73000b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 73010b57cec5SDimitry Andric auto *CoverageDataFile = 73020b57cec5SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); 73030b57cec5SDimitry Andric auto *CoverageNotesFile = 73040b57cec5SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); 73050b57cec5SDimitry Andric for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 73060b57cec5SDimitry Andric llvm::MDNode *CU = CUNode->getOperand(i); 73070b57cec5SDimitry Andric llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; 73080b57cec5SDimitry Andric GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 73090b57cec5SDimitry Andric } 73100b57cec5SDimitry Andric } 73110b57cec5SDimitry Andric 73120b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 73130b57cec5SDimitry Andric bool ForEH) { 73140b57cec5SDimitry Andric // Return a bogus pointer if RTTI is disabled, unless it's for EH. 73150b57cec5SDimitry Andric // FIXME: should we even be calling this method if RTTI is disabled 73160b57cec5SDimitry Andric // and it's not for EH? 7317fe013be4SDimitry Andric if (!shouldEmitRTTI(ForEH)) 7318fe013be4SDimitry Andric return llvm::Constant::getNullValue(GlobalsInt8PtrTy); 73190b57cec5SDimitry Andric 73200b57cec5SDimitry Andric if (ForEH && Ty->isObjCObjectPointerType() && 73210b57cec5SDimitry Andric LangOpts.ObjCRuntime.isGNUFamily()) 73220b57cec5SDimitry Andric return ObjCRuntime->GetEHType(Ty); 73230b57cec5SDimitry Andric 73240b57cec5SDimitry Andric return getCXXABI().getAddrOfRTTIDescriptor(Ty); 73250b57cec5SDimitry Andric } 73260b57cec5SDimitry Andric 73270b57cec5SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 73280b57cec5SDimitry Andric // Do not emit threadprivates in simd-only mode. 73290b57cec5SDimitry Andric if (LangOpts.OpenMP && LangOpts.OpenMPSimd) 73300b57cec5SDimitry Andric return; 73310b57cec5SDimitry Andric for (auto RefExpr : D->varlists()) { 73320b57cec5SDimitry Andric auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 73330b57cec5SDimitry Andric bool PerformInit = 73340b57cec5SDimitry Andric VD->getAnyInitializer() && 73350b57cec5SDimitry Andric !VD->getAnyInitializer()->isConstantInitializer(getContext(), 73360b57cec5SDimitry Andric /*ForRef=*/false); 73370b57cec5SDimitry Andric 733881ad6265SDimitry Andric Address Addr(GetAddrOfGlobalVar(VD), 733981ad6265SDimitry Andric getTypes().ConvertTypeForMem(VD->getType()), 734081ad6265SDimitry Andric getContext().getDeclAlign(VD)); 73410b57cec5SDimitry Andric if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 73420b57cec5SDimitry Andric VD, Addr, RefExpr->getBeginLoc(), PerformInit)) 73430b57cec5SDimitry Andric CXXGlobalInits.push_back(InitFunction); 73440b57cec5SDimitry Andric } 73450b57cec5SDimitry Andric } 73460b57cec5SDimitry Andric 73470b57cec5SDimitry Andric llvm::Metadata * 73480b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, 73490b57cec5SDimitry Andric StringRef Suffix) { 73500eae32dcSDimitry Andric if (auto *FnType = T->getAs<FunctionProtoType>()) 73510eae32dcSDimitry Andric T = getContext().getFunctionType( 73520eae32dcSDimitry Andric FnType->getReturnType(), FnType->getParamTypes(), 73530eae32dcSDimitry Andric FnType->getExtProtoInfo().withExceptionSpec(EST_None)); 73540eae32dcSDimitry Andric 73550b57cec5SDimitry Andric llvm::Metadata *&InternalId = Map[T.getCanonicalType()]; 73560b57cec5SDimitry Andric if (InternalId) 73570b57cec5SDimitry Andric return InternalId; 73580b57cec5SDimitry Andric 73590b57cec5SDimitry Andric if (isExternallyVisible(T->getLinkage())) { 73600b57cec5SDimitry Andric std::string OutName; 73610b57cec5SDimitry Andric llvm::raw_string_ostream Out(OutName); 7362c9157d92SDimitry Andric getCXXABI().getMangleContext().mangleCanonicalTypeName( 7363fe013be4SDimitry Andric T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers); 7364fe013be4SDimitry Andric 7365fe013be4SDimitry Andric if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers) 7366fe013be4SDimitry Andric Out << ".normalized"; 7367fe013be4SDimitry Andric 73680b57cec5SDimitry Andric Out << Suffix; 73690b57cec5SDimitry Andric 73700b57cec5SDimitry Andric InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 73710b57cec5SDimitry Andric } else { 73720b57cec5SDimitry Andric InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 73730b57cec5SDimitry Andric llvm::ArrayRef<llvm::Metadata *>()); 73740b57cec5SDimitry Andric } 73750b57cec5SDimitry Andric 73760b57cec5SDimitry Andric return InternalId; 73770b57cec5SDimitry Andric } 73780b57cec5SDimitry Andric 73790b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 73800b57cec5SDimitry Andric return CreateMetadataIdentifierImpl(T, MetadataIdMap, ""); 73810b57cec5SDimitry Andric } 73820b57cec5SDimitry Andric 73830b57cec5SDimitry Andric llvm::Metadata * 73840b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) { 73850b57cec5SDimitry Andric return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual"); 73860b57cec5SDimitry Andric } 73870b57cec5SDimitry Andric 73880b57cec5SDimitry Andric // Generalize pointer types to a void pointer with the qualifiers of the 73890b57cec5SDimitry Andric // originally pointed-to type, e.g. 'const char *' and 'char * const *' 73900b57cec5SDimitry Andric // generalize to 'const void *' while 'char *' and 'const char **' generalize to 73910b57cec5SDimitry Andric // 'void *'. 73920b57cec5SDimitry Andric static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) { 73930b57cec5SDimitry Andric if (!Ty->isPointerType()) 73940b57cec5SDimitry Andric return Ty; 73950b57cec5SDimitry Andric 73960b57cec5SDimitry Andric return Ctx.getPointerType( 73970b57cec5SDimitry Andric QualType(Ctx.VoidTy).withCVRQualifiers( 73980b57cec5SDimitry Andric Ty->getPointeeType().getCVRQualifiers())); 73990b57cec5SDimitry Andric } 74000b57cec5SDimitry Andric 74010b57cec5SDimitry Andric // Apply type generalization to a FunctionType's return and argument types 74020b57cec5SDimitry Andric static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) { 74030b57cec5SDimitry Andric if (auto *FnType = Ty->getAs<FunctionProtoType>()) { 74040b57cec5SDimitry Andric SmallVector<QualType, 8> GeneralizedParams; 74050b57cec5SDimitry Andric for (auto &Param : FnType->param_types()) 74060b57cec5SDimitry Andric GeneralizedParams.push_back(GeneralizeType(Ctx, Param)); 74070b57cec5SDimitry Andric 74080b57cec5SDimitry Andric return Ctx.getFunctionType( 74090b57cec5SDimitry Andric GeneralizeType(Ctx, FnType->getReturnType()), 74100b57cec5SDimitry Andric GeneralizedParams, FnType->getExtProtoInfo()); 74110b57cec5SDimitry Andric } 74120b57cec5SDimitry Andric 74130b57cec5SDimitry Andric if (auto *FnType = Ty->getAs<FunctionNoProtoType>()) 74140b57cec5SDimitry Andric return Ctx.getFunctionNoProtoType( 74150b57cec5SDimitry Andric GeneralizeType(Ctx, FnType->getReturnType())); 74160b57cec5SDimitry Andric 74170b57cec5SDimitry Andric llvm_unreachable("Encountered unknown FunctionType"); 74180b57cec5SDimitry Andric } 74190b57cec5SDimitry Andric 74200b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) { 74210b57cec5SDimitry Andric return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T), 74220b57cec5SDimitry Andric GeneralizedMetadataIdMap, ".generalized"); 74230b57cec5SDimitry Andric } 74240b57cec5SDimitry Andric 74250b57cec5SDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier. 74260b57cec5SDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const { 74270b57cec5SDimitry Andric // Returns true if at least one of vtable-based CFI checkers is enabled and 74280b57cec5SDimitry Andric // is not in the trapping mode. 74290b57cec5SDimitry Andric return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 74300b57cec5SDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 74310b57cec5SDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 74320b57cec5SDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 74330b57cec5SDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 74340b57cec5SDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 74350b57cec5SDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 74360b57cec5SDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 74370b57cec5SDimitry Andric } 74380b57cec5SDimitry Andric 74390b57cec5SDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 74400b57cec5SDimitry Andric CharUnits Offset, 74410b57cec5SDimitry Andric const CXXRecordDecl *RD) { 74420b57cec5SDimitry Andric llvm::Metadata *MD = 74430b57cec5SDimitry Andric CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 74440b57cec5SDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), MD); 74450b57cec5SDimitry Andric 74460b57cec5SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 74470b57cec5SDimitry Andric if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 74480b57cec5SDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), 74490b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 74500b57cec5SDimitry Andric 74510b57cec5SDimitry Andric if (NeedAllVtablesTypeId()) { 74520b57cec5SDimitry Andric llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 74530b57cec5SDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), MD); 74540b57cec5SDimitry Andric } 74550b57cec5SDimitry Andric } 74560b57cec5SDimitry Andric 74570b57cec5SDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 74580b57cec5SDimitry Andric if (!SanStats) 7459a7dea167SDimitry Andric SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule()); 74600b57cec5SDimitry Andric 74610b57cec5SDimitry Andric return *SanStats; 74620b57cec5SDimitry Andric } 746323408297SDimitry Andric 74640b57cec5SDimitry Andric llvm::Value * 74650b57cec5SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, 74660b57cec5SDimitry Andric CodeGenFunction &CGF) { 74670b57cec5SDimitry Andric llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType()); 746823408297SDimitry Andric auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr()); 746923408297SDimitry Andric auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); 7470fe6060f1SDimitry Andric auto *Call = CGF.EmitRuntimeCall( 747123408297SDimitry Andric CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C}); 747223408297SDimitry Andric return Call; 74730b57cec5SDimitry Andric } 74745ffd83dbSDimitry Andric 74755ffd83dbSDimitry Andric CharUnits CodeGenModule::getNaturalPointeeTypeAlignment( 74765ffd83dbSDimitry Andric QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) { 74775ffd83dbSDimitry Andric return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo, 74785ffd83dbSDimitry Andric /* forPointeeType= */ true); 74795ffd83dbSDimitry Andric } 74805ffd83dbSDimitry Andric 74815ffd83dbSDimitry Andric CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T, 74825ffd83dbSDimitry Andric LValueBaseInfo *BaseInfo, 74835ffd83dbSDimitry Andric TBAAAccessInfo *TBAAInfo, 74845ffd83dbSDimitry Andric bool forPointeeType) { 74855ffd83dbSDimitry Andric if (TBAAInfo) 74865ffd83dbSDimitry Andric *TBAAInfo = getTBAAAccessInfo(T); 74875ffd83dbSDimitry Andric 74885ffd83dbSDimitry Andric // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But 74895ffd83dbSDimitry Andric // that doesn't return the information we need to compute BaseInfo. 74905ffd83dbSDimitry Andric 74915ffd83dbSDimitry Andric // Honor alignment typedef attributes even on incomplete types. 74925ffd83dbSDimitry Andric // We also honor them straight for C++ class types, even as pointees; 74935ffd83dbSDimitry Andric // there's an expressivity gap here. 74945ffd83dbSDimitry Andric if (auto TT = T->getAs<TypedefType>()) { 74955ffd83dbSDimitry Andric if (auto Align = TT->getDecl()->getMaxAlignment()) { 74965ffd83dbSDimitry Andric if (BaseInfo) 74975ffd83dbSDimitry Andric *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType); 74985ffd83dbSDimitry Andric return getContext().toCharUnitsFromBits(Align); 74995ffd83dbSDimitry Andric } 75005ffd83dbSDimitry Andric } 75015ffd83dbSDimitry Andric 75025ffd83dbSDimitry Andric bool AlignForArray = T->isArrayType(); 75035ffd83dbSDimitry Andric 75045ffd83dbSDimitry Andric // Analyze the base element type, so we don't get confused by incomplete 75055ffd83dbSDimitry Andric // array types. 75065ffd83dbSDimitry Andric T = getContext().getBaseElementType(T); 75075ffd83dbSDimitry Andric 75085ffd83dbSDimitry Andric if (T->isIncompleteType()) { 75095ffd83dbSDimitry Andric // We could try to replicate the logic from 75105ffd83dbSDimitry Andric // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the 75115ffd83dbSDimitry Andric // type is incomplete, so it's impossible to test. We could try to reuse 75125ffd83dbSDimitry Andric // getTypeAlignIfKnown, but that doesn't return the information we need 75135ffd83dbSDimitry Andric // to set BaseInfo. So just ignore the possibility that the alignment is 75145ffd83dbSDimitry Andric // greater than one. 75155ffd83dbSDimitry Andric if (BaseInfo) 75165ffd83dbSDimitry Andric *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 75175ffd83dbSDimitry Andric return CharUnits::One(); 75185ffd83dbSDimitry Andric } 75195ffd83dbSDimitry Andric 75205ffd83dbSDimitry Andric if (BaseInfo) 75215ffd83dbSDimitry Andric *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 75225ffd83dbSDimitry Andric 75235ffd83dbSDimitry Andric CharUnits Alignment; 7524e8d8bef9SDimitry Andric const CXXRecordDecl *RD; 7525e8d8bef9SDimitry Andric if (T.getQualifiers().hasUnaligned()) { 7526e8d8bef9SDimitry Andric Alignment = CharUnits::One(); 7527e8d8bef9SDimitry Andric } else if (forPointeeType && !AlignForArray && 7528e8d8bef9SDimitry Andric (RD = T->getAsCXXRecordDecl())) { 75295ffd83dbSDimitry Andric // For C++ class pointees, we don't know whether we're pointing at a 75305ffd83dbSDimitry Andric // base or a complete object, so we generally need to use the 75315ffd83dbSDimitry Andric // non-virtual alignment. 75325ffd83dbSDimitry Andric Alignment = getClassPointerAlignment(RD); 75335ffd83dbSDimitry Andric } else { 75345ffd83dbSDimitry Andric Alignment = getContext().getTypeAlignInChars(T); 75355ffd83dbSDimitry Andric } 75365ffd83dbSDimitry Andric 75375ffd83dbSDimitry Andric // Cap to the global maximum type alignment unless the alignment 75385ffd83dbSDimitry Andric // was somehow explicit on the type. 75395ffd83dbSDimitry Andric if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { 75405ffd83dbSDimitry Andric if (Alignment.getQuantity() > MaxAlign && 75415ffd83dbSDimitry Andric !getContext().isAlignmentRequired(T)) 75425ffd83dbSDimitry Andric Alignment = CharUnits::fromQuantity(MaxAlign); 75435ffd83dbSDimitry Andric } 75445ffd83dbSDimitry Andric return Alignment; 75455ffd83dbSDimitry Andric } 75465ffd83dbSDimitry Andric 75475ffd83dbSDimitry Andric bool CodeGenModule::stopAutoInit() { 75485ffd83dbSDimitry Andric unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter; 75495ffd83dbSDimitry Andric if (StopAfter) { 75505ffd83dbSDimitry Andric // This number is positive only when -ftrivial-auto-var-init-stop-after=* is 75515ffd83dbSDimitry Andric // used 75525ffd83dbSDimitry Andric if (NumAutoVarInit >= StopAfter) { 75535ffd83dbSDimitry Andric return true; 75545ffd83dbSDimitry Andric } 75555ffd83dbSDimitry Andric if (!NumAutoVarInit) { 75565ffd83dbSDimitry Andric unsigned DiagID = getDiags().getCustomDiagID( 75575ffd83dbSDimitry Andric DiagnosticsEngine::Warning, 75585ffd83dbSDimitry Andric "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the " 75595ffd83dbSDimitry Andric "number of times ftrivial-auto-var-init=%1 gets applied."); 75605ffd83dbSDimitry Andric getDiags().Report(DiagID) 75615ffd83dbSDimitry Andric << StopAfter 75625ffd83dbSDimitry Andric << (getContext().getLangOpts().getTrivialAutoVarInit() == 75635ffd83dbSDimitry Andric LangOptions::TrivialAutoVarInitKind::Zero 75645ffd83dbSDimitry Andric ? "zero" 75655ffd83dbSDimitry Andric : "pattern"); 75665ffd83dbSDimitry Andric } 75675ffd83dbSDimitry Andric ++NumAutoVarInit; 75685ffd83dbSDimitry Andric } 75695ffd83dbSDimitry Andric return false; 75705ffd83dbSDimitry Andric } 7571fe6060f1SDimitry Andric 75722a66634dSDimitry Andric void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS, 75732a66634dSDimitry Andric const Decl *D) const { 75742a66634dSDimitry Andric // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers 75752a66634dSDimitry Andric // postfix beginning with '.' since the symbol name can be demangled. 75762a66634dSDimitry Andric if (LangOpts.HIP) 757781ad6265SDimitry Andric OS << (isa<VarDecl>(D) ? ".static." : ".intern."); 75782a66634dSDimitry Andric else 757981ad6265SDimitry Andric OS << (isa<VarDecl>(D) ? "__static__" : "__intern__"); 758081ad6265SDimitry Andric 758181ad6265SDimitry Andric // If the CUID is not specified we try to generate a unique postfix. 758281ad6265SDimitry Andric if (getLangOpts().CUID.empty()) { 758381ad6265SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 758481ad6265SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation()); 758581ad6265SDimitry Andric assert(PLoc.isValid() && "Source location is expected to be valid."); 758681ad6265SDimitry Andric 758781ad6265SDimitry Andric // Get the hash of the user defined macros. 758881ad6265SDimitry Andric llvm::MD5 Hash; 758981ad6265SDimitry Andric llvm::MD5::MD5Result Result; 759081ad6265SDimitry Andric for (const auto &Arg : PreprocessorOpts.Macros) 759181ad6265SDimitry Andric Hash.update(Arg.first); 759281ad6265SDimitry Andric Hash.final(Result); 759381ad6265SDimitry Andric 759481ad6265SDimitry Andric // Get the UniqueID for the file containing the decl. 759581ad6265SDimitry Andric llvm::sys::fs::UniqueID ID; 7596c9157d92SDimitry Andric if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) { 759781ad6265SDimitry Andric PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false); 759881ad6265SDimitry Andric assert(PLoc.isValid() && "Source location is expected to be valid."); 759981ad6265SDimitry Andric if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) 760081ad6265SDimitry Andric SM.getDiagnostics().Report(diag::err_cannot_open_file) 760181ad6265SDimitry Andric << PLoc.getFilename() << EC.message(); 760281ad6265SDimitry Andric } 760381ad6265SDimitry Andric OS << llvm::format("%x", ID.getFile()) << llvm::format("%x", ID.getDevice()) 760481ad6265SDimitry Andric << "_" << llvm::utohexstr(Result.low(), /*LowerCase=*/true, /*Width=*/8); 760581ad6265SDimitry Andric } else { 760681ad6265SDimitry Andric OS << getContext().getCUIDHash(); 760781ad6265SDimitry Andric } 7608fe6060f1SDimitry Andric } 7609fcaf7f86SDimitry Andric 7610fcaf7f86SDimitry Andric void CodeGenModule::moveLazyEmissionStates(CodeGenModule *NewBuilder) { 7611fcaf7f86SDimitry Andric assert(DeferredDeclsToEmit.empty() && 7612fcaf7f86SDimitry Andric "Should have emitted all decls deferred to emit."); 7613fcaf7f86SDimitry Andric assert(NewBuilder->DeferredDecls.empty() && 7614fcaf7f86SDimitry Andric "Newly created module should not have deferred decls"); 7615fcaf7f86SDimitry Andric NewBuilder->DeferredDecls = std::move(DeferredDecls); 7616c9157d92SDimitry Andric assert(EmittedDeferredDecls.empty() && 7617c9157d92SDimitry Andric "Still have (unmerged) EmittedDeferredDecls deferred decls"); 7618fcaf7f86SDimitry Andric 7619fcaf7f86SDimitry Andric assert(NewBuilder->DeferredVTables.empty() && 7620fcaf7f86SDimitry Andric "Newly created module should not have deferred vtables"); 7621fcaf7f86SDimitry Andric NewBuilder->DeferredVTables = std::move(DeferredVTables); 7622fcaf7f86SDimitry Andric 7623fcaf7f86SDimitry Andric assert(NewBuilder->MangledDeclNames.empty() && 7624fcaf7f86SDimitry Andric "Newly created module should not have mangled decl names"); 7625fcaf7f86SDimitry Andric assert(NewBuilder->Manglings.empty() && 7626fcaf7f86SDimitry Andric "Newly created module should not have manglings"); 7627fcaf7f86SDimitry Andric NewBuilder->Manglings = std::move(Manglings); 7628fcaf7f86SDimitry Andric 7629fcaf7f86SDimitry Andric NewBuilder->WeakRefReferences = std::move(WeakRefReferences); 7630fcaf7f86SDimitry Andric 7631fcaf7f86SDimitry Andric NewBuilder->TBAA = std::move(TBAA); 7632fcaf7f86SDimitry Andric 7633972a253aSDimitry Andric NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx); 7634fcaf7f86SDimitry Andric } 7635