1*0b57cec5SDimitry Andric //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 2*0b57cec5SDimitry Andric // 3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6*0b57cec5SDimitry Andric // 7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 8*0b57cec5SDimitry Andric // 9*0b57cec5SDimitry Andric // This coordinates the per-module state used while generating code. 10*0b57cec5SDimitry Andric // 11*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 12*0b57cec5SDimitry Andric 13*0b57cec5SDimitry Andric #include "CodeGenModule.h" 14fcaf7f86SDimitry Andric #include "ABIInfo.h" 15*0b57cec5SDimitry Andric #include "CGBlocks.h" 16*0b57cec5SDimitry Andric #include "CGCUDARuntime.h" 17*0b57cec5SDimitry Andric #include "CGCXXABI.h" 18*0b57cec5SDimitry Andric #include "CGCall.h" 19*0b57cec5SDimitry Andric #include "CGDebugInfo.h" 2081ad6265SDimitry Andric #include "CGHLSLRuntime.h" 21*0b57cec5SDimitry Andric #include "CGObjCRuntime.h" 22*0b57cec5SDimitry Andric #include "CGOpenCLRuntime.h" 23*0b57cec5SDimitry Andric #include "CGOpenMPRuntime.h" 24349cc55cSDimitry Andric #include "CGOpenMPRuntimeGPU.h" 25*0b57cec5SDimitry Andric #include "CodeGenFunction.h" 26*0b57cec5SDimitry Andric #include "CodeGenPGO.h" 27*0b57cec5SDimitry Andric #include "ConstantEmitter.h" 28*0b57cec5SDimitry Andric #include "CoverageMappingGen.h" 29*0b57cec5SDimitry Andric #include "TargetInfo.h" 30*0b57cec5SDimitry Andric #include "clang/AST/ASTContext.h" 31*0b57cec5SDimitry Andric #include "clang/AST/CharUnits.h" 32*0b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h" 33*0b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h" 34*0b57cec5SDimitry Andric #include "clang/AST/DeclTemplate.h" 35*0b57cec5SDimitry Andric #include "clang/AST/Mangle.h" 36*0b57cec5SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h" 37*0b57cec5SDimitry Andric #include "clang/AST/StmtVisitor.h" 38*0b57cec5SDimitry Andric #include "clang/Basic/Builtins.h" 39*0b57cec5SDimitry Andric #include "clang/Basic/CharInfo.h" 40*0b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h" 41*0b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h" 425ffd83dbSDimitry Andric #include "clang/Basic/FileManager.h" 43*0b57cec5SDimitry Andric #include "clang/Basic/Module.h" 44*0b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h" 45*0b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h" 46*0b57cec5SDimitry Andric #include "clang/Basic/Version.h" 4781ad6265SDimitry Andric #include "clang/CodeGen/BackendUtil.h" 48*0b57cec5SDimitry Andric #include "clang/CodeGen/ConstantInitBuilder.h" 49*0b57cec5SDimitry Andric #include "clang/Frontend/FrontendDiagnostic.h" 50bdd1243dSDimitry Andric #include "llvm/ADT/STLExtras.h" 51bdd1243dSDimitry Andric #include "llvm/ADT/StringExtras.h" 52*0b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h" 53*0b57cec5SDimitry Andric #include "llvm/ADT/Triple.h" 54*0b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h" 55480093f4SDimitry Andric #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 56*0b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h" 57*0b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h" 58*0b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h" 59*0b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h" 60*0b57cec5SDimitry Andric #include "llvm/IR/Module.h" 61*0b57cec5SDimitry Andric #include "llvm/IR/ProfileSummary.h" 62*0b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfReader.h" 63bdd1243dSDimitry Andric #include "llvm/ProfileData/SampleProf.h" 64fcaf7f86SDimitry Andric #include "llvm/Support/CRC.h" 65*0b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h" 66480093f4SDimitry Andric #include "llvm/Support/CommandLine.h" 67*0b57cec5SDimitry Andric #include "llvm/Support/ConvertUTF.h" 68*0b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h" 69*0b57cec5SDimitry Andric #include "llvm/Support/TimeProfiler.h" 70349cc55cSDimitry Andric #include "llvm/Support/X86TargetParser.h" 71bdd1243dSDimitry Andric #include "llvm/Support/xxhash.h" 72bdd1243dSDimitry Andric #include <optional> 73*0b57cec5SDimitry Andric 74*0b57cec5SDimitry Andric using namespace clang; 75*0b57cec5SDimitry Andric using namespace CodeGen; 76*0b57cec5SDimitry Andric 77*0b57cec5SDimitry Andric static llvm::cl::opt<bool> LimitedCoverage( 7881ad6265SDimitry Andric "limited-coverage-experimental", llvm::cl::Hidden, 7981ad6265SDimitry Andric llvm::cl::desc("Emit limited coverage mapping information (experimental)")); 80*0b57cec5SDimitry Andric 81*0b57cec5SDimitry Andric static const char AnnotationSection[] = "llvm.metadata"; 82*0b57cec5SDimitry Andric 83*0b57cec5SDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) { 84fe6060f1SDimitry Andric switch (CGM.getContext().getCXXABIKind()) { 85e8d8bef9SDimitry Andric case TargetCXXABI::AppleARM64: 86480093f4SDimitry Andric case TargetCXXABI::Fuchsia: 87*0b57cec5SDimitry Andric case TargetCXXABI::GenericAArch64: 88*0b57cec5SDimitry Andric case TargetCXXABI::GenericARM: 89*0b57cec5SDimitry Andric case TargetCXXABI::iOS: 90*0b57cec5SDimitry Andric case TargetCXXABI::WatchOS: 91*0b57cec5SDimitry Andric case TargetCXXABI::GenericMIPS: 92*0b57cec5SDimitry Andric case TargetCXXABI::GenericItanium: 93*0b57cec5SDimitry Andric case TargetCXXABI::WebAssembly: 945ffd83dbSDimitry Andric case TargetCXXABI::XL: 95*0b57cec5SDimitry Andric return CreateItaniumCXXABI(CGM); 96*0b57cec5SDimitry Andric case TargetCXXABI::Microsoft: 97*0b57cec5SDimitry Andric return CreateMicrosoftCXXABI(CGM); 98*0b57cec5SDimitry Andric } 99*0b57cec5SDimitry Andric 100*0b57cec5SDimitry Andric llvm_unreachable("invalid C++ ABI kind"); 101*0b57cec5SDimitry Andric } 102*0b57cec5SDimitry Andric 103972a253aSDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, 104972a253aSDimitry Andric IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS, 105972a253aSDimitry Andric const HeaderSearchOptions &HSO, 106*0b57cec5SDimitry Andric const PreprocessorOptions &PPO, 107*0b57cec5SDimitry Andric const CodeGenOptions &CGO, llvm::Module &M, 108*0b57cec5SDimitry Andric DiagnosticsEngine &diags, 109*0b57cec5SDimitry Andric CoverageSourceInfo *CoverageInfo) 110972a253aSDimitry Andric : Context(C), LangOpts(C.getLangOpts()), FS(std::move(FS)), 111972a253aSDimitry Andric HeaderSearchOpts(HSO), PreprocessorOpts(PPO), CodeGenOpts(CGO), 112972a253aSDimitry Andric TheModule(M), Diags(diags), Target(C.getTargetInfo()), 113972a253aSDimitry Andric ABI(createCXXABI(*this)), VMContext(M.getContext()), Types(*this), 114972a253aSDimitry Andric VTables(*this), SanitizerMD(new SanitizerMetadata(*this)) { 115*0b57cec5SDimitry Andric 116*0b57cec5SDimitry Andric // Initialize the type cache. 117*0b57cec5SDimitry Andric llvm::LLVMContext &LLVMContext = M.getContext(); 118*0b57cec5SDimitry Andric VoidTy = llvm::Type::getVoidTy(LLVMContext); 119*0b57cec5SDimitry Andric Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 120*0b57cec5SDimitry Andric Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 121*0b57cec5SDimitry Andric Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 122*0b57cec5SDimitry Andric Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 123*0b57cec5SDimitry Andric HalfTy = llvm::Type::getHalfTy(LLVMContext); 1245ffd83dbSDimitry Andric BFloatTy = llvm::Type::getBFloatTy(LLVMContext); 125*0b57cec5SDimitry Andric FloatTy = llvm::Type::getFloatTy(LLVMContext); 126*0b57cec5SDimitry Andric DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 127bdd1243dSDimitry Andric PointerWidthInBits = C.getTargetInfo().getPointerWidth(LangAS::Default); 128*0b57cec5SDimitry Andric PointerAlignInBytes = 129bdd1243dSDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(LangAS::Default)) 130bdd1243dSDimitry Andric .getQuantity(); 131*0b57cec5SDimitry Andric SizeSizeInBytes = 132*0b57cec5SDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity(); 133*0b57cec5SDimitry Andric IntAlignInBytes = 134*0b57cec5SDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity(); 135e8d8bef9SDimitry Andric CharTy = 136e8d8bef9SDimitry Andric llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth()); 137*0b57cec5SDimitry Andric IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 138*0b57cec5SDimitry Andric IntPtrTy = llvm::IntegerType::get(LLVMContext, 139*0b57cec5SDimitry Andric C.getTargetInfo().getMaxPointerWidth()); 140*0b57cec5SDimitry Andric Int8PtrTy = Int8Ty->getPointerTo(0); 141*0b57cec5SDimitry Andric Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 142349cc55cSDimitry Andric const llvm::DataLayout &DL = M.getDataLayout(); 143349cc55cSDimitry Andric AllocaInt8PtrTy = Int8Ty->getPointerTo(DL.getAllocaAddrSpace()); 144349cc55cSDimitry Andric GlobalsInt8PtrTy = Int8Ty->getPointerTo(DL.getDefaultGlobalsAddressSpace()); 145bdd1243dSDimitry Andric ConstGlobalsPtrTy = Int8Ty->getPointerTo( 146bdd1243dSDimitry Andric C.getTargetAddressSpace(GetGlobalConstantAddressSpace())); 147*0b57cec5SDimitry Andric ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace(); 148*0b57cec5SDimitry Andric 149fcaf7f86SDimitry Andric // Build C++20 Module initializers. 150fcaf7f86SDimitry Andric // TODO: Add Microsoft here once we know the mangling required for the 151fcaf7f86SDimitry Andric // initializers. 152fcaf7f86SDimitry Andric CXX20ModuleInits = 153fcaf7f86SDimitry Andric LangOpts.CPlusPlusModules && getCXXABI().getMangleContext().getKind() == 154fcaf7f86SDimitry Andric ItaniumMangleContext::MK_Itanium; 155fcaf7f86SDimitry Andric 156*0b57cec5SDimitry Andric RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 157*0b57cec5SDimitry Andric 158*0b57cec5SDimitry Andric if (LangOpts.ObjC) 159*0b57cec5SDimitry Andric createObjCRuntime(); 160*0b57cec5SDimitry Andric if (LangOpts.OpenCL) 161*0b57cec5SDimitry Andric createOpenCLRuntime(); 162*0b57cec5SDimitry Andric if (LangOpts.OpenMP) 163*0b57cec5SDimitry Andric createOpenMPRuntime(); 164*0b57cec5SDimitry Andric if (LangOpts.CUDA) 165*0b57cec5SDimitry Andric createCUDARuntime(); 16681ad6265SDimitry Andric if (LangOpts.HLSL) 16781ad6265SDimitry Andric createHLSLRuntime(); 168*0b57cec5SDimitry Andric 169*0b57cec5SDimitry Andric // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 170*0b57cec5SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::Thread) || 171*0b57cec5SDimitry Andric (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 172*0b57cec5SDimitry Andric TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(), 173*0b57cec5SDimitry Andric getCXXABI().getMangleContext())); 174*0b57cec5SDimitry Andric 175*0b57cec5SDimitry Andric // If debug info or coverage generation is enabled, create the CGDebugInfo 176*0b57cec5SDimitry Andric // object. 177*0b57cec5SDimitry Andric if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo || 178*0b57cec5SDimitry Andric CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) 179*0b57cec5SDimitry Andric DebugInfo.reset(new CGDebugInfo(*this)); 180*0b57cec5SDimitry Andric 181*0b57cec5SDimitry Andric Block.GlobalUniqueCount = 0; 182*0b57cec5SDimitry Andric 183*0b57cec5SDimitry Andric if (C.getLangOpts().ObjC) 184*0b57cec5SDimitry Andric ObjCData.reset(new ObjCEntrypoints()); 185*0b57cec5SDimitry Andric 186*0b57cec5SDimitry Andric if (CodeGenOpts.hasProfileClangUse()) { 187*0b57cec5SDimitry Andric auto ReaderOrErr = llvm::IndexedInstrProfReader::create( 188*0b57cec5SDimitry Andric CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile); 189bdd1243dSDimitry Andric // We're checking for profile read errors in CompilerInvocation, so if 190bdd1243dSDimitry Andric // there was an error it should've already been caught. If it hasn't been 191bdd1243dSDimitry Andric // somehow, trip an assertion. 192bdd1243dSDimitry Andric assert(ReaderOrErr); 193*0b57cec5SDimitry Andric PGOReader = std::move(ReaderOrErr.get()); 194*0b57cec5SDimitry Andric } 195*0b57cec5SDimitry Andric 196*0b57cec5SDimitry Andric // If coverage mapping generation is enabled, create the 197*0b57cec5SDimitry Andric // CoverageMappingModuleGen object. 198*0b57cec5SDimitry Andric if (CodeGenOpts.CoverageMapping) 199*0b57cec5SDimitry Andric CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); 200fe6060f1SDimitry Andric 201fe6060f1SDimitry Andric // Generate the module name hash here if needed. 202fe6060f1SDimitry Andric if (CodeGenOpts.UniqueInternalLinkageNames && 203fe6060f1SDimitry Andric !getModule().getSourceFileName().empty()) { 204fe6060f1SDimitry Andric std::string Path = getModule().getSourceFileName(); 205fe6060f1SDimitry Andric // Check if a path substitution is needed from the MacroPrefixMap. 2066e75b2fbSDimitry Andric for (const auto &Entry : LangOpts.MacroPrefixMap) 207fe6060f1SDimitry Andric if (Path.rfind(Entry.first, 0) != std::string::npos) { 208fe6060f1SDimitry Andric Path = Entry.second + Path.substr(Entry.first.size()); 209fe6060f1SDimitry Andric break; 210fe6060f1SDimitry Andric } 211bdd1243dSDimitry Andric ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path); 212fe6060f1SDimitry Andric } 213*0b57cec5SDimitry Andric } 214*0b57cec5SDimitry Andric 215*0b57cec5SDimitry Andric CodeGenModule::~CodeGenModule() {} 216*0b57cec5SDimitry Andric 217*0b57cec5SDimitry Andric void CodeGenModule::createObjCRuntime() { 218*0b57cec5SDimitry Andric // This is just isGNUFamily(), but we want to force implementors of 219*0b57cec5SDimitry Andric // new ABIs to decide how best to do this. 220*0b57cec5SDimitry Andric switch (LangOpts.ObjCRuntime.getKind()) { 221*0b57cec5SDimitry Andric case ObjCRuntime::GNUstep: 222*0b57cec5SDimitry Andric case ObjCRuntime::GCC: 223*0b57cec5SDimitry Andric case ObjCRuntime::ObjFW: 224*0b57cec5SDimitry Andric ObjCRuntime.reset(CreateGNUObjCRuntime(*this)); 225*0b57cec5SDimitry Andric return; 226*0b57cec5SDimitry Andric 227*0b57cec5SDimitry Andric case ObjCRuntime::FragileMacOSX: 228*0b57cec5SDimitry Andric case ObjCRuntime::MacOSX: 229*0b57cec5SDimitry Andric case ObjCRuntime::iOS: 230*0b57cec5SDimitry Andric case ObjCRuntime::WatchOS: 231*0b57cec5SDimitry Andric ObjCRuntime.reset(CreateMacObjCRuntime(*this)); 232*0b57cec5SDimitry Andric return; 233*0b57cec5SDimitry Andric } 234*0b57cec5SDimitry Andric llvm_unreachable("bad runtime kind"); 235*0b57cec5SDimitry Andric } 236*0b57cec5SDimitry Andric 237*0b57cec5SDimitry Andric void CodeGenModule::createOpenCLRuntime() { 238*0b57cec5SDimitry Andric OpenCLRuntime.reset(new CGOpenCLRuntime(*this)); 239*0b57cec5SDimitry Andric } 240*0b57cec5SDimitry Andric 241*0b57cec5SDimitry Andric void CodeGenModule::createOpenMPRuntime() { 242*0b57cec5SDimitry Andric // Select a specialized code generation class based on the target, if any. 243*0b57cec5SDimitry Andric // If it does not exist use the default implementation. 244*0b57cec5SDimitry Andric switch (getTriple().getArch()) { 245*0b57cec5SDimitry Andric case llvm::Triple::nvptx: 246*0b57cec5SDimitry Andric case llvm::Triple::nvptx64: 247e8d8bef9SDimitry Andric case llvm::Triple::amdgcn: 248e8d8bef9SDimitry Andric assert(getLangOpts().OpenMPIsDevice && 249349cc55cSDimitry Andric "OpenMP AMDGPU/NVPTX is only prepared to deal with device code."); 250349cc55cSDimitry Andric OpenMPRuntime.reset(new CGOpenMPRuntimeGPU(*this)); 251e8d8bef9SDimitry Andric break; 252*0b57cec5SDimitry Andric default: 253*0b57cec5SDimitry Andric if (LangOpts.OpenMPSimd) 254*0b57cec5SDimitry Andric OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this)); 255*0b57cec5SDimitry Andric else 256*0b57cec5SDimitry Andric OpenMPRuntime.reset(new CGOpenMPRuntime(*this)); 257*0b57cec5SDimitry Andric break; 258*0b57cec5SDimitry Andric } 259*0b57cec5SDimitry Andric } 260*0b57cec5SDimitry Andric 261*0b57cec5SDimitry Andric void CodeGenModule::createCUDARuntime() { 262*0b57cec5SDimitry Andric CUDARuntime.reset(CreateNVCUDARuntime(*this)); 263*0b57cec5SDimitry Andric } 264*0b57cec5SDimitry Andric 26581ad6265SDimitry Andric void CodeGenModule::createHLSLRuntime() { 26681ad6265SDimitry Andric HLSLRuntime.reset(new CGHLSLRuntime(*this)); 26781ad6265SDimitry Andric } 26881ad6265SDimitry Andric 269*0b57cec5SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { 270*0b57cec5SDimitry Andric Replacements[Name] = C; 271*0b57cec5SDimitry Andric } 272*0b57cec5SDimitry Andric 273*0b57cec5SDimitry Andric void CodeGenModule::applyReplacements() { 274*0b57cec5SDimitry Andric for (auto &I : Replacements) { 275*0b57cec5SDimitry Andric StringRef MangledName = I.first(); 276*0b57cec5SDimitry Andric llvm::Constant *Replacement = I.second; 277*0b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 278*0b57cec5SDimitry Andric if (!Entry) 279*0b57cec5SDimitry Andric continue; 280*0b57cec5SDimitry Andric auto *OldF = cast<llvm::Function>(Entry); 281*0b57cec5SDimitry Andric auto *NewF = dyn_cast<llvm::Function>(Replacement); 282*0b57cec5SDimitry Andric if (!NewF) { 283*0b57cec5SDimitry Andric if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 284*0b57cec5SDimitry Andric NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 285*0b57cec5SDimitry Andric } else { 286*0b57cec5SDimitry Andric auto *CE = cast<llvm::ConstantExpr>(Replacement); 287*0b57cec5SDimitry Andric assert(CE->getOpcode() == llvm::Instruction::BitCast || 288*0b57cec5SDimitry Andric CE->getOpcode() == llvm::Instruction::GetElementPtr); 289*0b57cec5SDimitry Andric NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 290*0b57cec5SDimitry Andric } 291*0b57cec5SDimitry Andric } 292*0b57cec5SDimitry Andric 293*0b57cec5SDimitry Andric // Replace old with new, but keep the old order. 294*0b57cec5SDimitry Andric OldF->replaceAllUsesWith(Replacement); 295*0b57cec5SDimitry Andric if (NewF) { 296*0b57cec5SDimitry Andric NewF->removeFromParent(); 297*0b57cec5SDimitry Andric OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(), 298*0b57cec5SDimitry Andric NewF); 299*0b57cec5SDimitry Andric } 300*0b57cec5SDimitry Andric OldF->eraseFromParent(); 301*0b57cec5SDimitry Andric } 302*0b57cec5SDimitry Andric } 303*0b57cec5SDimitry Andric 304*0b57cec5SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { 305*0b57cec5SDimitry Andric GlobalValReplacements.push_back(std::make_pair(GV, C)); 306*0b57cec5SDimitry Andric } 307*0b57cec5SDimitry Andric 308*0b57cec5SDimitry Andric void CodeGenModule::applyGlobalValReplacements() { 309*0b57cec5SDimitry Andric for (auto &I : GlobalValReplacements) { 310*0b57cec5SDimitry Andric llvm::GlobalValue *GV = I.first; 311*0b57cec5SDimitry Andric llvm::Constant *C = I.second; 312*0b57cec5SDimitry Andric 313*0b57cec5SDimitry Andric GV->replaceAllUsesWith(C); 314*0b57cec5SDimitry Andric GV->eraseFromParent(); 315*0b57cec5SDimitry Andric } 316*0b57cec5SDimitry Andric } 317*0b57cec5SDimitry Andric 318*0b57cec5SDimitry Andric // This is only used in aliases that we created and we know they have a 319*0b57cec5SDimitry Andric // linear structure. 320349cc55cSDimitry Andric static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) { 321349cc55cSDimitry Andric const llvm::Constant *C; 322349cc55cSDimitry Andric if (auto *GA = dyn_cast<llvm::GlobalAlias>(GV)) 323349cc55cSDimitry Andric C = GA->getAliasee(); 324349cc55cSDimitry Andric else if (auto *GI = dyn_cast<llvm::GlobalIFunc>(GV)) 325349cc55cSDimitry Andric C = GI->getResolver(); 326349cc55cSDimitry Andric else 327349cc55cSDimitry Andric return GV; 328349cc55cSDimitry Andric 329349cc55cSDimitry Andric const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(C->stripPointerCasts()); 330349cc55cSDimitry Andric if (!AliaseeGV) 331*0b57cec5SDimitry Andric return nullptr; 332349cc55cSDimitry Andric 333349cc55cSDimitry Andric const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject(); 334349cc55cSDimitry Andric if (FinalGV == GV) 335*0b57cec5SDimitry Andric return nullptr; 336349cc55cSDimitry Andric 337349cc55cSDimitry Andric return FinalGV; 338*0b57cec5SDimitry Andric } 339349cc55cSDimitry Andric 340349cc55cSDimitry Andric static bool checkAliasedGlobal(DiagnosticsEngine &Diags, 341349cc55cSDimitry Andric SourceLocation Location, bool IsIFunc, 342349cc55cSDimitry Andric const llvm::GlobalValue *Alias, 343349cc55cSDimitry Andric const llvm::GlobalValue *&GV) { 344349cc55cSDimitry Andric GV = getAliasedGlobal(Alias); 345349cc55cSDimitry Andric if (!GV) { 346349cc55cSDimitry Andric Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc; 347349cc55cSDimitry Andric return false; 348349cc55cSDimitry Andric } 349349cc55cSDimitry Andric 350349cc55cSDimitry Andric if (GV->isDeclaration()) { 351349cc55cSDimitry Andric Diags.Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc; 352349cc55cSDimitry Andric return false; 353349cc55cSDimitry Andric } 354349cc55cSDimitry Andric 355349cc55cSDimitry Andric if (IsIFunc) { 356349cc55cSDimitry Andric // Check resolver function type. 357349cc55cSDimitry Andric const auto *F = dyn_cast<llvm::Function>(GV); 358349cc55cSDimitry Andric if (!F) { 359349cc55cSDimitry Andric Diags.Report(Location, diag::err_alias_to_undefined) 360349cc55cSDimitry Andric << IsIFunc << IsIFunc; 361349cc55cSDimitry Andric return false; 362349cc55cSDimitry Andric } 363349cc55cSDimitry Andric 364349cc55cSDimitry Andric llvm::FunctionType *FTy = F->getFunctionType(); 365349cc55cSDimitry Andric if (!FTy->getReturnType()->isPointerTy()) { 366349cc55cSDimitry Andric Diags.Report(Location, diag::err_ifunc_resolver_return); 367349cc55cSDimitry Andric return false; 368349cc55cSDimitry Andric } 369349cc55cSDimitry Andric } 370349cc55cSDimitry Andric 371349cc55cSDimitry Andric return true; 372*0b57cec5SDimitry Andric } 373*0b57cec5SDimitry Andric 374*0b57cec5SDimitry Andric void CodeGenModule::checkAliases() { 375*0b57cec5SDimitry Andric // Check if the constructed aliases are well formed. It is really unfortunate 376*0b57cec5SDimitry Andric // that we have to do this in CodeGen, but we only construct mangled names 377*0b57cec5SDimitry Andric // and aliases during codegen. 378*0b57cec5SDimitry Andric bool Error = false; 379*0b57cec5SDimitry Andric DiagnosticsEngine &Diags = getDiags(); 380*0b57cec5SDimitry Andric for (const GlobalDecl &GD : Aliases) { 381*0b57cec5SDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 382*0b57cec5SDimitry Andric SourceLocation Location; 383*0b57cec5SDimitry Andric bool IsIFunc = D->hasAttr<IFuncAttr>(); 384*0b57cec5SDimitry Andric if (const Attr *A = D->getDefiningAttr()) 385*0b57cec5SDimitry Andric Location = A->getLocation(); 386*0b57cec5SDimitry Andric else 387*0b57cec5SDimitry Andric llvm_unreachable("Not an alias or ifunc?"); 388349cc55cSDimitry Andric 389*0b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 390349cc55cSDimitry Andric llvm::GlobalValue *Alias = GetGlobalValue(MangledName); 391349cc55cSDimitry Andric const llvm::GlobalValue *GV = nullptr; 392349cc55cSDimitry Andric if (!checkAliasedGlobal(Diags, Location, IsIFunc, Alias, GV)) { 393*0b57cec5SDimitry Andric Error = true; 394349cc55cSDimitry Andric continue; 395*0b57cec5SDimitry Andric } 396*0b57cec5SDimitry Andric 397349cc55cSDimitry Andric llvm::Constant *Aliasee = 398349cc55cSDimitry Andric IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver() 399349cc55cSDimitry Andric : cast<llvm::GlobalAlias>(Alias)->getAliasee(); 400349cc55cSDimitry Andric 401*0b57cec5SDimitry Andric llvm::GlobalValue *AliaseeGV; 402*0b57cec5SDimitry Andric if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 403*0b57cec5SDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 404*0b57cec5SDimitry Andric else 405*0b57cec5SDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 406*0b57cec5SDimitry Andric 407*0b57cec5SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 408*0b57cec5SDimitry Andric StringRef AliasSection = SA->getName(); 409*0b57cec5SDimitry Andric if (AliasSection != AliaseeGV->getSection()) 410*0b57cec5SDimitry Andric Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 411*0b57cec5SDimitry Andric << AliasSection << IsIFunc << IsIFunc; 412*0b57cec5SDimitry Andric } 413*0b57cec5SDimitry Andric 414*0b57cec5SDimitry Andric // We have to handle alias to weak aliases in here. LLVM itself disallows 415*0b57cec5SDimitry Andric // this since the object semantics would not match the IL one. For 416*0b57cec5SDimitry Andric // compatibility with gcc we implement it by just pointing the alias 417*0b57cec5SDimitry Andric // to its aliasee's aliasee. We also warn, since the user is probably 418*0b57cec5SDimitry Andric // expecting the link to be weak. 419349cc55cSDimitry Andric if (auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) { 420*0b57cec5SDimitry Andric if (GA->isInterposable()) { 421*0b57cec5SDimitry Andric Diags.Report(Location, diag::warn_alias_to_weak_alias) 422*0b57cec5SDimitry Andric << GV->getName() << GA->getName() << IsIFunc; 423*0b57cec5SDimitry Andric Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 424349cc55cSDimitry Andric GA->getAliasee(), Alias->getType()); 425349cc55cSDimitry Andric 426349cc55cSDimitry Andric if (IsIFunc) 427349cc55cSDimitry Andric cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee); 428349cc55cSDimitry Andric else 429349cc55cSDimitry Andric cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee); 430*0b57cec5SDimitry Andric } 431*0b57cec5SDimitry Andric } 432*0b57cec5SDimitry Andric } 433*0b57cec5SDimitry Andric if (!Error) 434*0b57cec5SDimitry Andric return; 435*0b57cec5SDimitry Andric 436*0b57cec5SDimitry Andric for (const GlobalDecl &GD : Aliases) { 437*0b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 438349cc55cSDimitry Andric llvm::GlobalValue *Alias = GetGlobalValue(MangledName); 439*0b57cec5SDimitry Andric Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 440*0b57cec5SDimitry Andric Alias->eraseFromParent(); 441*0b57cec5SDimitry Andric } 442*0b57cec5SDimitry Andric } 443*0b57cec5SDimitry Andric 444*0b57cec5SDimitry Andric void CodeGenModule::clear() { 445*0b57cec5SDimitry Andric DeferredDeclsToEmit.clear(); 446753f127fSDimitry Andric EmittedDeferredDecls.clear(); 447*0b57cec5SDimitry Andric if (OpenMPRuntime) 448*0b57cec5SDimitry Andric OpenMPRuntime->clear(); 449*0b57cec5SDimitry Andric } 450*0b57cec5SDimitry Andric 451*0b57cec5SDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 452*0b57cec5SDimitry Andric StringRef MainFile) { 453*0b57cec5SDimitry Andric if (!hasDiagnostics()) 454*0b57cec5SDimitry Andric return; 455*0b57cec5SDimitry Andric if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 456*0b57cec5SDimitry Andric if (MainFile.empty()) 457*0b57cec5SDimitry Andric MainFile = "<stdin>"; 458*0b57cec5SDimitry Andric Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 459*0b57cec5SDimitry Andric } else { 460*0b57cec5SDimitry Andric if (Mismatched > 0) 461*0b57cec5SDimitry Andric Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched; 462*0b57cec5SDimitry Andric 463*0b57cec5SDimitry Andric if (Missing > 0) 464*0b57cec5SDimitry Andric Diags.Report(diag::warn_profile_data_missing) << Visited << Missing; 465*0b57cec5SDimitry Andric } 466*0b57cec5SDimitry Andric } 467*0b57cec5SDimitry Andric 468e8d8bef9SDimitry Andric static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO, 469e8d8bef9SDimitry Andric llvm::Module &M) { 470e8d8bef9SDimitry Andric if (!LO.VisibilityFromDLLStorageClass) 471e8d8bef9SDimitry Andric return; 472e8d8bef9SDimitry Andric 473e8d8bef9SDimitry Andric llvm::GlobalValue::VisibilityTypes DLLExportVisibility = 474e8d8bef9SDimitry Andric CodeGenModule::GetLLVMVisibility(LO.getDLLExportVisibility()); 475e8d8bef9SDimitry Andric llvm::GlobalValue::VisibilityTypes NoDLLStorageClassVisibility = 476e8d8bef9SDimitry Andric CodeGenModule::GetLLVMVisibility(LO.getNoDLLStorageClassVisibility()); 477e8d8bef9SDimitry Andric llvm::GlobalValue::VisibilityTypes ExternDeclDLLImportVisibility = 478e8d8bef9SDimitry Andric CodeGenModule::GetLLVMVisibility(LO.getExternDeclDLLImportVisibility()); 479e8d8bef9SDimitry Andric llvm::GlobalValue::VisibilityTypes ExternDeclNoDLLStorageClassVisibility = 480e8d8bef9SDimitry Andric CodeGenModule::GetLLVMVisibility( 481e8d8bef9SDimitry Andric LO.getExternDeclNoDLLStorageClassVisibility()); 482e8d8bef9SDimitry Andric 483e8d8bef9SDimitry Andric for (llvm::GlobalValue &GV : M.global_values()) { 484e8d8bef9SDimitry Andric if (GV.hasAppendingLinkage() || GV.hasLocalLinkage()) 485e8d8bef9SDimitry Andric continue; 486e8d8bef9SDimitry Andric 487e8d8bef9SDimitry Andric // Reset DSO locality before setting the visibility. This removes 488e8d8bef9SDimitry Andric // any effects that visibility options and annotations may have 489e8d8bef9SDimitry Andric // had on the DSO locality. Setting the visibility will implicitly set 490e8d8bef9SDimitry Andric // appropriate globals to DSO Local; however, this will be pessimistic 491e8d8bef9SDimitry Andric // w.r.t. to the normal compiler IRGen. 492e8d8bef9SDimitry Andric GV.setDSOLocal(false); 493e8d8bef9SDimitry Andric 494e8d8bef9SDimitry Andric if (GV.isDeclarationForLinker()) { 495e8d8bef9SDimitry Andric GV.setVisibility(GV.getDLLStorageClass() == 496e8d8bef9SDimitry Andric llvm::GlobalValue::DLLImportStorageClass 497e8d8bef9SDimitry Andric ? ExternDeclDLLImportVisibility 498e8d8bef9SDimitry Andric : ExternDeclNoDLLStorageClassVisibility); 499e8d8bef9SDimitry Andric } else { 500e8d8bef9SDimitry Andric GV.setVisibility(GV.getDLLStorageClass() == 501e8d8bef9SDimitry Andric llvm::GlobalValue::DLLExportStorageClass 502e8d8bef9SDimitry Andric ? DLLExportVisibility 503e8d8bef9SDimitry Andric : NoDLLStorageClassVisibility); 504e8d8bef9SDimitry Andric } 505e8d8bef9SDimitry Andric 506e8d8bef9SDimitry Andric GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 507e8d8bef9SDimitry Andric } 508e8d8bef9SDimitry Andric } 509e8d8bef9SDimitry Andric 510*0b57cec5SDimitry Andric void CodeGenModule::Release() { 511fcaf7f86SDimitry Andric Module *Primary = getContext().getModuleForCodeGen(); 51261cfbce3SDimitry Andric if (CXX20ModuleInits && Primary && !Primary->isHeaderLikeModule()) 513fcaf7f86SDimitry Andric EmitModuleInitializers(Primary); 514*0b57cec5SDimitry Andric EmitDeferred(); 515753f127fSDimitry Andric DeferredDecls.insert(EmittedDeferredDecls.begin(), 516753f127fSDimitry Andric EmittedDeferredDecls.end()); 517753f127fSDimitry Andric EmittedDeferredDecls.clear(); 518*0b57cec5SDimitry Andric EmitVTablesOpportunistically(); 519*0b57cec5SDimitry Andric applyGlobalValReplacements(); 520*0b57cec5SDimitry Andric applyReplacements(); 521*0b57cec5SDimitry Andric emitMultiVersionFunctions(); 522bdd1243dSDimitry Andric 523bdd1243dSDimitry Andric if (Context.getLangOpts().IncrementalExtensions && 524bdd1243dSDimitry Andric GlobalTopLevelStmtBlockInFlight.first) { 525bdd1243dSDimitry Andric const TopLevelStmtDecl *TLSD = GlobalTopLevelStmtBlockInFlight.second; 526bdd1243dSDimitry Andric GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->getEndLoc()); 527bdd1243dSDimitry Andric GlobalTopLevelStmtBlockInFlight = {nullptr, nullptr}; 528bdd1243dSDimitry Andric } 529bdd1243dSDimitry Andric 530fcaf7f86SDimitry Andric if (CXX20ModuleInits && Primary && Primary->isInterfaceOrPartition()) 531fcaf7f86SDimitry Andric EmitCXXModuleInitFunc(Primary); 532fcaf7f86SDimitry Andric else 533*0b57cec5SDimitry Andric EmitCXXGlobalInitFunc(); 5345ffd83dbSDimitry Andric EmitCXXGlobalCleanUpFunc(); 535*0b57cec5SDimitry Andric registerGlobalDtorsWithAtExit(); 536*0b57cec5SDimitry Andric EmitCXXThreadLocalInitFunc(); 537*0b57cec5SDimitry Andric if (ObjCRuntime) 538*0b57cec5SDimitry Andric if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 539*0b57cec5SDimitry Andric AddGlobalCtor(ObjCInitFunction); 540fe6060f1SDimitry Andric if (Context.getLangOpts().CUDA && CUDARuntime) { 541fe6060f1SDimitry Andric if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule()) 542*0b57cec5SDimitry Andric AddGlobalCtor(CudaCtorFunction); 543*0b57cec5SDimitry Andric } 544*0b57cec5SDimitry Andric if (OpenMPRuntime) { 545*0b57cec5SDimitry Andric if (llvm::Function *OpenMPRequiresDirectiveRegFun = 546*0b57cec5SDimitry Andric OpenMPRuntime->emitRequiresDirectiveRegFun()) { 547*0b57cec5SDimitry Andric AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0); 548*0b57cec5SDimitry Andric } 549a7dea167SDimitry Andric OpenMPRuntime->createOffloadEntriesAndInfoMetadata(); 550*0b57cec5SDimitry Andric OpenMPRuntime->clear(); 551*0b57cec5SDimitry Andric } 552*0b57cec5SDimitry Andric if (PGOReader) { 553*0b57cec5SDimitry Andric getModule().setProfileSummary( 554*0b57cec5SDimitry Andric PGOReader->getSummary(/* UseCS */ false).getMD(VMContext), 555*0b57cec5SDimitry Andric llvm::ProfileSummary::PSK_Instr); 556*0b57cec5SDimitry Andric if (PGOStats.hasDiagnostics()) 557*0b57cec5SDimitry Andric PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 558*0b57cec5SDimitry Andric } 559bdd1243dSDimitry Andric llvm::stable_sort(GlobalCtors, [](const Structor &L, const Structor &R) { 560bdd1243dSDimitry Andric return L.LexOrder < R.LexOrder; 561bdd1243dSDimitry Andric }); 562*0b57cec5SDimitry Andric EmitCtorList(GlobalCtors, "llvm.global_ctors"); 563*0b57cec5SDimitry Andric EmitCtorList(GlobalDtors, "llvm.global_dtors"); 564*0b57cec5SDimitry Andric EmitGlobalAnnotations(); 565*0b57cec5SDimitry Andric EmitStaticExternCAliases(); 56681ad6265SDimitry Andric checkAliases(); 567*0b57cec5SDimitry Andric EmitDeferredUnusedCoverageMappings(); 568fe6060f1SDimitry Andric CodeGenPGO(*this).setValueProfilingFlag(getModule()); 569*0b57cec5SDimitry Andric if (CoverageMapping) 570*0b57cec5SDimitry Andric CoverageMapping->emit(); 571*0b57cec5SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 572*0b57cec5SDimitry Andric CodeGenFunction(*this).EmitCfiCheckFail(); 573*0b57cec5SDimitry Andric CodeGenFunction(*this).EmitCfiCheckStub(); 574*0b57cec5SDimitry Andric } 575bdd1243dSDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) 576bdd1243dSDimitry Andric finalizeKCFITypes(); 577*0b57cec5SDimitry Andric emitAtAvailableLinkGuard(); 57881ad6265SDimitry Andric if (Context.getTargetInfo().getTriple().isWasm()) 5795ffd83dbSDimitry Andric EmitMainVoidAlias(); 580fe6060f1SDimitry Andric 58181ad6265SDimitry Andric if (getTriple().isAMDGPU()) { 582fe6060f1SDimitry Andric // Emit reference of __amdgpu_device_library_preserve_asan_functions to 583fe6060f1SDimitry Andric // preserve ASAN functions in bitcode libraries. 58481ad6265SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::Address)) { 585fe6060f1SDimitry Andric auto *FT = llvm::FunctionType::get(VoidTy, {}); 586fe6060f1SDimitry Andric auto *F = llvm::Function::Create( 587fe6060f1SDimitry Andric FT, llvm::GlobalValue::ExternalLinkage, 588fe6060f1SDimitry Andric "__amdgpu_device_library_preserve_asan_functions", &getModule()); 589fe6060f1SDimitry Andric auto *Var = new llvm::GlobalVariable( 590fe6060f1SDimitry Andric getModule(), FT->getPointerTo(), 591fe6060f1SDimitry Andric /*isConstant=*/true, llvm::GlobalValue::WeakAnyLinkage, F, 592fe6060f1SDimitry Andric "__amdgpu_device_library_preserve_asan_functions_ptr", nullptr, 593fe6060f1SDimitry Andric llvm::GlobalVariable::NotThreadLocal); 594fe6060f1SDimitry Andric addCompilerUsedGlobal(Var); 595fe6060f1SDimitry Andric } 59681ad6265SDimitry Andric // Emit amdgpu_code_object_version module flag, which is code object version 59781ad6265SDimitry Andric // times 100. 598bdd1243dSDimitry Andric if (getTarget().getTargetOpts().CodeObjectVersion != 599bdd1243dSDimitry Andric TargetOptions::COV_None) { 60081ad6265SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, 60181ad6265SDimitry Andric "amdgpu_code_object_version", 60281ad6265SDimitry Andric getTarget().getTargetOpts().CodeObjectVersion); 60381ad6265SDimitry Andric } 60481ad6265SDimitry Andric } 60581ad6265SDimitry Andric 60681ad6265SDimitry Andric // Emit a global array containing all external kernels or device variables 60781ad6265SDimitry Andric // used by host functions and mark it as used for CUDA/HIP. This is necessary 60881ad6265SDimitry Andric // to get kernels or device variables in archives linked in even if these 60981ad6265SDimitry Andric // kernels or device variables are only used in host functions. 61081ad6265SDimitry Andric if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) { 61181ad6265SDimitry Andric SmallVector<llvm::Constant *, 8> UsedArray; 61281ad6265SDimitry Andric for (auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) { 61381ad6265SDimitry Andric GlobalDecl GD; 61481ad6265SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) 61581ad6265SDimitry Andric GD = GlobalDecl(FD, KernelReferenceKind::Kernel); 61681ad6265SDimitry Andric else 61781ad6265SDimitry Andric GD = GlobalDecl(D); 61881ad6265SDimitry Andric UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 61981ad6265SDimitry Andric GetAddrOfGlobal(GD), Int8PtrTy)); 62081ad6265SDimitry Andric } 62181ad6265SDimitry Andric 62281ad6265SDimitry Andric llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size()); 62381ad6265SDimitry Andric 62481ad6265SDimitry Andric auto *GV = new llvm::GlobalVariable( 62581ad6265SDimitry Andric getModule(), ATy, false, llvm::GlobalValue::InternalLinkage, 62681ad6265SDimitry Andric llvm::ConstantArray::get(ATy, UsedArray), "__clang_gpu_used_external"); 62781ad6265SDimitry Andric addCompilerUsedGlobal(GV); 62804eeddc0SDimitry Andric } 629fe6060f1SDimitry Andric 630*0b57cec5SDimitry Andric emitLLVMUsed(); 631*0b57cec5SDimitry Andric if (SanStats) 632*0b57cec5SDimitry Andric SanStats->finish(); 633*0b57cec5SDimitry Andric 634*0b57cec5SDimitry Andric if (CodeGenOpts.Autolink && 635*0b57cec5SDimitry Andric (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 636*0b57cec5SDimitry Andric EmitModuleLinkOptions(); 637*0b57cec5SDimitry Andric } 638*0b57cec5SDimitry Andric 639*0b57cec5SDimitry Andric // On ELF we pass the dependent library specifiers directly to the linker 640*0b57cec5SDimitry Andric // without manipulating them. This is in contrast to other platforms where 641*0b57cec5SDimitry Andric // they are mapped to a specific linker option by the compiler. This 642*0b57cec5SDimitry Andric // difference is a result of the greater variety of ELF linkers and the fact 643*0b57cec5SDimitry Andric // that ELF linkers tend to handle libraries in a more complicated fashion 644*0b57cec5SDimitry Andric // than on other platforms. This forces us to defer handling the dependent 645*0b57cec5SDimitry Andric // libs to the linker. 646*0b57cec5SDimitry Andric // 647*0b57cec5SDimitry Andric // CUDA/HIP device and host libraries are different. Currently there is no 648*0b57cec5SDimitry Andric // way to differentiate dependent libraries for host or device. Existing 649*0b57cec5SDimitry Andric // usage of #pragma comment(lib, *) is intended for host libraries on 650*0b57cec5SDimitry Andric // Windows. Therefore emit llvm.dependent-libraries only for host. 651*0b57cec5SDimitry Andric if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) { 652*0b57cec5SDimitry Andric auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries"); 653*0b57cec5SDimitry Andric for (auto *MD : ELFDependentLibraries) 654*0b57cec5SDimitry Andric NMD->addOperand(MD); 655*0b57cec5SDimitry Andric } 656*0b57cec5SDimitry Andric 657*0b57cec5SDimitry Andric // Record mregparm value now so it is visible through rest of codegen. 658*0b57cec5SDimitry Andric if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) 659*0b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters", 660*0b57cec5SDimitry Andric CodeGenOpts.NumRegisterParameters); 661*0b57cec5SDimitry Andric 662*0b57cec5SDimitry Andric if (CodeGenOpts.DwarfVersion) { 663480093f4SDimitry Andric getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version", 664*0b57cec5SDimitry Andric CodeGenOpts.DwarfVersion); 665*0b57cec5SDimitry Andric } 6665ffd83dbSDimitry Andric 667fe6060f1SDimitry Andric if (CodeGenOpts.Dwarf64) 668fe6060f1SDimitry Andric getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1); 669fe6060f1SDimitry Andric 6705ffd83dbSDimitry Andric if (Context.getLangOpts().SemanticInterposition) 6715ffd83dbSDimitry Andric // Require various optimization to respect semantic interposition. 67204eeddc0SDimitry Andric getModule().setSemanticInterposition(true); 6735ffd83dbSDimitry Andric 674*0b57cec5SDimitry Andric if (CodeGenOpts.EmitCodeView) { 675*0b57cec5SDimitry Andric // Indicate that we want CodeView in the metadata. 676*0b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); 677*0b57cec5SDimitry Andric } 678*0b57cec5SDimitry Andric if (CodeGenOpts.CodeViewGHash) { 679*0b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1); 680*0b57cec5SDimitry Andric } 681*0b57cec5SDimitry Andric if (CodeGenOpts.ControlFlowGuard) { 682480093f4SDimitry Andric // Function ID tables and checks for Control Flow Guard (cfguard=2). 683480093f4SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2); 684480093f4SDimitry Andric } else if (CodeGenOpts.ControlFlowGuardNoChecks) { 685480093f4SDimitry Andric // Function ID tables for Control Flow Guard (cfguard=1). 686480093f4SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1); 687*0b57cec5SDimitry Andric } 688fe6060f1SDimitry Andric if (CodeGenOpts.EHContGuard) { 689fe6060f1SDimitry Andric // Function ID tables for EH Continuation Guard. 690fe6060f1SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1); 691fe6060f1SDimitry Andric } 692bdd1243dSDimitry Andric if (Context.getLangOpts().Kernel) { 693bdd1243dSDimitry Andric // Note if we are compiling with /kernel. 694bdd1243dSDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "ms-kernel", 1); 695bdd1243dSDimitry Andric } 696*0b57cec5SDimitry Andric if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { 697*0b57cec5SDimitry Andric // We don't support LTO with 2 with different StrictVTablePointers 698*0b57cec5SDimitry Andric // FIXME: we could support it by stripping all the information introduced 699*0b57cec5SDimitry Andric // by StrictVTablePointers. 700*0b57cec5SDimitry Andric 701*0b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); 702*0b57cec5SDimitry Andric 703*0b57cec5SDimitry Andric llvm::Metadata *Ops[2] = { 704*0b57cec5SDimitry Andric llvm::MDString::get(VMContext, "StrictVTablePointers"), 705*0b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 706*0b57cec5SDimitry Andric llvm::Type::getInt32Ty(VMContext), 1))}; 707*0b57cec5SDimitry Andric 708*0b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Require, 709*0b57cec5SDimitry Andric "StrictVTablePointersRequirement", 710*0b57cec5SDimitry Andric llvm::MDNode::get(VMContext, Ops)); 711*0b57cec5SDimitry Andric } 7125ffd83dbSDimitry Andric if (getModuleDebugInfo()) 713*0b57cec5SDimitry Andric // We support a single version in the linked module. The LLVM 714*0b57cec5SDimitry Andric // parser will drop debug info with a different version number 715*0b57cec5SDimitry Andric // (and warn about it, too). 716*0b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 717*0b57cec5SDimitry Andric llvm::DEBUG_METADATA_VERSION); 718*0b57cec5SDimitry Andric 719*0b57cec5SDimitry Andric // We need to record the widths of enums and wchar_t, so that we can generate 720*0b57cec5SDimitry Andric // the correct build attributes in the ARM backend. wchar_size is also used by 721*0b57cec5SDimitry Andric // TargetLibraryInfo. 722*0b57cec5SDimitry Andric uint64_t WCharWidth = 723*0b57cec5SDimitry Andric Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 724*0b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 725*0b57cec5SDimitry Andric 726*0b57cec5SDimitry Andric llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 727*0b57cec5SDimitry Andric if ( Arch == llvm::Triple::arm 728*0b57cec5SDimitry Andric || Arch == llvm::Triple::armeb 729*0b57cec5SDimitry Andric || Arch == llvm::Triple::thumb 730*0b57cec5SDimitry Andric || Arch == llvm::Triple::thumbeb) { 731*0b57cec5SDimitry Andric // The minimum width of an enum in bytes 732*0b57cec5SDimitry Andric uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 733*0b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 734*0b57cec5SDimitry Andric } 735*0b57cec5SDimitry Andric 73613138422SDimitry Andric if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) { 73713138422SDimitry Andric StringRef ABIStr = Target.getABI(); 73813138422SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 73913138422SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "target-abi", 74013138422SDimitry Andric llvm::MDString::get(Ctx, ABIStr)); 74113138422SDimitry Andric } 74213138422SDimitry Andric 743*0b57cec5SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 744*0b57cec5SDimitry Andric // Indicate that we want cross-DSO control flow integrity checks. 745*0b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); 746*0b57cec5SDimitry Andric } 747*0b57cec5SDimitry Andric 7485ffd83dbSDimitry Andric if (CodeGenOpts.WholeProgramVTables) { 7495ffd83dbSDimitry Andric // Indicate whether VFE was enabled for this module, so that the 7505ffd83dbSDimitry Andric // vcall_visibility metadata added under whole program vtables is handled 7515ffd83dbSDimitry Andric // appropriately in the optimizer. 7525ffd83dbSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim", 7535ffd83dbSDimitry Andric CodeGenOpts.VirtualFunctionElimination); 7545ffd83dbSDimitry Andric } 7555ffd83dbSDimitry Andric 756a7dea167SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) { 757a7dea167SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, 758a7dea167SDimitry Andric "CFI Canonical Jump Tables", 759a7dea167SDimitry Andric CodeGenOpts.SanitizeCfiCanonicalJumpTables); 760a7dea167SDimitry Andric } 761a7dea167SDimitry Andric 762bdd1243dSDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) { 763bdd1243dSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "kcfi", 1); 764bdd1243dSDimitry Andric // KCFI assumes patchable-function-prefix is the same for all indirectly 765bdd1243dSDimitry Andric // called functions. Store the expected offset for code generation. 766bdd1243dSDimitry Andric if (CodeGenOpts.PatchableFunctionEntryOffset) 767bdd1243dSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "kcfi-offset", 768bdd1243dSDimitry Andric CodeGenOpts.PatchableFunctionEntryOffset); 769bdd1243dSDimitry Andric } 770bdd1243dSDimitry Andric 771*0b57cec5SDimitry Andric if (CodeGenOpts.CFProtectionReturn && 772*0b57cec5SDimitry Andric Target.checkCFProtectionReturnSupported(getDiags())) { 773*0b57cec5SDimitry Andric // Indicate that we want to instrument return control flow protection. 774fcaf7f86SDimitry Andric getModule().addModuleFlag(llvm::Module::Min, "cf-protection-return", 775*0b57cec5SDimitry Andric 1); 776*0b57cec5SDimitry Andric } 777*0b57cec5SDimitry Andric 778*0b57cec5SDimitry Andric if (CodeGenOpts.CFProtectionBranch && 779*0b57cec5SDimitry Andric Target.checkCFProtectionBranchSupported(getDiags())) { 780*0b57cec5SDimitry Andric // Indicate that we want to instrument branch control flow protection. 781fcaf7f86SDimitry Andric getModule().addModuleFlag(llvm::Module::Min, "cf-protection-branch", 782*0b57cec5SDimitry Andric 1); 783*0b57cec5SDimitry Andric } 784*0b57cec5SDimitry Andric 785fcaf7f86SDimitry Andric if (CodeGenOpts.FunctionReturnThunks) 786fcaf7f86SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "function_return_thunk_extern", 1); 78704eeddc0SDimitry Andric 788bdd1243dSDimitry Andric if (CodeGenOpts.IndirectBranchCSPrefix) 789bdd1243dSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "indirect_branch_cs_prefix", 1); 790bdd1243dSDimitry Andric 7914824e7fdSDimitry Andric // Add module metadata for return address signing (ignoring 7924824e7fdSDimitry Andric // non-leaf/all) and stack tagging. These are actually turned on by function 7934824e7fdSDimitry Andric // attributes, but we use module metadata to emit build attributes. This is 7944824e7fdSDimitry Andric // needed for LTO, where the function attributes are inside bitcode 7954824e7fdSDimitry Andric // serialised into a global variable by the time build attributes are 79681ad6265SDimitry Andric // emitted, so we can't access them. LTO objects could be compiled with 79781ad6265SDimitry Andric // different flags therefore module flags are set to "Min" behavior to achieve 79881ad6265SDimitry Andric // the same end result of the normal build where e.g BTI is off if any object 79981ad6265SDimitry Andric // doesn't support it. 8004824e7fdSDimitry Andric if (Context.getTargetInfo().hasFeature("ptrauth") && 8014824e7fdSDimitry Andric LangOpts.getSignReturnAddressScope() != 8024824e7fdSDimitry Andric LangOptions::SignReturnAddressScopeKind::None) 8034824e7fdSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, 8044824e7fdSDimitry Andric "sign-return-address-buildattr", 1); 80581ad6265SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::MemtagStack)) 8064824e7fdSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, 8074824e7fdSDimitry Andric "tag-stack-memory-buildattr", 1); 8084824e7fdSDimitry Andric 8094824e7fdSDimitry Andric if (Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb || 8101fd87a68SDimitry Andric Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb || 8114824e7fdSDimitry Andric Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 || 812e8d8bef9SDimitry Andric Arch == llvm::Triple::aarch64_be) { 813972a253aSDimitry Andric if (LangOpts.BranchTargetEnforcement) 81481ad6265SDimitry Andric getModule().addModuleFlag(llvm::Module::Min, "branch-target-enforcement", 815972a253aSDimitry Andric 1); 816972a253aSDimitry Andric if (LangOpts.hasSignReturnAddress()) 817972a253aSDimitry Andric getModule().addModuleFlag(llvm::Module::Min, "sign-return-address", 1); 818972a253aSDimitry Andric if (LangOpts.isSignReturnAddressScopeAll()) 81981ad6265SDimitry Andric getModule().addModuleFlag(llvm::Module::Min, "sign-return-address-all", 820972a253aSDimitry Andric 1); 821972a253aSDimitry Andric if (!LangOpts.isSignReturnAddressWithAKey()) 82281ad6265SDimitry Andric getModule().addModuleFlag(llvm::Module::Min, 823972a253aSDimitry Andric "sign-return-address-with-bkey", 1); 824e8d8bef9SDimitry Andric } 825e8d8bef9SDimitry Andric 826e8d8bef9SDimitry Andric if (!CodeGenOpts.MemoryProfileOutput.empty()) { 827e8d8bef9SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 828e8d8bef9SDimitry Andric getModule().addModuleFlag( 829e8d8bef9SDimitry Andric llvm::Module::Error, "MemProfProfileFilename", 830e8d8bef9SDimitry Andric llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput)); 831e8d8bef9SDimitry Andric } 832e8d8bef9SDimitry Andric 833*0b57cec5SDimitry Andric if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) { 834*0b57cec5SDimitry Andric // Indicate whether __nvvm_reflect should be configured to flush denormal 835*0b57cec5SDimitry Andric // floating point values to 0. (This corresponds to its "__CUDA_FTZ" 836*0b57cec5SDimitry Andric // property.) 837*0b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", 8385ffd83dbSDimitry Andric CodeGenOpts.FP32DenormalMode.Output != 8395ffd83dbSDimitry Andric llvm::DenormalMode::IEEE); 840*0b57cec5SDimitry Andric } 841*0b57cec5SDimitry Andric 842fe6060f1SDimitry Andric if (LangOpts.EHAsynch) 843fe6060f1SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1); 844fe6060f1SDimitry Andric 845fe6060f1SDimitry Andric // Indicate whether this Module was compiled with -fopenmp 846fe6060f1SDimitry Andric if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 847fe6060f1SDimitry Andric getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP); 848fe6060f1SDimitry Andric if (getLangOpts().OpenMPIsDevice) 849fe6060f1SDimitry Andric getModule().addModuleFlag(llvm::Module::Max, "openmp-device", 850fe6060f1SDimitry Andric LangOpts.OpenMP); 851fe6060f1SDimitry Andric 852*0b57cec5SDimitry Andric // Emit OpenCL specific module metadata: OpenCL/SPIR version. 85381ad6265SDimitry Andric if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice && getTriple().isSPIRV())) { 854*0b57cec5SDimitry Andric EmitOpenCLMetadata(); 855*0b57cec5SDimitry Andric // Emit SPIR version. 856*0b57cec5SDimitry Andric if (getTriple().isSPIR()) { 857*0b57cec5SDimitry Andric // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the 858*0b57cec5SDimitry Andric // opencl.spir.version named metadata. 859349cc55cSDimitry Andric // C++ for OpenCL has a distinct mapping for version compatibility with 860349cc55cSDimitry Andric // OpenCL. 861349cc55cSDimitry Andric auto Version = LangOpts.getOpenCLCompatibleVersion(); 862*0b57cec5SDimitry Andric llvm::Metadata *SPIRVerElts[] = { 863*0b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 864*0b57cec5SDimitry Andric Int32Ty, Version / 100)), 865*0b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 866*0b57cec5SDimitry Andric Int32Ty, (Version / 100 > 1) ? 0 : 2))}; 867*0b57cec5SDimitry Andric llvm::NamedMDNode *SPIRVerMD = 868*0b57cec5SDimitry Andric TheModule.getOrInsertNamedMetadata("opencl.spir.version"); 869*0b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 870*0b57cec5SDimitry Andric SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts)); 871*0b57cec5SDimitry Andric } 872*0b57cec5SDimitry Andric } 873*0b57cec5SDimitry Andric 87481ad6265SDimitry Andric // HLSL related end of code gen work items. 87581ad6265SDimitry Andric if (LangOpts.HLSL) 87681ad6265SDimitry Andric getHLSLRuntime().finishCodeGen(); 87781ad6265SDimitry Andric 878*0b57cec5SDimitry Andric if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 879*0b57cec5SDimitry Andric assert(PLevel < 3 && "Invalid PIC Level"); 880*0b57cec5SDimitry Andric getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel)); 881*0b57cec5SDimitry Andric if (Context.getLangOpts().PIE) 882*0b57cec5SDimitry Andric getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel)); 883*0b57cec5SDimitry Andric } 884*0b57cec5SDimitry Andric 885*0b57cec5SDimitry Andric if (getCodeGenOpts().CodeModel.size() > 0) { 886*0b57cec5SDimitry Andric unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel) 887*0b57cec5SDimitry Andric .Case("tiny", llvm::CodeModel::Tiny) 888*0b57cec5SDimitry Andric .Case("small", llvm::CodeModel::Small) 889*0b57cec5SDimitry Andric .Case("kernel", llvm::CodeModel::Kernel) 890*0b57cec5SDimitry Andric .Case("medium", llvm::CodeModel::Medium) 891*0b57cec5SDimitry Andric .Case("large", llvm::CodeModel::Large) 892*0b57cec5SDimitry Andric .Default(~0u); 893*0b57cec5SDimitry Andric if (CM != ~0u) { 894*0b57cec5SDimitry Andric llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM); 895*0b57cec5SDimitry Andric getModule().setCodeModel(codeModel); 896*0b57cec5SDimitry Andric } 897*0b57cec5SDimitry Andric } 898*0b57cec5SDimitry Andric 899*0b57cec5SDimitry Andric if (CodeGenOpts.NoPLT) 900*0b57cec5SDimitry Andric getModule().setRtLibUseGOT(); 901fe6060f1SDimitry Andric if (CodeGenOpts.UnwindTables) 90281ad6265SDimitry Andric getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables)); 903fe6060f1SDimitry Andric 904fe6060f1SDimitry Andric switch (CodeGenOpts.getFramePointer()) { 905fe6060f1SDimitry Andric case CodeGenOptions::FramePointerKind::None: 906fe6060f1SDimitry Andric // 0 ("none") is the default. 907fe6060f1SDimitry Andric break; 908fe6060f1SDimitry Andric case CodeGenOptions::FramePointerKind::NonLeaf: 909fe6060f1SDimitry Andric getModule().setFramePointer(llvm::FramePointerKind::NonLeaf); 910fe6060f1SDimitry Andric break; 911fe6060f1SDimitry Andric case CodeGenOptions::FramePointerKind::All: 912fe6060f1SDimitry Andric getModule().setFramePointer(llvm::FramePointerKind::All); 913fe6060f1SDimitry Andric break; 914fe6060f1SDimitry Andric } 915*0b57cec5SDimitry Andric 916*0b57cec5SDimitry Andric SimplifyPersonality(); 917*0b57cec5SDimitry Andric 918*0b57cec5SDimitry Andric if (getCodeGenOpts().EmitDeclMetadata) 919*0b57cec5SDimitry Andric EmitDeclMetadata(); 920*0b57cec5SDimitry Andric 921*0b57cec5SDimitry Andric if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 922*0b57cec5SDimitry Andric EmitCoverageFile(); 923*0b57cec5SDimitry Andric 9245ffd83dbSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 9255ffd83dbSDimitry Andric DI->finalize(); 926*0b57cec5SDimitry Andric 927*0b57cec5SDimitry Andric if (getCodeGenOpts().EmitVersionIdentMetadata) 928*0b57cec5SDimitry Andric EmitVersionIdentMetadata(); 929*0b57cec5SDimitry Andric 930*0b57cec5SDimitry Andric if (!getCodeGenOpts().RecordCommandLine.empty()) 931*0b57cec5SDimitry Andric EmitCommandLineMetadata(); 932*0b57cec5SDimitry Andric 933fe6060f1SDimitry Andric if (!getCodeGenOpts().StackProtectorGuard.empty()) 934fe6060f1SDimitry Andric getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard); 935fe6060f1SDimitry Andric if (!getCodeGenOpts().StackProtectorGuardReg.empty()) 936fe6060f1SDimitry Andric getModule().setStackProtectorGuardReg( 937fe6060f1SDimitry Andric getCodeGenOpts().StackProtectorGuardReg); 938753f127fSDimitry Andric if (!getCodeGenOpts().StackProtectorGuardSymbol.empty()) 939753f127fSDimitry Andric getModule().setStackProtectorGuardSymbol( 940753f127fSDimitry Andric getCodeGenOpts().StackProtectorGuardSymbol); 941fe6060f1SDimitry Andric if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX) 942fe6060f1SDimitry Andric getModule().setStackProtectorGuardOffset( 943fe6060f1SDimitry Andric getCodeGenOpts().StackProtectorGuardOffset); 944fe6060f1SDimitry Andric if (getCodeGenOpts().StackAlignment) 945fe6060f1SDimitry Andric getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment); 946349cc55cSDimitry Andric if (getCodeGenOpts().SkipRaxSetup) 947349cc55cSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "SkipRaxSetup", 1); 948fe6060f1SDimitry Andric 9495ffd83dbSDimitry Andric getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames); 9505ffd83dbSDimitry Andric 9515ffd83dbSDimitry Andric EmitBackendOptionsMetadata(getCodeGenOpts()); 952e8d8bef9SDimitry Andric 95381ad6265SDimitry Andric // If there is device offloading code embed it in the host now. 95481ad6265SDimitry Andric EmbedObject(&getModule(), CodeGenOpts, getDiags()); 95581ad6265SDimitry Andric 956e8d8bef9SDimitry Andric // Set visibility from DLL storage class 957e8d8bef9SDimitry Andric // We do this at the end of LLVM IR generation; after any operation 958e8d8bef9SDimitry Andric // that might affect the DLL storage class or the visibility, and 959e8d8bef9SDimitry Andric // before anything that might act on these. 960e8d8bef9SDimitry Andric setVisibilityFromDLLStorageClass(LangOpts, getModule()); 961*0b57cec5SDimitry Andric } 962*0b57cec5SDimitry Andric 963*0b57cec5SDimitry Andric void CodeGenModule::EmitOpenCLMetadata() { 964*0b57cec5SDimitry Andric // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the 965*0b57cec5SDimitry Andric // opencl.ocl.version named metadata node. 966349cc55cSDimitry Andric // C++ for OpenCL has a distinct mapping for versions compatibile with OpenCL. 967349cc55cSDimitry Andric auto Version = LangOpts.getOpenCLCompatibleVersion(); 968*0b57cec5SDimitry Andric llvm::Metadata *OCLVerElts[] = { 969*0b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 970*0b57cec5SDimitry Andric Int32Ty, Version / 100)), 971*0b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 972*0b57cec5SDimitry Andric Int32Ty, (Version % 100) / 10))}; 973*0b57cec5SDimitry Andric llvm::NamedMDNode *OCLVerMD = 974*0b57cec5SDimitry Andric TheModule.getOrInsertNamedMetadata("opencl.ocl.version"); 975*0b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 976*0b57cec5SDimitry Andric OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts)); 977*0b57cec5SDimitry Andric } 978*0b57cec5SDimitry Andric 9795ffd83dbSDimitry Andric void CodeGenModule::EmitBackendOptionsMetadata( 9805ffd83dbSDimitry Andric const CodeGenOptions CodeGenOpts) { 981bdd1243dSDimitry Andric if (getTriple().isRISCV()) { 9825ffd83dbSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "SmallDataLimit", 9835ffd83dbSDimitry Andric CodeGenOpts.SmallDataLimit); 9845ffd83dbSDimitry Andric } 9855ffd83dbSDimitry Andric } 9865ffd83dbSDimitry Andric 987*0b57cec5SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 988*0b57cec5SDimitry Andric // Make sure that this type is translated. 989*0b57cec5SDimitry Andric Types.UpdateCompletedType(TD); 990*0b57cec5SDimitry Andric } 991*0b57cec5SDimitry Andric 992*0b57cec5SDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { 993*0b57cec5SDimitry Andric // Make sure that this type is translated. 994*0b57cec5SDimitry Andric Types.RefreshTypeCacheForClass(RD); 995*0b57cec5SDimitry Andric } 996*0b57cec5SDimitry Andric 997*0b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) { 998*0b57cec5SDimitry Andric if (!TBAA) 999*0b57cec5SDimitry Andric return nullptr; 1000*0b57cec5SDimitry Andric return TBAA->getTypeInfo(QTy); 1001*0b57cec5SDimitry Andric } 1002*0b57cec5SDimitry Andric 1003*0b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) { 1004*0b57cec5SDimitry Andric if (!TBAA) 1005*0b57cec5SDimitry Andric return TBAAAccessInfo(); 10065ffd83dbSDimitry Andric if (getLangOpts().CUDAIsDevice) { 10075ffd83dbSDimitry Andric // As CUDA builtin surface/texture types are replaced, skip generating TBAA 10085ffd83dbSDimitry Andric // access info. 10095ffd83dbSDimitry Andric if (AccessType->isCUDADeviceBuiltinSurfaceType()) { 10105ffd83dbSDimitry Andric if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() != 10115ffd83dbSDimitry Andric nullptr) 10125ffd83dbSDimitry Andric return TBAAAccessInfo(); 10135ffd83dbSDimitry Andric } else if (AccessType->isCUDADeviceBuiltinTextureType()) { 10145ffd83dbSDimitry Andric if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() != 10155ffd83dbSDimitry Andric nullptr) 10165ffd83dbSDimitry Andric return TBAAAccessInfo(); 10175ffd83dbSDimitry Andric } 10185ffd83dbSDimitry Andric } 1019*0b57cec5SDimitry Andric return TBAA->getAccessInfo(AccessType); 1020*0b57cec5SDimitry Andric } 1021*0b57cec5SDimitry Andric 1022*0b57cec5SDimitry Andric TBAAAccessInfo 1023*0b57cec5SDimitry Andric CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) { 1024*0b57cec5SDimitry Andric if (!TBAA) 1025*0b57cec5SDimitry Andric return TBAAAccessInfo(); 1026*0b57cec5SDimitry Andric return TBAA->getVTablePtrAccessInfo(VTablePtrType); 1027*0b57cec5SDimitry Andric } 1028*0b57cec5SDimitry Andric 1029*0b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 1030*0b57cec5SDimitry Andric if (!TBAA) 1031*0b57cec5SDimitry Andric return nullptr; 1032*0b57cec5SDimitry Andric return TBAA->getTBAAStructInfo(QTy); 1033*0b57cec5SDimitry Andric } 1034*0b57cec5SDimitry Andric 1035*0b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) { 1036*0b57cec5SDimitry Andric if (!TBAA) 1037*0b57cec5SDimitry Andric return nullptr; 1038*0b57cec5SDimitry Andric return TBAA->getBaseTypeInfo(QTy); 1039*0b57cec5SDimitry Andric } 1040*0b57cec5SDimitry Andric 1041*0b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) { 1042*0b57cec5SDimitry Andric if (!TBAA) 1043*0b57cec5SDimitry Andric return nullptr; 1044*0b57cec5SDimitry Andric return TBAA->getAccessTagInfo(Info); 1045*0b57cec5SDimitry Andric } 1046*0b57cec5SDimitry Andric 1047*0b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, 1048*0b57cec5SDimitry Andric TBAAAccessInfo TargetInfo) { 1049*0b57cec5SDimitry Andric if (!TBAA) 1050*0b57cec5SDimitry Andric return TBAAAccessInfo(); 1051*0b57cec5SDimitry Andric return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo); 1052*0b57cec5SDimitry Andric } 1053*0b57cec5SDimitry Andric 1054*0b57cec5SDimitry Andric TBAAAccessInfo 1055*0b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, 1056*0b57cec5SDimitry Andric TBAAAccessInfo InfoB) { 1057*0b57cec5SDimitry Andric if (!TBAA) 1058*0b57cec5SDimitry Andric return TBAAAccessInfo(); 1059*0b57cec5SDimitry Andric return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB); 1060*0b57cec5SDimitry Andric } 1061*0b57cec5SDimitry Andric 1062*0b57cec5SDimitry Andric TBAAAccessInfo 1063*0b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, 1064*0b57cec5SDimitry Andric TBAAAccessInfo SrcInfo) { 1065*0b57cec5SDimitry Andric if (!TBAA) 1066*0b57cec5SDimitry Andric return TBAAAccessInfo(); 1067*0b57cec5SDimitry Andric return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo); 1068*0b57cec5SDimitry Andric } 1069*0b57cec5SDimitry Andric 1070*0b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, 1071*0b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo) { 1072*0b57cec5SDimitry Andric if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo)) 1073*0b57cec5SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag); 1074*0b57cec5SDimitry Andric } 1075*0b57cec5SDimitry Andric 1076*0b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup( 1077*0b57cec5SDimitry Andric llvm::Instruction *I, const CXXRecordDecl *RD) { 1078*0b57cec5SDimitry Andric I->setMetadata(llvm::LLVMContext::MD_invariant_group, 1079*0b57cec5SDimitry Andric llvm::MDNode::get(getLLVMContext(), {})); 1080*0b57cec5SDimitry Andric } 1081*0b57cec5SDimitry Andric 1082*0b57cec5SDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) { 1083*0b57cec5SDimitry Andric unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 1084*0b57cec5SDimitry Andric getDiags().Report(Context.getFullLoc(loc), diagID) << message; 1085*0b57cec5SDimitry Andric } 1086*0b57cec5SDimitry Andric 1087*0b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the 1088*0b57cec5SDimitry Andric /// specified stmt yet. 1089*0b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 1090*0b57cec5SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 1091*0b57cec5SDimitry Andric "cannot compile this %0 yet"); 1092*0b57cec5SDimitry Andric std::string Msg = Type; 1093*0b57cec5SDimitry Andric getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID) 1094*0b57cec5SDimitry Andric << Msg << S->getSourceRange(); 1095*0b57cec5SDimitry Andric } 1096*0b57cec5SDimitry Andric 1097*0b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the 1098*0b57cec5SDimitry Andric /// specified decl yet. 1099*0b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 1100*0b57cec5SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 1101*0b57cec5SDimitry Andric "cannot compile this %0 yet"); 1102*0b57cec5SDimitry Andric std::string Msg = Type; 1103*0b57cec5SDimitry Andric getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 1104*0b57cec5SDimitry Andric } 1105*0b57cec5SDimitry Andric 1106*0b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 1107*0b57cec5SDimitry Andric return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 1108*0b57cec5SDimitry Andric } 1109*0b57cec5SDimitry Andric 1110*0b57cec5SDimitry Andric void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 1111*0b57cec5SDimitry Andric const NamedDecl *D) const { 1112*0b57cec5SDimitry Andric // Internal definitions always have default visibility. 1113*0b57cec5SDimitry Andric if (GV->hasLocalLinkage()) { 1114*0b57cec5SDimitry Andric GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 1115*0b57cec5SDimitry Andric return; 1116*0b57cec5SDimitry Andric } 1117*0b57cec5SDimitry Andric if (!D) 1118*0b57cec5SDimitry Andric return; 1119*0b57cec5SDimitry Andric // Set visibility for definitions, and for declarations if requested globally 1120*0b57cec5SDimitry Andric // or set explicitly. 1121*0b57cec5SDimitry Andric LinkageInfo LV = D->getLinkageAndVisibility(); 1122bdd1243dSDimitry Andric if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) { 1123bdd1243dSDimitry Andric // Reject incompatible dlllstorage and visibility annotations. 1124bdd1243dSDimitry Andric if (!LV.isVisibilityExplicit()) 1125bdd1243dSDimitry Andric return; 1126bdd1243dSDimitry Andric if (GV->hasDLLExportStorageClass()) { 1127bdd1243dSDimitry Andric if (LV.getVisibility() == HiddenVisibility) 1128bdd1243dSDimitry Andric getDiags().Report(D->getLocation(), 1129bdd1243dSDimitry Andric diag::err_hidden_visibility_dllexport); 1130bdd1243dSDimitry Andric } else if (LV.getVisibility() != DefaultVisibility) { 1131bdd1243dSDimitry Andric getDiags().Report(D->getLocation(), 1132bdd1243dSDimitry Andric diag::err_non_default_visibility_dllimport); 1133bdd1243dSDimitry Andric } 1134bdd1243dSDimitry Andric return; 1135bdd1243dSDimitry Andric } 1136bdd1243dSDimitry Andric 1137*0b57cec5SDimitry Andric if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls || 1138*0b57cec5SDimitry Andric !GV->isDeclarationForLinker()) 1139*0b57cec5SDimitry Andric GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 1140*0b57cec5SDimitry Andric } 1141*0b57cec5SDimitry Andric 1142*0b57cec5SDimitry Andric static bool shouldAssumeDSOLocal(const CodeGenModule &CGM, 1143*0b57cec5SDimitry Andric llvm::GlobalValue *GV) { 1144*0b57cec5SDimitry Andric if (GV->hasLocalLinkage()) 1145*0b57cec5SDimitry Andric return true; 1146*0b57cec5SDimitry Andric 1147*0b57cec5SDimitry Andric if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()) 1148*0b57cec5SDimitry Andric return true; 1149*0b57cec5SDimitry Andric 1150*0b57cec5SDimitry Andric // DLLImport explicitly marks the GV as external. 1151*0b57cec5SDimitry Andric if (GV->hasDLLImportStorageClass()) 1152*0b57cec5SDimitry Andric return false; 1153*0b57cec5SDimitry Andric 1154*0b57cec5SDimitry Andric const llvm::Triple &TT = CGM.getTriple(); 1155*0b57cec5SDimitry Andric if (TT.isWindowsGNUEnvironment()) { 1156*0b57cec5SDimitry Andric // In MinGW, variables without DLLImport can still be automatically 1157*0b57cec5SDimitry Andric // imported from a DLL by the linker; don't mark variables that 1158*0b57cec5SDimitry Andric // potentially could come from another DLL as DSO local. 1159fe6060f1SDimitry Andric 1160fe6060f1SDimitry Andric // With EmulatedTLS, TLS variables can be autoimported from other DLLs 1161fe6060f1SDimitry Andric // (and this actually happens in the public interface of libstdc++), so 1162fe6060f1SDimitry Andric // such variables can't be marked as DSO local. (Native TLS variables 1163fe6060f1SDimitry Andric // can't be dllimported at all, though.) 1164*0b57cec5SDimitry Andric if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) && 1165fe6060f1SDimitry Andric (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS)) 1166*0b57cec5SDimitry Andric return false; 1167*0b57cec5SDimitry Andric } 1168*0b57cec5SDimitry Andric 1169*0b57cec5SDimitry Andric // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols 1170*0b57cec5SDimitry Andric // remain unresolved in the link, they can be resolved to zero, which is 1171*0b57cec5SDimitry Andric // outside the current DSO. 1172*0b57cec5SDimitry Andric if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage()) 1173*0b57cec5SDimitry Andric return false; 1174*0b57cec5SDimitry Andric 1175*0b57cec5SDimitry Andric // Every other GV is local on COFF. 1176*0b57cec5SDimitry Andric // Make an exception for windows OS in the triple: Some firmware builds use 1177*0b57cec5SDimitry Andric // *-win32-macho triples. This (accidentally?) produced windows relocations 1178*0b57cec5SDimitry Andric // without GOT tables in older clang versions; Keep this behaviour. 1179*0b57cec5SDimitry Andric // FIXME: even thread local variables? 1180*0b57cec5SDimitry Andric if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO())) 1181*0b57cec5SDimitry Andric return true; 1182*0b57cec5SDimitry Andric 1183*0b57cec5SDimitry Andric // Only handle COFF and ELF for now. 1184*0b57cec5SDimitry Andric if (!TT.isOSBinFormatELF()) 1185*0b57cec5SDimitry Andric return false; 1186*0b57cec5SDimitry Andric 1187fe6060f1SDimitry Andric // If this is not an executable, don't assume anything is local. 1188fe6060f1SDimitry Andric const auto &CGOpts = CGM.getCodeGenOpts(); 1189fe6060f1SDimitry Andric llvm::Reloc::Model RM = CGOpts.RelocationModel; 1190fe6060f1SDimitry Andric const auto &LOpts = CGM.getLangOpts(); 1191e8d8bef9SDimitry Andric if (RM != llvm::Reloc::Static && !LOpts.PIE) { 1192e8d8bef9SDimitry Andric // On ELF, if -fno-semantic-interposition is specified and the target 1193e8d8bef9SDimitry Andric // supports local aliases, there will be neither CC1 1194e8d8bef9SDimitry Andric // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set 1195fe6060f1SDimitry Andric // dso_local on the function if using a local alias is preferable (can avoid 1196fe6060f1SDimitry Andric // PLT indirection). 1197fe6060f1SDimitry Andric if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias())) 1198*0b57cec5SDimitry Andric return false; 1199e8d8bef9SDimitry Andric return !(CGM.getLangOpts().SemanticInterposition || 1200e8d8bef9SDimitry Andric CGM.getLangOpts().HalfNoSemanticInterposition); 1201e8d8bef9SDimitry Andric } 1202*0b57cec5SDimitry Andric 1203*0b57cec5SDimitry Andric // A definition cannot be preempted from an executable. 1204*0b57cec5SDimitry Andric if (!GV->isDeclarationForLinker()) 1205*0b57cec5SDimitry Andric return true; 1206*0b57cec5SDimitry Andric 1207*0b57cec5SDimitry Andric // Most PIC code sequences that assume that a symbol is local cannot produce a 1208*0b57cec5SDimitry Andric // 0 if it turns out the symbol is undefined. While this is ABI and relocation 1209*0b57cec5SDimitry Andric // depended, it seems worth it to handle it here. 1210*0b57cec5SDimitry Andric if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage()) 1211*0b57cec5SDimitry Andric return false; 1212*0b57cec5SDimitry Andric 1213e8d8bef9SDimitry Andric // PowerPC64 prefers TOC indirection to avoid copy relocations. 1214e8d8bef9SDimitry Andric if (TT.isPPC64()) 1215*0b57cec5SDimitry Andric return false; 1216*0b57cec5SDimitry Andric 1217e8d8bef9SDimitry Andric if (CGOpts.DirectAccessExternalData) { 1218e8d8bef9SDimitry Andric // If -fdirect-access-external-data (default for -fno-pic), set dso_local 1219e8d8bef9SDimitry Andric // for non-thread-local variables. If the symbol is not defined in the 1220e8d8bef9SDimitry Andric // executable, a copy relocation will be needed at link time. dso_local is 1221e8d8bef9SDimitry Andric // excluded for thread-local variables because they generally don't support 1222e8d8bef9SDimitry Andric // copy relocations. 1223*0b57cec5SDimitry Andric if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV)) 1224e8d8bef9SDimitry Andric if (!Var->isThreadLocal()) 1225*0b57cec5SDimitry Andric return true; 1226*0b57cec5SDimitry Andric 1227e8d8bef9SDimitry Andric // -fno-pic sets dso_local on a function declaration to allow direct 1228e8d8bef9SDimitry Andric // accesses when taking its address (similar to a data symbol). If the 1229e8d8bef9SDimitry Andric // function is not defined in the executable, a canonical PLT entry will be 1230e8d8bef9SDimitry Andric // needed at link time. -fno-direct-access-external-data can avoid the 1231e8d8bef9SDimitry Andric // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as 1232e8d8bef9SDimitry Andric // it could just cause trouble without providing perceptible benefits. 1233*0b57cec5SDimitry Andric if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static) 1234*0b57cec5SDimitry Andric return true; 1235e8d8bef9SDimitry Andric } 1236e8d8bef9SDimitry Andric 1237e8d8bef9SDimitry Andric // If we can use copy relocations we can assume it is local. 1238*0b57cec5SDimitry Andric 12395ffd83dbSDimitry Andric // Otherwise don't assume it is local. 1240*0b57cec5SDimitry Andric return false; 1241*0b57cec5SDimitry Andric } 1242*0b57cec5SDimitry Andric 1243*0b57cec5SDimitry Andric void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const { 1244*0b57cec5SDimitry Andric GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV)); 1245*0b57cec5SDimitry Andric } 1246*0b57cec5SDimitry Andric 1247*0b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 1248*0b57cec5SDimitry Andric GlobalDecl GD) const { 1249*0b57cec5SDimitry Andric const auto *D = dyn_cast<NamedDecl>(GD.getDecl()); 1250*0b57cec5SDimitry Andric // C++ destructors have a few C++ ABI specific special cases. 1251*0b57cec5SDimitry Andric if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) { 1252*0b57cec5SDimitry Andric getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType()); 1253*0b57cec5SDimitry Andric return; 1254*0b57cec5SDimitry Andric } 1255*0b57cec5SDimitry Andric setDLLImportDLLExport(GV, D); 1256*0b57cec5SDimitry Andric } 1257*0b57cec5SDimitry Andric 1258*0b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 1259*0b57cec5SDimitry Andric const NamedDecl *D) const { 1260*0b57cec5SDimitry Andric if (D && D->isExternallyVisible()) { 1261*0b57cec5SDimitry Andric if (D->hasAttr<DLLImportAttr>()) 1262*0b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 126381ad6265SDimitry Andric else if ((D->hasAttr<DLLExportAttr>() || 126481ad6265SDimitry Andric shouldMapVisibilityToDLLExport(D)) && 126581ad6265SDimitry Andric !GV->isDeclarationForLinker()) 1266*0b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 1267*0b57cec5SDimitry Andric } 1268*0b57cec5SDimitry Andric } 1269*0b57cec5SDimitry Andric 1270*0b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 1271*0b57cec5SDimitry Andric GlobalDecl GD) const { 1272*0b57cec5SDimitry Andric setDLLImportDLLExport(GV, GD); 1273*0b57cec5SDimitry Andric setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl())); 1274*0b57cec5SDimitry Andric } 1275*0b57cec5SDimitry Andric 1276*0b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 1277*0b57cec5SDimitry Andric const NamedDecl *D) const { 1278*0b57cec5SDimitry Andric setDLLImportDLLExport(GV, D); 1279*0b57cec5SDimitry Andric setGVPropertiesAux(GV, D); 1280*0b57cec5SDimitry Andric } 1281*0b57cec5SDimitry Andric 1282*0b57cec5SDimitry Andric void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV, 1283*0b57cec5SDimitry Andric const NamedDecl *D) const { 1284*0b57cec5SDimitry Andric setGlobalVisibility(GV, D); 1285*0b57cec5SDimitry Andric setDSOLocal(GV); 1286*0b57cec5SDimitry Andric GV->setPartition(CodeGenOpts.SymbolPartition); 1287*0b57cec5SDimitry Andric } 1288*0b57cec5SDimitry Andric 1289*0b57cec5SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 1290*0b57cec5SDimitry Andric return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 1291*0b57cec5SDimitry Andric .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 1292*0b57cec5SDimitry Andric .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 1293*0b57cec5SDimitry Andric .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 1294*0b57cec5SDimitry Andric .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 1295*0b57cec5SDimitry Andric } 1296*0b57cec5SDimitry Andric 12975ffd83dbSDimitry Andric llvm::GlobalVariable::ThreadLocalMode 12985ffd83dbSDimitry Andric CodeGenModule::GetDefaultLLVMTLSModel() const { 12995ffd83dbSDimitry Andric switch (CodeGenOpts.getDefaultTLSModel()) { 1300*0b57cec5SDimitry Andric case CodeGenOptions::GeneralDynamicTLSModel: 1301*0b57cec5SDimitry Andric return llvm::GlobalVariable::GeneralDynamicTLSModel; 1302*0b57cec5SDimitry Andric case CodeGenOptions::LocalDynamicTLSModel: 1303*0b57cec5SDimitry Andric return llvm::GlobalVariable::LocalDynamicTLSModel; 1304*0b57cec5SDimitry Andric case CodeGenOptions::InitialExecTLSModel: 1305*0b57cec5SDimitry Andric return llvm::GlobalVariable::InitialExecTLSModel; 1306*0b57cec5SDimitry Andric case CodeGenOptions::LocalExecTLSModel: 1307*0b57cec5SDimitry Andric return llvm::GlobalVariable::LocalExecTLSModel; 1308*0b57cec5SDimitry Andric } 1309*0b57cec5SDimitry Andric llvm_unreachable("Invalid TLS model!"); 1310*0b57cec5SDimitry Andric } 1311*0b57cec5SDimitry Andric 1312*0b57cec5SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 1313*0b57cec5SDimitry Andric assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 1314*0b57cec5SDimitry Andric 1315*0b57cec5SDimitry Andric llvm::GlobalValue::ThreadLocalMode TLM; 13165ffd83dbSDimitry Andric TLM = GetDefaultLLVMTLSModel(); 1317*0b57cec5SDimitry Andric 1318*0b57cec5SDimitry Andric // Override the TLS model if it is explicitly specified. 1319*0b57cec5SDimitry Andric if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 1320*0b57cec5SDimitry Andric TLM = GetLLVMTLSModel(Attr->getModel()); 1321*0b57cec5SDimitry Andric } 1322*0b57cec5SDimitry Andric 1323*0b57cec5SDimitry Andric GV->setThreadLocalMode(TLM); 1324*0b57cec5SDimitry Andric } 1325*0b57cec5SDimitry Andric 1326*0b57cec5SDimitry Andric static std::string getCPUSpecificMangling(const CodeGenModule &CGM, 1327*0b57cec5SDimitry Andric StringRef Name) { 1328*0b57cec5SDimitry Andric const TargetInfo &Target = CGM.getTarget(); 1329*0b57cec5SDimitry Andric return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str(); 1330*0b57cec5SDimitry Andric } 1331*0b57cec5SDimitry Andric 1332*0b57cec5SDimitry Andric static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, 1333*0b57cec5SDimitry Andric const CPUSpecificAttr *Attr, 1334*0b57cec5SDimitry Andric unsigned CPUIndex, 1335*0b57cec5SDimitry Andric raw_ostream &Out) { 1336*0b57cec5SDimitry Andric // cpu_specific gets the current name, dispatch gets the resolver if IFunc is 1337*0b57cec5SDimitry Andric // supported. 1338*0b57cec5SDimitry Andric if (Attr) 1339*0b57cec5SDimitry Andric Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName()); 1340*0b57cec5SDimitry Andric else if (CGM.getTarget().supportsIFunc()) 1341*0b57cec5SDimitry Andric Out << ".resolver"; 1342*0b57cec5SDimitry Andric } 1343*0b57cec5SDimitry Andric 1344bdd1243dSDimitry Andric static void AppendTargetVersionMangling(const CodeGenModule &CGM, 1345bdd1243dSDimitry Andric const TargetVersionAttr *Attr, 1346bdd1243dSDimitry Andric raw_ostream &Out) { 1347bdd1243dSDimitry Andric if (Attr->isDefaultVersion()) 1348bdd1243dSDimitry Andric return; 1349bdd1243dSDimitry Andric Out << "._"; 1350bdd1243dSDimitry Andric llvm::SmallVector<StringRef, 8> Feats; 1351bdd1243dSDimitry Andric Attr->getFeatures(Feats); 1352bdd1243dSDimitry Andric for (const auto &Feat : Feats) { 1353bdd1243dSDimitry Andric Out << 'M'; 1354bdd1243dSDimitry Andric Out << Feat; 1355bdd1243dSDimitry Andric } 1356bdd1243dSDimitry Andric } 1357bdd1243dSDimitry Andric 1358*0b57cec5SDimitry Andric static void AppendTargetMangling(const CodeGenModule &CGM, 1359*0b57cec5SDimitry Andric const TargetAttr *Attr, raw_ostream &Out) { 1360*0b57cec5SDimitry Andric if (Attr->isDefaultVersion()) 1361*0b57cec5SDimitry Andric return; 1362*0b57cec5SDimitry Andric 1363*0b57cec5SDimitry Andric Out << '.'; 1364*0b57cec5SDimitry Andric const TargetInfo &Target = CGM.getTarget(); 1365bdd1243dSDimitry Andric ParsedTargetAttr Info = Target.parseTargetAttr(Attr->getFeaturesStr()); 1366bdd1243dSDimitry Andric llvm::sort(Info.Features, [&Target](StringRef LHS, StringRef RHS) { 1367*0b57cec5SDimitry Andric // Multiversioning doesn't allow "no-${feature}", so we can 1368*0b57cec5SDimitry Andric // only have "+" prefixes here. 1369*0b57cec5SDimitry Andric assert(LHS.startswith("+") && RHS.startswith("+") && 1370*0b57cec5SDimitry Andric "Features should always have a prefix."); 1371*0b57cec5SDimitry Andric return Target.multiVersionSortPriority(LHS.substr(1)) > 1372*0b57cec5SDimitry Andric Target.multiVersionSortPriority(RHS.substr(1)); 1373*0b57cec5SDimitry Andric }); 1374*0b57cec5SDimitry Andric 1375*0b57cec5SDimitry Andric bool IsFirst = true; 1376*0b57cec5SDimitry Andric 1377bdd1243dSDimitry Andric if (!Info.CPU.empty()) { 1378*0b57cec5SDimitry Andric IsFirst = false; 1379bdd1243dSDimitry Andric Out << "arch_" << Info.CPU; 1380*0b57cec5SDimitry Andric } 1381*0b57cec5SDimitry Andric 1382*0b57cec5SDimitry Andric for (StringRef Feat : Info.Features) { 1383*0b57cec5SDimitry Andric if (!IsFirst) 1384*0b57cec5SDimitry Andric Out << '_'; 1385*0b57cec5SDimitry Andric IsFirst = false; 1386*0b57cec5SDimitry Andric Out << Feat.substr(1); 1387*0b57cec5SDimitry Andric } 1388*0b57cec5SDimitry Andric } 1389*0b57cec5SDimitry Andric 1390fe6060f1SDimitry Andric // Returns true if GD is a function decl with internal linkage and 1391fe6060f1SDimitry Andric // needs a unique suffix after the mangled name. 1392fe6060f1SDimitry Andric static bool isUniqueInternalLinkageDecl(GlobalDecl GD, 1393fe6060f1SDimitry Andric CodeGenModule &CGM) { 1394fe6060f1SDimitry Andric const Decl *D = GD.getDecl(); 1395fe6060f1SDimitry Andric return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) && 1396fe6060f1SDimitry Andric (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage); 1397fe6060f1SDimitry Andric } 1398fe6060f1SDimitry Andric 13994824e7fdSDimitry Andric static void AppendTargetClonesMangling(const CodeGenModule &CGM, 14004824e7fdSDimitry Andric const TargetClonesAttr *Attr, 14014824e7fdSDimitry Andric unsigned VersionIndex, 14024824e7fdSDimitry Andric raw_ostream &Out) { 1403bdd1243dSDimitry Andric if (CGM.getTarget().getTriple().isAArch64()) { 1404bdd1243dSDimitry Andric StringRef FeatureStr = Attr->getFeatureStr(VersionIndex); 1405bdd1243dSDimitry Andric if (FeatureStr == "default") 1406bdd1243dSDimitry Andric return; 1407bdd1243dSDimitry Andric Out << "._"; 1408bdd1243dSDimitry Andric SmallVector<StringRef, 8> Features; 1409bdd1243dSDimitry Andric FeatureStr.split(Features, "+"); 1410bdd1243dSDimitry Andric for (auto &Feat : Features) { 1411bdd1243dSDimitry Andric Out << 'M'; 1412bdd1243dSDimitry Andric Out << Feat; 1413bdd1243dSDimitry Andric } 1414bdd1243dSDimitry Andric } else { 14154824e7fdSDimitry Andric Out << '.'; 14164824e7fdSDimitry Andric StringRef FeatureStr = Attr->getFeatureStr(VersionIndex); 14174824e7fdSDimitry Andric if (FeatureStr.startswith("arch=")) 14184824e7fdSDimitry Andric Out << "arch_" << FeatureStr.substr(sizeof("arch=") - 1); 14194824e7fdSDimitry Andric else 14204824e7fdSDimitry Andric Out << FeatureStr; 14214824e7fdSDimitry Andric 14224824e7fdSDimitry Andric Out << '.' << Attr->getMangledIndex(VersionIndex); 14234824e7fdSDimitry Andric } 1424bdd1243dSDimitry Andric } 14254824e7fdSDimitry Andric 1426fe6060f1SDimitry Andric static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD, 1427*0b57cec5SDimitry Andric const NamedDecl *ND, 1428*0b57cec5SDimitry Andric bool OmitMultiVersionMangling = false) { 1429*0b57cec5SDimitry Andric SmallString<256> Buffer; 1430*0b57cec5SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 1431*0b57cec5SDimitry Andric MangleContext &MC = CGM.getCXXABI().getMangleContext(); 1432fe6060f1SDimitry Andric if (!CGM.getModuleNameHash().empty()) 1433fe6060f1SDimitry Andric MC.needsUniqueInternalLinkageNames(); 1434fe6060f1SDimitry Andric bool ShouldMangle = MC.shouldMangleDeclName(ND); 1435fe6060f1SDimitry Andric if (ShouldMangle) 14365ffd83dbSDimitry Andric MC.mangleName(GD.getWithDecl(ND), Out); 14375ffd83dbSDimitry Andric else { 1438*0b57cec5SDimitry Andric IdentifierInfo *II = ND->getIdentifier(); 1439*0b57cec5SDimitry Andric assert(II && "Attempt to mangle unnamed decl."); 1440*0b57cec5SDimitry Andric const auto *FD = dyn_cast<FunctionDecl>(ND); 1441*0b57cec5SDimitry Andric 1442*0b57cec5SDimitry Andric if (FD && 1443*0b57cec5SDimitry Andric FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { 1444*0b57cec5SDimitry Andric Out << "__regcall3__" << II->getName(); 14455ffd83dbSDimitry Andric } else if (FD && FD->hasAttr<CUDAGlobalAttr>() && 14465ffd83dbSDimitry Andric GD.getKernelReferenceKind() == KernelReferenceKind::Stub) { 14475ffd83dbSDimitry Andric Out << "__device_stub__" << II->getName(); 1448*0b57cec5SDimitry Andric } else { 1449*0b57cec5SDimitry Andric Out << II->getName(); 1450*0b57cec5SDimitry Andric } 1451*0b57cec5SDimitry Andric } 1452*0b57cec5SDimitry Andric 1453fe6060f1SDimitry Andric // Check if the module name hash should be appended for internal linkage 1454fe6060f1SDimitry Andric // symbols. This should come before multi-version target suffixes are 1455fe6060f1SDimitry Andric // appended. This is to keep the name and module hash suffix of the 1456fe6060f1SDimitry Andric // internal linkage function together. The unique suffix should only be 1457fe6060f1SDimitry Andric // added when name mangling is done to make sure that the final name can 1458fe6060f1SDimitry Andric // be properly demangled. For example, for C functions without prototypes, 1459fe6060f1SDimitry Andric // name mangling is not done and the unique suffix should not be appeneded 1460fe6060f1SDimitry Andric // then. 1461fe6060f1SDimitry Andric if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) { 1462fe6060f1SDimitry Andric assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames && 1463fe6060f1SDimitry Andric "Hash computed when not explicitly requested"); 1464fe6060f1SDimitry Andric Out << CGM.getModuleNameHash(); 1465fe6060f1SDimitry Andric } 1466fe6060f1SDimitry Andric 1467*0b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 1468*0b57cec5SDimitry Andric if (FD->isMultiVersion() && !OmitMultiVersionMangling) { 1469*0b57cec5SDimitry Andric switch (FD->getMultiVersionKind()) { 1470*0b57cec5SDimitry Andric case MultiVersionKind::CPUDispatch: 1471*0b57cec5SDimitry Andric case MultiVersionKind::CPUSpecific: 1472*0b57cec5SDimitry Andric AppendCPUSpecificCPUDispatchMangling(CGM, 1473*0b57cec5SDimitry Andric FD->getAttr<CPUSpecificAttr>(), 1474*0b57cec5SDimitry Andric GD.getMultiVersionIndex(), Out); 1475*0b57cec5SDimitry Andric break; 1476*0b57cec5SDimitry Andric case MultiVersionKind::Target: 1477*0b57cec5SDimitry Andric AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out); 1478*0b57cec5SDimitry Andric break; 1479bdd1243dSDimitry Andric case MultiVersionKind::TargetVersion: 1480bdd1243dSDimitry Andric AppendTargetVersionMangling(CGM, FD->getAttr<TargetVersionAttr>(), Out); 1481bdd1243dSDimitry Andric break; 14824824e7fdSDimitry Andric case MultiVersionKind::TargetClones: 14834824e7fdSDimitry Andric AppendTargetClonesMangling(CGM, FD->getAttr<TargetClonesAttr>(), 14844824e7fdSDimitry Andric GD.getMultiVersionIndex(), Out); 14854824e7fdSDimitry Andric break; 1486*0b57cec5SDimitry Andric case MultiVersionKind::None: 1487*0b57cec5SDimitry Andric llvm_unreachable("None multiversion type isn't valid here"); 1488*0b57cec5SDimitry Andric } 1489*0b57cec5SDimitry Andric } 1490*0b57cec5SDimitry Andric 1491fe6060f1SDimitry Andric // Make unique name for device side static file-scope variable for HIP. 149281ad6265SDimitry Andric if (CGM.getContext().shouldExternalize(ND) && 1493fe6060f1SDimitry Andric CGM.getLangOpts().GPURelocatableDeviceCode && 149481ad6265SDimitry Andric CGM.getLangOpts().CUDAIsDevice) 14952a66634dSDimitry Andric CGM.printPostfixForExternalizedDecl(Out, ND); 149681ad6265SDimitry Andric 14975ffd83dbSDimitry Andric return std::string(Out.str()); 1498*0b57cec5SDimitry Andric } 1499*0b57cec5SDimitry Andric 1500*0b57cec5SDimitry Andric void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD, 150104eeddc0SDimitry Andric const FunctionDecl *FD, 150204eeddc0SDimitry Andric StringRef &CurName) { 1503*0b57cec5SDimitry Andric if (!FD->isMultiVersion()) 1504*0b57cec5SDimitry Andric return; 1505*0b57cec5SDimitry Andric 1506*0b57cec5SDimitry Andric // Get the name of what this would be without the 'target' attribute. This 1507*0b57cec5SDimitry Andric // allows us to lookup the version that was emitted when this wasn't a 1508*0b57cec5SDimitry Andric // multiversion function. 1509*0b57cec5SDimitry Andric std::string NonTargetName = 1510*0b57cec5SDimitry Andric getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 1511*0b57cec5SDimitry Andric GlobalDecl OtherGD; 1512*0b57cec5SDimitry Andric if (lookupRepresentativeDecl(NonTargetName, OtherGD)) { 1513*0b57cec5SDimitry Andric assert(OtherGD.getCanonicalDecl() 1514*0b57cec5SDimitry Andric .getDecl() 1515*0b57cec5SDimitry Andric ->getAsFunction() 1516*0b57cec5SDimitry Andric ->isMultiVersion() && 1517*0b57cec5SDimitry Andric "Other GD should now be a multiversioned function"); 1518*0b57cec5SDimitry Andric // OtherFD is the version of this function that was mangled BEFORE 1519*0b57cec5SDimitry Andric // becoming a MultiVersion function. It potentially needs to be updated. 1520*0b57cec5SDimitry Andric const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl() 1521*0b57cec5SDimitry Andric .getDecl() 1522*0b57cec5SDimitry Andric ->getAsFunction() 1523*0b57cec5SDimitry Andric ->getMostRecentDecl(); 1524*0b57cec5SDimitry Andric std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD); 1525*0b57cec5SDimitry Andric // This is so that if the initial version was already the 'default' 1526*0b57cec5SDimitry Andric // version, we don't try to update it. 1527*0b57cec5SDimitry Andric if (OtherName != NonTargetName) { 1528*0b57cec5SDimitry Andric // Remove instead of erase, since others may have stored the StringRef 1529*0b57cec5SDimitry Andric // to this. 1530*0b57cec5SDimitry Andric const auto ExistingRecord = Manglings.find(NonTargetName); 1531*0b57cec5SDimitry Andric if (ExistingRecord != std::end(Manglings)) 1532*0b57cec5SDimitry Andric Manglings.remove(&(*ExistingRecord)); 1533*0b57cec5SDimitry Andric auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD)); 153404eeddc0SDimitry Andric StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] = 153504eeddc0SDimitry Andric Result.first->first(); 153604eeddc0SDimitry Andric // If this is the current decl is being created, make sure we update the name. 153704eeddc0SDimitry Andric if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl()) 153804eeddc0SDimitry Andric CurName = OtherNameRef; 1539*0b57cec5SDimitry Andric if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName)) 1540*0b57cec5SDimitry Andric Entry->setName(OtherName); 1541*0b57cec5SDimitry Andric } 1542*0b57cec5SDimitry Andric } 1543*0b57cec5SDimitry Andric } 1544*0b57cec5SDimitry Andric 1545*0b57cec5SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 1546*0b57cec5SDimitry Andric GlobalDecl CanonicalGD = GD.getCanonicalDecl(); 1547*0b57cec5SDimitry Andric 1548*0b57cec5SDimitry Andric // Some ABIs don't have constructor variants. Make sure that base and 1549*0b57cec5SDimitry Andric // complete constructors get mangled the same. 1550*0b57cec5SDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { 1551*0b57cec5SDimitry Andric if (!getTarget().getCXXABI().hasConstructorVariants()) { 1552*0b57cec5SDimitry Andric CXXCtorType OrigCtorType = GD.getCtorType(); 1553*0b57cec5SDimitry Andric assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); 1554*0b57cec5SDimitry Andric if (OrigCtorType == Ctor_Base) 1555*0b57cec5SDimitry Andric CanonicalGD = GlobalDecl(CD, Ctor_Complete); 1556*0b57cec5SDimitry Andric } 1557*0b57cec5SDimitry Andric } 1558*0b57cec5SDimitry Andric 1559fe6060f1SDimitry Andric // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a 1560fe6060f1SDimitry Andric // static device variable depends on whether the variable is referenced by 1561fe6060f1SDimitry Andric // a host or device host function. Therefore the mangled name cannot be 1562fe6060f1SDimitry Andric // cached. 156381ad6265SDimitry Andric if (!LangOpts.CUDAIsDevice || !getContext().mayExternalize(GD.getDecl())) { 1564*0b57cec5SDimitry Andric auto FoundName = MangledDeclNames.find(CanonicalGD); 1565*0b57cec5SDimitry Andric if (FoundName != MangledDeclNames.end()) 1566*0b57cec5SDimitry Andric return FoundName->second; 1567fe6060f1SDimitry Andric } 1568*0b57cec5SDimitry Andric 1569*0b57cec5SDimitry Andric // Keep the first result in the case of a mangling collision. 1570*0b57cec5SDimitry Andric const auto *ND = cast<NamedDecl>(GD.getDecl()); 1571*0b57cec5SDimitry Andric std::string MangledName = getMangledNameImpl(*this, GD, ND); 1572*0b57cec5SDimitry Andric 15735ffd83dbSDimitry Andric // Ensure either we have different ABIs between host and device compilations, 15745ffd83dbSDimitry Andric // says host compilation following MSVC ABI but device compilation follows 15755ffd83dbSDimitry Andric // Itanium C++ ABI or, if they follow the same ABI, kernel names after 15765ffd83dbSDimitry Andric // mangling should be the same after name stubbing. The later checking is 15775ffd83dbSDimitry Andric // very important as the device kernel name being mangled in host-compilation 15785ffd83dbSDimitry Andric // is used to resolve the device binaries to be executed. Inconsistent naming 15795ffd83dbSDimitry Andric // result in undefined behavior. Even though we cannot check that naming 15805ffd83dbSDimitry Andric // directly between host- and device-compilations, the host- and 15815ffd83dbSDimitry Andric // device-mangling in host compilation could help catching certain ones. 15825ffd83dbSDimitry Andric assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || 158381ad6265SDimitry Andric getContext().shouldExternalize(ND) || getLangOpts().CUDAIsDevice || 15845ffd83dbSDimitry Andric (getContext().getAuxTargetInfo() && 15855ffd83dbSDimitry Andric (getContext().getAuxTargetInfo()->getCXXABI() != 15865ffd83dbSDimitry Andric getContext().getTargetInfo().getCXXABI())) || 15875ffd83dbSDimitry Andric getCUDARuntime().getDeviceSideName(ND) == 15885ffd83dbSDimitry Andric getMangledNameImpl( 15895ffd83dbSDimitry Andric *this, 15905ffd83dbSDimitry Andric GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), 15915ffd83dbSDimitry Andric ND)); 1592*0b57cec5SDimitry Andric 1593*0b57cec5SDimitry Andric auto Result = Manglings.insert(std::make_pair(MangledName, GD)); 1594*0b57cec5SDimitry Andric return MangledDeclNames[CanonicalGD] = Result.first->first(); 1595*0b57cec5SDimitry Andric } 1596*0b57cec5SDimitry Andric 1597*0b57cec5SDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 1598*0b57cec5SDimitry Andric const BlockDecl *BD) { 1599*0b57cec5SDimitry Andric MangleContext &MangleCtx = getCXXABI().getMangleContext(); 1600*0b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 1601*0b57cec5SDimitry Andric 1602*0b57cec5SDimitry Andric SmallString<256> Buffer; 1603*0b57cec5SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 1604*0b57cec5SDimitry Andric if (!D) 1605*0b57cec5SDimitry Andric MangleCtx.mangleGlobalBlock(BD, 1606*0b57cec5SDimitry Andric dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 1607*0b57cec5SDimitry Andric else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 1608*0b57cec5SDimitry Andric MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 1609*0b57cec5SDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 1610*0b57cec5SDimitry Andric MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 1611*0b57cec5SDimitry Andric else 1612*0b57cec5SDimitry Andric MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 1613*0b57cec5SDimitry Andric 1614*0b57cec5SDimitry Andric auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 1615*0b57cec5SDimitry Andric return Result.first->first(); 1616*0b57cec5SDimitry Andric } 1617*0b57cec5SDimitry Andric 161881ad6265SDimitry Andric const GlobalDecl CodeGenModule::getMangledNameDecl(StringRef Name) { 161981ad6265SDimitry Andric auto it = MangledDeclNames.begin(); 162081ad6265SDimitry Andric while (it != MangledDeclNames.end()) { 162181ad6265SDimitry Andric if (it->second == Name) 162281ad6265SDimitry Andric return it->first; 162381ad6265SDimitry Andric it++; 162481ad6265SDimitry Andric } 162581ad6265SDimitry Andric return GlobalDecl(); 162681ad6265SDimitry Andric } 162781ad6265SDimitry Andric 1628*0b57cec5SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 1629*0b57cec5SDimitry Andric return getModule().getNamedValue(Name); 1630*0b57cec5SDimitry Andric } 1631*0b57cec5SDimitry Andric 1632*0b57cec5SDimitry Andric /// AddGlobalCtor - Add a function to the list that will be called before 1633*0b57cec5SDimitry Andric /// main() runs. 1634*0b57cec5SDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 1635bdd1243dSDimitry Andric unsigned LexOrder, 1636*0b57cec5SDimitry Andric llvm::Constant *AssociatedData) { 1637*0b57cec5SDimitry Andric // FIXME: Type coercion of void()* types. 1638bdd1243dSDimitry Andric GlobalCtors.push_back(Structor(Priority, LexOrder, Ctor, AssociatedData)); 1639*0b57cec5SDimitry Andric } 1640*0b57cec5SDimitry Andric 1641*0b57cec5SDimitry Andric /// AddGlobalDtor - Add a function to the list that will be called 1642*0b57cec5SDimitry Andric /// when the module is unloaded. 1643e8d8bef9SDimitry Andric void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority, 1644e8d8bef9SDimitry Andric bool IsDtorAttrFunc) { 1645e8d8bef9SDimitry Andric if (CodeGenOpts.RegisterGlobalDtorsWithAtExit && 1646e8d8bef9SDimitry Andric (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) { 1647*0b57cec5SDimitry Andric DtorsUsingAtExit[Priority].push_back(Dtor); 1648*0b57cec5SDimitry Andric return; 1649*0b57cec5SDimitry Andric } 1650*0b57cec5SDimitry Andric 1651*0b57cec5SDimitry Andric // FIXME: Type coercion of void()* types. 1652bdd1243dSDimitry Andric GlobalDtors.push_back(Structor(Priority, ~0U, Dtor, nullptr)); 1653*0b57cec5SDimitry Andric } 1654*0b57cec5SDimitry Andric 1655*0b57cec5SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { 1656*0b57cec5SDimitry Andric if (Fns.empty()) return; 1657*0b57cec5SDimitry Andric 1658*0b57cec5SDimitry Andric // Ctor function type is void()*. 1659*0b57cec5SDimitry Andric llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 1660*0b57cec5SDimitry Andric llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy, 1661*0b57cec5SDimitry Andric TheModule.getDataLayout().getProgramAddressSpace()); 1662*0b57cec5SDimitry Andric 1663*0b57cec5SDimitry Andric // Get the type of a ctor entry, { i32, void ()*, i8* }. 1664*0b57cec5SDimitry Andric llvm::StructType *CtorStructTy = llvm::StructType::get( 1665*0b57cec5SDimitry Andric Int32Ty, CtorPFTy, VoidPtrTy); 1666*0b57cec5SDimitry Andric 1667*0b57cec5SDimitry Andric // Construct the constructor and destructor arrays. 1668*0b57cec5SDimitry Andric ConstantInitBuilder builder(*this); 1669*0b57cec5SDimitry Andric auto ctors = builder.beginArray(CtorStructTy); 1670*0b57cec5SDimitry Andric for (const auto &I : Fns) { 1671*0b57cec5SDimitry Andric auto ctor = ctors.beginStruct(CtorStructTy); 1672*0b57cec5SDimitry Andric ctor.addInt(Int32Ty, I.Priority); 1673*0b57cec5SDimitry Andric ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy)); 1674*0b57cec5SDimitry Andric if (I.AssociatedData) 1675*0b57cec5SDimitry Andric ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)); 1676*0b57cec5SDimitry Andric else 1677*0b57cec5SDimitry Andric ctor.addNullPointer(VoidPtrTy); 1678*0b57cec5SDimitry Andric ctor.finishAndAddTo(ctors); 1679*0b57cec5SDimitry Andric } 1680*0b57cec5SDimitry Andric 1681*0b57cec5SDimitry Andric auto list = 1682*0b57cec5SDimitry Andric ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(), 1683*0b57cec5SDimitry Andric /*constant*/ false, 1684*0b57cec5SDimitry Andric llvm::GlobalValue::AppendingLinkage); 1685*0b57cec5SDimitry Andric 1686*0b57cec5SDimitry Andric // The LTO linker doesn't seem to like it when we set an alignment 1687*0b57cec5SDimitry Andric // on appending variables. Take it off as a workaround. 1688bdd1243dSDimitry Andric list->setAlignment(std::nullopt); 1689*0b57cec5SDimitry Andric 1690*0b57cec5SDimitry Andric Fns.clear(); 1691*0b57cec5SDimitry Andric } 1692*0b57cec5SDimitry Andric 1693*0b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes 1694*0b57cec5SDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 1695*0b57cec5SDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 1696*0b57cec5SDimitry Andric 1697*0b57cec5SDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 1698*0b57cec5SDimitry Andric 1699*0b57cec5SDimitry Andric if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D)) 1700*0b57cec5SDimitry Andric return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType()); 1701*0b57cec5SDimitry Andric 1702*0b57cec5SDimitry Andric if (isa<CXXConstructorDecl>(D) && 1703*0b57cec5SDimitry Andric cast<CXXConstructorDecl>(D)->isInheritingConstructor() && 1704*0b57cec5SDimitry Andric Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1705*0b57cec5SDimitry Andric // Our approach to inheriting constructors is fundamentally different from 1706*0b57cec5SDimitry Andric // that used by the MS ABI, so keep our inheriting constructor thunks 1707*0b57cec5SDimitry Andric // internal rather than trying to pick an unambiguous mangling for them. 1708*0b57cec5SDimitry Andric return llvm::GlobalValue::InternalLinkage; 1709*0b57cec5SDimitry Andric } 1710*0b57cec5SDimitry Andric 1711*0b57cec5SDimitry Andric return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false); 1712*0b57cec5SDimitry Andric } 1713*0b57cec5SDimitry Andric 1714*0b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { 1715*0b57cec5SDimitry Andric llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 1716*0b57cec5SDimitry Andric if (!MDS) return nullptr; 1717*0b57cec5SDimitry Andric 1718*0b57cec5SDimitry Andric return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString())); 1719*0b57cec5SDimitry Andric } 1720*0b57cec5SDimitry Andric 1721bdd1243dSDimitry Andric llvm::ConstantInt *CodeGenModule::CreateKCFITypeId(QualType T) { 1722bdd1243dSDimitry Andric if (auto *FnType = T->getAs<FunctionProtoType>()) 1723bdd1243dSDimitry Andric T = getContext().getFunctionType( 1724bdd1243dSDimitry Andric FnType->getReturnType(), FnType->getParamTypes(), 1725bdd1243dSDimitry Andric FnType->getExtProtoInfo().withExceptionSpec(EST_None)); 1726bdd1243dSDimitry Andric 1727bdd1243dSDimitry Andric std::string OutName; 1728bdd1243dSDimitry Andric llvm::raw_string_ostream Out(OutName); 1729bdd1243dSDimitry Andric getCXXABI().getMangleContext().mangleTypeName(T, Out); 1730bdd1243dSDimitry Andric 1731bdd1243dSDimitry Andric return llvm::ConstantInt::get(Int32Ty, 1732bdd1243dSDimitry Andric static_cast<uint32_t>(llvm::xxHash64(OutName))); 1733bdd1243dSDimitry Andric } 1734bdd1243dSDimitry Andric 1735*0b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD, 1736*0b57cec5SDimitry Andric const CGFunctionInfo &Info, 1737fe6060f1SDimitry Andric llvm::Function *F, bool IsThunk) { 1738*0b57cec5SDimitry Andric unsigned CallingConv; 1739*0b57cec5SDimitry Andric llvm::AttributeList PAL; 1740fe6060f1SDimitry Andric ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, 1741fe6060f1SDimitry Andric /*AttrOnCallSite=*/false, IsThunk); 1742*0b57cec5SDimitry Andric F->setAttributes(PAL); 1743*0b57cec5SDimitry Andric F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 1744*0b57cec5SDimitry Andric } 1745*0b57cec5SDimitry Andric 1746*0b57cec5SDimitry Andric static void removeImageAccessQualifier(std::string& TyName) { 1747*0b57cec5SDimitry Andric std::string ReadOnlyQual("__read_only"); 1748*0b57cec5SDimitry Andric std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual); 1749*0b57cec5SDimitry Andric if (ReadOnlyPos != std::string::npos) 1750*0b57cec5SDimitry Andric // "+ 1" for the space after access qualifier. 1751*0b57cec5SDimitry Andric TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1); 1752*0b57cec5SDimitry Andric else { 1753*0b57cec5SDimitry Andric std::string WriteOnlyQual("__write_only"); 1754*0b57cec5SDimitry Andric std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual); 1755*0b57cec5SDimitry Andric if (WriteOnlyPos != std::string::npos) 1756*0b57cec5SDimitry Andric TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1); 1757*0b57cec5SDimitry Andric else { 1758*0b57cec5SDimitry Andric std::string ReadWriteQual("__read_write"); 1759*0b57cec5SDimitry Andric std::string::size_type ReadWritePos = TyName.find(ReadWriteQual); 1760*0b57cec5SDimitry Andric if (ReadWritePos != std::string::npos) 1761*0b57cec5SDimitry Andric TyName.erase(ReadWritePos, ReadWriteQual.size() + 1); 1762*0b57cec5SDimitry Andric } 1763*0b57cec5SDimitry Andric } 1764*0b57cec5SDimitry Andric } 1765*0b57cec5SDimitry Andric 1766*0b57cec5SDimitry Andric // Returns the address space id that should be produced to the 1767*0b57cec5SDimitry Andric // kernel_arg_addr_space metadata. This is always fixed to the ids 1768*0b57cec5SDimitry Andric // as specified in the SPIR 2.0 specification in order to differentiate 1769*0b57cec5SDimitry Andric // for example in clGetKernelArgInfo() implementation between the address 1770*0b57cec5SDimitry Andric // spaces with targets without unique mapping to the OpenCL address spaces 1771*0b57cec5SDimitry Andric // (basically all single AS CPUs). 1772*0b57cec5SDimitry Andric static unsigned ArgInfoAddressSpace(LangAS AS) { 1773*0b57cec5SDimitry Andric switch (AS) { 1774e8d8bef9SDimitry Andric case LangAS::opencl_global: 1775e8d8bef9SDimitry Andric return 1; 1776e8d8bef9SDimitry Andric case LangAS::opencl_constant: 1777e8d8bef9SDimitry Andric return 2; 1778e8d8bef9SDimitry Andric case LangAS::opencl_local: 1779e8d8bef9SDimitry Andric return 3; 1780e8d8bef9SDimitry Andric case LangAS::opencl_generic: 1781e8d8bef9SDimitry Andric return 4; // Not in SPIR 2.0 specs. 1782e8d8bef9SDimitry Andric case LangAS::opencl_global_device: 1783e8d8bef9SDimitry Andric return 5; 1784e8d8bef9SDimitry Andric case LangAS::opencl_global_host: 1785e8d8bef9SDimitry Andric return 6; 1786*0b57cec5SDimitry Andric default: 1787*0b57cec5SDimitry Andric return 0; // Assume private. 1788*0b57cec5SDimitry Andric } 1789*0b57cec5SDimitry Andric } 1790*0b57cec5SDimitry Andric 179181ad6265SDimitry Andric void CodeGenModule::GenKernelArgMetadata(llvm::Function *Fn, 1792*0b57cec5SDimitry Andric const FunctionDecl *FD, 1793*0b57cec5SDimitry Andric CodeGenFunction *CGF) { 1794*0b57cec5SDimitry Andric assert(((FD && CGF) || (!FD && !CGF)) && 1795*0b57cec5SDimitry Andric "Incorrect use - FD and CGF should either be both null or not!"); 1796*0b57cec5SDimitry Andric // Create MDNodes that represent the kernel arg metadata. 1797*0b57cec5SDimitry Andric // Each MDNode is a list in the form of "key", N number of values which is 1798*0b57cec5SDimitry Andric // the same number of values as their are kernel arguments. 1799*0b57cec5SDimitry Andric 1800*0b57cec5SDimitry Andric const PrintingPolicy &Policy = Context.getPrintingPolicy(); 1801*0b57cec5SDimitry Andric 1802*0b57cec5SDimitry Andric // MDNode for the kernel argument address space qualifiers. 1803*0b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> addressQuals; 1804*0b57cec5SDimitry Andric 1805*0b57cec5SDimitry Andric // MDNode for the kernel argument access qualifiers (images only). 1806*0b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> accessQuals; 1807*0b57cec5SDimitry Andric 1808*0b57cec5SDimitry Andric // MDNode for the kernel argument type names. 1809*0b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> argTypeNames; 1810*0b57cec5SDimitry Andric 1811*0b57cec5SDimitry Andric // MDNode for the kernel argument base type names. 1812*0b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> argBaseTypeNames; 1813*0b57cec5SDimitry Andric 1814*0b57cec5SDimitry Andric // MDNode for the kernel argument type qualifiers. 1815*0b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> argTypeQuals; 1816*0b57cec5SDimitry Andric 1817*0b57cec5SDimitry Andric // MDNode for the kernel argument names. 1818*0b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> argNames; 1819*0b57cec5SDimitry Andric 1820*0b57cec5SDimitry Andric if (FD && CGF) 1821*0b57cec5SDimitry Andric for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { 1822*0b57cec5SDimitry Andric const ParmVarDecl *parm = FD->getParamDecl(i); 182381ad6265SDimitry Andric // Get argument name. 182481ad6265SDimitry Andric argNames.push_back(llvm::MDString::get(VMContext, parm->getName())); 182581ad6265SDimitry Andric 182681ad6265SDimitry Andric if (!getLangOpts().OpenCL) 182781ad6265SDimitry Andric continue; 1828*0b57cec5SDimitry Andric QualType ty = parm->getType(); 1829*0b57cec5SDimitry Andric std::string typeQuals; 1830*0b57cec5SDimitry Andric 1831fe6060f1SDimitry Andric // Get image and pipe access qualifier: 1832fe6060f1SDimitry Andric if (ty->isImageType() || ty->isPipeType()) { 1833fe6060f1SDimitry Andric const Decl *PDecl = parm; 1834bdd1243dSDimitry Andric if (const auto *TD = ty->getAs<TypedefType>()) 1835fe6060f1SDimitry Andric PDecl = TD->getDecl(); 1836fe6060f1SDimitry Andric const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>(); 1837fe6060f1SDimitry Andric if (A && A->isWriteOnly()) 1838fe6060f1SDimitry Andric accessQuals.push_back(llvm::MDString::get(VMContext, "write_only")); 1839fe6060f1SDimitry Andric else if (A && A->isReadWrite()) 1840fe6060f1SDimitry Andric accessQuals.push_back(llvm::MDString::get(VMContext, "read_write")); 1841fe6060f1SDimitry Andric else 1842fe6060f1SDimitry Andric accessQuals.push_back(llvm::MDString::get(VMContext, "read_only")); 1843fe6060f1SDimitry Andric } else 1844fe6060f1SDimitry Andric accessQuals.push_back(llvm::MDString::get(VMContext, "none")); 1845fe6060f1SDimitry Andric 1846fe6060f1SDimitry Andric auto getTypeSpelling = [&](QualType Ty) { 1847fe6060f1SDimitry Andric auto typeName = Ty.getUnqualifiedType().getAsString(Policy); 1848fe6060f1SDimitry Andric 1849fe6060f1SDimitry Andric if (Ty.isCanonical()) { 1850fe6060f1SDimitry Andric StringRef typeNameRef = typeName; 1851fe6060f1SDimitry Andric // Turn "unsigned type" to "utype" 1852fe6060f1SDimitry Andric if (typeNameRef.consume_front("unsigned ")) 1853fe6060f1SDimitry Andric return std::string("u") + typeNameRef.str(); 1854fe6060f1SDimitry Andric if (typeNameRef.consume_front("signed ")) 1855fe6060f1SDimitry Andric return typeNameRef.str(); 1856fe6060f1SDimitry Andric } 1857fe6060f1SDimitry Andric 1858fe6060f1SDimitry Andric return typeName; 1859fe6060f1SDimitry Andric }; 1860fe6060f1SDimitry Andric 1861*0b57cec5SDimitry Andric if (ty->isPointerType()) { 1862*0b57cec5SDimitry Andric QualType pointeeTy = ty->getPointeeType(); 1863*0b57cec5SDimitry Andric 1864*0b57cec5SDimitry Andric // Get address qualifier. 1865*0b57cec5SDimitry Andric addressQuals.push_back( 1866*0b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(CGF->Builder.getInt32( 1867*0b57cec5SDimitry Andric ArgInfoAddressSpace(pointeeTy.getAddressSpace())))); 1868*0b57cec5SDimitry Andric 1869*0b57cec5SDimitry Andric // Get argument type name. 1870fe6060f1SDimitry Andric std::string typeName = getTypeSpelling(pointeeTy) + "*"; 1871*0b57cec5SDimitry Andric std::string baseTypeName = 1872fe6060f1SDimitry Andric getTypeSpelling(pointeeTy.getCanonicalType()) + "*"; 1873fe6060f1SDimitry Andric argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 1874*0b57cec5SDimitry Andric argBaseTypeNames.push_back( 1875*0b57cec5SDimitry Andric llvm::MDString::get(VMContext, baseTypeName)); 1876*0b57cec5SDimitry Andric 1877*0b57cec5SDimitry Andric // Get argument type qualifiers: 1878*0b57cec5SDimitry Andric if (ty.isRestrictQualified()) 1879*0b57cec5SDimitry Andric typeQuals = "restrict"; 1880*0b57cec5SDimitry Andric if (pointeeTy.isConstQualified() || 1881*0b57cec5SDimitry Andric (pointeeTy.getAddressSpace() == LangAS::opencl_constant)) 1882*0b57cec5SDimitry Andric typeQuals += typeQuals.empty() ? "const" : " const"; 1883*0b57cec5SDimitry Andric if (pointeeTy.isVolatileQualified()) 1884*0b57cec5SDimitry Andric typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 1885*0b57cec5SDimitry Andric } else { 1886*0b57cec5SDimitry Andric uint32_t AddrSpc = 0; 1887*0b57cec5SDimitry Andric bool isPipe = ty->isPipeType(); 1888*0b57cec5SDimitry Andric if (ty->isImageType() || isPipe) 1889*0b57cec5SDimitry Andric AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global); 1890*0b57cec5SDimitry Andric 1891*0b57cec5SDimitry Andric addressQuals.push_back( 1892*0b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc))); 1893*0b57cec5SDimitry Andric 1894*0b57cec5SDimitry Andric // Get argument type name. 1895fe6060f1SDimitry Andric ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty; 1896fe6060f1SDimitry Andric std::string typeName = getTypeSpelling(ty); 1897fe6060f1SDimitry Andric std::string baseTypeName = getTypeSpelling(ty.getCanonicalType()); 1898*0b57cec5SDimitry Andric 1899*0b57cec5SDimitry Andric // Remove access qualifiers on images 1900*0b57cec5SDimitry Andric // (as they are inseparable from type in clang implementation, 1901*0b57cec5SDimitry Andric // but OpenCL spec provides a special query to get access qualifier 1902*0b57cec5SDimitry Andric // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER): 1903*0b57cec5SDimitry Andric if (ty->isImageType()) { 1904*0b57cec5SDimitry Andric removeImageAccessQualifier(typeName); 1905*0b57cec5SDimitry Andric removeImageAccessQualifier(baseTypeName); 1906*0b57cec5SDimitry Andric } 1907*0b57cec5SDimitry Andric 1908*0b57cec5SDimitry Andric argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 1909*0b57cec5SDimitry Andric argBaseTypeNames.push_back( 1910*0b57cec5SDimitry Andric llvm::MDString::get(VMContext, baseTypeName)); 1911*0b57cec5SDimitry Andric 1912*0b57cec5SDimitry Andric if (isPipe) 1913*0b57cec5SDimitry Andric typeQuals = "pipe"; 1914*0b57cec5SDimitry Andric } 1915*0b57cec5SDimitry Andric argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals)); 1916*0b57cec5SDimitry Andric } 1917*0b57cec5SDimitry Andric 191881ad6265SDimitry Andric if (getLangOpts().OpenCL) { 1919*0b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_addr_space", 1920*0b57cec5SDimitry Andric llvm::MDNode::get(VMContext, addressQuals)); 1921*0b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_access_qual", 1922*0b57cec5SDimitry Andric llvm::MDNode::get(VMContext, accessQuals)); 1923*0b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_type", 1924*0b57cec5SDimitry Andric llvm::MDNode::get(VMContext, argTypeNames)); 1925*0b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_base_type", 1926*0b57cec5SDimitry Andric llvm::MDNode::get(VMContext, argBaseTypeNames)); 1927*0b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_type_qual", 1928*0b57cec5SDimitry Andric llvm::MDNode::get(VMContext, argTypeQuals)); 192981ad6265SDimitry Andric } 193081ad6265SDimitry Andric if (getCodeGenOpts().EmitOpenCLArgMetadata || 193181ad6265SDimitry Andric getCodeGenOpts().HIPSaveKernelArgName) 1932*0b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_name", 1933*0b57cec5SDimitry Andric llvm::MDNode::get(VMContext, argNames)); 1934*0b57cec5SDimitry Andric } 1935*0b57cec5SDimitry Andric 1936*0b57cec5SDimitry Andric /// Determines whether the language options require us to model 1937*0b57cec5SDimitry Andric /// unwind exceptions. We treat -fexceptions as mandating this 1938*0b57cec5SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions 1939*0b57cec5SDimitry Andric /// enabled. This means, for example, that C with -fexceptions 1940*0b57cec5SDimitry Andric /// enables this. 1941*0b57cec5SDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) { 1942*0b57cec5SDimitry Andric // If exceptions are completely disabled, obviously this is false. 1943*0b57cec5SDimitry Andric if (!LangOpts.Exceptions) return false; 1944*0b57cec5SDimitry Andric 1945*0b57cec5SDimitry Andric // If C++ exceptions are enabled, this is true. 1946*0b57cec5SDimitry Andric if (LangOpts.CXXExceptions) return true; 1947*0b57cec5SDimitry Andric 1948*0b57cec5SDimitry Andric // If ObjC exceptions are enabled, this depends on the ABI. 1949*0b57cec5SDimitry Andric if (LangOpts.ObjCExceptions) { 1950*0b57cec5SDimitry Andric return LangOpts.ObjCRuntime.hasUnwindExceptions(); 1951*0b57cec5SDimitry Andric } 1952*0b57cec5SDimitry Andric 1953*0b57cec5SDimitry Andric return true; 1954*0b57cec5SDimitry Andric } 1955*0b57cec5SDimitry Andric 1956*0b57cec5SDimitry Andric static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, 1957*0b57cec5SDimitry Andric const CXXMethodDecl *MD) { 1958*0b57cec5SDimitry Andric // Check that the type metadata can ever actually be used by a call. 1959*0b57cec5SDimitry Andric if (!CGM.getCodeGenOpts().LTOUnit || 1960*0b57cec5SDimitry Andric !CGM.HasHiddenLTOVisibility(MD->getParent())) 1961*0b57cec5SDimitry Andric return false; 1962*0b57cec5SDimitry Andric 1963*0b57cec5SDimitry Andric // Only functions whose address can be taken with a member function pointer 1964*0b57cec5SDimitry Andric // need this sort of type metadata. 1965*0b57cec5SDimitry Andric return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) && 1966*0b57cec5SDimitry Andric !isa<CXXDestructorDecl>(MD); 1967*0b57cec5SDimitry Andric } 1968*0b57cec5SDimitry Andric 1969*0b57cec5SDimitry Andric std::vector<const CXXRecordDecl *> 1970*0b57cec5SDimitry Andric CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) { 1971*0b57cec5SDimitry Andric llvm::SetVector<const CXXRecordDecl *> MostBases; 1972*0b57cec5SDimitry Andric 1973*0b57cec5SDimitry Andric std::function<void (const CXXRecordDecl *)> CollectMostBases; 1974*0b57cec5SDimitry Andric CollectMostBases = [&](const CXXRecordDecl *RD) { 1975*0b57cec5SDimitry Andric if (RD->getNumBases() == 0) 1976*0b57cec5SDimitry Andric MostBases.insert(RD); 1977*0b57cec5SDimitry Andric for (const CXXBaseSpecifier &B : RD->bases()) 1978*0b57cec5SDimitry Andric CollectMostBases(B.getType()->getAsCXXRecordDecl()); 1979*0b57cec5SDimitry Andric }; 1980*0b57cec5SDimitry Andric CollectMostBases(RD); 1981*0b57cec5SDimitry Andric return MostBases.takeVector(); 1982*0b57cec5SDimitry Andric } 1983*0b57cec5SDimitry Andric 198481ad6265SDimitry Andric llvm::GlobalVariable * 198581ad6265SDimitry Andric CodeGenModule::GetOrCreateRTTIProxyGlobalVariable(llvm::Constant *Addr) { 198681ad6265SDimitry Andric auto It = RTTIProxyMap.find(Addr); 198781ad6265SDimitry Andric if (It != RTTIProxyMap.end()) 198881ad6265SDimitry Andric return It->second; 198981ad6265SDimitry Andric 199081ad6265SDimitry Andric auto *FTRTTIProxy = new llvm::GlobalVariable( 199181ad6265SDimitry Andric TheModule, Addr->getType(), 199281ad6265SDimitry Andric /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, Addr, 199381ad6265SDimitry Andric "__llvm_rtti_proxy"); 199481ad6265SDimitry Andric FTRTTIProxy->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 199581ad6265SDimitry Andric 199681ad6265SDimitry Andric RTTIProxyMap[Addr] = FTRTTIProxy; 199781ad6265SDimitry Andric return FTRTTIProxy; 199881ad6265SDimitry Andric } 199981ad6265SDimitry Andric 2000*0b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 2001*0b57cec5SDimitry Andric llvm::Function *F) { 200204eeddc0SDimitry Andric llvm::AttrBuilder B(F->getContext()); 2003*0b57cec5SDimitry Andric 2004bdd1243dSDimitry Andric if ((!D || !D->hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables) 200581ad6265SDimitry Andric B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables)); 2006*0b57cec5SDimitry Andric 20075ffd83dbSDimitry Andric if (CodeGenOpts.StackClashProtector) 20085ffd83dbSDimitry Andric B.addAttribute("probe-stack", "inline-asm"); 20095ffd83dbSDimitry Andric 2010*0b57cec5SDimitry Andric if (!hasUnwindExceptions(LangOpts)) 2011*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoUnwind); 2012*0b57cec5SDimitry Andric 2013bdd1243dSDimitry Andric if (D && D->hasAttr<NoStackProtectorAttr>()) 2014bdd1243dSDimitry Andric ; // Do nothing. 2015bdd1243dSDimitry Andric else if (D && D->hasAttr<StrictGuardStackCheckAttr>() && 2016bdd1243dSDimitry Andric LangOpts.getStackProtector() == LangOptions::SSPOn) 2017bdd1243dSDimitry Andric B.addAttribute(llvm::Attribute::StackProtectStrong); 2018bdd1243dSDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPOn) 2019*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::StackProtect); 2020*0b57cec5SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 2021*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectStrong); 2022*0b57cec5SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 2023*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectReq); 2024*0b57cec5SDimitry Andric 2025*0b57cec5SDimitry Andric if (!D) { 2026*0b57cec5SDimitry Andric // If we don't have a declaration to control inlining, the function isn't 2027*0b57cec5SDimitry Andric // explicitly marked as alwaysinline for semantic reasons, and inlining is 2028*0b57cec5SDimitry Andric // disabled, mark the function as noinline. 2029*0b57cec5SDimitry Andric if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 2030*0b57cec5SDimitry Andric CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) 2031*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 2032*0b57cec5SDimitry Andric 2033349cc55cSDimitry Andric F->addFnAttrs(B); 2034*0b57cec5SDimitry Andric return; 2035*0b57cec5SDimitry Andric } 2036*0b57cec5SDimitry Andric 2037*0b57cec5SDimitry Andric // Track whether we need to add the optnone LLVM attribute, 2038*0b57cec5SDimitry Andric // starting with the default for this optimization level. 2039*0b57cec5SDimitry Andric bool ShouldAddOptNone = 2040*0b57cec5SDimitry Andric !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0; 2041*0b57cec5SDimitry Andric // We can't add optnone in the following cases, it won't pass the verifier. 2042*0b57cec5SDimitry Andric ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>(); 2043*0b57cec5SDimitry Andric ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>(); 2044*0b57cec5SDimitry Andric 2045480093f4SDimitry Andric // Add optnone, but do so only if the function isn't always_inline. 2046480093f4SDimitry Andric if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) && 2047480093f4SDimitry Andric !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 2048*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::OptimizeNone); 2049*0b57cec5SDimitry Andric 2050*0b57cec5SDimitry Andric // OptimizeNone implies noinline; we should not be inlining such functions. 2051*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 2052*0b57cec5SDimitry Andric 2053*0b57cec5SDimitry Andric // We still need to handle naked functions even though optnone subsumes 2054*0b57cec5SDimitry Andric // much of their semantics. 2055*0b57cec5SDimitry Andric if (D->hasAttr<NakedAttr>()) 2056*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::Naked); 2057*0b57cec5SDimitry Andric 2058*0b57cec5SDimitry Andric // OptimizeNone wins over OptimizeForSize and MinSize. 2059*0b57cec5SDimitry Andric F->removeFnAttr(llvm::Attribute::OptimizeForSize); 2060*0b57cec5SDimitry Andric F->removeFnAttr(llvm::Attribute::MinSize); 2061*0b57cec5SDimitry Andric } else if (D->hasAttr<NakedAttr>()) { 2062*0b57cec5SDimitry Andric // Naked implies noinline: we should not be inlining such functions. 2063*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::Naked); 2064*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 2065*0b57cec5SDimitry Andric } else if (D->hasAttr<NoDuplicateAttr>()) { 2066*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoDuplicate); 2067480093f4SDimitry Andric } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 2068480093f4SDimitry Andric // Add noinline if the function isn't always_inline. 2069*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 2070*0b57cec5SDimitry Andric } else if (D->hasAttr<AlwaysInlineAttr>() && 2071*0b57cec5SDimitry Andric !F->hasFnAttribute(llvm::Attribute::NoInline)) { 2072*0b57cec5SDimitry Andric // (noinline wins over always_inline, and we can't specify both in IR) 2073*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::AlwaysInline); 2074*0b57cec5SDimitry Andric } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { 2075*0b57cec5SDimitry Andric // If we're not inlining, then force everything that isn't always_inline to 2076*0b57cec5SDimitry Andric // carry an explicit noinline attribute. 2077*0b57cec5SDimitry Andric if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) 2078*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 2079*0b57cec5SDimitry Andric } else { 2080*0b57cec5SDimitry Andric // Otherwise, propagate the inline hint attribute and potentially use its 2081*0b57cec5SDimitry Andric // absence to mark things as noinline. 2082*0b57cec5SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) { 2083*0b57cec5SDimitry Andric // Search function and template pattern redeclarations for inline. 2084*0b57cec5SDimitry Andric auto CheckForInline = [](const FunctionDecl *FD) { 2085*0b57cec5SDimitry Andric auto CheckRedeclForInline = [](const FunctionDecl *Redecl) { 2086*0b57cec5SDimitry Andric return Redecl->isInlineSpecified(); 2087*0b57cec5SDimitry Andric }; 2088*0b57cec5SDimitry Andric if (any_of(FD->redecls(), CheckRedeclForInline)) 2089*0b57cec5SDimitry Andric return true; 2090*0b57cec5SDimitry Andric const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern(); 2091*0b57cec5SDimitry Andric if (!Pattern) 2092*0b57cec5SDimitry Andric return false; 2093*0b57cec5SDimitry Andric return any_of(Pattern->redecls(), CheckRedeclForInline); 2094*0b57cec5SDimitry Andric }; 2095*0b57cec5SDimitry Andric if (CheckForInline(FD)) { 2096*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::InlineHint); 2097*0b57cec5SDimitry Andric } else if (CodeGenOpts.getInlining() == 2098*0b57cec5SDimitry Andric CodeGenOptions::OnlyHintInlining && 2099*0b57cec5SDimitry Andric !FD->isInlined() && 2100*0b57cec5SDimitry Andric !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 2101*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 2102*0b57cec5SDimitry Andric } 2103*0b57cec5SDimitry Andric } 2104*0b57cec5SDimitry Andric } 2105*0b57cec5SDimitry Andric 2106*0b57cec5SDimitry Andric // Add other optimization related attributes if we are optimizing this 2107*0b57cec5SDimitry Andric // function. 2108*0b57cec5SDimitry Andric if (!D->hasAttr<OptimizeNoneAttr>()) { 2109*0b57cec5SDimitry Andric if (D->hasAttr<ColdAttr>()) { 2110*0b57cec5SDimitry Andric if (!ShouldAddOptNone) 2111*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::OptimizeForSize); 2112*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::Cold); 2113*0b57cec5SDimitry Andric } 2114e8d8bef9SDimitry Andric if (D->hasAttr<HotAttr>()) 2115e8d8bef9SDimitry Andric B.addAttribute(llvm::Attribute::Hot); 2116*0b57cec5SDimitry Andric if (D->hasAttr<MinSizeAttr>()) 2117*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::MinSize); 2118*0b57cec5SDimitry Andric } 2119*0b57cec5SDimitry Andric 2120349cc55cSDimitry Andric F->addFnAttrs(B); 2121*0b57cec5SDimitry Andric 2122*0b57cec5SDimitry Andric unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 2123*0b57cec5SDimitry Andric if (alignment) 2124a7dea167SDimitry Andric F->setAlignment(llvm::Align(alignment)); 2125*0b57cec5SDimitry Andric 2126*0b57cec5SDimitry Andric if (!D->hasAttr<AlignedAttr>()) 2127*0b57cec5SDimitry Andric if (LangOpts.FunctionAlignment) 2128a7dea167SDimitry Andric F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment)); 2129*0b57cec5SDimitry Andric 2130*0b57cec5SDimitry Andric // Some C++ ABIs require 2-byte alignment for member functions, in order to 2131*0b57cec5SDimitry Andric // reserve a bit for differentiating between virtual and non-virtual member 2132*0b57cec5SDimitry Andric // functions. If the current target's C++ ABI requires this and this is a 2133*0b57cec5SDimitry Andric // member function, set its alignment accordingly. 2134*0b57cec5SDimitry Andric if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 2135*0b57cec5SDimitry Andric if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 2136a7dea167SDimitry Andric F->setAlignment(llvm::Align(2)); 2137*0b57cec5SDimitry Andric } 2138*0b57cec5SDimitry Andric 2139a7dea167SDimitry Andric // In the cross-dso CFI mode with canonical jump tables, we want !type 2140a7dea167SDimitry Andric // attributes on definitions only. 2141a7dea167SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso && 2142a7dea167SDimitry Andric CodeGenOpts.SanitizeCfiCanonicalJumpTables) { 2143a7dea167SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) { 2144a7dea167SDimitry Andric // Skip available_externally functions. They won't be codegen'ed in the 2145a7dea167SDimitry Andric // current module anyway. 2146a7dea167SDimitry Andric if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally) 2147*0b57cec5SDimitry Andric CreateFunctionTypeMetadataForIcall(FD, F); 2148a7dea167SDimitry Andric } 2149a7dea167SDimitry Andric } 2150*0b57cec5SDimitry Andric 2151*0b57cec5SDimitry Andric // Emit type metadata on member functions for member function pointer checks. 2152*0b57cec5SDimitry Andric // These are only ever necessary on definitions; we're guaranteed that the 2153*0b57cec5SDimitry Andric // definition will be present in the LTO unit as a result of LTO visibility. 2154*0b57cec5SDimitry Andric auto *MD = dyn_cast<CXXMethodDecl>(D); 2155*0b57cec5SDimitry Andric if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) { 2156*0b57cec5SDimitry Andric for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) { 2157*0b57cec5SDimitry Andric llvm::Metadata *Id = 2158*0b57cec5SDimitry Andric CreateMetadataIdentifierForType(Context.getMemberPointerType( 2159*0b57cec5SDimitry Andric MD->getType(), Context.getRecordType(Base).getTypePtr())); 2160*0b57cec5SDimitry Andric F->addTypeMetadata(0, Id); 2161*0b57cec5SDimitry Andric } 2162*0b57cec5SDimitry Andric } 2163*0b57cec5SDimitry Andric } 2164*0b57cec5SDimitry Andric 2165e8d8bef9SDimitry Andric void CodeGenModule::setLLVMFunctionFEnvAttributes(const FunctionDecl *D, 2166e8d8bef9SDimitry Andric llvm::Function *F) { 2167e8d8bef9SDimitry Andric if (D->hasAttr<StrictFPAttr>()) { 216804eeddc0SDimitry Andric llvm::AttrBuilder FuncAttrs(F->getContext()); 2169e8d8bef9SDimitry Andric FuncAttrs.addAttribute("strictfp"); 2170349cc55cSDimitry Andric F->addFnAttrs(FuncAttrs); 2171e8d8bef9SDimitry Andric } 2172e8d8bef9SDimitry Andric } 2173e8d8bef9SDimitry Andric 2174*0b57cec5SDimitry Andric void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) { 2175*0b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 2176349cc55cSDimitry Andric if (isa_and_nonnull<NamedDecl>(D)) 2177*0b57cec5SDimitry Andric setGVProperties(GV, GD); 2178*0b57cec5SDimitry Andric else 2179*0b57cec5SDimitry Andric GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 2180*0b57cec5SDimitry Andric 2181*0b57cec5SDimitry Andric if (D && D->hasAttr<UsedAttr>()) 2182fe6060f1SDimitry Andric addUsedOrCompilerUsedGlobal(GV); 2183*0b57cec5SDimitry Andric 2184*0b57cec5SDimitry Andric if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) { 2185*0b57cec5SDimitry Andric const auto *VD = cast<VarDecl>(D); 2186*0b57cec5SDimitry Andric if (VD->getType().isConstQualified() && 2187*0b57cec5SDimitry Andric VD->getStorageDuration() == SD_Static) 2188fe6060f1SDimitry Andric addUsedOrCompilerUsedGlobal(GV); 2189*0b57cec5SDimitry Andric } 2190*0b57cec5SDimitry Andric } 2191*0b57cec5SDimitry Andric 2192*0b57cec5SDimitry Andric bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD, 2193*0b57cec5SDimitry Andric llvm::AttrBuilder &Attrs) { 2194*0b57cec5SDimitry Andric // Add target-cpu and target-features attributes to functions. If 2195*0b57cec5SDimitry Andric // we have a decl for the function and it has a target attribute then 2196*0b57cec5SDimitry Andric // parse that and add it to the feature set. 2197*0b57cec5SDimitry Andric StringRef TargetCPU = getTarget().getTargetOpts().CPU; 2198e8d8bef9SDimitry Andric StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU; 2199*0b57cec5SDimitry Andric std::vector<std::string> Features; 2200*0b57cec5SDimitry Andric const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl()); 2201*0b57cec5SDimitry Andric FD = FD ? FD->getMostRecentDecl() : FD; 2202*0b57cec5SDimitry Andric const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr; 2203bdd1243dSDimitry Andric const auto *TV = FD ? FD->getAttr<TargetVersionAttr>() : nullptr; 2204bdd1243dSDimitry Andric assert((!TD || !TV) && "both target_version and target specified"); 2205*0b57cec5SDimitry Andric const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr; 22064824e7fdSDimitry Andric const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr; 2207*0b57cec5SDimitry Andric bool AddedAttr = false; 2208bdd1243dSDimitry Andric if (TD || TV || SD || TC) { 2209*0b57cec5SDimitry Andric llvm::StringMap<bool> FeatureMap; 2210480093f4SDimitry Andric getContext().getFunctionFeatureMap(FeatureMap, GD); 2211*0b57cec5SDimitry Andric 2212*0b57cec5SDimitry Andric // Produce the canonical string for this set of features. 2213*0b57cec5SDimitry Andric for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap) 2214*0b57cec5SDimitry Andric Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str()); 2215*0b57cec5SDimitry Andric 2216*0b57cec5SDimitry Andric // Now add the target-cpu and target-features to the function. 2217*0b57cec5SDimitry Andric // While we populated the feature map above, we still need to 2218*0b57cec5SDimitry Andric // get and parse the target attribute so we can get the cpu for 2219*0b57cec5SDimitry Andric // the function. 2220*0b57cec5SDimitry Andric if (TD) { 2221bdd1243dSDimitry Andric ParsedTargetAttr ParsedAttr = 2222bdd1243dSDimitry Andric Target.parseTargetAttr(TD->getFeaturesStr()); 2223bdd1243dSDimitry Andric if (!ParsedAttr.CPU.empty() && 2224bdd1243dSDimitry Andric getTarget().isValidCPUName(ParsedAttr.CPU)) { 2225bdd1243dSDimitry Andric TargetCPU = ParsedAttr.CPU; 2226e8d8bef9SDimitry Andric TuneCPU = ""; // Clear the tune CPU. 2227e8d8bef9SDimitry Andric } 2228e8d8bef9SDimitry Andric if (!ParsedAttr.Tune.empty() && 2229e8d8bef9SDimitry Andric getTarget().isValidCPUName(ParsedAttr.Tune)) 2230e8d8bef9SDimitry Andric TuneCPU = ParsedAttr.Tune; 2231*0b57cec5SDimitry Andric } 223281ad6265SDimitry Andric 223381ad6265SDimitry Andric if (SD) { 223481ad6265SDimitry Andric // Apply the given CPU name as the 'tune-cpu' so that the optimizer can 223581ad6265SDimitry Andric // favor this processor. 223681ad6265SDimitry Andric TuneCPU = getTarget().getCPUSpecificTuneName( 223781ad6265SDimitry Andric SD->getCPUName(GD.getMultiVersionIndex())->getName()); 223881ad6265SDimitry Andric } 2239*0b57cec5SDimitry Andric } else { 2240*0b57cec5SDimitry Andric // Otherwise just add the existing target cpu and target features to the 2241*0b57cec5SDimitry Andric // function. 2242*0b57cec5SDimitry Andric Features = getTarget().getTargetOpts().Features; 2243*0b57cec5SDimitry Andric } 2244*0b57cec5SDimitry Andric 2245e8d8bef9SDimitry Andric if (!TargetCPU.empty()) { 2246*0b57cec5SDimitry Andric Attrs.addAttribute("target-cpu", TargetCPU); 2247*0b57cec5SDimitry Andric AddedAttr = true; 2248*0b57cec5SDimitry Andric } 2249e8d8bef9SDimitry Andric if (!TuneCPU.empty()) { 2250e8d8bef9SDimitry Andric Attrs.addAttribute("tune-cpu", TuneCPU); 2251e8d8bef9SDimitry Andric AddedAttr = true; 2252e8d8bef9SDimitry Andric } 2253*0b57cec5SDimitry Andric if (!Features.empty()) { 2254*0b57cec5SDimitry Andric llvm::sort(Features); 2255*0b57cec5SDimitry Andric Attrs.addAttribute("target-features", llvm::join(Features, ",")); 2256*0b57cec5SDimitry Andric AddedAttr = true; 2257*0b57cec5SDimitry Andric } 2258*0b57cec5SDimitry Andric 2259*0b57cec5SDimitry Andric return AddedAttr; 2260*0b57cec5SDimitry Andric } 2261*0b57cec5SDimitry Andric 2262*0b57cec5SDimitry Andric void CodeGenModule::setNonAliasAttributes(GlobalDecl GD, 2263*0b57cec5SDimitry Andric llvm::GlobalObject *GO) { 2264*0b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 2265*0b57cec5SDimitry Andric SetCommonAttributes(GD, GO); 2266*0b57cec5SDimitry Andric 2267*0b57cec5SDimitry Andric if (D) { 2268*0b57cec5SDimitry Andric if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) { 2269fe6060f1SDimitry Andric if (D->hasAttr<RetainAttr>()) 2270fe6060f1SDimitry Andric addUsedGlobal(GV); 2271*0b57cec5SDimitry Andric if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) 2272*0b57cec5SDimitry Andric GV->addAttribute("bss-section", SA->getName()); 2273*0b57cec5SDimitry Andric if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) 2274*0b57cec5SDimitry Andric GV->addAttribute("data-section", SA->getName()); 2275*0b57cec5SDimitry Andric if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) 2276*0b57cec5SDimitry Andric GV->addAttribute("rodata-section", SA->getName()); 2277a7dea167SDimitry Andric if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>()) 2278a7dea167SDimitry Andric GV->addAttribute("relro-section", SA->getName()); 2279*0b57cec5SDimitry Andric } 2280*0b57cec5SDimitry Andric 2281*0b57cec5SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(GO)) { 2282fe6060f1SDimitry Andric if (D->hasAttr<RetainAttr>()) 2283fe6060f1SDimitry Andric addUsedGlobal(F); 2284*0b57cec5SDimitry Andric if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) 2285*0b57cec5SDimitry Andric if (!D->getAttr<SectionAttr>()) 2286*0b57cec5SDimitry Andric F->addFnAttr("implicit-section-name", SA->getName()); 2287*0b57cec5SDimitry Andric 228804eeddc0SDimitry Andric llvm::AttrBuilder Attrs(F->getContext()); 2289*0b57cec5SDimitry Andric if (GetCPUAndFeaturesAttributes(GD, Attrs)) { 2290*0b57cec5SDimitry Andric // We know that GetCPUAndFeaturesAttributes will always have the 2291*0b57cec5SDimitry Andric // newest set, since it has the newest possible FunctionDecl, so the 2292*0b57cec5SDimitry Andric // new ones should replace the old. 229304eeddc0SDimitry Andric llvm::AttributeMask RemoveAttrs; 2294e8d8bef9SDimitry Andric RemoveAttrs.addAttribute("target-cpu"); 2295e8d8bef9SDimitry Andric RemoveAttrs.addAttribute("target-features"); 2296e8d8bef9SDimitry Andric RemoveAttrs.addAttribute("tune-cpu"); 2297349cc55cSDimitry Andric F->removeFnAttrs(RemoveAttrs); 2298349cc55cSDimitry Andric F->addFnAttrs(Attrs); 2299*0b57cec5SDimitry Andric } 2300*0b57cec5SDimitry Andric } 2301*0b57cec5SDimitry Andric 2302*0b57cec5SDimitry Andric if (const auto *CSA = D->getAttr<CodeSegAttr>()) 2303*0b57cec5SDimitry Andric GO->setSection(CSA->getName()); 2304*0b57cec5SDimitry Andric else if (const auto *SA = D->getAttr<SectionAttr>()) 2305*0b57cec5SDimitry Andric GO->setSection(SA->getName()); 2306*0b57cec5SDimitry Andric } 2307*0b57cec5SDimitry Andric 2308*0b57cec5SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 2309*0b57cec5SDimitry Andric } 2310*0b57cec5SDimitry Andric 2311*0b57cec5SDimitry Andric void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD, 2312*0b57cec5SDimitry Andric llvm::Function *F, 2313*0b57cec5SDimitry Andric const CGFunctionInfo &FI) { 2314*0b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 2315fe6060f1SDimitry Andric SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false); 2316*0b57cec5SDimitry Andric SetLLVMFunctionAttributesForDefinition(D, F); 2317*0b57cec5SDimitry Andric 2318*0b57cec5SDimitry Andric F->setLinkage(llvm::Function::InternalLinkage); 2319*0b57cec5SDimitry Andric 2320*0b57cec5SDimitry Andric setNonAliasAttributes(GD, F); 2321*0b57cec5SDimitry Andric } 2322*0b57cec5SDimitry Andric 2323*0b57cec5SDimitry Andric static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) { 2324*0b57cec5SDimitry Andric // Set linkage and visibility in case we never see a definition. 2325*0b57cec5SDimitry Andric LinkageInfo LV = ND->getLinkageAndVisibility(); 2326*0b57cec5SDimitry Andric // Don't set internal linkage on declarations. 2327*0b57cec5SDimitry Andric // "extern_weak" is overloaded in LLVM; we probably should have 2328*0b57cec5SDimitry Andric // separate linkage types for this. 2329*0b57cec5SDimitry Andric if (isExternallyVisible(LV.getLinkage()) && 2330*0b57cec5SDimitry Andric (ND->hasAttr<WeakAttr>() || ND->isWeakImported())) 2331*0b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 2332*0b57cec5SDimitry Andric } 2333*0b57cec5SDimitry Andric 2334*0b57cec5SDimitry Andric void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, 2335*0b57cec5SDimitry Andric llvm::Function *F) { 2336*0b57cec5SDimitry Andric // Only if we are checking indirect calls. 2337*0b57cec5SDimitry Andric if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 2338*0b57cec5SDimitry Andric return; 2339*0b57cec5SDimitry Andric 2340*0b57cec5SDimitry Andric // Non-static class methods are handled via vtable or member function pointer 2341*0b57cec5SDimitry Andric // checks elsewhere. 2342*0b57cec5SDimitry Andric if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 2343*0b57cec5SDimitry Andric return; 2344*0b57cec5SDimitry Andric 2345*0b57cec5SDimitry Andric llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 2346*0b57cec5SDimitry Andric F->addTypeMetadata(0, MD); 2347*0b57cec5SDimitry Andric F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType())); 2348*0b57cec5SDimitry Andric 2349*0b57cec5SDimitry Andric // Emit a hash-based bit set entry for cross-DSO calls. 2350*0b57cec5SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 2351*0b57cec5SDimitry Andric if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 2352*0b57cec5SDimitry Andric F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 2353*0b57cec5SDimitry Andric } 2354*0b57cec5SDimitry Andric 2355bdd1243dSDimitry Andric void CodeGenModule::setKCFIType(const FunctionDecl *FD, llvm::Function *F) { 2356bdd1243dSDimitry Andric if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 2357bdd1243dSDimitry Andric return; 2358bdd1243dSDimitry Andric 2359bdd1243dSDimitry Andric llvm::LLVMContext &Ctx = F->getContext(); 2360bdd1243dSDimitry Andric llvm::MDBuilder MDB(Ctx); 2361bdd1243dSDimitry Andric F->setMetadata(llvm::LLVMContext::MD_kcfi_type, 2362bdd1243dSDimitry Andric llvm::MDNode::get( 2363bdd1243dSDimitry Andric Ctx, MDB.createConstant(CreateKCFITypeId(FD->getType())))); 2364bdd1243dSDimitry Andric } 2365bdd1243dSDimitry Andric 2366bdd1243dSDimitry Andric static bool allowKCFIIdentifier(StringRef Name) { 2367bdd1243dSDimitry Andric // KCFI type identifier constants are only necessary for external assembly 2368bdd1243dSDimitry Andric // functions, which means it's safe to skip unusual names. Subset of 2369bdd1243dSDimitry Andric // MCAsmInfo::isAcceptableChar() and MCAsmInfoXCOFF::isAcceptableChar(). 2370bdd1243dSDimitry Andric return llvm::all_of(Name, [](const char &C) { 2371bdd1243dSDimitry Andric return llvm::isAlnum(C) || C == '_' || C == '.'; 2372bdd1243dSDimitry Andric }); 2373bdd1243dSDimitry Andric } 2374bdd1243dSDimitry Andric 2375bdd1243dSDimitry Andric void CodeGenModule::finalizeKCFITypes() { 2376bdd1243dSDimitry Andric llvm::Module &M = getModule(); 2377bdd1243dSDimitry Andric for (auto &F : M.functions()) { 2378bdd1243dSDimitry Andric // Remove KCFI type metadata from non-address-taken local functions. 2379bdd1243dSDimitry Andric bool AddressTaken = F.hasAddressTaken(); 2380bdd1243dSDimitry Andric if (!AddressTaken && F.hasLocalLinkage()) 2381bdd1243dSDimitry Andric F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type); 2382bdd1243dSDimitry Andric 2383bdd1243dSDimitry Andric // Generate a constant with the expected KCFI type identifier for all 2384bdd1243dSDimitry Andric // address-taken function declarations to support annotating indirectly 2385bdd1243dSDimitry Andric // called assembly functions. 2386bdd1243dSDimitry Andric if (!AddressTaken || !F.isDeclaration()) 2387bdd1243dSDimitry Andric continue; 2388bdd1243dSDimitry Andric 2389bdd1243dSDimitry Andric const llvm::ConstantInt *Type; 2390bdd1243dSDimitry Andric if (const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type)) 2391bdd1243dSDimitry Andric Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0)); 2392bdd1243dSDimitry Andric else 2393bdd1243dSDimitry Andric continue; 2394bdd1243dSDimitry Andric 2395bdd1243dSDimitry Andric StringRef Name = F.getName(); 2396bdd1243dSDimitry Andric if (!allowKCFIIdentifier(Name)) 2397bdd1243dSDimitry Andric continue; 2398bdd1243dSDimitry Andric 2399bdd1243dSDimitry Andric std::string Asm = (".weak __kcfi_typeid_" + Name + "\n.set __kcfi_typeid_" + 2400bdd1243dSDimitry Andric Name + ", " + Twine(Type->getZExtValue()) + "\n") 2401bdd1243dSDimitry Andric .str(); 2402bdd1243dSDimitry Andric M.appendModuleInlineAsm(Asm); 2403bdd1243dSDimitry Andric } 2404bdd1243dSDimitry Andric } 2405bdd1243dSDimitry Andric 2406*0b57cec5SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 2407*0b57cec5SDimitry Andric bool IsIncompleteFunction, 2408*0b57cec5SDimitry Andric bool IsThunk) { 2409*0b57cec5SDimitry Andric 2410*0b57cec5SDimitry Andric if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 2411*0b57cec5SDimitry Andric // If this is an intrinsic function, set the function's attributes 2412*0b57cec5SDimitry Andric // to the intrinsic's attributes. 2413*0b57cec5SDimitry Andric F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 2414*0b57cec5SDimitry Andric return; 2415*0b57cec5SDimitry Andric } 2416*0b57cec5SDimitry Andric 2417*0b57cec5SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 2418*0b57cec5SDimitry Andric 2419*0b57cec5SDimitry Andric if (!IsIncompleteFunction) 2420fe6060f1SDimitry Andric SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F, 2421fe6060f1SDimitry Andric IsThunk); 2422*0b57cec5SDimitry Andric 2423*0b57cec5SDimitry Andric // Add the Returned attribute for "this", except for iOS 5 and earlier 2424*0b57cec5SDimitry Andric // where substantial code, including the libstdc++ dylib, was compiled with 2425*0b57cec5SDimitry Andric // GCC and does not actually return "this". 2426*0b57cec5SDimitry Andric if (!IsThunk && getCXXABI().HasThisReturn(GD) && 2427*0b57cec5SDimitry Andric !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { 2428*0b57cec5SDimitry Andric assert(!F->arg_empty() && 2429*0b57cec5SDimitry Andric F->arg_begin()->getType() 2430*0b57cec5SDimitry Andric ->canLosslesslyBitCastTo(F->getReturnType()) && 2431*0b57cec5SDimitry Andric "unexpected this return"); 2432349cc55cSDimitry Andric F->addParamAttr(0, llvm::Attribute::Returned); 2433*0b57cec5SDimitry Andric } 2434*0b57cec5SDimitry Andric 2435*0b57cec5SDimitry Andric // Only a few attributes are set on declarations; these may later be 2436*0b57cec5SDimitry Andric // overridden by a definition. 2437*0b57cec5SDimitry Andric 2438*0b57cec5SDimitry Andric setLinkageForGV(F, FD); 2439*0b57cec5SDimitry Andric setGVProperties(F, FD); 2440*0b57cec5SDimitry Andric 2441*0b57cec5SDimitry Andric // Setup target-specific attributes. 2442*0b57cec5SDimitry Andric if (!IsIncompleteFunction && F->isDeclaration()) 2443*0b57cec5SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(FD, F, *this); 2444*0b57cec5SDimitry Andric 2445*0b57cec5SDimitry Andric if (const auto *CSA = FD->getAttr<CodeSegAttr>()) 2446*0b57cec5SDimitry Andric F->setSection(CSA->getName()); 2447*0b57cec5SDimitry Andric else if (const auto *SA = FD->getAttr<SectionAttr>()) 2448*0b57cec5SDimitry Andric F->setSection(SA->getName()); 2449*0b57cec5SDimitry Andric 2450349cc55cSDimitry Andric if (const auto *EA = FD->getAttr<ErrorAttr>()) { 2451349cc55cSDimitry Andric if (EA->isError()) 2452349cc55cSDimitry Andric F->addFnAttr("dontcall-error", EA->getUserDiagnostic()); 2453349cc55cSDimitry Andric else if (EA->isWarning()) 2454349cc55cSDimitry Andric F->addFnAttr("dontcall-warn", EA->getUserDiagnostic()); 2455349cc55cSDimitry Andric } 2456349cc55cSDimitry Andric 2457d65cd7a5SDimitry Andric // If we plan on emitting this inline builtin, we can't treat it as a builtin. 2458480093f4SDimitry Andric if (FD->isInlineBuiltinDeclaration()) { 2459d65cd7a5SDimitry Andric const FunctionDecl *FDBody; 2460d65cd7a5SDimitry Andric bool HasBody = FD->hasBody(FDBody); 2461d65cd7a5SDimitry Andric (void)HasBody; 2462d65cd7a5SDimitry Andric assert(HasBody && "Inline builtin declarations should always have an " 2463d65cd7a5SDimitry Andric "available body!"); 2464d65cd7a5SDimitry Andric if (shouldEmitFunction(FDBody)) 2465349cc55cSDimitry Andric F->addFnAttr(llvm::Attribute::NoBuiltin); 2466480093f4SDimitry Andric } 2467480093f4SDimitry Andric 2468*0b57cec5SDimitry Andric if (FD->isReplaceableGlobalAllocationFunction()) { 2469*0b57cec5SDimitry Andric // A replaceable global allocation function does not act like a builtin by 2470*0b57cec5SDimitry Andric // default, only if it is invoked by a new-expression or delete-expression. 2471349cc55cSDimitry Andric F->addFnAttr(llvm::Attribute::NoBuiltin); 2472*0b57cec5SDimitry Andric } 2473*0b57cec5SDimitry Andric 2474*0b57cec5SDimitry Andric if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 2475*0b57cec5SDimitry Andric F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2476*0b57cec5SDimitry Andric else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 2477*0b57cec5SDimitry Andric if (MD->isVirtual()) 2478*0b57cec5SDimitry Andric F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2479*0b57cec5SDimitry Andric 2480*0b57cec5SDimitry Andric // Don't emit entries for function declarations in the cross-DSO mode. This 2481a7dea167SDimitry Andric // is handled with better precision by the receiving DSO. But if jump tables 2482a7dea167SDimitry Andric // are non-canonical then we need type metadata in order to produce the local 2483a7dea167SDimitry Andric // jump table. 2484a7dea167SDimitry Andric if (!CodeGenOpts.SanitizeCfiCrossDso || 2485a7dea167SDimitry Andric !CodeGenOpts.SanitizeCfiCanonicalJumpTables) 2486*0b57cec5SDimitry Andric CreateFunctionTypeMetadataForIcall(FD, F); 2487*0b57cec5SDimitry Andric 2488bdd1243dSDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) 2489bdd1243dSDimitry Andric setKCFIType(FD, F); 2490bdd1243dSDimitry Andric 2491*0b57cec5SDimitry Andric if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) 2492*0b57cec5SDimitry Andric getOpenMPRuntime().emitDeclareSimdFunction(FD, F); 2493*0b57cec5SDimitry Andric 2494bdd1243dSDimitry Andric if (CodeGenOpts.InlineMaxStackSize != UINT_MAX) 2495bdd1243dSDimitry Andric F->addFnAttr("inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize)); 2496bdd1243dSDimitry Andric 2497*0b57cec5SDimitry Andric if (const auto *CB = FD->getAttr<CallbackAttr>()) { 2498*0b57cec5SDimitry Andric // Annotate the callback behavior as metadata: 2499*0b57cec5SDimitry Andric // - The callback callee (as argument number). 2500*0b57cec5SDimitry Andric // - The callback payloads (as argument numbers). 2501*0b57cec5SDimitry Andric llvm::LLVMContext &Ctx = F->getContext(); 2502*0b57cec5SDimitry Andric llvm::MDBuilder MDB(Ctx); 2503*0b57cec5SDimitry Andric 2504*0b57cec5SDimitry Andric // The payload indices are all but the first one in the encoding. The first 2505*0b57cec5SDimitry Andric // identifies the callback callee. 2506*0b57cec5SDimitry Andric int CalleeIdx = *CB->encoding_begin(); 2507*0b57cec5SDimitry Andric ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end()); 2508*0b57cec5SDimitry Andric F->addMetadata(llvm::LLVMContext::MD_callback, 2509*0b57cec5SDimitry Andric *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding( 2510*0b57cec5SDimitry Andric CalleeIdx, PayloadIndices, 2511*0b57cec5SDimitry Andric /* VarArgsArePassed */ false)})); 2512*0b57cec5SDimitry Andric } 2513*0b57cec5SDimitry Andric } 2514*0b57cec5SDimitry Andric 2515*0b57cec5SDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 2516e8d8bef9SDimitry Andric assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 2517*0b57cec5SDimitry Andric "Only globals with definition can force usage."); 2518*0b57cec5SDimitry Andric LLVMUsed.emplace_back(GV); 2519*0b57cec5SDimitry Andric } 2520*0b57cec5SDimitry Andric 2521*0b57cec5SDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 2522*0b57cec5SDimitry Andric assert(!GV->isDeclaration() && 2523*0b57cec5SDimitry Andric "Only globals with definition can force usage."); 2524*0b57cec5SDimitry Andric LLVMCompilerUsed.emplace_back(GV); 2525*0b57cec5SDimitry Andric } 2526*0b57cec5SDimitry Andric 2527fe6060f1SDimitry Andric void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) { 2528fe6060f1SDimitry Andric assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 2529fe6060f1SDimitry Andric "Only globals with definition can force usage."); 2530fe6060f1SDimitry Andric if (getTriple().isOSBinFormatELF()) 2531fe6060f1SDimitry Andric LLVMCompilerUsed.emplace_back(GV); 2532fe6060f1SDimitry Andric else 2533fe6060f1SDimitry Andric LLVMUsed.emplace_back(GV); 2534fe6060f1SDimitry Andric } 2535fe6060f1SDimitry Andric 2536*0b57cec5SDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name, 2537*0b57cec5SDimitry Andric std::vector<llvm::WeakTrackingVH> &List) { 2538*0b57cec5SDimitry Andric // Don't create llvm.used if there is no need. 2539*0b57cec5SDimitry Andric if (List.empty()) 2540*0b57cec5SDimitry Andric return; 2541*0b57cec5SDimitry Andric 2542*0b57cec5SDimitry Andric // Convert List to what ConstantArray needs. 2543*0b57cec5SDimitry Andric SmallVector<llvm::Constant*, 8> UsedArray; 2544*0b57cec5SDimitry Andric UsedArray.resize(List.size()); 2545*0b57cec5SDimitry Andric for (unsigned i = 0, e = List.size(); i != e; ++i) { 2546*0b57cec5SDimitry Andric UsedArray[i] = 2547*0b57cec5SDimitry Andric llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 2548*0b57cec5SDimitry Andric cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 2549*0b57cec5SDimitry Andric } 2550*0b57cec5SDimitry Andric 2551*0b57cec5SDimitry Andric if (UsedArray.empty()) 2552*0b57cec5SDimitry Andric return; 2553*0b57cec5SDimitry Andric llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 2554*0b57cec5SDimitry Andric 2555*0b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 2556*0b57cec5SDimitry Andric CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 2557*0b57cec5SDimitry Andric llvm::ConstantArray::get(ATy, UsedArray), Name); 2558*0b57cec5SDimitry Andric 2559*0b57cec5SDimitry Andric GV->setSection("llvm.metadata"); 2560*0b57cec5SDimitry Andric } 2561*0b57cec5SDimitry Andric 2562*0b57cec5SDimitry Andric void CodeGenModule::emitLLVMUsed() { 2563*0b57cec5SDimitry Andric emitUsed(*this, "llvm.used", LLVMUsed); 2564*0b57cec5SDimitry Andric emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 2565*0b57cec5SDimitry Andric } 2566*0b57cec5SDimitry Andric 2567*0b57cec5SDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 2568*0b57cec5SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 2569*0b57cec5SDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 2570*0b57cec5SDimitry Andric } 2571*0b57cec5SDimitry Andric 2572*0b57cec5SDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 2573*0b57cec5SDimitry Andric llvm::SmallString<32> Opt; 2574*0b57cec5SDimitry Andric getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 2575480093f4SDimitry Andric if (Opt.empty()) 2576480093f4SDimitry Andric return; 2577*0b57cec5SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 2578*0b57cec5SDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 2579*0b57cec5SDimitry Andric } 2580*0b57cec5SDimitry Andric 2581*0b57cec5SDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) { 2582*0b57cec5SDimitry Andric auto &C = getLLVMContext(); 2583*0b57cec5SDimitry Andric if (getTarget().getTriple().isOSBinFormatELF()) { 2584*0b57cec5SDimitry Andric ELFDependentLibraries.push_back( 2585*0b57cec5SDimitry Andric llvm::MDNode::get(C, llvm::MDString::get(C, Lib))); 2586*0b57cec5SDimitry Andric return; 2587*0b57cec5SDimitry Andric } 2588*0b57cec5SDimitry Andric 2589*0b57cec5SDimitry Andric llvm::SmallString<24> Opt; 2590*0b57cec5SDimitry Andric getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 2591*0b57cec5SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 2592*0b57cec5SDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts)); 2593*0b57cec5SDimitry Andric } 2594*0b57cec5SDimitry Andric 2595*0b57cec5SDimitry Andric /// Add link options implied by the given module, including modules 2596*0b57cec5SDimitry Andric /// it depends on, using a postorder walk. 2597*0b57cec5SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 2598*0b57cec5SDimitry Andric SmallVectorImpl<llvm::MDNode *> &Metadata, 2599*0b57cec5SDimitry Andric llvm::SmallPtrSet<Module *, 16> &Visited) { 2600*0b57cec5SDimitry Andric // Import this module's parent. 2601*0b57cec5SDimitry Andric if (Mod->Parent && Visited.insert(Mod->Parent).second) { 2602*0b57cec5SDimitry Andric addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 2603*0b57cec5SDimitry Andric } 2604*0b57cec5SDimitry Andric 2605*0b57cec5SDimitry Andric // Import this module's dependencies. 2606349cc55cSDimitry Andric for (Module *Import : llvm::reverse(Mod->Imports)) { 2607349cc55cSDimitry Andric if (Visited.insert(Import).second) 2608349cc55cSDimitry Andric addLinkOptionsPostorder(CGM, Import, Metadata, Visited); 2609*0b57cec5SDimitry Andric } 2610*0b57cec5SDimitry Andric 2611*0b57cec5SDimitry Andric // Add linker options to link against the libraries/frameworks 2612*0b57cec5SDimitry Andric // described by this module. 2613*0b57cec5SDimitry Andric llvm::LLVMContext &Context = CGM.getLLVMContext(); 2614*0b57cec5SDimitry Andric bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF(); 2615*0b57cec5SDimitry Andric 2616*0b57cec5SDimitry Andric // For modules that use export_as for linking, use that module 2617*0b57cec5SDimitry Andric // name instead. 2618*0b57cec5SDimitry Andric if (Mod->UseExportAsModuleLinkName) 2619*0b57cec5SDimitry Andric return; 2620*0b57cec5SDimitry Andric 2621349cc55cSDimitry Andric for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) { 2622*0b57cec5SDimitry Andric // Link against a framework. Frameworks are currently Darwin only, so we 2623*0b57cec5SDimitry Andric // don't to ask TargetCodeGenInfo for the spelling of the linker option. 2624349cc55cSDimitry Andric if (LL.IsFramework) { 2625349cc55cSDimitry Andric llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"), 2626349cc55cSDimitry Andric llvm::MDString::get(Context, LL.Library)}; 2627*0b57cec5SDimitry Andric 2628*0b57cec5SDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, Args)); 2629*0b57cec5SDimitry Andric continue; 2630*0b57cec5SDimitry Andric } 2631*0b57cec5SDimitry Andric 2632*0b57cec5SDimitry Andric // Link against a library. 2633*0b57cec5SDimitry Andric if (IsELF) { 2634*0b57cec5SDimitry Andric llvm::Metadata *Args[2] = { 2635*0b57cec5SDimitry Andric llvm::MDString::get(Context, "lib"), 2636349cc55cSDimitry Andric llvm::MDString::get(Context, LL.Library), 2637*0b57cec5SDimitry Andric }; 2638*0b57cec5SDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, Args)); 2639*0b57cec5SDimitry Andric } else { 2640*0b57cec5SDimitry Andric llvm::SmallString<24> Opt; 2641349cc55cSDimitry Andric CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt); 2642*0b57cec5SDimitry Andric auto *OptString = llvm::MDString::get(Context, Opt); 2643*0b57cec5SDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, OptString)); 2644*0b57cec5SDimitry Andric } 2645*0b57cec5SDimitry Andric } 2646*0b57cec5SDimitry Andric } 2647*0b57cec5SDimitry Andric 2648fcaf7f86SDimitry Andric void CodeGenModule::EmitModuleInitializers(clang::Module *Primary) { 2649fcaf7f86SDimitry Andric // Emit the initializers in the order that sub-modules appear in the 2650fcaf7f86SDimitry Andric // source, first Global Module Fragments, if present. 2651fcaf7f86SDimitry Andric if (auto GMF = Primary->getGlobalModuleFragment()) { 2652fcaf7f86SDimitry Andric for (Decl *D : getContext().getModuleInitializers(GMF)) { 265361cfbce3SDimitry Andric if (isa<ImportDecl>(D)) 265461cfbce3SDimitry Andric continue; 265561cfbce3SDimitry Andric assert(isa<VarDecl>(D) && "GMF initializer decl is not a var?"); 2656fcaf7f86SDimitry Andric EmitTopLevelDecl(D); 2657fcaf7f86SDimitry Andric } 2658fcaf7f86SDimitry Andric } 2659fcaf7f86SDimitry Andric // Second any associated with the module, itself. 2660fcaf7f86SDimitry Andric for (Decl *D : getContext().getModuleInitializers(Primary)) { 2661fcaf7f86SDimitry Andric // Skip import decls, the inits for those are called explicitly. 266261cfbce3SDimitry Andric if (isa<ImportDecl>(D)) 2663fcaf7f86SDimitry Andric continue; 2664fcaf7f86SDimitry Andric EmitTopLevelDecl(D); 2665fcaf7f86SDimitry Andric } 2666fcaf7f86SDimitry Andric // Third any associated with the Privat eMOdule Fragment, if present. 2667fcaf7f86SDimitry Andric if (auto PMF = Primary->getPrivateModuleFragment()) { 2668fcaf7f86SDimitry Andric for (Decl *D : getContext().getModuleInitializers(PMF)) { 266961cfbce3SDimitry Andric assert(isa<VarDecl>(D) && "PMF initializer decl is not a var?"); 2670fcaf7f86SDimitry Andric EmitTopLevelDecl(D); 2671fcaf7f86SDimitry Andric } 2672fcaf7f86SDimitry Andric } 2673fcaf7f86SDimitry Andric } 2674fcaf7f86SDimitry Andric 2675*0b57cec5SDimitry Andric void CodeGenModule::EmitModuleLinkOptions() { 2676*0b57cec5SDimitry Andric // Collect the set of all of the modules we want to visit to emit link 2677*0b57cec5SDimitry Andric // options, which is essentially the imported modules and all of their 2678*0b57cec5SDimitry Andric // non-explicit child modules. 2679*0b57cec5SDimitry Andric llvm::SetVector<clang::Module *> LinkModules; 2680*0b57cec5SDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 2681*0b57cec5SDimitry Andric SmallVector<clang::Module *, 16> Stack; 2682*0b57cec5SDimitry Andric 2683*0b57cec5SDimitry Andric // Seed the stack with imported modules. 2684*0b57cec5SDimitry Andric for (Module *M : ImportedModules) { 2685*0b57cec5SDimitry Andric // Do not add any link flags when an implementation TU of a module imports 2686*0b57cec5SDimitry Andric // a header of that same module. 2687*0b57cec5SDimitry Andric if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && 2688*0b57cec5SDimitry Andric !getLangOpts().isCompilingModule()) 2689*0b57cec5SDimitry Andric continue; 2690*0b57cec5SDimitry Andric if (Visited.insert(M).second) 2691*0b57cec5SDimitry Andric Stack.push_back(M); 2692*0b57cec5SDimitry Andric } 2693*0b57cec5SDimitry Andric 2694*0b57cec5SDimitry Andric // Find all of the modules to import, making a little effort to prune 2695*0b57cec5SDimitry Andric // non-leaf modules. 2696*0b57cec5SDimitry Andric while (!Stack.empty()) { 2697*0b57cec5SDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 2698*0b57cec5SDimitry Andric 2699*0b57cec5SDimitry Andric bool AnyChildren = false; 2700*0b57cec5SDimitry Andric 2701*0b57cec5SDimitry Andric // Visit the submodules of this module. 2702*0b57cec5SDimitry Andric for (const auto &SM : Mod->submodules()) { 2703*0b57cec5SDimitry Andric // Skip explicit children; they need to be explicitly imported to be 2704*0b57cec5SDimitry Andric // linked against. 2705*0b57cec5SDimitry Andric if (SM->IsExplicit) 2706*0b57cec5SDimitry Andric continue; 2707*0b57cec5SDimitry Andric 2708*0b57cec5SDimitry Andric if (Visited.insert(SM).second) { 2709*0b57cec5SDimitry Andric Stack.push_back(SM); 2710*0b57cec5SDimitry Andric AnyChildren = true; 2711*0b57cec5SDimitry Andric } 2712*0b57cec5SDimitry Andric } 2713*0b57cec5SDimitry Andric 2714*0b57cec5SDimitry Andric // We didn't find any children, so add this module to the list of 2715*0b57cec5SDimitry Andric // modules to link against. 2716*0b57cec5SDimitry Andric if (!AnyChildren) { 2717*0b57cec5SDimitry Andric LinkModules.insert(Mod); 2718*0b57cec5SDimitry Andric } 2719*0b57cec5SDimitry Andric } 2720*0b57cec5SDimitry Andric 2721*0b57cec5SDimitry Andric // Add link options for all of the imported modules in reverse topological 2722*0b57cec5SDimitry Andric // order. We don't do anything to try to order import link flags with respect 2723*0b57cec5SDimitry Andric // to linker options inserted by things like #pragma comment(). 2724*0b57cec5SDimitry Andric SmallVector<llvm::MDNode *, 16> MetadataArgs; 2725*0b57cec5SDimitry Andric Visited.clear(); 2726*0b57cec5SDimitry Andric for (Module *M : LinkModules) 2727*0b57cec5SDimitry Andric if (Visited.insert(M).second) 2728*0b57cec5SDimitry Andric addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 2729*0b57cec5SDimitry Andric std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 2730*0b57cec5SDimitry Andric LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 2731*0b57cec5SDimitry Andric 2732*0b57cec5SDimitry Andric // Add the linker options metadata flag. 2733*0b57cec5SDimitry Andric auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options"); 2734*0b57cec5SDimitry Andric for (auto *MD : LinkerOptionsMetadata) 2735*0b57cec5SDimitry Andric NMD->addOperand(MD); 2736*0b57cec5SDimitry Andric } 2737*0b57cec5SDimitry Andric 2738*0b57cec5SDimitry Andric void CodeGenModule::EmitDeferred() { 2739*0b57cec5SDimitry Andric // Emit deferred declare target declarations. 2740*0b57cec5SDimitry Andric if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 2741*0b57cec5SDimitry Andric getOpenMPRuntime().emitDeferredTargetDecls(); 2742*0b57cec5SDimitry Andric 2743*0b57cec5SDimitry Andric // Emit code for any potentially referenced deferred decls. Since a 2744*0b57cec5SDimitry Andric // previously unused static decl may become used during the generation of code 2745*0b57cec5SDimitry Andric // for a static function, iterate until no changes are made. 2746*0b57cec5SDimitry Andric 2747*0b57cec5SDimitry Andric if (!DeferredVTables.empty()) { 2748*0b57cec5SDimitry Andric EmitDeferredVTables(); 2749*0b57cec5SDimitry Andric 2750*0b57cec5SDimitry Andric // Emitting a vtable doesn't directly cause more vtables to 2751*0b57cec5SDimitry Andric // become deferred, although it can cause functions to be 2752*0b57cec5SDimitry Andric // emitted that then need those vtables. 2753*0b57cec5SDimitry Andric assert(DeferredVTables.empty()); 2754*0b57cec5SDimitry Andric } 2755*0b57cec5SDimitry Andric 2756e8d8bef9SDimitry Andric // Emit CUDA/HIP static device variables referenced by host code only. 2757fe6060f1SDimitry Andric // Note we should not clear CUDADeviceVarODRUsedByHost since it is still 2758fe6060f1SDimitry Andric // needed for further handling. 2759fe6060f1SDimitry Andric if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) 276081ad6265SDimitry Andric llvm::append_range(DeferredDeclsToEmit, 276181ad6265SDimitry Andric getContext().CUDADeviceVarODRUsedByHost); 2762e8d8bef9SDimitry Andric 2763*0b57cec5SDimitry Andric // Stop if we're out of both deferred vtables and deferred declarations. 2764*0b57cec5SDimitry Andric if (DeferredDeclsToEmit.empty()) 2765*0b57cec5SDimitry Andric return; 2766*0b57cec5SDimitry Andric 2767*0b57cec5SDimitry Andric // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 2768*0b57cec5SDimitry Andric // work, it will not interfere with this. 2769*0b57cec5SDimitry Andric std::vector<GlobalDecl> CurDeclsToEmit; 2770*0b57cec5SDimitry Andric CurDeclsToEmit.swap(DeferredDeclsToEmit); 2771*0b57cec5SDimitry Andric 2772*0b57cec5SDimitry Andric for (GlobalDecl &D : CurDeclsToEmit) { 2773*0b57cec5SDimitry Andric // We should call GetAddrOfGlobal with IsForDefinition set to true in order 2774*0b57cec5SDimitry Andric // to get GlobalValue with exactly the type we need, not something that 2775*0b57cec5SDimitry Andric // might had been created for another decl with the same mangled name but 2776*0b57cec5SDimitry Andric // different type. 2777*0b57cec5SDimitry Andric llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 2778*0b57cec5SDimitry Andric GetAddrOfGlobal(D, ForDefinition)); 2779*0b57cec5SDimitry Andric 2780*0b57cec5SDimitry Andric // In case of different address spaces, we may still get a cast, even with 2781*0b57cec5SDimitry Andric // IsForDefinition equal to true. Query mangled names table to get 2782*0b57cec5SDimitry Andric // GlobalValue. 2783*0b57cec5SDimitry Andric if (!GV) 2784*0b57cec5SDimitry Andric GV = GetGlobalValue(getMangledName(D)); 2785*0b57cec5SDimitry Andric 2786*0b57cec5SDimitry Andric // Make sure GetGlobalValue returned non-null. 2787*0b57cec5SDimitry Andric assert(GV); 2788*0b57cec5SDimitry Andric 2789*0b57cec5SDimitry Andric // Check to see if we've already emitted this. This is necessary 2790*0b57cec5SDimitry Andric // for a couple of reasons: first, decls can end up in the 2791*0b57cec5SDimitry Andric // deferred-decls queue multiple times, and second, decls can end 2792*0b57cec5SDimitry Andric // up with definitions in unusual ways (e.g. by an extern inline 2793*0b57cec5SDimitry Andric // function acquiring a strong function redefinition). Just 2794*0b57cec5SDimitry Andric // ignore these cases. 2795*0b57cec5SDimitry Andric if (!GV->isDeclaration()) 2796*0b57cec5SDimitry Andric continue; 2797*0b57cec5SDimitry Andric 2798a7dea167SDimitry Andric // If this is OpenMP, check if it is legal to emit this global normally. 2799a7dea167SDimitry Andric if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D)) 2800a7dea167SDimitry Andric continue; 2801a7dea167SDimitry Andric 2802*0b57cec5SDimitry Andric // Otherwise, emit the definition and move on to the next one. 2803*0b57cec5SDimitry Andric EmitGlobalDefinition(D, GV); 2804*0b57cec5SDimitry Andric 2805*0b57cec5SDimitry Andric // If we found out that we need to emit more decls, do that recursively. 2806*0b57cec5SDimitry Andric // This has the advantage that the decls are emitted in a DFS and related 2807*0b57cec5SDimitry Andric // ones are close together, which is convenient for testing. 2808*0b57cec5SDimitry Andric if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 2809*0b57cec5SDimitry Andric EmitDeferred(); 2810*0b57cec5SDimitry Andric assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 2811*0b57cec5SDimitry Andric } 2812*0b57cec5SDimitry Andric } 2813*0b57cec5SDimitry Andric } 2814*0b57cec5SDimitry Andric 2815*0b57cec5SDimitry Andric void CodeGenModule::EmitVTablesOpportunistically() { 2816*0b57cec5SDimitry Andric // Try to emit external vtables as available_externally if they have emitted 2817*0b57cec5SDimitry Andric // all inlined virtual functions. It runs after EmitDeferred() and therefore 2818*0b57cec5SDimitry Andric // is not allowed to create new references to things that need to be emitted 2819*0b57cec5SDimitry Andric // lazily. Note that it also uses fact that we eagerly emitting RTTI. 2820*0b57cec5SDimitry Andric 2821*0b57cec5SDimitry Andric assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) 2822*0b57cec5SDimitry Andric && "Only emit opportunistic vtables with optimizations"); 2823*0b57cec5SDimitry Andric 2824*0b57cec5SDimitry Andric for (const CXXRecordDecl *RD : OpportunisticVTables) { 2825*0b57cec5SDimitry Andric assert(getVTables().isVTableExternal(RD) && 2826*0b57cec5SDimitry Andric "This queue should only contain external vtables"); 2827*0b57cec5SDimitry Andric if (getCXXABI().canSpeculativelyEmitVTable(RD)) 2828*0b57cec5SDimitry Andric VTables.GenerateClassData(RD); 2829*0b57cec5SDimitry Andric } 2830*0b57cec5SDimitry Andric OpportunisticVTables.clear(); 2831*0b57cec5SDimitry Andric } 2832*0b57cec5SDimitry Andric 2833*0b57cec5SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() { 2834*0b57cec5SDimitry Andric if (Annotations.empty()) 2835*0b57cec5SDimitry Andric return; 2836*0b57cec5SDimitry Andric 2837*0b57cec5SDimitry Andric // Create a new global variable for the ConstantStruct in the Module. 2838*0b57cec5SDimitry Andric llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 2839*0b57cec5SDimitry Andric Annotations[0]->getType(), Annotations.size()), Annotations); 2840*0b57cec5SDimitry Andric auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 2841*0b57cec5SDimitry Andric llvm::GlobalValue::AppendingLinkage, 2842*0b57cec5SDimitry Andric Array, "llvm.global.annotations"); 2843*0b57cec5SDimitry Andric gv->setSection(AnnotationSection); 2844*0b57cec5SDimitry Andric } 2845*0b57cec5SDimitry Andric 2846*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 2847*0b57cec5SDimitry Andric llvm::Constant *&AStr = AnnotationStrings[Str]; 2848*0b57cec5SDimitry Andric if (AStr) 2849*0b57cec5SDimitry Andric return AStr; 2850*0b57cec5SDimitry Andric 2851*0b57cec5SDimitry Andric // Not found yet, create a new global. 2852*0b57cec5SDimitry Andric llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 2853bdd1243dSDimitry Andric auto *gv = new llvm::GlobalVariable( 2854bdd1243dSDimitry Andric getModule(), s->getType(), true, llvm::GlobalValue::PrivateLinkage, s, 2855bdd1243dSDimitry Andric ".str", nullptr, llvm::GlobalValue::NotThreadLocal, 2856bdd1243dSDimitry Andric ConstGlobalsPtrTy->getAddressSpace()); 2857*0b57cec5SDimitry Andric gv->setSection(AnnotationSection); 2858*0b57cec5SDimitry Andric gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2859*0b57cec5SDimitry Andric AStr = gv; 2860*0b57cec5SDimitry Andric return gv; 2861*0b57cec5SDimitry Andric } 2862*0b57cec5SDimitry Andric 2863*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 2864*0b57cec5SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 2865*0b57cec5SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(Loc); 2866*0b57cec5SDimitry Andric if (PLoc.isValid()) 2867*0b57cec5SDimitry Andric return EmitAnnotationString(PLoc.getFilename()); 2868*0b57cec5SDimitry Andric return EmitAnnotationString(SM.getBufferName(Loc)); 2869*0b57cec5SDimitry Andric } 2870*0b57cec5SDimitry Andric 2871*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 2872*0b57cec5SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 2873*0b57cec5SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(L); 2874*0b57cec5SDimitry Andric unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 2875*0b57cec5SDimitry Andric SM.getExpansionLineNumber(L); 2876*0b57cec5SDimitry Andric return llvm::ConstantInt::get(Int32Ty, LineNo); 2877*0b57cec5SDimitry Andric } 2878*0b57cec5SDimitry Andric 2879e8d8bef9SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) { 2880e8d8bef9SDimitry Andric ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()}; 2881e8d8bef9SDimitry Andric if (Exprs.empty()) 2882bdd1243dSDimitry Andric return llvm::ConstantPointerNull::get(ConstGlobalsPtrTy); 2883e8d8bef9SDimitry Andric 2884e8d8bef9SDimitry Andric llvm::FoldingSetNodeID ID; 2885e8d8bef9SDimitry Andric for (Expr *E : Exprs) { 2886e8d8bef9SDimitry Andric ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult()); 2887e8d8bef9SDimitry Andric } 2888e8d8bef9SDimitry Andric llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()]; 2889e8d8bef9SDimitry Andric if (Lookup) 2890e8d8bef9SDimitry Andric return Lookup; 2891e8d8bef9SDimitry Andric 2892e8d8bef9SDimitry Andric llvm::SmallVector<llvm::Constant *, 4> LLVMArgs; 2893e8d8bef9SDimitry Andric LLVMArgs.reserve(Exprs.size()); 2894e8d8bef9SDimitry Andric ConstantEmitter ConstEmiter(*this); 2895e8d8bef9SDimitry Andric llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) { 2896e8d8bef9SDimitry Andric const auto *CE = cast<clang::ConstantExpr>(E); 2897e8d8bef9SDimitry Andric return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(), 2898e8d8bef9SDimitry Andric CE->getType()); 2899e8d8bef9SDimitry Andric }); 2900e8d8bef9SDimitry Andric auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs); 2901e8d8bef9SDimitry Andric auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true, 2902e8d8bef9SDimitry Andric llvm::GlobalValue::PrivateLinkage, Struct, 2903e8d8bef9SDimitry Andric ".args"); 2904e8d8bef9SDimitry Andric GV->setSection(AnnotationSection); 2905e8d8bef9SDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2906349cc55cSDimitry Andric auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, GlobalsInt8PtrTy); 2907e8d8bef9SDimitry Andric 2908e8d8bef9SDimitry Andric Lookup = Bitcasted; 2909e8d8bef9SDimitry Andric return Bitcasted; 2910e8d8bef9SDimitry Andric } 2911e8d8bef9SDimitry Andric 2912*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 2913*0b57cec5SDimitry Andric const AnnotateAttr *AA, 2914*0b57cec5SDimitry Andric SourceLocation L) { 2915*0b57cec5SDimitry Andric // Get the globals for file name, annotation, and the line number. 2916*0b57cec5SDimitry Andric llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 2917*0b57cec5SDimitry Andric *UnitGV = EmitAnnotationUnit(L), 2918e8d8bef9SDimitry Andric *LineNoCst = EmitAnnotationLineNo(L), 2919e8d8bef9SDimitry Andric *Args = EmitAnnotationArgs(AA); 2920*0b57cec5SDimitry Andric 2921349cc55cSDimitry Andric llvm::Constant *GVInGlobalsAS = GV; 2922349cc55cSDimitry Andric if (GV->getAddressSpace() != 2923349cc55cSDimitry Andric getDataLayout().getDefaultGlobalsAddressSpace()) { 2924349cc55cSDimitry Andric GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast( 2925349cc55cSDimitry Andric GV, GV->getValueType()->getPointerTo( 2926349cc55cSDimitry Andric getDataLayout().getDefaultGlobalsAddressSpace())); 2927480093f4SDimitry Andric } 2928480093f4SDimitry Andric 2929*0b57cec5SDimitry Andric // Create the ConstantStruct for the global annotation. 2930e8d8bef9SDimitry Andric llvm::Constant *Fields[] = { 2931349cc55cSDimitry Andric llvm::ConstantExpr::getBitCast(GVInGlobalsAS, GlobalsInt8PtrTy), 2932bdd1243dSDimitry Andric llvm::ConstantExpr::getBitCast(AnnoGV, ConstGlobalsPtrTy), 2933bdd1243dSDimitry Andric llvm::ConstantExpr::getBitCast(UnitGV, ConstGlobalsPtrTy), 2934e8d8bef9SDimitry Andric LineNoCst, 2935e8d8bef9SDimitry Andric Args, 2936*0b57cec5SDimitry Andric }; 2937*0b57cec5SDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 2938*0b57cec5SDimitry Andric } 2939*0b57cec5SDimitry Andric 2940*0b57cec5SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 2941*0b57cec5SDimitry Andric llvm::GlobalValue *GV) { 2942*0b57cec5SDimitry Andric assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 2943*0b57cec5SDimitry Andric // Get the struct elements for these annotations. 2944*0b57cec5SDimitry Andric for (const auto *I : D->specific_attrs<AnnotateAttr>()) 2945*0b57cec5SDimitry Andric Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 2946*0b57cec5SDimitry Andric } 2947*0b57cec5SDimitry Andric 2948fe6060f1SDimitry Andric bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, 2949*0b57cec5SDimitry Andric SourceLocation Loc) const { 2950fe6060f1SDimitry Andric const auto &NoSanitizeL = getContext().getNoSanitizeList(); 2951fe6060f1SDimitry Andric // NoSanitize by function name. 2952fe6060f1SDimitry Andric if (NoSanitizeL.containsFunction(Kind, Fn->getName())) 2953*0b57cec5SDimitry Andric return true; 2954fcaf7f86SDimitry Andric // NoSanitize by location. Check "mainfile" prefix. 2955fcaf7f86SDimitry Andric auto &SM = Context.getSourceManager(); 2956fcaf7f86SDimitry Andric const FileEntry &MainFile = *SM.getFileEntryForID(SM.getMainFileID()); 2957fcaf7f86SDimitry Andric if (NoSanitizeL.containsMainFile(Kind, MainFile.getName())) 2958fcaf7f86SDimitry Andric return true; 2959fcaf7f86SDimitry Andric 2960fcaf7f86SDimitry Andric // Check "src" prefix. 2961*0b57cec5SDimitry Andric if (Loc.isValid()) 2962fe6060f1SDimitry Andric return NoSanitizeL.containsLocation(Kind, Loc); 2963*0b57cec5SDimitry Andric // If location is unknown, this may be a compiler-generated function. Assume 2964*0b57cec5SDimitry Andric // it's located in the main file. 2965fcaf7f86SDimitry Andric return NoSanitizeL.containsFile(Kind, MainFile.getName()); 2966*0b57cec5SDimitry Andric } 2967*0b57cec5SDimitry Andric 296881ad6265SDimitry Andric bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, 296981ad6265SDimitry Andric llvm::GlobalVariable *GV, 2970*0b57cec5SDimitry Andric SourceLocation Loc, QualType Ty, 2971*0b57cec5SDimitry Andric StringRef Category) const { 2972fe6060f1SDimitry Andric const auto &NoSanitizeL = getContext().getNoSanitizeList(); 297381ad6265SDimitry Andric if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category)) 2974*0b57cec5SDimitry Andric return true; 2975fcaf7f86SDimitry Andric auto &SM = Context.getSourceManager(); 2976fcaf7f86SDimitry Andric if (NoSanitizeL.containsMainFile( 2977fcaf7f86SDimitry Andric Kind, SM.getFileEntryForID(SM.getMainFileID())->getName(), Category)) 2978fcaf7f86SDimitry Andric return true; 297981ad6265SDimitry Andric if (NoSanitizeL.containsLocation(Kind, Loc, Category)) 2980*0b57cec5SDimitry Andric return true; 2981fcaf7f86SDimitry Andric 2982*0b57cec5SDimitry Andric // Check global type. 2983*0b57cec5SDimitry Andric if (!Ty.isNull()) { 2984*0b57cec5SDimitry Andric // Drill down the array types: if global variable of a fixed type is 2985fe6060f1SDimitry Andric // not sanitized, we also don't instrument arrays of them. 2986*0b57cec5SDimitry Andric while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 2987*0b57cec5SDimitry Andric Ty = AT->getElementType(); 2988*0b57cec5SDimitry Andric Ty = Ty.getCanonicalType().getUnqualifiedType(); 2989fe6060f1SDimitry Andric // Only record types (classes, structs etc.) are ignored. 2990*0b57cec5SDimitry Andric if (Ty->isRecordType()) { 2991*0b57cec5SDimitry Andric std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 299281ad6265SDimitry Andric if (NoSanitizeL.containsType(Kind, TypeStr, Category)) 2993*0b57cec5SDimitry Andric return true; 2994*0b57cec5SDimitry Andric } 2995*0b57cec5SDimitry Andric } 2996*0b57cec5SDimitry Andric return false; 2997*0b57cec5SDimitry Andric } 2998*0b57cec5SDimitry Andric 2999*0b57cec5SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 3000*0b57cec5SDimitry Andric StringRef Category) const { 3001*0b57cec5SDimitry Andric const auto &XRayFilter = getContext().getXRayFilter(); 3002*0b57cec5SDimitry Andric using ImbueAttr = XRayFunctionFilter::ImbueAttribute; 3003*0b57cec5SDimitry Andric auto Attr = ImbueAttr::NONE; 3004*0b57cec5SDimitry Andric if (Loc.isValid()) 3005*0b57cec5SDimitry Andric Attr = XRayFilter.shouldImbueLocation(Loc, Category); 3006*0b57cec5SDimitry Andric if (Attr == ImbueAttr::NONE) 3007*0b57cec5SDimitry Andric Attr = XRayFilter.shouldImbueFunction(Fn->getName()); 3008*0b57cec5SDimitry Andric switch (Attr) { 3009*0b57cec5SDimitry Andric case ImbueAttr::NONE: 3010*0b57cec5SDimitry Andric return false; 3011*0b57cec5SDimitry Andric case ImbueAttr::ALWAYS: 3012*0b57cec5SDimitry Andric Fn->addFnAttr("function-instrument", "xray-always"); 3013*0b57cec5SDimitry Andric break; 3014*0b57cec5SDimitry Andric case ImbueAttr::ALWAYS_ARG1: 3015*0b57cec5SDimitry Andric Fn->addFnAttr("function-instrument", "xray-always"); 3016*0b57cec5SDimitry Andric Fn->addFnAttr("xray-log-args", "1"); 3017*0b57cec5SDimitry Andric break; 3018*0b57cec5SDimitry Andric case ImbueAttr::NEVER: 3019*0b57cec5SDimitry Andric Fn->addFnAttr("function-instrument", "xray-never"); 3020*0b57cec5SDimitry Andric break; 3021*0b57cec5SDimitry Andric } 3022*0b57cec5SDimitry Andric return true; 3023*0b57cec5SDimitry Andric } 3024*0b57cec5SDimitry Andric 3025bdd1243dSDimitry Andric ProfileList::ExclusionType 3026bdd1243dSDimitry Andric CodeGenModule::isFunctionBlockedByProfileList(llvm::Function *Fn, 3027e8d8bef9SDimitry Andric SourceLocation Loc) const { 3028e8d8bef9SDimitry Andric const auto &ProfileList = getContext().getProfileList(); 3029e8d8bef9SDimitry Andric // If the profile list is empty, then instrument everything. 3030e8d8bef9SDimitry Andric if (ProfileList.isEmpty()) 3031bdd1243dSDimitry Andric return ProfileList::Allow; 3032e8d8bef9SDimitry Andric CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr(); 3033e8d8bef9SDimitry Andric // First, check the function name. 3034bdd1243dSDimitry Andric if (auto V = ProfileList.isFunctionExcluded(Fn->getName(), Kind)) 3035e8d8bef9SDimitry Andric return *V; 3036e8d8bef9SDimitry Andric // Next, check the source location. 3037bdd1243dSDimitry Andric if (Loc.isValid()) 3038bdd1243dSDimitry Andric if (auto V = ProfileList.isLocationExcluded(Loc, Kind)) 3039e8d8bef9SDimitry Andric return *V; 3040e8d8bef9SDimitry Andric // If location is unknown, this may be a compiler-generated function. Assume 3041e8d8bef9SDimitry Andric // it's located in the main file. 3042e8d8bef9SDimitry Andric auto &SM = Context.getSourceManager(); 3043bdd1243dSDimitry Andric if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) 3044bdd1243dSDimitry Andric if (auto V = ProfileList.isFileExcluded(MainFile->getName(), Kind)) 3045e8d8bef9SDimitry Andric return *V; 3046bdd1243dSDimitry Andric return ProfileList.getDefault(Kind); 3047e8d8bef9SDimitry Andric } 3048e8d8bef9SDimitry Andric 3049bdd1243dSDimitry Andric ProfileList::ExclusionType 3050bdd1243dSDimitry Andric CodeGenModule::isFunctionBlockedFromProfileInstr(llvm::Function *Fn, 3051bdd1243dSDimitry Andric SourceLocation Loc) const { 3052bdd1243dSDimitry Andric auto V = isFunctionBlockedByProfileList(Fn, Loc); 3053bdd1243dSDimitry Andric if (V != ProfileList::Allow) 3054bdd1243dSDimitry Andric return V; 3055fcaf7f86SDimitry Andric 3056fcaf7f86SDimitry Andric auto NumGroups = getCodeGenOpts().ProfileTotalFunctionGroups; 3057fcaf7f86SDimitry Andric if (NumGroups > 1) { 3058fcaf7f86SDimitry Andric auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups; 3059fcaf7f86SDimitry Andric if (Group != getCodeGenOpts().ProfileSelectedFunctionGroup) 3060bdd1243dSDimitry Andric return ProfileList::Skip; 3061fcaf7f86SDimitry Andric } 3062bdd1243dSDimitry Andric return ProfileList::Allow; 3063fcaf7f86SDimitry Andric } 3064fcaf7f86SDimitry Andric 3065*0b57cec5SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 3066*0b57cec5SDimitry Andric // Never defer when EmitAllDecls is specified. 3067*0b57cec5SDimitry Andric if (LangOpts.EmitAllDecls) 3068*0b57cec5SDimitry Andric return true; 3069*0b57cec5SDimitry Andric 3070*0b57cec5SDimitry Andric if (CodeGenOpts.KeepStaticConsts) { 3071*0b57cec5SDimitry Andric const auto *VD = dyn_cast<VarDecl>(Global); 3072*0b57cec5SDimitry Andric if (VD && VD->getType().isConstQualified() && 3073*0b57cec5SDimitry Andric VD->getStorageDuration() == SD_Static) 3074*0b57cec5SDimitry Andric return true; 3075*0b57cec5SDimitry Andric } 3076*0b57cec5SDimitry Andric 3077*0b57cec5SDimitry Andric return getContext().DeclMustBeEmitted(Global); 3078*0b57cec5SDimitry Andric } 3079*0b57cec5SDimitry Andric 3080*0b57cec5SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 3081fe6060f1SDimitry Andric // In OpenMP 5.0 variables and function may be marked as 3082fe6060f1SDimitry Andric // device_type(host/nohost) and we should not emit them eagerly unless we sure 3083fe6060f1SDimitry Andric // that they must be emitted on the host/device. To be sure we need to have 3084fe6060f1SDimitry Andric // seen a declare target with an explicit mentioning of the function, we know 3085fe6060f1SDimitry Andric // we have if the level of the declare target attribute is -1. Note that we 3086fe6060f1SDimitry Andric // check somewhere else if we should emit this at all. 3087fe6060f1SDimitry Andric if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) { 3088bdd1243dSDimitry Andric std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr = 3089fe6060f1SDimitry Andric OMPDeclareTargetDeclAttr::getActiveAttr(Global); 3090fe6060f1SDimitry Andric if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1) 3091fe6060f1SDimitry Andric return false; 3092fe6060f1SDimitry Andric } 3093fe6060f1SDimitry Andric 3094a7dea167SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 3095*0b57cec5SDimitry Andric if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 3096*0b57cec5SDimitry Andric // Implicit template instantiations may change linkage if they are later 3097*0b57cec5SDimitry Andric // explicitly instantiated, so they should not be emitted eagerly. 3098*0b57cec5SDimitry Andric return false; 3099a7dea167SDimitry Andric } 3100fcaf7f86SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(Global)) { 3101*0b57cec5SDimitry Andric if (Context.getInlineVariableDefinitionKind(VD) == 3102*0b57cec5SDimitry Andric ASTContext::InlineVariableDefinitionKind::WeakUnknown) 3103*0b57cec5SDimitry Andric // A definition of an inline constexpr static data member may change 3104*0b57cec5SDimitry Andric // linkage later if it's redeclared outside the class. 3105*0b57cec5SDimitry Andric return false; 3106fcaf7f86SDimitry Andric if (CXX20ModuleInits && VD->getOwningModule() && 3107fcaf7f86SDimitry Andric !VD->getOwningModule()->isModuleMapModule()) { 3108fcaf7f86SDimitry Andric // For CXX20, module-owned initializers need to be deferred, since it is 3109fcaf7f86SDimitry Andric // not known at this point if they will be run for the current module or 3110fcaf7f86SDimitry Andric // as part of the initializer for an imported one. 3111fcaf7f86SDimitry Andric return false; 3112fcaf7f86SDimitry Andric } 3113fcaf7f86SDimitry Andric } 3114*0b57cec5SDimitry Andric // If OpenMP is enabled and threadprivates must be generated like TLS, delay 3115*0b57cec5SDimitry Andric // codegen for global variables, because they may be marked as threadprivate. 3116*0b57cec5SDimitry Andric if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 3117*0b57cec5SDimitry Andric getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) && 3118*0b57cec5SDimitry Andric !isTypeConstant(Global->getType(), false) && 3119*0b57cec5SDimitry Andric !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global)) 3120*0b57cec5SDimitry Andric return false; 3121*0b57cec5SDimitry Andric 3122*0b57cec5SDimitry Andric return true; 3123*0b57cec5SDimitry Andric } 3124*0b57cec5SDimitry Andric 31255ffd83dbSDimitry Andric ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) { 31265ffd83dbSDimitry Andric StringRef Name = getMangledName(GD); 3127*0b57cec5SDimitry Andric 3128*0b57cec5SDimitry Andric // The UUID descriptor should be pointer aligned. 3129*0b57cec5SDimitry Andric CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 3130*0b57cec5SDimitry Andric 3131*0b57cec5SDimitry Andric // Look for an existing global. 3132*0b57cec5SDimitry Andric if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 31330eae32dcSDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 3134*0b57cec5SDimitry Andric 31355ffd83dbSDimitry Andric ConstantEmitter Emitter(*this); 31365ffd83dbSDimitry Andric llvm::Constant *Init; 31375ffd83dbSDimitry Andric 31385ffd83dbSDimitry Andric APValue &V = GD->getAsAPValue(); 31395ffd83dbSDimitry Andric if (!V.isAbsent()) { 31405ffd83dbSDimitry Andric // If possible, emit the APValue version of the initializer. In particular, 31415ffd83dbSDimitry Andric // this gets the type of the constant right. 31425ffd83dbSDimitry Andric Init = Emitter.emitForInitializer( 31435ffd83dbSDimitry Andric GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType()); 31445ffd83dbSDimitry Andric } else { 31455ffd83dbSDimitry Andric // As a fallback, directly construct the constant. 31465ffd83dbSDimitry Andric // FIXME: This may get padding wrong under esoteric struct layout rules. 31475ffd83dbSDimitry Andric // MSVC appears to create a complete type 'struct __s_GUID' that it 31485ffd83dbSDimitry Andric // presumably uses to represent these constants. 31495ffd83dbSDimitry Andric MSGuidDecl::Parts Parts = GD->getParts(); 31505ffd83dbSDimitry Andric llvm::Constant *Fields[4] = { 31515ffd83dbSDimitry Andric llvm::ConstantInt::get(Int32Ty, Parts.Part1), 31525ffd83dbSDimitry Andric llvm::ConstantInt::get(Int16Ty, Parts.Part2), 31535ffd83dbSDimitry Andric llvm::ConstantInt::get(Int16Ty, Parts.Part3), 31545ffd83dbSDimitry Andric llvm::ConstantDataArray::getRaw( 31555ffd83dbSDimitry Andric StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8, 31565ffd83dbSDimitry Andric Int8Ty)}; 31575ffd83dbSDimitry Andric Init = llvm::ConstantStruct::getAnon(Fields); 31585ffd83dbSDimitry Andric } 3159*0b57cec5SDimitry Andric 3160*0b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 3161*0b57cec5SDimitry Andric getModule(), Init->getType(), 3162*0b57cec5SDimitry Andric /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 3163*0b57cec5SDimitry Andric if (supportsCOMDAT()) 3164*0b57cec5SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3165*0b57cec5SDimitry Andric setDSOLocal(GV); 31665ffd83dbSDimitry Andric 31675ffd83dbSDimitry Andric if (!V.isAbsent()) { 31685ffd83dbSDimitry Andric Emitter.finalize(GV); 31690eae32dcSDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 31705ffd83dbSDimitry Andric } 31710eae32dcSDimitry Andric 31720eae32dcSDimitry Andric llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType()); 31730eae32dcSDimitry Andric llvm::Constant *Addr = llvm::ConstantExpr::getBitCast( 31740eae32dcSDimitry Andric GV, Ty->getPointerTo(GV->getAddressSpace())); 31750eae32dcSDimitry Andric return ConstantAddress(Addr, Ty, Alignment); 3176*0b57cec5SDimitry Andric } 3177*0b57cec5SDimitry Andric 317881ad6265SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUnnamedGlobalConstantDecl( 317981ad6265SDimitry Andric const UnnamedGlobalConstantDecl *GCD) { 318081ad6265SDimitry Andric CharUnits Alignment = getContext().getTypeAlignInChars(GCD->getType()); 318181ad6265SDimitry Andric 318281ad6265SDimitry Andric llvm::GlobalVariable **Entry = nullptr; 318381ad6265SDimitry Andric Entry = &UnnamedGlobalConstantDeclMap[GCD]; 318481ad6265SDimitry Andric if (*Entry) 318581ad6265SDimitry Andric return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment); 318681ad6265SDimitry Andric 318781ad6265SDimitry Andric ConstantEmitter Emitter(*this); 318881ad6265SDimitry Andric llvm::Constant *Init; 318981ad6265SDimitry Andric 319081ad6265SDimitry Andric const APValue &V = GCD->getValue(); 319181ad6265SDimitry Andric 319281ad6265SDimitry Andric assert(!V.isAbsent()); 319381ad6265SDimitry Andric Init = Emitter.emitForInitializer(V, GCD->getType().getAddressSpace(), 319481ad6265SDimitry Andric GCD->getType()); 319581ad6265SDimitry Andric 319681ad6265SDimitry Andric auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(), 319781ad6265SDimitry Andric /*isConstant=*/true, 319881ad6265SDimitry Andric llvm::GlobalValue::PrivateLinkage, Init, 319981ad6265SDimitry Andric ".constant"); 320081ad6265SDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 320181ad6265SDimitry Andric GV->setAlignment(Alignment.getAsAlign()); 320281ad6265SDimitry Andric 320381ad6265SDimitry Andric Emitter.finalize(GV); 320481ad6265SDimitry Andric 320581ad6265SDimitry Andric *Entry = GV; 320681ad6265SDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 320781ad6265SDimitry Andric } 320881ad6265SDimitry Andric 3209e8d8bef9SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject( 3210e8d8bef9SDimitry Andric const TemplateParamObjectDecl *TPO) { 3211e8d8bef9SDimitry Andric StringRef Name = getMangledName(TPO); 3212e8d8bef9SDimitry Andric CharUnits Alignment = getNaturalTypeAlignment(TPO->getType()); 3213e8d8bef9SDimitry Andric 3214e8d8bef9SDimitry Andric if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 32150eae32dcSDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 3216e8d8bef9SDimitry Andric 3217e8d8bef9SDimitry Andric ConstantEmitter Emitter(*this); 3218e8d8bef9SDimitry Andric llvm::Constant *Init = Emitter.emitForInitializer( 3219e8d8bef9SDimitry Andric TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType()); 3220e8d8bef9SDimitry Andric 3221e8d8bef9SDimitry Andric if (!Init) { 3222e8d8bef9SDimitry Andric ErrorUnsupported(TPO, "template parameter object"); 3223e8d8bef9SDimitry Andric return ConstantAddress::invalid(); 3224e8d8bef9SDimitry Andric } 3225e8d8bef9SDimitry Andric 3226e8d8bef9SDimitry Andric auto *GV = new llvm::GlobalVariable( 3227e8d8bef9SDimitry Andric getModule(), Init->getType(), 3228e8d8bef9SDimitry Andric /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 3229e8d8bef9SDimitry Andric if (supportsCOMDAT()) 3230e8d8bef9SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3231e8d8bef9SDimitry Andric Emitter.finalize(GV); 3232e8d8bef9SDimitry Andric 32330eae32dcSDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 3234e8d8bef9SDimitry Andric } 3235e8d8bef9SDimitry Andric 3236*0b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 3237*0b57cec5SDimitry Andric const AliasAttr *AA = VD->getAttr<AliasAttr>(); 3238*0b57cec5SDimitry Andric assert(AA && "No alias?"); 3239*0b57cec5SDimitry Andric 3240*0b57cec5SDimitry Andric CharUnits Alignment = getContext().getDeclAlign(VD); 3241*0b57cec5SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 3242*0b57cec5SDimitry Andric 3243*0b57cec5SDimitry Andric // See if there is already something with the target's name in the module. 3244*0b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 3245*0b57cec5SDimitry Andric if (Entry) { 3246bdd1243dSDimitry Andric unsigned AS = getTypes().getTargetAddressSpace(VD->getType()); 3247*0b57cec5SDimitry Andric auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 32480eae32dcSDimitry Andric return ConstantAddress(Ptr, DeclTy, Alignment); 3249*0b57cec5SDimitry Andric } 3250*0b57cec5SDimitry Andric 3251*0b57cec5SDimitry Andric llvm::Constant *Aliasee; 3252*0b57cec5SDimitry Andric if (isa<llvm::FunctionType>(DeclTy)) 3253*0b57cec5SDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 3254*0b57cec5SDimitry Andric GlobalDecl(cast<FunctionDecl>(VD)), 3255*0b57cec5SDimitry Andric /*ForVTable=*/false); 3256*0b57cec5SDimitry Andric else 3257349cc55cSDimitry Andric Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 3258349cc55cSDimitry Andric nullptr); 3259*0b57cec5SDimitry Andric 3260*0b57cec5SDimitry Andric auto *F = cast<llvm::GlobalValue>(Aliasee); 3261*0b57cec5SDimitry Andric F->setLinkage(llvm::Function::ExternalWeakLinkage); 3262*0b57cec5SDimitry Andric WeakRefReferences.insert(F); 3263*0b57cec5SDimitry Andric 32640eae32dcSDimitry Andric return ConstantAddress(Aliasee, DeclTy, Alignment); 3265*0b57cec5SDimitry Andric } 3266*0b57cec5SDimitry Andric 3267*0b57cec5SDimitry Andric void CodeGenModule::EmitGlobal(GlobalDecl GD) { 3268*0b57cec5SDimitry Andric const auto *Global = cast<ValueDecl>(GD.getDecl()); 3269*0b57cec5SDimitry Andric 3270*0b57cec5SDimitry Andric // Weak references don't produce any output by themselves. 3271*0b57cec5SDimitry Andric if (Global->hasAttr<WeakRefAttr>()) 3272*0b57cec5SDimitry Andric return; 3273*0b57cec5SDimitry Andric 3274*0b57cec5SDimitry Andric // If this is an alias definition (which otherwise looks like a declaration) 3275*0b57cec5SDimitry Andric // emit it now. 3276*0b57cec5SDimitry Andric if (Global->hasAttr<AliasAttr>()) 3277*0b57cec5SDimitry Andric return EmitAliasDefinition(GD); 3278*0b57cec5SDimitry Andric 3279*0b57cec5SDimitry Andric // IFunc like an alias whose value is resolved at runtime by calling resolver. 3280*0b57cec5SDimitry Andric if (Global->hasAttr<IFuncAttr>()) 3281*0b57cec5SDimitry Andric return emitIFuncDefinition(GD); 3282*0b57cec5SDimitry Andric 3283*0b57cec5SDimitry Andric // If this is a cpu_dispatch multiversion function, emit the resolver. 3284*0b57cec5SDimitry Andric if (Global->hasAttr<CPUDispatchAttr>()) 3285*0b57cec5SDimitry Andric return emitCPUDispatchDefinition(GD); 3286*0b57cec5SDimitry Andric 3287*0b57cec5SDimitry Andric // If this is CUDA, be selective about which declarations we emit. 3288*0b57cec5SDimitry Andric if (LangOpts.CUDA) { 3289*0b57cec5SDimitry Andric if (LangOpts.CUDAIsDevice) { 3290*0b57cec5SDimitry Andric if (!Global->hasAttr<CUDADeviceAttr>() && 3291*0b57cec5SDimitry Andric !Global->hasAttr<CUDAGlobalAttr>() && 3292*0b57cec5SDimitry Andric !Global->hasAttr<CUDAConstantAttr>() && 3293*0b57cec5SDimitry Andric !Global->hasAttr<CUDASharedAttr>() && 32945ffd83dbSDimitry Andric !Global->getType()->isCUDADeviceBuiltinSurfaceType() && 32955ffd83dbSDimitry Andric !Global->getType()->isCUDADeviceBuiltinTextureType()) 3296*0b57cec5SDimitry Andric return; 3297*0b57cec5SDimitry Andric } else { 3298*0b57cec5SDimitry Andric // We need to emit host-side 'shadows' for all global 3299*0b57cec5SDimitry Andric // device-side variables because the CUDA runtime needs their 3300*0b57cec5SDimitry Andric // size and host-side address in order to provide access to 3301*0b57cec5SDimitry Andric // their device-side incarnations. 3302*0b57cec5SDimitry Andric 3303*0b57cec5SDimitry Andric // So device-only functions are the only things we skip. 3304*0b57cec5SDimitry Andric if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 3305*0b57cec5SDimitry Andric Global->hasAttr<CUDADeviceAttr>()) 3306*0b57cec5SDimitry Andric return; 3307*0b57cec5SDimitry Andric 3308*0b57cec5SDimitry Andric assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 3309*0b57cec5SDimitry Andric "Expected Variable or Function"); 3310*0b57cec5SDimitry Andric } 3311*0b57cec5SDimitry Andric } 3312*0b57cec5SDimitry Andric 3313*0b57cec5SDimitry Andric if (LangOpts.OpenMP) { 3314a7dea167SDimitry Andric // If this is OpenMP, check if it is legal to emit this global normally. 3315*0b57cec5SDimitry Andric if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 3316*0b57cec5SDimitry Andric return; 3317*0b57cec5SDimitry Andric if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 3318*0b57cec5SDimitry Andric if (MustBeEmitted(Global)) 3319*0b57cec5SDimitry Andric EmitOMPDeclareReduction(DRD); 3320*0b57cec5SDimitry Andric return; 3321*0b57cec5SDimitry Andric } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) { 3322*0b57cec5SDimitry Andric if (MustBeEmitted(Global)) 3323*0b57cec5SDimitry Andric EmitOMPDeclareMapper(DMD); 3324*0b57cec5SDimitry Andric return; 3325*0b57cec5SDimitry Andric } 3326*0b57cec5SDimitry Andric } 3327*0b57cec5SDimitry Andric 3328*0b57cec5SDimitry Andric // Ignore declarations, they will be emitted on their first use. 3329*0b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 3330*0b57cec5SDimitry Andric // Forward declarations are emitted lazily on first use. 3331*0b57cec5SDimitry Andric if (!FD->doesThisDeclarationHaveABody()) { 3332*0b57cec5SDimitry Andric if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 3333*0b57cec5SDimitry Andric return; 3334*0b57cec5SDimitry Andric 3335*0b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 3336*0b57cec5SDimitry Andric 3337*0b57cec5SDimitry Andric // Compute the function info and LLVM type. 3338*0b57cec5SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 3339*0b57cec5SDimitry Andric llvm::Type *Ty = getTypes().GetFunctionType(FI); 3340*0b57cec5SDimitry Andric 3341*0b57cec5SDimitry Andric GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 3342*0b57cec5SDimitry Andric /*DontDefer=*/false); 3343*0b57cec5SDimitry Andric return; 3344*0b57cec5SDimitry Andric } 3345*0b57cec5SDimitry Andric } else { 3346*0b57cec5SDimitry Andric const auto *VD = cast<VarDecl>(Global); 3347*0b57cec5SDimitry Andric assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 3348*0b57cec5SDimitry Andric if (VD->isThisDeclarationADefinition() != VarDecl::Definition && 3349*0b57cec5SDimitry Andric !Context.isMSStaticDataMemberInlineDefinition(VD)) { 3350*0b57cec5SDimitry Andric if (LangOpts.OpenMP) { 3351*0b57cec5SDimitry Andric // Emit declaration of the must-be-emitted declare target variable. 3352bdd1243dSDimitry Andric if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 3353*0b57cec5SDimitry Andric OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 3354*0b57cec5SDimitry Andric bool UnifiedMemoryEnabled = 3355*0b57cec5SDimitry Andric getOpenMPRuntime().hasRequiresUnifiedSharedMemory(); 3356bdd1243dSDimitry Andric if ((*Res == OMPDeclareTargetDeclAttr::MT_To || 3357bdd1243dSDimitry Andric *Res == OMPDeclareTargetDeclAttr::MT_Enter) && 3358*0b57cec5SDimitry Andric !UnifiedMemoryEnabled) { 3359*0b57cec5SDimitry Andric (void)GetAddrOfGlobalVar(VD); 3360*0b57cec5SDimitry Andric } else { 3361*0b57cec5SDimitry Andric assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) || 3362bdd1243dSDimitry Andric ((*Res == OMPDeclareTargetDeclAttr::MT_To || 3363bdd1243dSDimitry Andric *Res == OMPDeclareTargetDeclAttr::MT_Enter) && 3364*0b57cec5SDimitry Andric UnifiedMemoryEnabled)) && 3365*0b57cec5SDimitry Andric "Link clause or to clause with unified memory expected."); 3366*0b57cec5SDimitry Andric (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD); 3367*0b57cec5SDimitry Andric } 3368*0b57cec5SDimitry Andric 3369*0b57cec5SDimitry Andric return; 3370*0b57cec5SDimitry Andric } 3371*0b57cec5SDimitry Andric } 3372*0b57cec5SDimitry Andric // If this declaration may have caused an inline variable definition to 3373*0b57cec5SDimitry Andric // change linkage, make sure that it's emitted. 3374*0b57cec5SDimitry Andric if (Context.getInlineVariableDefinitionKind(VD) == 3375*0b57cec5SDimitry Andric ASTContext::InlineVariableDefinitionKind::Strong) 3376*0b57cec5SDimitry Andric GetAddrOfGlobalVar(VD); 3377*0b57cec5SDimitry Andric return; 3378*0b57cec5SDimitry Andric } 3379*0b57cec5SDimitry Andric } 3380*0b57cec5SDimitry Andric 3381*0b57cec5SDimitry Andric // Defer code generation to first use when possible, e.g. if this is an inline 3382*0b57cec5SDimitry Andric // function. If the global must always be emitted, do it eagerly if possible 3383*0b57cec5SDimitry Andric // to benefit from cache locality. 3384*0b57cec5SDimitry Andric if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 3385*0b57cec5SDimitry Andric // Emit the definition if it can't be deferred. 3386*0b57cec5SDimitry Andric EmitGlobalDefinition(GD); 3387*0b57cec5SDimitry Andric return; 3388*0b57cec5SDimitry Andric } 3389*0b57cec5SDimitry Andric 3390*0b57cec5SDimitry Andric // If we're deferring emission of a C++ variable with an 3391*0b57cec5SDimitry Andric // initializer, remember the order in which it appeared in the file. 3392*0b57cec5SDimitry Andric if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 3393*0b57cec5SDimitry Andric cast<VarDecl>(Global)->hasInit()) { 3394*0b57cec5SDimitry Andric DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 3395*0b57cec5SDimitry Andric CXXGlobalInits.push_back(nullptr); 3396*0b57cec5SDimitry Andric } 3397*0b57cec5SDimitry Andric 3398*0b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 3399*0b57cec5SDimitry Andric if (GetGlobalValue(MangledName) != nullptr) { 3400*0b57cec5SDimitry Andric // The value has already been used and should therefore be emitted. 3401*0b57cec5SDimitry Andric addDeferredDeclToEmit(GD); 3402*0b57cec5SDimitry Andric } else if (MustBeEmitted(Global)) { 3403*0b57cec5SDimitry Andric // The value must be emitted, but cannot be emitted eagerly. 3404*0b57cec5SDimitry Andric assert(!MayBeEmittedEagerly(Global)); 3405*0b57cec5SDimitry Andric addDeferredDeclToEmit(GD); 3406bdd1243dSDimitry Andric EmittedDeferredDecls[MangledName] = GD; 3407*0b57cec5SDimitry Andric } else { 3408*0b57cec5SDimitry Andric // Otherwise, remember that we saw a deferred decl with this name. The 3409*0b57cec5SDimitry Andric // first use of the mangled name will cause it to move into 3410*0b57cec5SDimitry Andric // DeferredDeclsToEmit. 3411*0b57cec5SDimitry Andric DeferredDecls[MangledName] = GD; 3412*0b57cec5SDimitry Andric } 3413*0b57cec5SDimitry Andric } 3414*0b57cec5SDimitry Andric 3415*0b57cec5SDimitry Andric // Check if T is a class type with a destructor that's not dllimport. 3416*0b57cec5SDimitry Andric static bool HasNonDllImportDtor(QualType T) { 3417*0b57cec5SDimitry Andric if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) 3418*0b57cec5SDimitry Andric if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 3419*0b57cec5SDimitry Andric if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) 3420*0b57cec5SDimitry Andric return true; 3421*0b57cec5SDimitry Andric 3422*0b57cec5SDimitry Andric return false; 3423*0b57cec5SDimitry Andric } 3424*0b57cec5SDimitry Andric 3425*0b57cec5SDimitry Andric namespace { 3426*0b57cec5SDimitry Andric struct FunctionIsDirectlyRecursive 3427*0b57cec5SDimitry Andric : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> { 3428*0b57cec5SDimitry Andric const StringRef Name; 3429*0b57cec5SDimitry Andric const Builtin::Context &BI; 3430*0b57cec5SDimitry Andric FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) 3431*0b57cec5SDimitry Andric : Name(N), BI(C) {} 3432*0b57cec5SDimitry Andric 3433*0b57cec5SDimitry Andric bool VisitCallExpr(const CallExpr *E) { 3434*0b57cec5SDimitry Andric const FunctionDecl *FD = E->getDirectCallee(); 3435*0b57cec5SDimitry Andric if (!FD) 3436*0b57cec5SDimitry Andric return false; 3437*0b57cec5SDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 3438*0b57cec5SDimitry Andric if (Attr && Name == Attr->getLabel()) 3439*0b57cec5SDimitry Andric return true; 3440*0b57cec5SDimitry Andric unsigned BuiltinID = FD->getBuiltinID(); 3441*0b57cec5SDimitry Andric if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 3442*0b57cec5SDimitry Andric return false; 3443*0b57cec5SDimitry Andric StringRef BuiltinName = BI.getName(BuiltinID); 3444*0b57cec5SDimitry Andric if (BuiltinName.startswith("__builtin_") && 3445*0b57cec5SDimitry Andric Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 3446*0b57cec5SDimitry Andric return true; 3447*0b57cec5SDimitry Andric } 3448*0b57cec5SDimitry Andric return false; 3449*0b57cec5SDimitry Andric } 3450*0b57cec5SDimitry Andric 3451*0b57cec5SDimitry Andric bool VisitStmt(const Stmt *S) { 3452*0b57cec5SDimitry Andric for (const Stmt *Child : S->children()) 3453*0b57cec5SDimitry Andric if (Child && this->Visit(Child)) 3454*0b57cec5SDimitry Andric return true; 3455*0b57cec5SDimitry Andric return false; 3456*0b57cec5SDimitry Andric } 3457*0b57cec5SDimitry Andric }; 3458*0b57cec5SDimitry Andric 3459*0b57cec5SDimitry Andric // Make sure we're not referencing non-imported vars or functions. 3460*0b57cec5SDimitry Andric struct DLLImportFunctionVisitor 3461*0b57cec5SDimitry Andric : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 3462*0b57cec5SDimitry Andric bool SafeToInline = true; 3463*0b57cec5SDimitry Andric 3464*0b57cec5SDimitry Andric bool shouldVisitImplicitCode() const { return true; } 3465*0b57cec5SDimitry Andric 3466*0b57cec5SDimitry Andric bool VisitVarDecl(VarDecl *VD) { 3467*0b57cec5SDimitry Andric if (VD->getTLSKind()) { 3468*0b57cec5SDimitry Andric // A thread-local variable cannot be imported. 3469*0b57cec5SDimitry Andric SafeToInline = false; 3470*0b57cec5SDimitry Andric return SafeToInline; 3471*0b57cec5SDimitry Andric } 3472*0b57cec5SDimitry Andric 3473*0b57cec5SDimitry Andric // A variable definition might imply a destructor call. 3474*0b57cec5SDimitry Andric if (VD->isThisDeclarationADefinition()) 3475*0b57cec5SDimitry Andric SafeToInline = !HasNonDllImportDtor(VD->getType()); 3476*0b57cec5SDimitry Andric 3477*0b57cec5SDimitry Andric return SafeToInline; 3478*0b57cec5SDimitry Andric } 3479*0b57cec5SDimitry Andric 3480*0b57cec5SDimitry Andric bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 3481*0b57cec5SDimitry Andric if (const auto *D = E->getTemporary()->getDestructor()) 3482*0b57cec5SDimitry Andric SafeToInline = D->hasAttr<DLLImportAttr>(); 3483*0b57cec5SDimitry Andric return SafeToInline; 3484*0b57cec5SDimitry Andric } 3485*0b57cec5SDimitry Andric 3486*0b57cec5SDimitry Andric bool VisitDeclRefExpr(DeclRefExpr *E) { 3487*0b57cec5SDimitry Andric ValueDecl *VD = E->getDecl(); 3488*0b57cec5SDimitry Andric if (isa<FunctionDecl>(VD)) 3489*0b57cec5SDimitry Andric SafeToInline = VD->hasAttr<DLLImportAttr>(); 3490*0b57cec5SDimitry Andric else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 3491*0b57cec5SDimitry Andric SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 3492*0b57cec5SDimitry Andric return SafeToInline; 3493*0b57cec5SDimitry Andric } 3494*0b57cec5SDimitry Andric 3495*0b57cec5SDimitry Andric bool VisitCXXConstructExpr(CXXConstructExpr *E) { 3496*0b57cec5SDimitry Andric SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); 3497*0b57cec5SDimitry Andric return SafeToInline; 3498*0b57cec5SDimitry Andric } 3499*0b57cec5SDimitry Andric 3500*0b57cec5SDimitry Andric bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3501*0b57cec5SDimitry Andric CXXMethodDecl *M = E->getMethodDecl(); 3502*0b57cec5SDimitry Andric if (!M) { 3503*0b57cec5SDimitry Andric // Call through a pointer to member function. This is safe to inline. 3504*0b57cec5SDimitry Andric SafeToInline = true; 3505*0b57cec5SDimitry Andric } else { 3506*0b57cec5SDimitry Andric SafeToInline = M->hasAttr<DLLImportAttr>(); 3507*0b57cec5SDimitry Andric } 3508*0b57cec5SDimitry Andric return SafeToInline; 3509*0b57cec5SDimitry Andric } 3510*0b57cec5SDimitry Andric 3511*0b57cec5SDimitry Andric bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 3512*0b57cec5SDimitry Andric SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 3513*0b57cec5SDimitry Andric return SafeToInline; 3514*0b57cec5SDimitry Andric } 3515*0b57cec5SDimitry Andric 3516*0b57cec5SDimitry Andric bool VisitCXXNewExpr(CXXNewExpr *E) { 3517*0b57cec5SDimitry Andric SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 3518*0b57cec5SDimitry Andric return SafeToInline; 3519*0b57cec5SDimitry Andric } 3520*0b57cec5SDimitry Andric }; 3521*0b57cec5SDimitry Andric } 3522*0b57cec5SDimitry Andric 3523*0b57cec5SDimitry Andric // isTriviallyRecursive - Check if this function calls another 3524*0b57cec5SDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin, 3525*0b57cec5SDimitry Andric // ends up pointing to itself. 3526*0b57cec5SDimitry Andric bool 3527*0b57cec5SDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 3528*0b57cec5SDimitry Andric StringRef Name; 3529*0b57cec5SDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 3530*0b57cec5SDimitry Andric // asm labels are a special kind of mangling we have to support. 3531*0b57cec5SDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 3532*0b57cec5SDimitry Andric if (!Attr) 3533*0b57cec5SDimitry Andric return false; 3534*0b57cec5SDimitry Andric Name = Attr->getLabel(); 3535*0b57cec5SDimitry Andric } else { 3536*0b57cec5SDimitry Andric Name = FD->getName(); 3537*0b57cec5SDimitry Andric } 3538*0b57cec5SDimitry Andric 3539*0b57cec5SDimitry Andric FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 3540*0b57cec5SDimitry Andric const Stmt *Body = FD->getBody(); 3541*0b57cec5SDimitry Andric return Body ? Walker.Visit(Body) : false; 3542*0b57cec5SDimitry Andric } 3543*0b57cec5SDimitry Andric 3544*0b57cec5SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 3545*0b57cec5SDimitry Andric if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 3546*0b57cec5SDimitry Andric return true; 3547*0b57cec5SDimitry Andric const auto *F = cast<FunctionDecl>(GD.getDecl()); 3548*0b57cec5SDimitry Andric if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 3549*0b57cec5SDimitry Andric return false; 3550*0b57cec5SDimitry Andric 3551fe6060f1SDimitry Andric if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) { 3552*0b57cec5SDimitry Andric // Check whether it would be safe to inline this dllimport function. 3553*0b57cec5SDimitry Andric DLLImportFunctionVisitor Visitor; 3554*0b57cec5SDimitry Andric Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 3555*0b57cec5SDimitry Andric if (!Visitor.SafeToInline) 3556*0b57cec5SDimitry Andric return false; 3557*0b57cec5SDimitry Andric 3558*0b57cec5SDimitry Andric if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { 3559*0b57cec5SDimitry Andric // Implicit destructor invocations aren't captured in the AST, so the 3560*0b57cec5SDimitry Andric // check above can't see them. Check for them manually here. 3561*0b57cec5SDimitry Andric for (const Decl *Member : Dtor->getParent()->decls()) 3562*0b57cec5SDimitry Andric if (isa<FieldDecl>(Member)) 3563*0b57cec5SDimitry Andric if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) 3564*0b57cec5SDimitry Andric return false; 3565*0b57cec5SDimitry Andric for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) 3566*0b57cec5SDimitry Andric if (HasNonDllImportDtor(B.getType())) 3567*0b57cec5SDimitry Andric return false; 3568*0b57cec5SDimitry Andric } 3569*0b57cec5SDimitry Andric } 3570*0b57cec5SDimitry Andric 3571349cc55cSDimitry Andric // Inline builtins declaration must be emitted. They often are fortified 3572349cc55cSDimitry Andric // functions. 3573349cc55cSDimitry Andric if (F->isInlineBuiltinDeclaration()) 3574349cc55cSDimitry Andric return true; 3575349cc55cSDimitry Andric 3576*0b57cec5SDimitry Andric // PR9614. Avoid cases where the source code is lying to us. An available 3577*0b57cec5SDimitry Andric // externally function should have an equivalent function somewhere else, 35785ffd83dbSDimitry Andric // but a function that calls itself through asm label/`__builtin_` trickery is 35795ffd83dbSDimitry Andric // clearly not equivalent to the real implementation. 3580*0b57cec5SDimitry Andric // This happens in glibc's btowc and in some configure checks. 3581*0b57cec5SDimitry Andric return !isTriviallyRecursive(F); 3582*0b57cec5SDimitry Andric } 3583*0b57cec5SDimitry Andric 3584*0b57cec5SDimitry Andric bool CodeGenModule::shouldOpportunisticallyEmitVTables() { 3585*0b57cec5SDimitry Andric return CodeGenOpts.OptimizationLevel > 0; 3586*0b57cec5SDimitry Andric } 3587*0b57cec5SDimitry Andric 3588*0b57cec5SDimitry Andric void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD, 3589*0b57cec5SDimitry Andric llvm::GlobalValue *GV) { 3590*0b57cec5SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3591*0b57cec5SDimitry Andric 3592*0b57cec5SDimitry Andric if (FD->isCPUSpecificMultiVersion()) { 3593*0b57cec5SDimitry Andric auto *Spec = FD->getAttr<CPUSpecificAttr>(); 3594*0b57cec5SDimitry Andric for (unsigned I = 0; I < Spec->cpus_size(); ++I) 3595*0b57cec5SDimitry Andric EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); 35964824e7fdSDimitry Andric } else if (FD->isTargetClonesMultiVersion()) { 35974824e7fdSDimitry Andric auto *Clone = FD->getAttr<TargetClonesAttr>(); 35984824e7fdSDimitry Andric for (unsigned I = 0; I < Clone->featuresStrs_size(); ++I) 35994824e7fdSDimitry Andric if (Clone->isFirstOfVersion(I)) 36004824e7fdSDimitry Andric EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); 360181ad6265SDimitry Andric // Ensure that the resolver function is also emitted. 360281ad6265SDimitry Andric GetOrCreateMultiVersionResolver(GD); 3603*0b57cec5SDimitry Andric } else 3604*0b57cec5SDimitry Andric EmitGlobalFunctionDefinition(GD, GV); 3605*0b57cec5SDimitry Andric } 3606*0b57cec5SDimitry Andric 3607*0b57cec5SDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 3608*0b57cec5SDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 3609*0b57cec5SDimitry Andric 3610*0b57cec5SDimitry Andric PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 3611*0b57cec5SDimitry Andric Context.getSourceManager(), 3612*0b57cec5SDimitry Andric "Generating code for declaration"); 3613*0b57cec5SDimitry Andric 3614*0b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 3615*0b57cec5SDimitry Andric // At -O0, don't generate IR for functions with available_externally 3616*0b57cec5SDimitry Andric // linkage. 3617*0b57cec5SDimitry Andric if (!shouldEmitFunction(GD)) 3618*0b57cec5SDimitry Andric return; 3619*0b57cec5SDimitry Andric 3620*0b57cec5SDimitry Andric llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() { 3621*0b57cec5SDimitry Andric std::string Name; 3622*0b57cec5SDimitry Andric llvm::raw_string_ostream OS(Name); 3623*0b57cec5SDimitry Andric FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(), 3624*0b57cec5SDimitry Andric /*Qualified=*/true); 3625*0b57cec5SDimitry Andric return Name; 3626*0b57cec5SDimitry Andric }); 3627*0b57cec5SDimitry Andric 3628*0b57cec5SDimitry Andric if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 3629*0b57cec5SDimitry Andric // Make sure to emit the definition(s) before we emit the thunks. 3630*0b57cec5SDimitry Andric // This is necessary for the generation of certain thunks. 3631*0b57cec5SDimitry Andric if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method)) 3632*0b57cec5SDimitry Andric ABI->emitCXXStructor(GD); 3633*0b57cec5SDimitry Andric else if (FD->isMultiVersion()) 3634*0b57cec5SDimitry Andric EmitMultiVersionFunctionDefinition(GD, GV); 3635*0b57cec5SDimitry Andric else 3636*0b57cec5SDimitry Andric EmitGlobalFunctionDefinition(GD, GV); 3637*0b57cec5SDimitry Andric 3638*0b57cec5SDimitry Andric if (Method->isVirtual()) 3639*0b57cec5SDimitry Andric getVTables().EmitThunks(GD); 3640*0b57cec5SDimitry Andric 3641*0b57cec5SDimitry Andric return; 3642*0b57cec5SDimitry Andric } 3643*0b57cec5SDimitry Andric 3644*0b57cec5SDimitry Andric if (FD->isMultiVersion()) 3645*0b57cec5SDimitry Andric return EmitMultiVersionFunctionDefinition(GD, GV); 3646*0b57cec5SDimitry Andric return EmitGlobalFunctionDefinition(GD, GV); 3647*0b57cec5SDimitry Andric } 3648*0b57cec5SDimitry Andric 3649*0b57cec5SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 3650*0b57cec5SDimitry Andric return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 3651*0b57cec5SDimitry Andric 3652*0b57cec5SDimitry Andric llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 3653*0b57cec5SDimitry Andric } 3654*0b57cec5SDimitry Andric 3655*0b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 3656*0b57cec5SDimitry Andric llvm::Function *NewFn); 3657*0b57cec5SDimitry Andric 3658*0b57cec5SDimitry Andric static unsigned 3659*0b57cec5SDimitry Andric TargetMVPriority(const TargetInfo &TI, 3660*0b57cec5SDimitry Andric const CodeGenFunction::MultiVersionResolverOption &RO) { 3661*0b57cec5SDimitry Andric unsigned Priority = 0; 3662bdd1243dSDimitry Andric unsigned NumFeatures = 0; 3663bdd1243dSDimitry Andric for (StringRef Feat : RO.Conditions.Features) { 3664*0b57cec5SDimitry Andric Priority = std::max(Priority, TI.multiVersionSortPriority(Feat)); 3665bdd1243dSDimitry Andric NumFeatures++; 3666bdd1243dSDimitry Andric } 3667*0b57cec5SDimitry Andric 3668*0b57cec5SDimitry Andric if (!RO.Conditions.Architecture.empty()) 3669*0b57cec5SDimitry Andric Priority = std::max( 3670*0b57cec5SDimitry Andric Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture)); 3671bdd1243dSDimitry Andric 3672bdd1243dSDimitry Andric Priority += TI.multiVersionFeatureCost() * NumFeatures; 3673bdd1243dSDimitry Andric 3674*0b57cec5SDimitry Andric return Priority; 3675*0b57cec5SDimitry Andric } 3676*0b57cec5SDimitry Andric 3677349cc55cSDimitry Andric // Multiversion functions should be at most 'WeakODRLinkage' so that a different 3678349cc55cSDimitry Andric // TU can forward declare the function without causing problems. Particularly 3679349cc55cSDimitry Andric // in the cases of CPUDispatch, this causes issues. This also makes sure we 3680349cc55cSDimitry Andric // work with internal linkage functions, so that the same function name can be 3681349cc55cSDimitry Andric // used with internal linkage in multiple TUs. 3682349cc55cSDimitry Andric llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM, 3683349cc55cSDimitry Andric GlobalDecl GD) { 3684349cc55cSDimitry Andric const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 3685349cc55cSDimitry Andric if (FD->getFormalLinkage() == InternalLinkage) 3686349cc55cSDimitry Andric return llvm::GlobalValue::InternalLinkage; 3687349cc55cSDimitry Andric return llvm::GlobalValue::WeakODRLinkage; 3688349cc55cSDimitry Andric } 3689349cc55cSDimitry Andric 3690*0b57cec5SDimitry Andric void CodeGenModule::emitMultiVersionFunctions() { 3691fe6060f1SDimitry Andric std::vector<GlobalDecl> MVFuncsToEmit; 3692fe6060f1SDimitry Andric MultiVersionFuncs.swap(MVFuncsToEmit); 3693fe6060f1SDimitry Andric for (GlobalDecl GD : MVFuncsToEmit) { 369481ad6265SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 369581ad6265SDimitry Andric assert(FD && "Expected a FunctionDecl"); 369681ad6265SDimitry Andric 3697*0b57cec5SDimitry Andric SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 369881ad6265SDimitry Andric if (FD->isTargetMultiVersion()) { 3699*0b57cec5SDimitry Andric getContext().forEachMultiversionedFunctionVersion( 3700*0b57cec5SDimitry Andric FD, [this, &GD, &Options](const FunctionDecl *CurFD) { 3701*0b57cec5SDimitry Andric GlobalDecl CurGD{ 3702*0b57cec5SDimitry Andric (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)}; 3703*0b57cec5SDimitry Andric StringRef MangledName = getMangledName(CurGD); 3704*0b57cec5SDimitry Andric llvm::Constant *Func = GetGlobalValue(MangledName); 3705*0b57cec5SDimitry Andric if (!Func) { 3706*0b57cec5SDimitry Andric if (CurFD->isDefined()) { 3707*0b57cec5SDimitry Andric EmitGlobalFunctionDefinition(CurGD, nullptr); 3708*0b57cec5SDimitry Andric Func = GetGlobalValue(MangledName); 3709*0b57cec5SDimitry Andric } else { 3710*0b57cec5SDimitry Andric const CGFunctionInfo &FI = 3711*0b57cec5SDimitry Andric getTypes().arrangeGlobalDeclaration(GD); 3712*0b57cec5SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 3713*0b57cec5SDimitry Andric Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, 3714*0b57cec5SDimitry Andric /*DontDefer=*/false, ForDefinition); 3715*0b57cec5SDimitry Andric } 3716*0b57cec5SDimitry Andric assert(Func && "This should have just been created"); 3717*0b57cec5SDimitry Andric } 3718bdd1243dSDimitry Andric if (CurFD->getMultiVersionKind() == MultiVersionKind::Target) { 3719*0b57cec5SDimitry Andric const auto *TA = CurFD->getAttr<TargetAttr>(); 3720*0b57cec5SDimitry Andric llvm::SmallVector<StringRef, 8> Feats; 3721*0b57cec5SDimitry Andric TA->getAddedFeatures(Feats); 3722*0b57cec5SDimitry Andric Options.emplace_back(cast<llvm::Function>(Func), 3723*0b57cec5SDimitry Andric TA->getArchitecture(), Feats); 3724bdd1243dSDimitry Andric } else { 3725bdd1243dSDimitry Andric const auto *TVA = CurFD->getAttr<TargetVersionAttr>(); 3726bdd1243dSDimitry Andric llvm::SmallVector<StringRef, 8> Feats; 3727bdd1243dSDimitry Andric TVA->getFeatures(Feats); 3728bdd1243dSDimitry Andric Options.emplace_back(cast<llvm::Function>(Func), 3729bdd1243dSDimitry Andric /*Architecture*/ "", Feats); 3730bdd1243dSDimitry Andric } 3731*0b57cec5SDimitry Andric }); 373281ad6265SDimitry Andric } else if (FD->isTargetClonesMultiVersion()) { 373381ad6265SDimitry Andric const auto *TC = FD->getAttr<TargetClonesAttr>(); 373481ad6265SDimitry Andric for (unsigned VersionIndex = 0; VersionIndex < TC->featuresStrs_size(); 373581ad6265SDimitry Andric ++VersionIndex) { 373681ad6265SDimitry Andric if (!TC->isFirstOfVersion(VersionIndex)) 373781ad6265SDimitry Andric continue; 373881ad6265SDimitry Andric GlobalDecl CurGD{(FD->isDefined() ? FD->getDefinition() : FD), 373981ad6265SDimitry Andric VersionIndex}; 374081ad6265SDimitry Andric StringRef Version = TC->getFeatureStr(VersionIndex); 374181ad6265SDimitry Andric StringRef MangledName = getMangledName(CurGD); 374281ad6265SDimitry Andric llvm::Constant *Func = GetGlobalValue(MangledName); 374381ad6265SDimitry Andric if (!Func) { 374481ad6265SDimitry Andric if (FD->isDefined()) { 374581ad6265SDimitry Andric EmitGlobalFunctionDefinition(CurGD, nullptr); 374681ad6265SDimitry Andric Func = GetGlobalValue(MangledName); 3747a7dea167SDimitry Andric } else { 374881ad6265SDimitry Andric const CGFunctionInfo &FI = 374981ad6265SDimitry Andric getTypes().arrangeGlobalDeclaration(CurGD); 375081ad6265SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 375181ad6265SDimitry Andric Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, 375281ad6265SDimitry Andric /*DontDefer=*/false, ForDefinition); 3753a7dea167SDimitry Andric } 375481ad6265SDimitry Andric assert(Func && "This should have just been created"); 375581ad6265SDimitry Andric } 375681ad6265SDimitry Andric 375781ad6265SDimitry Andric StringRef Architecture; 375881ad6265SDimitry Andric llvm::SmallVector<StringRef, 1> Feature; 375981ad6265SDimitry Andric 3760bdd1243dSDimitry Andric if (getTarget().getTriple().isAArch64()) { 3761bdd1243dSDimitry Andric if (Version != "default") { 3762bdd1243dSDimitry Andric llvm::SmallVector<StringRef, 8> VerFeats; 3763bdd1243dSDimitry Andric Version.split(VerFeats, "+"); 3764bdd1243dSDimitry Andric for (auto &CurFeat : VerFeats) 3765bdd1243dSDimitry Andric Feature.push_back(CurFeat.trim()); 3766bdd1243dSDimitry Andric } 3767bdd1243dSDimitry Andric } else { 376881ad6265SDimitry Andric if (Version.startswith("arch=")) 376981ad6265SDimitry Andric Architecture = Version.drop_front(sizeof("arch=") - 1); 377081ad6265SDimitry Andric else if (Version != "default") 377181ad6265SDimitry Andric Feature.push_back(Version); 3772bdd1243dSDimitry Andric } 377381ad6265SDimitry Andric 377481ad6265SDimitry Andric Options.emplace_back(cast<llvm::Function>(Func), Architecture, Feature); 377581ad6265SDimitry Andric } 377681ad6265SDimitry Andric } else { 377781ad6265SDimitry Andric assert(0 && "Expected a target or target_clones multiversion function"); 377881ad6265SDimitry Andric continue; 377981ad6265SDimitry Andric } 378081ad6265SDimitry Andric 378181ad6265SDimitry Andric llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD); 378281ad6265SDimitry Andric if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) 378381ad6265SDimitry Andric ResolverConstant = IFunc->getResolver(); 378481ad6265SDimitry Andric llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant); 378581ad6265SDimitry Andric 378681ad6265SDimitry Andric ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD)); 3787*0b57cec5SDimitry Andric 3788*0b57cec5SDimitry Andric if (supportsCOMDAT()) 3789*0b57cec5SDimitry Andric ResolverFunc->setComdat( 3790*0b57cec5SDimitry Andric getModule().getOrInsertComdat(ResolverFunc->getName())); 3791*0b57cec5SDimitry Andric 379281ad6265SDimitry Andric const TargetInfo &TI = getTarget(); 3793*0b57cec5SDimitry Andric llvm::stable_sort( 3794*0b57cec5SDimitry Andric Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS, 3795*0b57cec5SDimitry Andric const CodeGenFunction::MultiVersionResolverOption &RHS) { 3796*0b57cec5SDimitry Andric return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS); 3797*0b57cec5SDimitry Andric }); 3798*0b57cec5SDimitry Andric CodeGenFunction CGF(*this); 3799*0b57cec5SDimitry Andric CGF.EmitMultiVersionResolver(ResolverFunc, Options); 3800*0b57cec5SDimitry Andric } 3801fe6060f1SDimitry Andric 3802fe6060f1SDimitry Andric // Ensure that any additions to the deferred decls list caused by emitting a 3803fe6060f1SDimitry Andric // variant are emitted. This can happen when the variant itself is inline and 3804fe6060f1SDimitry Andric // calls a function without linkage. 3805fe6060f1SDimitry Andric if (!MVFuncsToEmit.empty()) 3806fe6060f1SDimitry Andric EmitDeferred(); 3807fe6060f1SDimitry Andric 3808fe6060f1SDimitry Andric // Ensure that any additions to the multiversion funcs list from either the 3809fe6060f1SDimitry Andric // deferred decls or the multiversion functions themselves are emitted. 3810fe6060f1SDimitry Andric if (!MultiVersionFuncs.empty()) 3811fe6060f1SDimitry Andric emitMultiVersionFunctions(); 3812*0b57cec5SDimitry Andric } 3813*0b57cec5SDimitry Andric 3814*0b57cec5SDimitry Andric void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) { 3815*0b57cec5SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3816*0b57cec5SDimitry Andric assert(FD && "Not a FunctionDecl?"); 381704eeddc0SDimitry Andric assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?"); 3818*0b57cec5SDimitry Andric const auto *DD = FD->getAttr<CPUDispatchAttr>(); 3819*0b57cec5SDimitry Andric assert(DD && "Not a cpu_dispatch Function?"); 3820*0b57cec5SDimitry Andric 382181ad6265SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 382281ad6265SDimitry Andric llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI); 3823*0b57cec5SDimitry Andric 3824*0b57cec5SDimitry Andric StringRef ResolverName = getMangledName(GD); 382504eeddc0SDimitry Andric UpdateMultiVersionNames(GD, FD, ResolverName); 3826*0b57cec5SDimitry Andric 3827*0b57cec5SDimitry Andric llvm::Type *ResolverType; 3828*0b57cec5SDimitry Andric GlobalDecl ResolverGD; 382904eeddc0SDimitry Andric if (getTarget().supportsIFunc()) { 3830*0b57cec5SDimitry Andric ResolverType = llvm::FunctionType::get( 3831*0b57cec5SDimitry Andric llvm::PointerType::get(DeclTy, 3832bdd1243dSDimitry Andric getTypes().getTargetAddressSpace(FD->getType())), 3833*0b57cec5SDimitry Andric false); 383404eeddc0SDimitry Andric } 3835*0b57cec5SDimitry Andric else { 3836*0b57cec5SDimitry Andric ResolverType = DeclTy; 3837*0b57cec5SDimitry Andric ResolverGD = GD; 3838*0b57cec5SDimitry Andric } 3839*0b57cec5SDimitry Andric 3840*0b57cec5SDimitry Andric auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction( 3841*0b57cec5SDimitry Andric ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false)); 3842349cc55cSDimitry Andric ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD)); 3843a7dea167SDimitry Andric if (supportsCOMDAT()) 3844a7dea167SDimitry Andric ResolverFunc->setComdat( 3845a7dea167SDimitry Andric getModule().getOrInsertComdat(ResolverFunc->getName())); 3846*0b57cec5SDimitry Andric 3847*0b57cec5SDimitry Andric SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 3848*0b57cec5SDimitry Andric const TargetInfo &Target = getTarget(); 3849*0b57cec5SDimitry Andric unsigned Index = 0; 3850*0b57cec5SDimitry Andric for (const IdentifierInfo *II : DD->cpus()) { 3851*0b57cec5SDimitry Andric // Get the name of the target function so we can look it up/create it. 3852*0b57cec5SDimitry Andric std::string MangledName = getMangledNameImpl(*this, GD, FD, true) + 3853*0b57cec5SDimitry Andric getCPUSpecificMangling(*this, II->getName()); 3854*0b57cec5SDimitry Andric 3855*0b57cec5SDimitry Andric llvm::Constant *Func = GetGlobalValue(MangledName); 3856*0b57cec5SDimitry Andric 3857*0b57cec5SDimitry Andric if (!Func) { 3858*0b57cec5SDimitry Andric GlobalDecl ExistingDecl = Manglings.lookup(MangledName); 3859*0b57cec5SDimitry Andric if (ExistingDecl.getDecl() && 3860*0b57cec5SDimitry Andric ExistingDecl.getDecl()->getAsFunction()->isDefined()) { 3861*0b57cec5SDimitry Andric EmitGlobalFunctionDefinition(ExistingDecl, nullptr); 3862*0b57cec5SDimitry Andric Func = GetGlobalValue(MangledName); 3863*0b57cec5SDimitry Andric } else { 3864*0b57cec5SDimitry Andric if (!ExistingDecl.getDecl()) 3865*0b57cec5SDimitry Andric ExistingDecl = GD.getWithMultiVersionIndex(Index); 3866*0b57cec5SDimitry Andric 3867*0b57cec5SDimitry Andric Func = GetOrCreateLLVMFunction( 3868*0b57cec5SDimitry Andric MangledName, DeclTy, ExistingDecl, 3869*0b57cec5SDimitry Andric /*ForVTable=*/false, /*DontDefer=*/true, 3870*0b57cec5SDimitry Andric /*IsThunk=*/false, llvm::AttributeList(), ForDefinition); 3871*0b57cec5SDimitry Andric } 3872*0b57cec5SDimitry Andric } 3873*0b57cec5SDimitry Andric 3874*0b57cec5SDimitry Andric llvm::SmallVector<StringRef, 32> Features; 3875*0b57cec5SDimitry Andric Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features); 3876*0b57cec5SDimitry Andric llvm::transform(Features, Features.begin(), 3877*0b57cec5SDimitry Andric [](StringRef Str) { return Str.substr(1); }); 3878349cc55cSDimitry Andric llvm::erase_if(Features, [&Target](StringRef Feat) { 3879*0b57cec5SDimitry Andric return !Target.validateCpuSupports(Feat); 3880349cc55cSDimitry Andric }); 3881*0b57cec5SDimitry Andric Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features); 3882*0b57cec5SDimitry Andric ++Index; 3883*0b57cec5SDimitry Andric } 3884*0b57cec5SDimitry Andric 3885fe6060f1SDimitry Andric llvm::stable_sort( 3886*0b57cec5SDimitry Andric Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS, 3887*0b57cec5SDimitry Andric const CodeGenFunction::MultiVersionResolverOption &RHS) { 3888349cc55cSDimitry Andric return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) > 3889349cc55cSDimitry Andric llvm::X86::getCpuSupportsMask(RHS.Conditions.Features); 3890*0b57cec5SDimitry Andric }); 3891*0b57cec5SDimitry Andric 3892*0b57cec5SDimitry Andric // If the list contains multiple 'default' versions, such as when it contains 3893*0b57cec5SDimitry Andric // 'pentium' and 'generic', don't emit the call to the generic one (since we 3894*0b57cec5SDimitry Andric // always run on at least a 'pentium'). We do this by deleting the 'least 3895*0b57cec5SDimitry Andric // advanced' (read, lowest mangling letter). 3896*0b57cec5SDimitry Andric while (Options.size() > 1 && 3897349cc55cSDimitry Andric llvm::X86::getCpuSupportsMask( 3898*0b57cec5SDimitry Andric (Options.end() - 2)->Conditions.Features) == 0) { 3899*0b57cec5SDimitry Andric StringRef LHSName = (Options.end() - 2)->Function->getName(); 3900*0b57cec5SDimitry Andric StringRef RHSName = (Options.end() - 1)->Function->getName(); 3901*0b57cec5SDimitry Andric if (LHSName.compare(RHSName) < 0) 3902*0b57cec5SDimitry Andric Options.erase(Options.end() - 2); 3903*0b57cec5SDimitry Andric else 3904*0b57cec5SDimitry Andric Options.erase(Options.end() - 1); 3905*0b57cec5SDimitry Andric } 3906*0b57cec5SDimitry Andric 3907*0b57cec5SDimitry Andric CodeGenFunction CGF(*this); 3908*0b57cec5SDimitry Andric CGF.EmitMultiVersionResolver(ResolverFunc, Options); 3909a7dea167SDimitry Andric 3910a7dea167SDimitry Andric if (getTarget().supportsIFunc()) { 391181ad6265SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = getMultiversionLinkage(*this, GD); 391281ad6265SDimitry Andric auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD)); 391381ad6265SDimitry Andric 391481ad6265SDimitry Andric // Fix up function declarations that were created for cpu_specific before 391581ad6265SDimitry Andric // cpu_dispatch was known 391681ad6265SDimitry Andric if (!isa<llvm::GlobalIFunc>(IFunc)) { 391781ad6265SDimitry Andric assert(cast<llvm::Function>(IFunc)->isDeclaration()); 391881ad6265SDimitry Andric auto *GI = llvm::GlobalIFunc::create(DeclTy, 0, Linkage, "", ResolverFunc, 391981ad6265SDimitry Andric &getModule()); 392081ad6265SDimitry Andric GI->takeName(IFunc); 392181ad6265SDimitry Andric IFunc->replaceAllUsesWith(GI); 392281ad6265SDimitry Andric IFunc->eraseFromParent(); 392381ad6265SDimitry Andric IFunc = GI; 392481ad6265SDimitry Andric } 392581ad6265SDimitry Andric 3926a7dea167SDimitry Andric std::string AliasName = getMangledNameImpl( 3927a7dea167SDimitry Andric *this, GD, FD, /*OmitMultiVersionMangling=*/true); 3928a7dea167SDimitry Andric llvm::Constant *AliasFunc = GetGlobalValue(AliasName); 3929a7dea167SDimitry Andric if (!AliasFunc) { 393081ad6265SDimitry Andric auto *GA = llvm::GlobalAlias::create(DeclTy, 0, Linkage, AliasName, IFunc, 393181ad6265SDimitry Andric &getModule()); 3932a7dea167SDimitry Andric SetCommonAttributes(GD, GA); 3933a7dea167SDimitry Andric } 3934a7dea167SDimitry Andric } 3935*0b57cec5SDimitry Andric } 3936*0b57cec5SDimitry Andric 3937*0b57cec5SDimitry Andric /// If a dispatcher for the specified mangled name is not in the module, create 3938*0b57cec5SDimitry Andric /// and return an llvm Function with the specified type. 393981ad6265SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) { 394081ad6265SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 394181ad6265SDimitry Andric assert(FD && "Not a FunctionDecl?"); 394281ad6265SDimitry Andric 3943*0b57cec5SDimitry Andric std::string MangledName = 3944*0b57cec5SDimitry Andric getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 3945*0b57cec5SDimitry Andric 3946*0b57cec5SDimitry Andric // Holds the name of the resolver, in ifunc mode this is the ifunc (which has 3947*0b57cec5SDimitry Andric // a separate resolver). 3948*0b57cec5SDimitry Andric std::string ResolverName = MangledName; 3949*0b57cec5SDimitry Andric if (getTarget().supportsIFunc()) 3950*0b57cec5SDimitry Andric ResolverName += ".ifunc"; 3951*0b57cec5SDimitry Andric else if (FD->isTargetMultiVersion()) 3952*0b57cec5SDimitry Andric ResolverName += ".resolver"; 3953*0b57cec5SDimitry Andric 395481ad6265SDimitry Andric // If the resolver has already been created, just return it. 3955*0b57cec5SDimitry Andric if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName)) 3956*0b57cec5SDimitry Andric return ResolverGV; 3957*0b57cec5SDimitry Andric 395881ad6265SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 395981ad6265SDimitry Andric llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI); 3960*0b57cec5SDimitry Andric 396181ad6265SDimitry Andric // The resolver needs to be created. For target and target_clones, defer 396281ad6265SDimitry Andric // creation until the end of the TU. 396381ad6265SDimitry Andric if (FD->isTargetMultiVersion() || FD->isTargetClonesMultiVersion()) 396481ad6265SDimitry Andric MultiVersionFuncs.push_back(GD); 396581ad6265SDimitry Andric 396681ad6265SDimitry Andric // For cpu_specific, don't create an ifunc yet because we don't know if the 396781ad6265SDimitry Andric // cpu_dispatch will be emitted in this translation unit. 396881ad6265SDimitry Andric if (getTarget().supportsIFunc() && !FD->isCPUSpecificMultiVersion()) { 3969*0b57cec5SDimitry Andric llvm::Type *ResolverType = llvm::FunctionType::get( 3970bdd1243dSDimitry Andric llvm::PointerType::get(DeclTy, 3971bdd1243dSDimitry Andric getTypes().getTargetAddressSpace(FD->getType())), 3972*0b57cec5SDimitry Andric false); 3973*0b57cec5SDimitry Andric llvm::Constant *Resolver = GetOrCreateLLVMFunction( 3974*0b57cec5SDimitry Andric MangledName + ".resolver", ResolverType, GlobalDecl{}, 3975*0b57cec5SDimitry Andric /*ForVTable=*/false); 3976349cc55cSDimitry Andric llvm::GlobalIFunc *GIF = 3977349cc55cSDimitry Andric llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD), 3978349cc55cSDimitry Andric "", Resolver, &getModule()); 3979*0b57cec5SDimitry Andric GIF->setName(ResolverName); 3980*0b57cec5SDimitry Andric SetCommonAttributes(FD, GIF); 3981*0b57cec5SDimitry Andric 3982*0b57cec5SDimitry Andric return GIF; 3983*0b57cec5SDimitry Andric } 3984*0b57cec5SDimitry Andric 3985*0b57cec5SDimitry Andric llvm::Constant *Resolver = GetOrCreateLLVMFunction( 3986*0b57cec5SDimitry Andric ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false); 3987*0b57cec5SDimitry Andric assert(isa<llvm::GlobalValue>(Resolver) && 3988*0b57cec5SDimitry Andric "Resolver should be created for the first time"); 3989*0b57cec5SDimitry Andric SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver)); 3990*0b57cec5SDimitry Andric return Resolver; 3991*0b57cec5SDimitry Andric } 3992*0b57cec5SDimitry Andric 3993*0b57cec5SDimitry Andric /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 3994*0b57cec5SDimitry Andric /// module, create and return an llvm Function with the specified type. If there 3995*0b57cec5SDimitry Andric /// is something in the module with the specified name, return it potentially 3996*0b57cec5SDimitry Andric /// bitcasted to the right type. 3997*0b57cec5SDimitry Andric /// 3998*0b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this. This is used 3999*0b57cec5SDimitry Andric /// to set the attributes on the function when it is first created. 4000*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( 4001*0b57cec5SDimitry Andric StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, 4002*0b57cec5SDimitry Andric bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, 4003*0b57cec5SDimitry Andric ForDefinition_t IsForDefinition) { 4004*0b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 4005*0b57cec5SDimitry Andric 4006*0b57cec5SDimitry Andric // Any attempts to use a MultiVersion function should result in retrieving 4007*0b57cec5SDimitry Andric // the iFunc instead. Name Mangling will handle the rest of the changes. 4008*0b57cec5SDimitry Andric if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) { 4009*0b57cec5SDimitry Andric // For the device mark the function as one that should be emitted. 4010*0b57cec5SDimitry Andric if (getLangOpts().OpenMPIsDevice && OpenMPRuntime && 4011*0b57cec5SDimitry Andric !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() && 4012*0b57cec5SDimitry Andric !DontDefer && !IsForDefinition) { 4013*0b57cec5SDimitry Andric if (const FunctionDecl *FDDef = FD->getDefinition()) { 4014*0b57cec5SDimitry Andric GlobalDecl GDDef; 4015*0b57cec5SDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef)) 4016*0b57cec5SDimitry Andric GDDef = GlobalDecl(CD, GD.getCtorType()); 4017*0b57cec5SDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef)) 4018*0b57cec5SDimitry Andric GDDef = GlobalDecl(DD, GD.getDtorType()); 4019*0b57cec5SDimitry Andric else 4020*0b57cec5SDimitry Andric GDDef = GlobalDecl(FDDef); 4021*0b57cec5SDimitry Andric EmitGlobal(GDDef); 4022*0b57cec5SDimitry Andric } 4023*0b57cec5SDimitry Andric } 4024*0b57cec5SDimitry Andric 4025*0b57cec5SDimitry Andric if (FD->isMultiVersion()) { 402604eeddc0SDimitry Andric UpdateMultiVersionNames(GD, FD, MangledName); 4027*0b57cec5SDimitry Andric if (!IsForDefinition) 402881ad6265SDimitry Andric return GetOrCreateMultiVersionResolver(GD); 4029*0b57cec5SDimitry Andric } 4030*0b57cec5SDimitry Andric } 4031*0b57cec5SDimitry Andric 4032*0b57cec5SDimitry Andric // Lookup the entry, lazily creating it if necessary. 4033*0b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4034*0b57cec5SDimitry Andric if (Entry) { 4035*0b57cec5SDimitry Andric if (WeakRefReferences.erase(Entry)) { 4036*0b57cec5SDimitry Andric const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 4037*0b57cec5SDimitry Andric if (FD && !FD->hasAttr<WeakAttr>()) 4038*0b57cec5SDimitry Andric Entry->setLinkage(llvm::Function::ExternalLinkage); 4039*0b57cec5SDimitry Andric } 4040*0b57cec5SDimitry Andric 4041*0b57cec5SDimitry Andric // Handle dropped DLL attributes. 404281ad6265SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() && 404381ad6265SDimitry Andric !shouldMapVisibilityToDLLExport(cast_or_null<NamedDecl>(D))) { 4044*0b57cec5SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 4045*0b57cec5SDimitry Andric setDSOLocal(Entry); 4046*0b57cec5SDimitry Andric } 4047*0b57cec5SDimitry Andric 4048*0b57cec5SDimitry Andric // If there are two attempts to define the same mangled name, issue an 4049*0b57cec5SDimitry Andric // error. 4050*0b57cec5SDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 4051*0b57cec5SDimitry Andric GlobalDecl OtherGD; 4052*0b57cec5SDimitry Andric // Check that GD is not yet in DiagnosedConflictingDefinitions is required 4053*0b57cec5SDimitry Andric // to make sure that we issue an error only once. 4054*0b57cec5SDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 4055*0b57cec5SDimitry Andric (GD.getCanonicalDecl().getDecl() != 4056*0b57cec5SDimitry Andric OtherGD.getCanonicalDecl().getDecl()) && 4057*0b57cec5SDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 4058*0b57cec5SDimitry Andric getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 4059*0b57cec5SDimitry Andric << MangledName; 4060*0b57cec5SDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 4061*0b57cec5SDimitry Andric diag::note_previous_definition); 4062*0b57cec5SDimitry Andric } 4063*0b57cec5SDimitry Andric } 4064*0b57cec5SDimitry Andric 4065*0b57cec5SDimitry Andric if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 40665ffd83dbSDimitry Andric (Entry->getValueType() == Ty)) { 4067*0b57cec5SDimitry Andric return Entry; 4068*0b57cec5SDimitry Andric } 4069*0b57cec5SDimitry Andric 4070*0b57cec5SDimitry Andric // Make sure the result is of the correct type. 4071*0b57cec5SDimitry Andric // (If function is requested for a definition, we always need to create a new 4072*0b57cec5SDimitry Andric // function, not just return a bitcast.) 4073*0b57cec5SDimitry Andric if (!IsForDefinition) 4074bdd1243dSDimitry Andric return llvm::ConstantExpr::getBitCast( 4075bdd1243dSDimitry Andric Entry, Ty->getPointerTo(Entry->getAddressSpace())); 4076*0b57cec5SDimitry Andric } 4077*0b57cec5SDimitry Andric 4078*0b57cec5SDimitry Andric // This function doesn't have a complete type (for example, the return 4079*0b57cec5SDimitry Andric // type is an incomplete struct). Use a fake type instead, and make 4080*0b57cec5SDimitry Andric // sure not to try to set attributes. 4081*0b57cec5SDimitry Andric bool IsIncompleteFunction = false; 4082*0b57cec5SDimitry Andric 4083*0b57cec5SDimitry Andric llvm::FunctionType *FTy; 4084*0b57cec5SDimitry Andric if (isa<llvm::FunctionType>(Ty)) { 4085*0b57cec5SDimitry Andric FTy = cast<llvm::FunctionType>(Ty); 4086*0b57cec5SDimitry Andric } else { 4087*0b57cec5SDimitry Andric FTy = llvm::FunctionType::get(VoidTy, false); 4088*0b57cec5SDimitry Andric IsIncompleteFunction = true; 4089*0b57cec5SDimitry Andric } 4090*0b57cec5SDimitry Andric 4091*0b57cec5SDimitry Andric llvm::Function *F = 4092*0b57cec5SDimitry Andric llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 4093*0b57cec5SDimitry Andric Entry ? StringRef() : MangledName, &getModule()); 4094*0b57cec5SDimitry Andric 4095*0b57cec5SDimitry Andric // If we already created a function with the same mangled name (but different 4096*0b57cec5SDimitry Andric // type) before, take its name and add it to the list of functions to be 4097*0b57cec5SDimitry Andric // replaced with F at the end of CodeGen. 4098*0b57cec5SDimitry Andric // 4099*0b57cec5SDimitry Andric // This happens if there is a prototype for a function (e.g. "int f()") and 4100*0b57cec5SDimitry Andric // then a definition of a different type (e.g. "int f(int x)"). 4101*0b57cec5SDimitry Andric if (Entry) { 4102*0b57cec5SDimitry Andric F->takeName(Entry); 4103*0b57cec5SDimitry Andric 4104*0b57cec5SDimitry Andric // This might be an implementation of a function without a prototype, in 4105*0b57cec5SDimitry Andric // which case, try to do special replacement of calls which match the new 4106*0b57cec5SDimitry Andric // prototype. The really key thing here is that we also potentially drop 4107*0b57cec5SDimitry Andric // arguments from the call site so as to make a direct call, which makes the 4108*0b57cec5SDimitry Andric // inliner happier and suppresses a number of optimizer warnings (!) about 4109*0b57cec5SDimitry Andric // dropping arguments. 4110*0b57cec5SDimitry Andric if (!Entry->use_empty()) { 4111*0b57cec5SDimitry Andric ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 4112*0b57cec5SDimitry Andric Entry->removeDeadConstantUsers(); 4113*0b57cec5SDimitry Andric } 4114*0b57cec5SDimitry Andric 4115*0b57cec5SDimitry Andric llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 4116bdd1243dSDimitry Andric F, Entry->getValueType()->getPointerTo(Entry->getAddressSpace())); 4117*0b57cec5SDimitry Andric addGlobalValReplacement(Entry, BC); 4118*0b57cec5SDimitry Andric } 4119*0b57cec5SDimitry Andric 4120*0b57cec5SDimitry Andric assert(F->getName() == MangledName && "name was uniqued!"); 4121*0b57cec5SDimitry Andric if (D) 4122*0b57cec5SDimitry Andric SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 4123349cc55cSDimitry Andric if (ExtraAttrs.hasFnAttrs()) { 412404eeddc0SDimitry Andric llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs()); 4125349cc55cSDimitry Andric F->addFnAttrs(B); 4126*0b57cec5SDimitry Andric } 4127*0b57cec5SDimitry Andric 4128*0b57cec5SDimitry Andric if (!DontDefer) { 4129*0b57cec5SDimitry Andric // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 4130*0b57cec5SDimitry Andric // each other bottoming out with the base dtor. Therefore we emit non-base 4131*0b57cec5SDimitry Andric // dtors on usage, even if there is no dtor definition in the TU. 4132bdd1243dSDimitry Andric if (isa_and_nonnull<CXXDestructorDecl>(D) && 4133*0b57cec5SDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 4134*0b57cec5SDimitry Andric GD.getDtorType())) 4135*0b57cec5SDimitry Andric addDeferredDeclToEmit(GD); 4136*0b57cec5SDimitry Andric 4137*0b57cec5SDimitry Andric // This is the first use or definition of a mangled name. If there is a 4138*0b57cec5SDimitry Andric // deferred decl with this name, remember that we need to emit it at the end 4139*0b57cec5SDimitry Andric // of the file. 4140*0b57cec5SDimitry Andric auto DDI = DeferredDecls.find(MangledName); 4141*0b57cec5SDimitry Andric if (DDI != DeferredDecls.end()) { 4142*0b57cec5SDimitry Andric // Move the potentially referenced deferred decl to the 4143*0b57cec5SDimitry Andric // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 4144*0b57cec5SDimitry Andric // don't need it anymore). 4145*0b57cec5SDimitry Andric addDeferredDeclToEmit(DDI->second); 4146bdd1243dSDimitry Andric EmittedDeferredDecls[DDI->first] = DDI->second; 4147*0b57cec5SDimitry Andric DeferredDecls.erase(DDI); 4148*0b57cec5SDimitry Andric 4149*0b57cec5SDimitry Andric // Otherwise, there are cases we have to worry about where we're 4150*0b57cec5SDimitry Andric // using a declaration for which we must emit a definition but where 4151*0b57cec5SDimitry Andric // we might not find a top-level definition: 4152*0b57cec5SDimitry Andric // - member functions defined inline in their classes 4153*0b57cec5SDimitry Andric // - friend functions defined inline in some class 4154*0b57cec5SDimitry Andric // - special member functions with implicit definitions 4155*0b57cec5SDimitry Andric // If we ever change our AST traversal to walk into class methods, 4156*0b57cec5SDimitry Andric // this will be unnecessary. 4157*0b57cec5SDimitry Andric // 4158*0b57cec5SDimitry Andric // We also don't emit a definition for a function if it's going to be an 4159*0b57cec5SDimitry Andric // entry in a vtable, unless it's already marked as used. 4160*0b57cec5SDimitry Andric } else if (getLangOpts().CPlusPlus && D) { 4161*0b57cec5SDimitry Andric // Look for a declaration that's lexically in a record. 4162*0b57cec5SDimitry Andric for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 4163*0b57cec5SDimitry Andric FD = FD->getPreviousDecl()) { 4164*0b57cec5SDimitry Andric if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 4165*0b57cec5SDimitry Andric if (FD->doesThisDeclarationHaveABody()) { 4166*0b57cec5SDimitry Andric addDeferredDeclToEmit(GD.getWithDecl(FD)); 4167*0b57cec5SDimitry Andric break; 4168*0b57cec5SDimitry Andric } 4169*0b57cec5SDimitry Andric } 4170*0b57cec5SDimitry Andric } 4171*0b57cec5SDimitry Andric } 4172*0b57cec5SDimitry Andric } 4173*0b57cec5SDimitry Andric 4174*0b57cec5SDimitry Andric // Make sure the result is of the requested type. 4175*0b57cec5SDimitry Andric if (!IsIncompleteFunction) { 41765ffd83dbSDimitry Andric assert(F->getFunctionType() == Ty); 4177*0b57cec5SDimitry Andric return F; 4178*0b57cec5SDimitry Andric } 4179*0b57cec5SDimitry Andric 4180bdd1243dSDimitry Andric return llvm::ConstantExpr::getBitCast(F, 4181bdd1243dSDimitry Andric Ty->getPointerTo(F->getAddressSpace())); 4182*0b57cec5SDimitry Andric } 4183*0b57cec5SDimitry Andric 4184*0b57cec5SDimitry Andric /// GetAddrOfFunction - Return the address of the given function. If Ty is 4185*0b57cec5SDimitry Andric /// non-null, then this function will use the specified type if it has to 4186*0b57cec5SDimitry Andric /// create it (this occurs when we see a definition of the function). 4187*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 4188*0b57cec5SDimitry Andric llvm::Type *Ty, 4189*0b57cec5SDimitry Andric bool ForVTable, 4190*0b57cec5SDimitry Andric bool DontDefer, 4191*0b57cec5SDimitry Andric ForDefinition_t IsForDefinition) { 41925ffd83dbSDimitry Andric assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() && 41935ffd83dbSDimitry Andric "consteval function should never be emitted"); 4194*0b57cec5SDimitry Andric // If there was no specific requested type, just convert it now. 4195*0b57cec5SDimitry Andric if (!Ty) { 4196*0b57cec5SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 4197*0b57cec5SDimitry Andric Ty = getTypes().ConvertType(FD->getType()); 4198*0b57cec5SDimitry Andric } 4199*0b57cec5SDimitry Andric 4200*0b57cec5SDimitry Andric // Devirtualized destructor calls may come through here instead of via 4201*0b57cec5SDimitry Andric // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead 4202*0b57cec5SDimitry Andric // of the complete destructor when necessary. 4203*0b57cec5SDimitry Andric if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) { 4204*0b57cec5SDimitry Andric if (getTarget().getCXXABI().isMicrosoft() && 4205*0b57cec5SDimitry Andric GD.getDtorType() == Dtor_Complete && 4206*0b57cec5SDimitry Andric DD->getParent()->getNumVBases() == 0) 4207*0b57cec5SDimitry Andric GD = GlobalDecl(DD, Dtor_Base); 4208*0b57cec5SDimitry Andric } 4209*0b57cec5SDimitry Andric 4210*0b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 4211fe6060f1SDimitry Andric auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 4212*0b57cec5SDimitry Andric /*IsThunk=*/false, llvm::AttributeList(), 4213*0b57cec5SDimitry Andric IsForDefinition); 4214fe6060f1SDimitry Andric // Returns kernel handle for HIP kernel stub function. 4215fe6060f1SDimitry Andric if (LangOpts.CUDA && !LangOpts.CUDAIsDevice && 4216fe6060f1SDimitry Andric cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) { 4217fe6060f1SDimitry Andric auto *Handle = getCUDARuntime().getKernelHandle( 4218fe6060f1SDimitry Andric cast<llvm::Function>(F->stripPointerCasts()), GD); 4219fe6060f1SDimitry Andric if (IsForDefinition) 4220fe6060f1SDimitry Andric return F; 4221fe6060f1SDimitry Andric return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo()); 4222fe6060f1SDimitry Andric } 4223fe6060f1SDimitry Andric return F; 4224*0b57cec5SDimitry Andric } 4225*0b57cec5SDimitry Andric 42260eae32dcSDimitry Andric llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) { 42270eae32dcSDimitry Andric llvm::GlobalValue *F = 42280eae32dcSDimitry Andric cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts()); 42290eae32dcSDimitry Andric 4230bdd1243dSDimitry Andric return llvm::ConstantExpr::getBitCast( 4231bdd1243dSDimitry Andric llvm::NoCFIValue::get(F), 4232bdd1243dSDimitry Andric llvm::Type::getInt8PtrTy(VMContext, F->getAddressSpace())); 42330eae32dcSDimitry Andric } 42340eae32dcSDimitry Andric 4235*0b57cec5SDimitry Andric static const FunctionDecl * 4236*0b57cec5SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { 4237*0b57cec5SDimitry Andric TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 4238*0b57cec5SDimitry Andric DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 4239*0b57cec5SDimitry Andric 4240*0b57cec5SDimitry Andric IdentifierInfo &CII = C.Idents.get(Name); 4241fe6060f1SDimitry Andric for (const auto *Result : DC->lookup(&CII)) 4242fe6060f1SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 4243*0b57cec5SDimitry Andric return FD; 4244*0b57cec5SDimitry Andric 4245*0b57cec5SDimitry Andric if (!C.getLangOpts().CPlusPlus) 4246*0b57cec5SDimitry Andric return nullptr; 4247*0b57cec5SDimitry Andric 4248*0b57cec5SDimitry Andric // Demangle the premangled name from getTerminateFn() 4249*0b57cec5SDimitry Andric IdentifierInfo &CXXII = 4250*0b57cec5SDimitry Andric (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ") 4251*0b57cec5SDimitry Andric ? C.Idents.get("terminate") 4252*0b57cec5SDimitry Andric : C.Idents.get(Name); 4253*0b57cec5SDimitry Andric 4254*0b57cec5SDimitry Andric for (const auto &N : {"__cxxabiv1", "std"}) { 4255*0b57cec5SDimitry Andric IdentifierInfo &NS = C.Idents.get(N); 4256fe6060f1SDimitry Andric for (const auto *Result : DC->lookup(&NS)) { 4257fe6060f1SDimitry Andric const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); 4258fe6060f1SDimitry Andric if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result)) 4259fe6060f1SDimitry Andric for (const auto *Result : LSD->lookup(&NS)) 4260*0b57cec5SDimitry Andric if ((ND = dyn_cast<NamespaceDecl>(Result))) 4261*0b57cec5SDimitry Andric break; 4262*0b57cec5SDimitry Andric 4263*0b57cec5SDimitry Andric if (ND) 4264fe6060f1SDimitry Andric for (const auto *Result : ND->lookup(&CXXII)) 4265*0b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 4266*0b57cec5SDimitry Andric return FD; 4267*0b57cec5SDimitry Andric } 4268*0b57cec5SDimitry Andric } 4269*0b57cec5SDimitry Andric 4270*0b57cec5SDimitry Andric return nullptr; 4271*0b57cec5SDimitry Andric } 4272*0b57cec5SDimitry Andric 4273*0b57cec5SDimitry Andric /// CreateRuntimeFunction - Create a new runtime function with the specified 4274*0b57cec5SDimitry Andric /// type and name. 4275*0b57cec5SDimitry Andric llvm::FunctionCallee 4276*0b57cec5SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, 4277480093f4SDimitry Andric llvm::AttributeList ExtraAttrs, bool Local, 4278480093f4SDimitry Andric bool AssumeConvergent) { 4279480093f4SDimitry Andric if (AssumeConvergent) { 4280480093f4SDimitry Andric ExtraAttrs = 4281349cc55cSDimitry Andric ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent); 4282480093f4SDimitry Andric } 4283480093f4SDimitry Andric 4284*0b57cec5SDimitry Andric llvm::Constant *C = 4285*0b57cec5SDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 4286*0b57cec5SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, 4287*0b57cec5SDimitry Andric ExtraAttrs); 4288*0b57cec5SDimitry Andric 4289*0b57cec5SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) { 4290*0b57cec5SDimitry Andric if (F->empty()) { 4291*0b57cec5SDimitry Andric F->setCallingConv(getRuntimeCC()); 4292*0b57cec5SDimitry Andric 4293*0b57cec5SDimitry Andric // In Windows Itanium environments, try to mark runtime functions 4294*0b57cec5SDimitry Andric // dllimport. For Mingw and MSVC, don't. We don't really know if the user 4295*0b57cec5SDimitry Andric // will link their standard library statically or dynamically. Marking 4296*0b57cec5SDimitry Andric // functions imported when they are not imported can cause linker errors 4297*0b57cec5SDimitry Andric // and warnings. 4298*0b57cec5SDimitry Andric if (!Local && getTriple().isWindowsItaniumEnvironment() && 4299*0b57cec5SDimitry Andric !getCodeGenOpts().LTOVisibilityPublicStd) { 4300*0b57cec5SDimitry Andric const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); 4301*0b57cec5SDimitry Andric if (!FD || FD->hasAttr<DLLImportAttr>()) { 4302*0b57cec5SDimitry Andric F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 4303*0b57cec5SDimitry Andric F->setLinkage(llvm::GlobalValue::ExternalLinkage); 4304*0b57cec5SDimitry Andric } 4305*0b57cec5SDimitry Andric } 4306*0b57cec5SDimitry Andric setDSOLocal(F); 4307*0b57cec5SDimitry Andric } 4308*0b57cec5SDimitry Andric } 4309*0b57cec5SDimitry Andric 4310*0b57cec5SDimitry Andric return {FTy, C}; 4311*0b57cec5SDimitry Andric } 4312*0b57cec5SDimitry Andric 4313*0b57cec5SDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted 4314*0b57cec5SDimitry Andric /// as a constant. 4315*0b57cec5SDimitry Andric /// 4316*0b57cec5SDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs 4317*0b57cec5SDimitry Andric /// will not be considered. The caller will need to verify that the object is 4318*0b57cec5SDimitry Andric /// not written to during its construction. 4319*0b57cec5SDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 4320*0b57cec5SDimitry Andric if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 4321*0b57cec5SDimitry Andric return false; 4322*0b57cec5SDimitry Andric 4323*0b57cec5SDimitry Andric if (Context.getLangOpts().CPlusPlus) { 4324*0b57cec5SDimitry Andric if (const CXXRecordDecl *Record 4325*0b57cec5SDimitry Andric = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 4326*0b57cec5SDimitry Andric return ExcludeCtor && !Record->hasMutableFields() && 4327*0b57cec5SDimitry Andric Record->hasTrivialDestructor(); 4328*0b57cec5SDimitry Andric } 4329*0b57cec5SDimitry Andric 4330*0b57cec5SDimitry Andric return true; 4331*0b57cec5SDimitry Andric } 4332*0b57cec5SDimitry Andric 4333*0b57cec5SDimitry Andric /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 4334fe6060f1SDimitry Andric /// create and return an llvm GlobalVariable with the specified type and address 4335fe6060f1SDimitry Andric /// space. If there is something in the module with the specified name, return 4336fe6060f1SDimitry Andric /// it potentially bitcasted to the right type. 4337*0b57cec5SDimitry Andric /// 4338*0b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this. This is used 4339*0b57cec5SDimitry Andric /// to set the attributes on the global when it is first created. 4340*0b57cec5SDimitry Andric /// 4341*0b57cec5SDimitry Andric /// If IsForDefinition is true, it is guaranteed that an actual global with 4342*0b57cec5SDimitry Andric /// type Ty will be returned, not conversion of a variable with the same 4343*0b57cec5SDimitry Andric /// mangled name but some other type. 4344*0b57cec5SDimitry Andric llvm::Constant * 4345fe6060f1SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, 4346349cc55cSDimitry Andric LangAS AddrSpace, const VarDecl *D, 4347*0b57cec5SDimitry Andric ForDefinition_t IsForDefinition) { 4348*0b57cec5SDimitry Andric // Lookup the entry, lazily creating it if necessary. 4349*0b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4350349cc55cSDimitry Andric unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace); 4351*0b57cec5SDimitry Andric if (Entry) { 4352*0b57cec5SDimitry Andric if (WeakRefReferences.erase(Entry)) { 4353*0b57cec5SDimitry Andric if (D && !D->hasAttr<WeakAttr>()) 4354*0b57cec5SDimitry Andric Entry->setLinkage(llvm::Function::ExternalLinkage); 4355*0b57cec5SDimitry Andric } 4356*0b57cec5SDimitry Andric 4357*0b57cec5SDimitry Andric // Handle dropped DLL attributes. 435881ad6265SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() && 435981ad6265SDimitry Andric !shouldMapVisibilityToDLLExport(D)) 4360*0b57cec5SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 4361*0b57cec5SDimitry Andric 4362*0b57cec5SDimitry Andric if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D) 4363*0b57cec5SDimitry Andric getOpenMPRuntime().registerTargetGlobalVariable(D, Entry); 4364*0b57cec5SDimitry Andric 4365349cc55cSDimitry Andric if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS) 4366*0b57cec5SDimitry Andric return Entry; 4367*0b57cec5SDimitry Andric 4368*0b57cec5SDimitry Andric // If there are two attempts to define the same mangled name, issue an 4369*0b57cec5SDimitry Andric // error. 4370*0b57cec5SDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 4371*0b57cec5SDimitry Andric GlobalDecl OtherGD; 4372*0b57cec5SDimitry Andric const VarDecl *OtherD; 4373*0b57cec5SDimitry Andric 4374*0b57cec5SDimitry Andric // Check that D is not yet in DiagnosedConflictingDefinitions is required 4375*0b57cec5SDimitry Andric // to make sure that we issue an error only once. 4376*0b57cec5SDimitry Andric if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 4377*0b57cec5SDimitry Andric (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 4378*0b57cec5SDimitry Andric (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 4379*0b57cec5SDimitry Andric OtherD->hasInit() && 4380*0b57cec5SDimitry Andric DiagnosedConflictingDefinitions.insert(D).second) { 4381*0b57cec5SDimitry Andric getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 4382*0b57cec5SDimitry Andric << MangledName; 4383*0b57cec5SDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 4384*0b57cec5SDimitry Andric diag::note_previous_definition); 4385*0b57cec5SDimitry Andric } 4386*0b57cec5SDimitry Andric } 4387*0b57cec5SDimitry Andric 4388*0b57cec5SDimitry Andric // Make sure the result is of the correct type. 4389349cc55cSDimitry Andric if (Entry->getType()->getAddressSpace() != TargetAS) { 4390fe6060f1SDimitry Andric return llvm::ConstantExpr::getAddrSpaceCast(Entry, 4391349cc55cSDimitry Andric Ty->getPointerTo(TargetAS)); 4392fe6060f1SDimitry Andric } 4393*0b57cec5SDimitry Andric 4394*0b57cec5SDimitry Andric // (If global is requested for a definition, we always need to create a new 4395*0b57cec5SDimitry Andric // global, not just return a bitcast.) 4396*0b57cec5SDimitry Andric if (!IsForDefinition) 4397349cc55cSDimitry Andric return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(TargetAS)); 4398*0b57cec5SDimitry Andric } 4399*0b57cec5SDimitry Andric 4400fe6060f1SDimitry Andric auto DAddrSpace = GetGlobalVarAddressSpace(D); 4401*0b57cec5SDimitry Andric 4402*0b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 4403fe6060f1SDimitry Andric getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr, 4404fe6060f1SDimitry Andric MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal, 4405349cc55cSDimitry Andric getContext().getTargetAddressSpace(DAddrSpace)); 4406*0b57cec5SDimitry Andric 4407*0b57cec5SDimitry Andric // If we already created a global with the same mangled name (but different 4408*0b57cec5SDimitry Andric // type) before, take its name and remove it from its parent. 4409*0b57cec5SDimitry Andric if (Entry) { 4410*0b57cec5SDimitry Andric GV->takeName(Entry); 4411*0b57cec5SDimitry Andric 4412*0b57cec5SDimitry Andric if (!Entry->use_empty()) { 4413*0b57cec5SDimitry Andric llvm::Constant *NewPtrForOldDecl = 4414*0b57cec5SDimitry Andric llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 4415*0b57cec5SDimitry Andric Entry->replaceAllUsesWith(NewPtrForOldDecl); 4416*0b57cec5SDimitry Andric } 4417*0b57cec5SDimitry Andric 4418*0b57cec5SDimitry Andric Entry->eraseFromParent(); 4419*0b57cec5SDimitry Andric } 4420*0b57cec5SDimitry Andric 4421*0b57cec5SDimitry Andric // This is the first use or definition of a mangled name. If there is a 4422*0b57cec5SDimitry Andric // deferred decl with this name, remember that we need to emit it at the end 4423*0b57cec5SDimitry Andric // of the file. 4424*0b57cec5SDimitry Andric auto DDI = DeferredDecls.find(MangledName); 4425*0b57cec5SDimitry Andric if (DDI != DeferredDecls.end()) { 4426*0b57cec5SDimitry Andric // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 4427*0b57cec5SDimitry Andric // list, and remove it from DeferredDecls (since we don't need it anymore). 4428*0b57cec5SDimitry Andric addDeferredDeclToEmit(DDI->second); 4429bdd1243dSDimitry Andric EmittedDeferredDecls[DDI->first] = DDI->second; 4430*0b57cec5SDimitry Andric DeferredDecls.erase(DDI); 4431*0b57cec5SDimitry Andric } 4432*0b57cec5SDimitry Andric 4433*0b57cec5SDimitry Andric // Handle things which are present even on external declarations. 4434*0b57cec5SDimitry Andric if (D) { 4435*0b57cec5SDimitry Andric if (LangOpts.OpenMP && !LangOpts.OpenMPSimd) 4436*0b57cec5SDimitry Andric getOpenMPRuntime().registerTargetGlobalVariable(D, GV); 4437*0b57cec5SDimitry Andric 4438*0b57cec5SDimitry Andric // FIXME: This code is overly simple and should be merged with other global 4439*0b57cec5SDimitry Andric // handling. 4440*0b57cec5SDimitry Andric GV->setConstant(isTypeConstant(D->getType(), false)); 4441*0b57cec5SDimitry Andric 4442a7dea167SDimitry Andric GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); 4443*0b57cec5SDimitry Andric 4444*0b57cec5SDimitry Andric setLinkageForGV(GV, D); 4445*0b57cec5SDimitry Andric 4446*0b57cec5SDimitry Andric if (D->getTLSKind()) { 4447*0b57cec5SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 4448*0b57cec5SDimitry Andric CXXThreadLocals.push_back(D); 4449*0b57cec5SDimitry Andric setTLSMode(GV, *D); 4450*0b57cec5SDimitry Andric } 4451*0b57cec5SDimitry Andric 4452*0b57cec5SDimitry Andric setGVProperties(GV, D); 4453*0b57cec5SDimitry Andric 4454*0b57cec5SDimitry Andric // If required by the ABI, treat declarations of static data members with 4455*0b57cec5SDimitry Andric // inline initializers as definitions. 4456*0b57cec5SDimitry Andric if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 4457*0b57cec5SDimitry Andric EmitGlobalVarDefinition(D); 4458*0b57cec5SDimitry Andric } 4459*0b57cec5SDimitry Andric 4460*0b57cec5SDimitry Andric // Emit section information for extern variables. 4461*0b57cec5SDimitry Andric if (D->hasExternalStorage()) { 4462*0b57cec5SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 4463*0b57cec5SDimitry Andric GV->setSection(SA->getName()); 4464*0b57cec5SDimitry Andric } 4465*0b57cec5SDimitry Andric 4466*0b57cec5SDimitry Andric // Handle XCore specific ABI requirements. 4467*0b57cec5SDimitry Andric if (getTriple().getArch() == llvm::Triple::xcore && 4468*0b57cec5SDimitry Andric D->getLanguageLinkage() == CLanguageLinkage && 4469*0b57cec5SDimitry Andric D->getType().isConstant(Context) && 4470*0b57cec5SDimitry Andric isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 4471*0b57cec5SDimitry Andric GV->setSection(".cp.rodata"); 4472*0b57cec5SDimitry Andric 4473*0b57cec5SDimitry Andric // Check if we a have a const declaration with an initializer, we may be 4474*0b57cec5SDimitry Andric // able to emit it as available_externally to expose it's value to the 4475*0b57cec5SDimitry Andric // optimizer. 4476*0b57cec5SDimitry Andric if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() && 4477*0b57cec5SDimitry Andric D->getType().isConstQualified() && !GV->hasInitializer() && 4478*0b57cec5SDimitry Andric !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) { 4479*0b57cec5SDimitry Andric const auto *Record = 4480*0b57cec5SDimitry Andric Context.getBaseElementType(D->getType())->getAsCXXRecordDecl(); 4481*0b57cec5SDimitry Andric bool HasMutableFields = Record && Record->hasMutableFields(); 4482*0b57cec5SDimitry Andric if (!HasMutableFields) { 4483*0b57cec5SDimitry Andric const VarDecl *InitDecl; 4484*0b57cec5SDimitry Andric const Expr *InitExpr = D->getAnyInitializer(InitDecl); 4485*0b57cec5SDimitry Andric if (InitExpr) { 4486*0b57cec5SDimitry Andric ConstantEmitter emitter(*this); 4487*0b57cec5SDimitry Andric llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl); 4488*0b57cec5SDimitry Andric if (Init) { 4489*0b57cec5SDimitry Andric auto *InitType = Init->getType(); 44905ffd83dbSDimitry Andric if (GV->getValueType() != InitType) { 4491*0b57cec5SDimitry Andric // The type of the initializer does not match the definition. 4492*0b57cec5SDimitry Andric // This happens when an initializer has a different type from 4493*0b57cec5SDimitry Andric // the type of the global (because of padding at the end of a 4494*0b57cec5SDimitry Andric // structure for instance). 4495*0b57cec5SDimitry Andric GV->setName(StringRef()); 4496*0b57cec5SDimitry Andric // Make a new global with the correct type, this is now guaranteed 4497*0b57cec5SDimitry Andric // to work. 4498*0b57cec5SDimitry Andric auto *NewGV = cast<llvm::GlobalVariable>( 4499a7dea167SDimitry Andric GetAddrOfGlobalVar(D, InitType, IsForDefinition) 4500a7dea167SDimitry Andric ->stripPointerCasts()); 4501*0b57cec5SDimitry Andric 4502*0b57cec5SDimitry Andric // Erase the old global, since it is no longer used. 4503*0b57cec5SDimitry Andric GV->eraseFromParent(); 4504*0b57cec5SDimitry Andric GV = NewGV; 4505*0b57cec5SDimitry Andric } else { 4506*0b57cec5SDimitry Andric GV->setInitializer(Init); 4507*0b57cec5SDimitry Andric GV->setConstant(true); 4508*0b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 4509*0b57cec5SDimitry Andric } 4510*0b57cec5SDimitry Andric emitter.finalize(GV); 4511*0b57cec5SDimitry Andric } 4512*0b57cec5SDimitry Andric } 4513*0b57cec5SDimitry Andric } 4514*0b57cec5SDimitry Andric } 4515*0b57cec5SDimitry Andric } 4516*0b57cec5SDimitry Andric 4517fe6060f1SDimitry Andric if (GV->isDeclaration()) { 4518480093f4SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(D, GV, *this); 4519fe6060f1SDimitry Andric // External HIP managed variables needed to be recorded for transformation 4520fe6060f1SDimitry Andric // in both device and host compilations. 4521fe6060f1SDimitry Andric if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() && 4522fe6060f1SDimitry Andric D->hasExternalStorage()) 4523fe6060f1SDimitry Andric getCUDARuntime().handleVarRegistration(D, *GV); 4524fe6060f1SDimitry Andric } 4525480093f4SDimitry Andric 4526753f127fSDimitry Andric if (D) 4527753f127fSDimitry Andric SanitizerMD->reportGlobal(GV, *D); 4528753f127fSDimitry Andric 4529*0b57cec5SDimitry Andric LangAS ExpectedAS = 4530*0b57cec5SDimitry Andric D ? D->getType().getAddressSpace() 4531*0b57cec5SDimitry Andric : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default); 4532349cc55cSDimitry Andric assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS); 4533fe6060f1SDimitry Andric if (DAddrSpace != ExpectedAS) { 4534fe6060f1SDimitry Andric return getTargetCodeGenInfo().performAddrSpaceCast( 4535349cc55cSDimitry Andric *this, GV, DAddrSpace, ExpectedAS, Ty->getPointerTo(TargetAS)); 4536fe6060f1SDimitry Andric } 4537*0b57cec5SDimitry Andric 4538*0b57cec5SDimitry Andric return GV; 4539*0b57cec5SDimitry Andric } 4540*0b57cec5SDimitry Andric 4541*0b57cec5SDimitry Andric llvm::Constant * 45425ffd83dbSDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) { 4543*0b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 45445ffd83dbSDimitry Andric 4545*0b57cec5SDimitry Andric if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 4546*0b57cec5SDimitry Andric return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr, 4547*0b57cec5SDimitry Andric /*DontDefer=*/false, IsForDefinition); 45485ffd83dbSDimitry Andric 45495ffd83dbSDimitry Andric if (isa<CXXMethodDecl>(D)) { 45505ffd83dbSDimitry Andric auto FInfo = 45515ffd83dbSDimitry Andric &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D)); 4552*0b57cec5SDimitry Andric auto Ty = getTypes().GetFunctionType(*FInfo); 4553*0b57cec5SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 4554*0b57cec5SDimitry Andric IsForDefinition); 45555ffd83dbSDimitry Andric } 45565ffd83dbSDimitry Andric 45575ffd83dbSDimitry Andric if (isa<FunctionDecl>(D)) { 4558*0b57cec5SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 4559*0b57cec5SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 4560*0b57cec5SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 4561*0b57cec5SDimitry Andric IsForDefinition); 45625ffd83dbSDimitry Andric } 45635ffd83dbSDimitry Andric 45645ffd83dbSDimitry Andric return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition); 4565*0b57cec5SDimitry Andric } 4566*0b57cec5SDimitry Andric 4567*0b57cec5SDimitry Andric llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable( 4568*0b57cec5SDimitry Andric StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, 4569bdd1243dSDimitry Andric llvm::Align Alignment) { 4570*0b57cec5SDimitry Andric llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 4571*0b57cec5SDimitry Andric llvm::GlobalVariable *OldGV = nullptr; 4572*0b57cec5SDimitry Andric 4573*0b57cec5SDimitry Andric if (GV) { 4574*0b57cec5SDimitry Andric // Check if the variable has the right type. 45755ffd83dbSDimitry Andric if (GV->getValueType() == Ty) 4576*0b57cec5SDimitry Andric return GV; 4577*0b57cec5SDimitry Andric 4578*0b57cec5SDimitry Andric // Because C++ name mangling, the only way we can end up with an already 4579*0b57cec5SDimitry Andric // existing global with the same name is if it has been declared extern "C". 4580*0b57cec5SDimitry Andric assert(GV->isDeclaration() && "Declaration has wrong type!"); 4581*0b57cec5SDimitry Andric OldGV = GV; 4582*0b57cec5SDimitry Andric } 4583*0b57cec5SDimitry Andric 4584*0b57cec5SDimitry Andric // Create a new variable. 4585*0b57cec5SDimitry Andric GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 4586*0b57cec5SDimitry Andric Linkage, nullptr, Name); 4587*0b57cec5SDimitry Andric 4588*0b57cec5SDimitry Andric if (OldGV) { 4589*0b57cec5SDimitry Andric // Replace occurrences of the old variable if needed. 4590*0b57cec5SDimitry Andric GV->takeName(OldGV); 4591*0b57cec5SDimitry Andric 4592*0b57cec5SDimitry Andric if (!OldGV->use_empty()) { 4593*0b57cec5SDimitry Andric llvm::Constant *NewPtrForOldDecl = 4594*0b57cec5SDimitry Andric llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 4595*0b57cec5SDimitry Andric OldGV->replaceAllUsesWith(NewPtrForOldDecl); 4596*0b57cec5SDimitry Andric } 4597*0b57cec5SDimitry Andric 4598*0b57cec5SDimitry Andric OldGV->eraseFromParent(); 4599*0b57cec5SDimitry Andric } 4600*0b57cec5SDimitry Andric 4601*0b57cec5SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker() && 4602*0b57cec5SDimitry Andric !GV->hasAvailableExternallyLinkage()) 4603*0b57cec5SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 4604*0b57cec5SDimitry Andric 4605bdd1243dSDimitry Andric GV->setAlignment(Alignment); 4606*0b57cec5SDimitry Andric 4607*0b57cec5SDimitry Andric return GV; 4608*0b57cec5SDimitry Andric } 4609*0b57cec5SDimitry Andric 4610*0b57cec5SDimitry Andric /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 4611*0b57cec5SDimitry Andric /// given global variable. If Ty is non-null and if the global doesn't exist, 4612*0b57cec5SDimitry Andric /// then it will be created with the specified type instead of whatever the 4613*0b57cec5SDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guaranteed 4614*0b57cec5SDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a 4615*0b57cec5SDimitry Andric /// variable with the same mangled name but some other type. 4616*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 4617*0b57cec5SDimitry Andric llvm::Type *Ty, 4618*0b57cec5SDimitry Andric ForDefinition_t IsForDefinition) { 4619*0b57cec5SDimitry Andric assert(D->hasGlobalStorage() && "Not a global variable"); 4620*0b57cec5SDimitry Andric QualType ASTTy = D->getType(); 4621*0b57cec5SDimitry Andric if (!Ty) 4622*0b57cec5SDimitry Andric Ty = getTypes().ConvertTypeForMem(ASTTy); 4623*0b57cec5SDimitry Andric 4624*0b57cec5SDimitry Andric StringRef MangledName = getMangledName(D); 4625349cc55cSDimitry Andric return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D, 4626fe6060f1SDimitry Andric IsForDefinition); 4627*0b57cec5SDimitry Andric } 4628*0b57cec5SDimitry Andric 4629*0b57cec5SDimitry Andric /// CreateRuntimeVariable - Create a new runtime global variable with the 4630*0b57cec5SDimitry Andric /// specified type and name. 4631*0b57cec5SDimitry Andric llvm::Constant * 4632*0b57cec5SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 4633*0b57cec5SDimitry Andric StringRef Name) { 4634349cc55cSDimitry Andric LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global 4635349cc55cSDimitry Andric : LangAS::Default; 4636fe6060f1SDimitry Andric auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr); 4637*0b57cec5SDimitry Andric setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts())); 4638*0b57cec5SDimitry Andric return Ret; 4639*0b57cec5SDimitry Andric } 4640*0b57cec5SDimitry Andric 4641*0b57cec5SDimitry Andric void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 4642*0b57cec5SDimitry Andric assert(!D->getInit() && "Cannot emit definite definitions here!"); 4643*0b57cec5SDimitry Andric 4644*0b57cec5SDimitry Andric StringRef MangledName = getMangledName(D); 4645*0b57cec5SDimitry Andric llvm::GlobalValue *GV = GetGlobalValue(MangledName); 4646*0b57cec5SDimitry Andric 4647*0b57cec5SDimitry Andric // We already have a definition, not declaration, with the same mangled name. 4648*0b57cec5SDimitry Andric // Emitting of declaration is not required (and actually overwrites emitted 4649*0b57cec5SDimitry Andric // definition). 4650*0b57cec5SDimitry Andric if (GV && !GV->isDeclaration()) 4651*0b57cec5SDimitry Andric return; 4652*0b57cec5SDimitry Andric 4653*0b57cec5SDimitry Andric // If we have not seen a reference to this variable yet, place it into the 4654*0b57cec5SDimitry Andric // deferred declarations table to be emitted if needed later. 4655*0b57cec5SDimitry Andric if (!MustBeEmitted(D) && !GV) { 4656*0b57cec5SDimitry Andric DeferredDecls[MangledName] = D; 4657*0b57cec5SDimitry Andric return; 4658*0b57cec5SDimitry Andric } 4659*0b57cec5SDimitry Andric 4660*0b57cec5SDimitry Andric // The tentative definition is the only definition. 4661*0b57cec5SDimitry Andric EmitGlobalVarDefinition(D); 4662*0b57cec5SDimitry Andric } 4663*0b57cec5SDimitry Andric 4664480093f4SDimitry Andric void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) { 4665480093f4SDimitry Andric EmitExternalVarDeclaration(D); 4666480093f4SDimitry Andric } 4667480093f4SDimitry Andric 4668*0b57cec5SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 4669*0b57cec5SDimitry Andric return Context.toCharUnitsFromBits( 4670*0b57cec5SDimitry Andric getDataLayout().getTypeStoreSizeInBits(Ty)); 4671*0b57cec5SDimitry Andric } 4672*0b57cec5SDimitry Andric 4673*0b57cec5SDimitry Andric LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { 4674*0b57cec5SDimitry Andric if (LangOpts.OpenCL) { 4675349cc55cSDimitry Andric LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global; 4676349cc55cSDimitry Andric assert(AS == LangAS::opencl_global || 4677349cc55cSDimitry Andric AS == LangAS::opencl_global_device || 4678349cc55cSDimitry Andric AS == LangAS::opencl_global_host || 4679349cc55cSDimitry Andric AS == LangAS::opencl_constant || 4680349cc55cSDimitry Andric AS == LangAS::opencl_local || 4681349cc55cSDimitry Andric AS >= LangAS::FirstTargetAddressSpace); 4682349cc55cSDimitry Andric return AS; 4683*0b57cec5SDimitry Andric } 4684*0b57cec5SDimitry Andric 4685fe6060f1SDimitry Andric if (LangOpts.SYCLIsDevice && 4686fe6060f1SDimitry Andric (!D || D->getType().getAddressSpace() == LangAS::Default)) 4687fe6060f1SDimitry Andric return LangAS::sycl_global; 4688fe6060f1SDimitry Andric 4689*0b57cec5SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { 4690*0b57cec5SDimitry Andric if (D && D->hasAttr<CUDAConstantAttr>()) 4691*0b57cec5SDimitry Andric return LangAS::cuda_constant; 4692*0b57cec5SDimitry Andric else if (D && D->hasAttr<CUDASharedAttr>()) 4693*0b57cec5SDimitry Andric return LangAS::cuda_shared; 4694*0b57cec5SDimitry Andric else if (D && D->hasAttr<CUDADeviceAttr>()) 4695*0b57cec5SDimitry Andric return LangAS::cuda_device; 4696*0b57cec5SDimitry Andric else if (D && D->getType().isConstQualified()) 4697*0b57cec5SDimitry Andric return LangAS::cuda_constant; 4698*0b57cec5SDimitry Andric else 4699*0b57cec5SDimitry Andric return LangAS::cuda_device; 4700*0b57cec5SDimitry Andric } 4701*0b57cec5SDimitry Andric 4702*0b57cec5SDimitry Andric if (LangOpts.OpenMP) { 4703*0b57cec5SDimitry Andric LangAS AS; 4704*0b57cec5SDimitry Andric if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS)) 4705*0b57cec5SDimitry Andric return AS; 4706*0b57cec5SDimitry Andric } 4707*0b57cec5SDimitry Andric return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D); 4708*0b57cec5SDimitry Andric } 4709*0b57cec5SDimitry Andric 4710fe6060f1SDimitry Andric LangAS CodeGenModule::GetGlobalConstantAddressSpace() const { 4711*0b57cec5SDimitry Andric // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 4712*0b57cec5SDimitry Andric if (LangOpts.OpenCL) 4713*0b57cec5SDimitry Andric return LangAS::opencl_constant; 4714fe6060f1SDimitry Andric if (LangOpts.SYCLIsDevice) 4715fe6060f1SDimitry Andric return LangAS::sycl_global; 4716d56accc7SDimitry Andric if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV()) 4717d56accc7SDimitry Andric // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V) 4718d56accc7SDimitry Andric // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up 4719d56accc7SDimitry Andric // with OpVariable instructions with Generic storage class which is not 4720d56accc7SDimitry Andric // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V 4721d56accc7SDimitry Andric // UniformConstant storage class is not viable as pointers to it may not be 4722d56accc7SDimitry Andric // casted to Generic pointers which are used to model HIP's "flat" pointers. 4723d56accc7SDimitry Andric return LangAS::cuda_device; 4724*0b57cec5SDimitry Andric if (auto AS = getTarget().getConstantAddressSpace()) 472581ad6265SDimitry Andric return *AS; 4726*0b57cec5SDimitry Andric return LangAS::Default; 4727*0b57cec5SDimitry Andric } 4728*0b57cec5SDimitry Andric 4729*0b57cec5SDimitry Andric // In address space agnostic languages, string literals are in default address 4730*0b57cec5SDimitry Andric // space in AST. However, certain targets (e.g. amdgcn) request them to be 4731*0b57cec5SDimitry Andric // emitted in constant address space in LLVM IR. To be consistent with other 4732*0b57cec5SDimitry Andric // parts of AST, string literal global variables in constant address space 4733*0b57cec5SDimitry Andric // need to be casted to default address space before being put into address 4734*0b57cec5SDimitry Andric // map and referenced by other part of CodeGen. 4735*0b57cec5SDimitry Andric // In OpenCL, string literals are in constant address space in AST, therefore 4736*0b57cec5SDimitry Andric // they should not be casted to default address space. 4737*0b57cec5SDimitry Andric static llvm::Constant * 4738*0b57cec5SDimitry Andric castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, 4739*0b57cec5SDimitry Andric llvm::GlobalVariable *GV) { 4740*0b57cec5SDimitry Andric llvm::Constant *Cast = GV; 4741*0b57cec5SDimitry Andric if (!CGM.getLangOpts().OpenCL) { 4742fe6060f1SDimitry Andric auto AS = CGM.GetGlobalConstantAddressSpace(); 4743*0b57cec5SDimitry Andric if (AS != LangAS::Default) 4744*0b57cec5SDimitry Andric Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast( 4745fe6060f1SDimitry Andric CGM, GV, AS, LangAS::Default, 4746*0b57cec5SDimitry Andric GV->getValueType()->getPointerTo( 4747*0b57cec5SDimitry Andric CGM.getContext().getTargetAddressSpace(LangAS::Default))); 4748*0b57cec5SDimitry Andric } 4749*0b57cec5SDimitry Andric return Cast; 4750*0b57cec5SDimitry Andric } 4751*0b57cec5SDimitry Andric 4752*0b57cec5SDimitry Andric template<typename SomeDecl> 4753*0b57cec5SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 4754*0b57cec5SDimitry Andric llvm::GlobalValue *GV) { 4755*0b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus) 4756*0b57cec5SDimitry Andric return; 4757*0b57cec5SDimitry Andric 4758*0b57cec5SDimitry Andric // Must have 'used' attribute, or else inline assembly can't rely on 4759*0b57cec5SDimitry Andric // the name existing. 4760*0b57cec5SDimitry Andric if (!D->template hasAttr<UsedAttr>()) 4761*0b57cec5SDimitry Andric return; 4762*0b57cec5SDimitry Andric 4763*0b57cec5SDimitry Andric // Must have internal linkage and an ordinary name. 4764*0b57cec5SDimitry Andric if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 4765*0b57cec5SDimitry Andric return; 4766*0b57cec5SDimitry Andric 4767*0b57cec5SDimitry Andric // Must be in an extern "C" context. Entities declared directly within 4768*0b57cec5SDimitry Andric // a record are not extern "C" even if the record is in such a context. 4769*0b57cec5SDimitry Andric const SomeDecl *First = D->getFirstDecl(); 4770*0b57cec5SDimitry Andric if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 4771*0b57cec5SDimitry Andric return; 4772*0b57cec5SDimitry Andric 4773*0b57cec5SDimitry Andric // OK, this is an internal linkage entity inside an extern "C" linkage 4774*0b57cec5SDimitry Andric // specification. Make a note of that so we can give it the "expected" 4775*0b57cec5SDimitry Andric // mangled name if nothing else is using that name. 4776*0b57cec5SDimitry Andric std::pair<StaticExternCMap::iterator, bool> R = 4777*0b57cec5SDimitry Andric StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 4778*0b57cec5SDimitry Andric 4779*0b57cec5SDimitry Andric // If we have multiple internal linkage entities with the same name 4780*0b57cec5SDimitry Andric // in extern "C" regions, none of them gets that name. 4781*0b57cec5SDimitry Andric if (!R.second) 4782*0b57cec5SDimitry Andric R.first->second = nullptr; 4783*0b57cec5SDimitry Andric } 4784*0b57cec5SDimitry Andric 4785*0b57cec5SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 4786*0b57cec5SDimitry Andric if (!CGM.supportsCOMDAT()) 4787*0b57cec5SDimitry Andric return false; 4788*0b57cec5SDimitry Andric 4789*0b57cec5SDimitry Andric if (D.hasAttr<SelectAnyAttr>()) 4790*0b57cec5SDimitry Andric return true; 4791*0b57cec5SDimitry Andric 4792*0b57cec5SDimitry Andric GVALinkage Linkage; 4793*0b57cec5SDimitry Andric if (auto *VD = dyn_cast<VarDecl>(&D)) 4794*0b57cec5SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 4795*0b57cec5SDimitry Andric else 4796*0b57cec5SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 4797*0b57cec5SDimitry Andric 4798*0b57cec5SDimitry Andric switch (Linkage) { 4799*0b57cec5SDimitry Andric case GVA_Internal: 4800*0b57cec5SDimitry Andric case GVA_AvailableExternally: 4801*0b57cec5SDimitry Andric case GVA_StrongExternal: 4802*0b57cec5SDimitry Andric return false; 4803*0b57cec5SDimitry Andric case GVA_DiscardableODR: 4804*0b57cec5SDimitry Andric case GVA_StrongODR: 4805*0b57cec5SDimitry Andric return true; 4806*0b57cec5SDimitry Andric } 4807*0b57cec5SDimitry Andric llvm_unreachable("No such linkage"); 4808*0b57cec5SDimitry Andric } 4809*0b57cec5SDimitry Andric 4810*0b57cec5SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 4811*0b57cec5SDimitry Andric llvm::GlobalObject &GO) { 4812*0b57cec5SDimitry Andric if (!shouldBeInCOMDAT(*this, D)) 4813*0b57cec5SDimitry Andric return; 4814*0b57cec5SDimitry Andric GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 4815*0b57cec5SDimitry Andric } 4816*0b57cec5SDimitry Andric 4817*0b57cec5SDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition. 4818*0b57cec5SDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 4819*0b57cec5SDimitry Andric bool IsTentative) { 4820*0b57cec5SDimitry Andric // OpenCL global variables of sampler type are translated to function calls, 4821*0b57cec5SDimitry Andric // therefore no need to be translated. 4822*0b57cec5SDimitry Andric QualType ASTTy = D->getType(); 4823*0b57cec5SDimitry Andric if (getLangOpts().OpenCL && ASTTy->isSamplerT()) 4824*0b57cec5SDimitry Andric return; 4825*0b57cec5SDimitry Andric 4826*0b57cec5SDimitry Andric // If this is OpenMP device, check if it is legal to emit this global 4827*0b57cec5SDimitry Andric // normally. 4828*0b57cec5SDimitry Andric if (LangOpts.OpenMPIsDevice && OpenMPRuntime && 4829*0b57cec5SDimitry Andric OpenMPRuntime->emitTargetGlobalVariable(D)) 4830*0b57cec5SDimitry Andric return; 4831*0b57cec5SDimitry Andric 4832fe6060f1SDimitry Andric llvm::TrackingVH<llvm::Constant> Init; 4833*0b57cec5SDimitry Andric bool NeedsGlobalCtor = false; 4834bdd1243dSDimitry Andric // Whether the definition of the variable is available externally. 4835bdd1243dSDimitry Andric // If yes, we shouldn't emit the GloablCtor and GlobalDtor for the variable 4836bdd1243dSDimitry Andric // since this is the job for its original source. 4837bdd1243dSDimitry Andric bool IsDefinitionAvailableExternally = 4838bdd1243dSDimitry Andric getContext().GetGVALinkageForVariable(D) == GVA_AvailableExternally; 4839a7dea167SDimitry Andric bool NeedsGlobalDtor = 4840bdd1243dSDimitry Andric !IsDefinitionAvailableExternally && 4841a7dea167SDimitry Andric D->needsDestruction(getContext()) == QualType::DK_cxx_destructor; 4842*0b57cec5SDimitry Andric 4843*0b57cec5SDimitry Andric const VarDecl *InitDecl; 4844*0b57cec5SDimitry Andric const Expr *InitExpr = D->getAnyInitializer(InitDecl); 4845*0b57cec5SDimitry Andric 4846bdd1243dSDimitry Andric std::optional<ConstantEmitter> emitter; 4847*0b57cec5SDimitry Andric 4848*0b57cec5SDimitry Andric // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 4849*0b57cec5SDimitry Andric // as part of their declaration." Sema has already checked for 4850*0b57cec5SDimitry Andric // error cases, so we just need to set Init to UndefValue. 4851*0b57cec5SDimitry Andric bool IsCUDASharedVar = 4852*0b57cec5SDimitry Andric getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>(); 4853*0b57cec5SDimitry Andric // Shadows of initialized device-side global variables are also left 4854*0b57cec5SDimitry Andric // undefined. 4855fe6060f1SDimitry Andric // Managed Variables should be initialized on both host side and device side. 4856*0b57cec5SDimitry Andric bool IsCUDAShadowVar = 4857e8d8bef9SDimitry Andric !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 4858*0b57cec5SDimitry Andric (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() || 4859*0b57cec5SDimitry Andric D->hasAttr<CUDASharedAttr>()); 48605ffd83dbSDimitry Andric bool IsCUDADeviceShadowVar = 4861fe6060f1SDimitry Andric getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 48625ffd83dbSDimitry Andric (D->getType()->isCUDADeviceBuiltinSurfaceType() || 4863fe6060f1SDimitry Andric D->getType()->isCUDADeviceBuiltinTextureType()); 4864*0b57cec5SDimitry Andric if (getLangOpts().CUDA && 48655ffd83dbSDimitry Andric (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) 4866fe6060f1SDimitry Andric Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 48675ffd83dbSDimitry Andric else if (D->hasAttr<LoaderUninitializedAttr>()) 4868fe6060f1SDimitry Andric Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 4869*0b57cec5SDimitry Andric else if (!InitExpr) { 4870*0b57cec5SDimitry Andric // This is a tentative definition; tentative definitions are 4871*0b57cec5SDimitry Andric // implicitly initialized with { 0 }. 4872*0b57cec5SDimitry Andric // 4873*0b57cec5SDimitry Andric // Note that tentative definitions are only emitted at the end of 4874*0b57cec5SDimitry Andric // a translation unit, so they should never have incomplete 4875*0b57cec5SDimitry Andric // type. In addition, EmitTentativeDefinition makes sure that we 4876*0b57cec5SDimitry Andric // never attempt to emit a tentative definition if a real one 4877*0b57cec5SDimitry Andric // exists. A use may still exists, however, so we still may need 4878*0b57cec5SDimitry Andric // to do a RAUW. 4879*0b57cec5SDimitry Andric assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 4880*0b57cec5SDimitry Andric Init = EmitNullConstant(D->getType()); 4881*0b57cec5SDimitry Andric } else { 4882*0b57cec5SDimitry Andric initializedGlobalDecl = GlobalDecl(D); 4883*0b57cec5SDimitry Andric emitter.emplace(*this); 4884fe6060f1SDimitry Andric llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl); 4885fe6060f1SDimitry Andric if (!Initializer) { 4886*0b57cec5SDimitry Andric QualType T = InitExpr->getType(); 4887*0b57cec5SDimitry Andric if (D->getType()->isReferenceType()) 4888*0b57cec5SDimitry Andric T = D->getType(); 4889*0b57cec5SDimitry Andric 4890*0b57cec5SDimitry Andric if (getLangOpts().CPlusPlus) { 489181ad6265SDimitry Andric if (InitDecl->hasFlexibleArrayInit(getContext())) 489281ad6265SDimitry Andric ErrorUnsupported(D, "flexible array initializer"); 4893*0b57cec5SDimitry Andric Init = EmitNullConstant(T); 4894bdd1243dSDimitry Andric 4895bdd1243dSDimitry Andric if (!IsDefinitionAvailableExternally) 4896*0b57cec5SDimitry Andric NeedsGlobalCtor = true; 4897*0b57cec5SDimitry Andric } else { 4898*0b57cec5SDimitry Andric ErrorUnsupported(D, "static initializer"); 4899*0b57cec5SDimitry Andric Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 4900*0b57cec5SDimitry Andric } 4901*0b57cec5SDimitry Andric } else { 4902fe6060f1SDimitry Andric Init = Initializer; 4903*0b57cec5SDimitry Andric // We don't need an initializer, so remove the entry for the delayed 4904*0b57cec5SDimitry Andric // initializer position (just in case this entry was delayed) if we 4905*0b57cec5SDimitry Andric // also don't need to register a destructor. 4906*0b57cec5SDimitry Andric if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 4907*0b57cec5SDimitry Andric DelayedCXXInitPosition.erase(D); 490881ad6265SDimitry Andric 490981ad6265SDimitry Andric #ifndef NDEBUG 491081ad6265SDimitry Andric CharUnits VarSize = getContext().getTypeSizeInChars(ASTTy) + 491181ad6265SDimitry Andric InitDecl->getFlexibleArrayInitChars(getContext()); 491281ad6265SDimitry Andric CharUnits CstSize = CharUnits::fromQuantity( 491381ad6265SDimitry Andric getDataLayout().getTypeAllocSize(Init->getType())); 491481ad6265SDimitry Andric assert(VarSize == CstSize && "Emitted constant has unexpected size"); 491581ad6265SDimitry Andric #endif 4916*0b57cec5SDimitry Andric } 4917*0b57cec5SDimitry Andric } 4918*0b57cec5SDimitry Andric 4919*0b57cec5SDimitry Andric llvm::Type* InitType = Init->getType(); 4920*0b57cec5SDimitry Andric llvm::Constant *Entry = 4921*0b57cec5SDimitry Andric GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); 4922*0b57cec5SDimitry Andric 4923a7dea167SDimitry Andric // Strip off pointer casts if we got them. 4924a7dea167SDimitry Andric Entry = Entry->stripPointerCasts(); 4925*0b57cec5SDimitry Andric 4926*0b57cec5SDimitry Andric // Entry is now either a Function or GlobalVariable. 4927*0b57cec5SDimitry Andric auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 4928*0b57cec5SDimitry Andric 4929*0b57cec5SDimitry Andric // We have a definition after a declaration with the wrong type. 4930*0b57cec5SDimitry Andric // We must make a new GlobalVariable* and update everything that used OldGV 4931*0b57cec5SDimitry Andric // (a declaration or tentative definition) with the new GlobalVariable* 4932*0b57cec5SDimitry Andric // (which will be a definition). 4933*0b57cec5SDimitry Andric // 4934*0b57cec5SDimitry Andric // This happens if there is a prototype for a global (e.g. 4935*0b57cec5SDimitry Andric // "extern int x[];") and then a definition of a different type (e.g. 4936*0b57cec5SDimitry Andric // "int x[10];"). This also happens when an initializer has a different type 4937*0b57cec5SDimitry Andric // from the type of the global (this happens with unions). 49385ffd83dbSDimitry Andric if (!GV || GV->getValueType() != InitType || 4939*0b57cec5SDimitry Andric GV->getType()->getAddressSpace() != 4940*0b57cec5SDimitry Andric getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) { 4941*0b57cec5SDimitry Andric 4942*0b57cec5SDimitry Andric // Move the old entry aside so that we'll create a new one. 4943*0b57cec5SDimitry Andric Entry->setName(StringRef()); 4944*0b57cec5SDimitry Andric 4945*0b57cec5SDimitry Andric // Make a new global with the correct type, this is now guaranteed to work. 4946*0b57cec5SDimitry Andric GV = cast<llvm::GlobalVariable>( 4947a7dea167SDimitry Andric GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)) 4948a7dea167SDimitry Andric ->stripPointerCasts()); 4949*0b57cec5SDimitry Andric 4950*0b57cec5SDimitry Andric // Replace all uses of the old global with the new global 4951*0b57cec5SDimitry Andric llvm::Constant *NewPtrForOldDecl = 4952fe6060f1SDimitry Andric llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, 4953fe6060f1SDimitry Andric Entry->getType()); 4954*0b57cec5SDimitry Andric Entry->replaceAllUsesWith(NewPtrForOldDecl); 4955*0b57cec5SDimitry Andric 4956*0b57cec5SDimitry Andric // Erase the old global, since it is no longer used. 4957*0b57cec5SDimitry Andric cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 4958*0b57cec5SDimitry Andric } 4959*0b57cec5SDimitry Andric 4960*0b57cec5SDimitry Andric MaybeHandleStaticInExternC(D, GV); 4961*0b57cec5SDimitry Andric 4962*0b57cec5SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 4963*0b57cec5SDimitry Andric AddGlobalAnnotations(D, GV); 4964*0b57cec5SDimitry Andric 4965*0b57cec5SDimitry Andric // Set the llvm linkage type as appropriate. 4966*0b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 4967*0b57cec5SDimitry Andric getLLVMLinkageVarDefinition(D, GV->isConstant()); 4968*0b57cec5SDimitry Andric 4969*0b57cec5SDimitry Andric // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 4970*0b57cec5SDimitry Andric // the device. [...]" 4971*0b57cec5SDimitry Andric // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 4972*0b57cec5SDimitry Andric // __device__, declares a variable that: [...] 4973*0b57cec5SDimitry Andric // Is accessible from all the threads within the grid and from the host 4974*0b57cec5SDimitry Andric // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 4975*0b57cec5SDimitry Andric // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 4976*0b57cec5SDimitry Andric if (GV && LangOpts.CUDA) { 4977*0b57cec5SDimitry Andric if (LangOpts.CUDAIsDevice) { 4978*0b57cec5SDimitry Andric if (Linkage != llvm::GlobalValue::InternalLinkage && 4979349cc55cSDimitry Andric (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 4980349cc55cSDimitry Andric D->getType()->isCUDADeviceBuiltinSurfaceType() || 4981349cc55cSDimitry Andric D->getType()->isCUDADeviceBuiltinTextureType())) 4982*0b57cec5SDimitry Andric GV->setExternallyInitialized(true); 4983*0b57cec5SDimitry Andric } else { 4984fe6060f1SDimitry Andric getCUDARuntime().internalizeDeviceSideVar(D, Linkage); 49855ffd83dbSDimitry Andric } 4986fe6060f1SDimitry Andric getCUDARuntime().handleVarRegistration(D, *GV); 4987*0b57cec5SDimitry Andric } 4988*0b57cec5SDimitry Andric 4989*0b57cec5SDimitry Andric GV->setInitializer(Init); 49905ffd83dbSDimitry Andric if (emitter) 49915ffd83dbSDimitry Andric emitter->finalize(GV); 4992*0b57cec5SDimitry Andric 4993*0b57cec5SDimitry Andric // If it is safe to mark the global 'constant', do so now. 4994*0b57cec5SDimitry Andric GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 4995*0b57cec5SDimitry Andric isTypeConstant(D->getType(), true)); 4996*0b57cec5SDimitry Andric 4997*0b57cec5SDimitry Andric // If it is in a read-only section, mark it 'constant'. 4998*0b57cec5SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 4999*0b57cec5SDimitry Andric const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 5000*0b57cec5SDimitry Andric if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 5001*0b57cec5SDimitry Andric GV->setConstant(true); 5002*0b57cec5SDimitry Andric } 5003*0b57cec5SDimitry Andric 500481ad6265SDimitry Andric CharUnits AlignVal = getContext().getDeclAlign(D); 500581ad6265SDimitry Andric // Check for alignment specifed in an 'omp allocate' directive. 5006bdd1243dSDimitry Andric if (std::optional<CharUnits> AlignValFromAllocate = 500781ad6265SDimitry Andric getOMPAllocateAlignment(D)) 500881ad6265SDimitry Andric AlignVal = *AlignValFromAllocate; 500981ad6265SDimitry Andric GV->setAlignment(AlignVal.getAsAlign()); 5010*0b57cec5SDimitry Andric 50115ffd83dbSDimitry Andric // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper 50125ffd83dbSDimitry Andric // function is only defined alongside the variable, not also alongside 50135ffd83dbSDimitry Andric // callers. Normally, all accesses to a thread_local go through the 50145ffd83dbSDimitry Andric // thread-wrapper in order to ensure initialization has occurred, underlying 50155ffd83dbSDimitry Andric // variable will never be used other than the thread-wrapper, so it can be 50165ffd83dbSDimitry Andric // converted to internal linkage. 50175ffd83dbSDimitry Andric // 50185ffd83dbSDimitry Andric // However, if the variable has the 'constinit' attribute, it _can_ be 50195ffd83dbSDimitry Andric // referenced directly, without calling the thread-wrapper, so the linkage 50205ffd83dbSDimitry Andric // must not be changed. 50215ffd83dbSDimitry Andric // 50225ffd83dbSDimitry Andric // Additionally, if the variable isn't plain external linkage, e.g. if it's 50235ffd83dbSDimitry Andric // weak or linkonce, the de-duplication semantics are important to preserve, 50245ffd83dbSDimitry Andric // so we don't change the linkage. 50255ffd83dbSDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic && 50265ffd83dbSDimitry Andric Linkage == llvm::GlobalValue::ExternalLinkage && 5027*0b57cec5SDimitry Andric Context.getTargetInfo().getTriple().isOSDarwin() && 50285ffd83dbSDimitry Andric !D->hasAttr<ConstInitAttr>()) 5029*0b57cec5SDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 5030*0b57cec5SDimitry Andric 5031*0b57cec5SDimitry Andric GV->setLinkage(Linkage); 5032*0b57cec5SDimitry Andric if (D->hasAttr<DLLImportAttr>()) 5033*0b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 5034*0b57cec5SDimitry Andric else if (D->hasAttr<DLLExportAttr>()) 5035*0b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 5036*0b57cec5SDimitry Andric else 5037*0b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 5038*0b57cec5SDimitry Andric 5039*0b57cec5SDimitry Andric if (Linkage == llvm::GlobalVariable::CommonLinkage) { 5040*0b57cec5SDimitry Andric // common vars aren't constant even if declared const. 5041*0b57cec5SDimitry Andric GV->setConstant(false); 5042*0b57cec5SDimitry Andric // Tentative definition of global variables may be initialized with 5043*0b57cec5SDimitry Andric // non-zero null pointers. In this case they should have weak linkage 5044*0b57cec5SDimitry Andric // since common linkage must have zero initializer and must not have 5045*0b57cec5SDimitry Andric // explicit section therefore cannot have non-zero initial value. 5046*0b57cec5SDimitry Andric if (!GV->getInitializer()->isNullValue()) 5047*0b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 5048*0b57cec5SDimitry Andric } 5049*0b57cec5SDimitry Andric 5050*0b57cec5SDimitry Andric setNonAliasAttributes(D, GV); 5051*0b57cec5SDimitry Andric 5052*0b57cec5SDimitry Andric if (D->getTLSKind() && !GV->isThreadLocal()) { 5053*0b57cec5SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 5054*0b57cec5SDimitry Andric CXXThreadLocals.push_back(D); 5055*0b57cec5SDimitry Andric setTLSMode(GV, *D); 5056*0b57cec5SDimitry Andric } 5057*0b57cec5SDimitry Andric 5058*0b57cec5SDimitry Andric maybeSetTrivialComdat(*D, *GV); 5059*0b57cec5SDimitry Andric 5060*0b57cec5SDimitry Andric // Emit the initializer function if necessary. 5061*0b57cec5SDimitry Andric if (NeedsGlobalCtor || NeedsGlobalDtor) 5062*0b57cec5SDimitry Andric EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 5063*0b57cec5SDimitry Andric 506481ad6265SDimitry Andric SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor); 5065*0b57cec5SDimitry Andric 5066*0b57cec5SDimitry Andric // Emit global variable debug information. 5067*0b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 5068480093f4SDimitry Andric if (getCodeGenOpts().hasReducedDebugInfo()) 5069*0b57cec5SDimitry Andric DI->EmitGlobalVariable(GV, D); 5070*0b57cec5SDimitry Andric } 5071*0b57cec5SDimitry Andric 5072480093f4SDimitry Andric void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) { 5073480093f4SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 5074480093f4SDimitry Andric if (getCodeGenOpts().hasReducedDebugInfo()) { 5075480093f4SDimitry Andric QualType ASTTy = D->getType(); 5076480093f4SDimitry Andric llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType()); 5077349cc55cSDimitry Andric llvm::Constant *GV = 5078349cc55cSDimitry Andric GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D); 5079480093f4SDimitry Andric DI->EmitExternalVariable( 5080480093f4SDimitry Andric cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D); 5081480093f4SDimitry Andric } 5082480093f4SDimitry Andric } 5083480093f4SDimitry Andric 5084*0b57cec5SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context, 5085*0b57cec5SDimitry Andric CodeGenModule &CGM, const VarDecl *D, 5086*0b57cec5SDimitry Andric bool NoCommon) { 5087*0b57cec5SDimitry Andric // Don't give variables common linkage if -fno-common was specified unless it 5088*0b57cec5SDimitry Andric // was overridden by a NoCommon attribute. 5089*0b57cec5SDimitry Andric if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 5090*0b57cec5SDimitry Andric return true; 5091*0b57cec5SDimitry Andric 5092*0b57cec5SDimitry Andric // C11 6.9.2/2: 5093*0b57cec5SDimitry Andric // A declaration of an identifier for an object that has file scope without 5094*0b57cec5SDimitry Andric // an initializer, and without a storage-class specifier or with the 5095*0b57cec5SDimitry Andric // storage-class specifier static, constitutes a tentative definition. 5096*0b57cec5SDimitry Andric if (D->getInit() || D->hasExternalStorage()) 5097*0b57cec5SDimitry Andric return true; 5098*0b57cec5SDimitry Andric 5099*0b57cec5SDimitry Andric // A variable cannot be both common and exist in a section. 5100*0b57cec5SDimitry Andric if (D->hasAttr<SectionAttr>()) 5101*0b57cec5SDimitry Andric return true; 5102*0b57cec5SDimitry Andric 5103*0b57cec5SDimitry Andric // A variable cannot be both common and exist in a section. 5104*0b57cec5SDimitry Andric // We don't try to determine which is the right section in the front-end. 5105*0b57cec5SDimitry Andric // If no specialized section name is applicable, it will resort to default. 5106*0b57cec5SDimitry Andric if (D->hasAttr<PragmaClangBSSSectionAttr>() || 5107*0b57cec5SDimitry Andric D->hasAttr<PragmaClangDataSectionAttr>() || 5108a7dea167SDimitry Andric D->hasAttr<PragmaClangRelroSectionAttr>() || 5109*0b57cec5SDimitry Andric D->hasAttr<PragmaClangRodataSectionAttr>()) 5110*0b57cec5SDimitry Andric return true; 5111*0b57cec5SDimitry Andric 5112*0b57cec5SDimitry Andric // Thread local vars aren't considered common linkage. 5113*0b57cec5SDimitry Andric if (D->getTLSKind()) 5114*0b57cec5SDimitry Andric return true; 5115*0b57cec5SDimitry Andric 5116*0b57cec5SDimitry Andric // Tentative definitions marked with WeakImportAttr are true definitions. 5117*0b57cec5SDimitry Andric if (D->hasAttr<WeakImportAttr>()) 5118*0b57cec5SDimitry Andric return true; 5119*0b57cec5SDimitry Andric 5120*0b57cec5SDimitry Andric // A variable cannot be both common and exist in a comdat. 5121*0b57cec5SDimitry Andric if (shouldBeInCOMDAT(CGM, *D)) 5122*0b57cec5SDimitry Andric return true; 5123*0b57cec5SDimitry Andric 5124*0b57cec5SDimitry Andric // Declarations with a required alignment do not have common linkage in MSVC 5125*0b57cec5SDimitry Andric // mode. 5126*0b57cec5SDimitry Andric if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5127*0b57cec5SDimitry Andric if (D->hasAttr<AlignedAttr>()) 5128*0b57cec5SDimitry Andric return true; 5129*0b57cec5SDimitry Andric QualType VarType = D->getType(); 5130*0b57cec5SDimitry Andric if (Context.isAlignmentRequired(VarType)) 5131*0b57cec5SDimitry Andric return true; 5132*0b57cec5SDimitry Andric 5133*0b57cec5SDimitry Andric if (const auto *RT = VarType->getAs<RecordType>()) { 5134*0b57cec5SDimitry Andric const RecordDecl *RD = RT->getDecl(); 5135*0b57cec5SDimitry Andric for (const FieldDecl *FD : RD->fields()) { 5136*0b57cec5SDimitry Andric if (FD->isBitField()) 5137*0b57cec5SDimitry Andric continue; 5138*0b57cec5SDimitry Andric if (FD->hasAttr<AlignedAttr>()) 5139*0b57cec5SDimitry Andric return true; 5140*0b57cec5SDimitry Andric if (Context.isAlignmentRequired(FD->getType())) 5141*0b57cec5SDimitry Andric return true; 5142*0b57cec5SDimitry Andric } 5143*0b57cec5SDimitry Andric } 5144*0b57cec5SDimitry Andric } 5145*0b57cec5SDimitry Andric 5146*0b57cec5SDimitry Andric // Microsoft's link.exe doesn't support alignments greater than 32 bytes for 5147*0b57cec5SDimitry Andric // common symbols, so symbols with greater alignment requirements cannot be 5148*0b57cec5SDimitry Andric // common. 5149*0b57cec5SDimitry Andric // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two 5150*0b57cec5SDimitry Andric // alignments for common symbols via the aligncomm directive, so this 5151*0b57cec5SDimitry Andric // restriction only applies to MSVC environments. 5152*0b57cec5SDimitry Andric if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() && 5153*0b57cec5SDimitry Andric Context.getTypeAlignIfKnown(D->getType()) > 5154*0b57cec5SDimitry Andric Context.toBits(CharUnits::fromQuantity(32))) 5155*0b57cec5SDimitry Andric return true; 5156*0b57cec5SDimitry Andric 5157*0b57cec5SDimitry Andric return false; 5158*0b57cec5SDimitry Andric } 5159*0b57cec5SDimitry Andric 5160*0b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 5161*0b57cec5SDimitry Andric const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 5162*0b57cec5SDimitry Andric if (Linkage == GVA_Internal) 5163*0b57cec5SDimitry Andric return llvm::Function::InternalLinkage; 5164*0b57cec5SDimitry Andric 516581ad6265SDimitry Andric if (D->hasAttr<WeakAttr>()) 5166*0b57cec5SDimitry Andric return llvm::GlobalVariable::WeakAnyLinkage; 5167*0b57cec5SDimitry Andric 5168*0b57cec5SDimitry Andric if (const auto *FD = D->getAsFunction()) 5169*0b57cec5SDimitry Andric if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally) 5170*0b57cec5SDimitry Andric return llvm::GlobalVariable::LinkOnceAnyLinkage; 5171*0b57cec5SDimitry Andric 5172*0b57cec5SDimitry Andric // We are guaranteed to have a strong definition somewhere else, 5173*0b57cec5SDimitry Andric // so we can use available_externally linkage. 5174*0b57cec5SDimitry Andric if (Linkage == GVA_AvailableExternally) 5175*0b57cec5SDimitry Andric return llvm::GlobalValue::AvailableExternallyLinkage; 5176*0b57cec5SDimitry Andric 5177*0b57cec5SDimitry Andric // Note that Apple's kernel linker doesn't support symbol 5178*0b57cec5SDimitry Andric // coalescing, so we need to avoid linkonce and weak linkages there. 5179*0b57cec5SDimitry Andric // Normally, this means we just map to internal, but for explicit 5180*0b57cec5SDimitry Andric // instantiations we'll map to external. 5181*0b57cec5SDimitry Andric 5182*0b57cec5SDimitry Andric // In C++, the compiler has to emit a definition in every translation unit 5183*0b57cec5SDimitry Andric // that references the function. We should use linkonce_odr because 5184*0b57cec5SDimitry Andric // a) if all references in this translation unit are optimized away, we 5185*0b57cec5SDimitry Andric // don't need to codegen it. b) if the function persists, it needs to be 5186*0b57cec5SDimitry Andric // merged with other definitions. c) C++ has the ODR, so we know the 5187*0b57cec5SDimitry Andric // definition is dependable. 5188*0b57cec5SDimitry Andric if (Linkage == GVA_DiscardableODR) 5189*0b57cec5SDimitry Andric return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 5190*0b57cec5SDimitry Andric : llvm::Function::InternalLinkage; 5191*0b57cec5SDimitry Andric 5192*0b57cec5SDimitry Andric // An explicit instantiation of a template has weak linkage, since 5193*0b57cec5SDimitry Andric // explicit instantiations can occur in multiple translation units 5194*0b57cec5SDimitry Andric // and must all be equivalent. However, we are not allowed to 5195*0b57cec5SDimitry Andric // throw away these explicit instantiations. 5196*0b57cec5SDimitry Andric // 5197e8d8bef9SDimitry Andric // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU, 5198*0b57cec5SDimitry Andric // so say that CUDA templates are either external (for kernels) or internal. 5199e8d8bef9SDimitry Andric // This lets llvm perform aggressive inter-procedural optimizations. For 5200e8d8bef9SDimitry Andric // -fgpu-rdc case, device function calls across multiple TU's are allowed, 5201e8d8bef9SDimitry Andric // therefore we need to follow the normal linkage paradigm. 5202*0b57cec5SDimitry Andric if (Linkage == GVA_StrongODR) { 5203e8d8bef9SDimitry Andric if (getLangOpts().AppleKext) 5204*0b57cec5SDimitry Andric return llvm::Function::ExternalLinkage; 5205e8d8bef9SDimitry Andric if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 5206e8d8bef9SDimitry Andric !getLangOpts().GPURelocatableDeviceCode) 5207*0b57cec5SDimitry Andric return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage 5208*0b57cec5SDimitry Andric : llvm::Function::InternalLinkage; 5209*0b57cec5SDimitry Andric return llvm::Function::WeakODRLinkage; 5210*0b57cec5SDimitry Andric } 5211*0b57cec5SDimitry Andric 5212*0b57cec5SDimitry Andric // C++ doesn't have tentative definitions and thus cannot have common 5213*0b57cec5SDimitry Andric // linkage. 5214*0b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 5215*0b57cec5SDimitry Andric !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 5216*0b57cec5SDimitry Andric CodeGenOpts.NoCommon)) 5217*0b57cec5SDimitry Andric return llvm::GlobalVariable::CommonLinkage; 5218*0b57cec5SDimitry Andric 5219*0b57cec5SDimitry Andric // selectany symbols are externally visible, so use weak instead of 5220*0b57cec5SDimitry Andric // linkonce. MSVC optimizes away references to const selectany globals, so 5221*0b57cec5SDimitry Andric // all definitions should be the same and ODR linkage should be used. 5222*0b57cec5SDimitry Andric // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 5223*0b57cec5SDimitry Andric if (D->hasAttr<SelectAnyAttr>()) 5224*0b57cec5SDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 5225*0b57cec5SDimitry Andric 5226*0b57cec5SDimitry Andric // Otherwise, we have strong external linkage. 5227*0b57cec5SDimitry Andric assert(Linkage == GVA_StrongExternal); 5228*0b57cec5SDimitry Andric return llvm::GlobalVariable::ExternalLinkage; 5229*0b57cec5SDimitry Andric } 5230*0b57cec5SDimitry Andric 5231*0b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 5232*0b57cec5SDimitry Andric const VarDecl *VD, bool IsConstant) { 5233*0b57cec5SDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 5234*0b57cec5SDimitry Andric return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 5235*0b57cec5SDimitry Andric } 5236*0b57cec5SDimitry Andric 5237*0b57cec5SDimitry Andric /// Replace the uses of a function that was declared with a non-proto type. 5238*0b57cec5SDimitry Andric /// We want to silently drop extra arguments from call sites 5239*0b57cec5SDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 5240*0b57cec5SDimitry Andric llvm::Function *newFn) { 5241*0b57cec5SDimitry Andric // Fast path. 5242*0b57cec5SDimitry Andric if (old->use_empty()) return; 5243*0b57cec5SDimitry Andric 5244*0b57cec5SDimitry Andric llvm::Type *newRetTy = newFn->getReturnType(); 5245*0b57cec5SDimitry Andric SmallVector<llvm::Value*, 4> newArgs; 5246*0b57cec5SDimitry Andric 5247*0b57cec5SDimitry Andric for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 5248*0b57cec5SDimitry Andric ui != ue; ) { 5249*0b57cec5SDimitry Andric llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 5250*0b57cec5SDimitry Andric llvm::User *user = use->getUser(); 5251*0b57cec5SDimitry Andric 5252*0b57cec5SDimitry Andric // Recognize and replace uses of bitcasts. Most calls to 5253*0b57cec5SDimitry Andric // unprototyped functions will use bitcasts. 5254*0b57cec5SDimitry Andric if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 5255*0b57cec5SDimitry Andric if (bitcast->getOpcode() == llvm::Instruction::BitCast) 5256*0b57cec5SDimitry Andric replaceUsesOfNonProtoConstant(bitcast, newFn); 5257*0b57cec5SDimitry Andric continue; 5258*0b57cec5SDimitry Andric } 5259*0b57cec5SDimitry Andric 5260*0b57cec5SDimitry Andric // Recognize calls to the function. 5261*0b57cec5SDimitry Andric llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user); 5262*0b57cec5SDimitry Andric if (!callSite) continue; 5263*0b57cec5SDimitry Andric if (!callSite->isCallee(&*use)) 5264*0b57cec5SDimitry Andric continue; 5265*0b57cec5SDimitry Andric 5266*0b57cec5SDimitry Andric // If the return types don't match exactly, then we can't 5267*0b57cec5SDimitry Andric // transform this call unless it's dead. 5268*0b57cec5SDimitry Andric if (callSite->getType() != newRetTy && !callSite->use_empty()) 5269*0b57cec5SDimitry Andric continue; 5270*0b57cec5SDimitry Andric 5271*0b57cec5SDimitry Andric // Get the call site's attribute list. 5272*0b57cec5SDimitry Andric SmallVector<llvm::AttributeSet, 8> newArgAttrs; 5273*0b57cec5SDimitry Andric llvm::AttributeList oldAttrs = callSite->getAttributes(); 5274*0b57cec5SDimitry Andric 5275*0b57cec5SDimitry Andric // If the function was passed too few arguments, don't transform. 5276*0b57cec5SDimitry Andric unsigned newNumArgs = newFn->arg_size(); 5277*0b57cec5SDimitry Andric if (callSite->arg_size() < newNumArgs) 5278*0b57cec5SDimitry Andric continue; 5279*0b57cec5SDimitry Andric 5280*0b57cec5SDimitry Andric // If extra arguments were passed, we silently drop them. 5281*0b57cec5SDimitry Andric // If any of the types mismatch, we don't transform. 5282*0b57cec5SDimitry Andric unsigned argNo = 0; 5283*0b57cec5SDimitry Andric bool dontTransform = false; 5284*0b57cec5SDimitry Andric for (llvm::Argument &A : newFn->args()) { 5285*0b57cec5SDimitry Andric if (callSite->getArgOperand(argNo)->getType() != A.getType()) { 5286*0b57cec5SDimitry Andric dontTransform = true; 5287*0b57cec5SDimitry Andric break; 5288*0b57cec5SDimitry Andric } 5289*0b57cec5SDimitry Andric 5290*0b57cec5SDimitry Andric // Add any parameter attributes. 5291349cc55cSDimitry Andric newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo)); 5292*0b57cec5SDimitry Andric argNo++; 5293*0b57cec5SDimitry Andric } 5294*0b57cec5SDimitry Andric if (dontTransform) 5295*0b57cec5SDimitry Andric continue; 5296*0b57cec5SDimitry Andric 5297*0b57cec5SDimitry Andric // Okay, we can transform this. Create the new call instruction and copy 5298*0b57cec5SDimitry Andric // over the required information. 5299*0b57cec5SDimitry Andric newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo); 5300*0b57cec5SDimitry Andric 5301*0b57cec5SDimitry Andric // Copy over any operand bundles. 5302fe6060f1SDimitry Andric SmallVector<llvm::OperandBundleDef, 1> newBundles; 5303*0b57cec5SDimitry Andric callSite->getOperandBundlesAsDefs(newBundles); 5304*0b57cec5SDimitry Andric 5305*0b57cec5SDimitry Andric llvm::CallBase *newCall; 5306349cc55cSDimitry Andric if (isa<llvm::CallInst>(callSite)) { 5307*0b57cec5SDimitry Andric newCall = 5308*0b57cec5SDimitry Andric llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite); 5309*0b57cec5SDimitry Andric } else { 5310*0b57cec5SDimitry Andric auto *oldInvoke = cast<llvm::InvokeInst>(callSite); 5311*0b57cec5SDimitry Andric newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(), 5312*0b57cec5SDimitry Andric oldInvoke->getUnwindDest(), newArgs, 5313*0b57cec5SDimitry Andric newBundles, "", callSite); 5314*0b57cec5SDimitry Andric } 5315*0b57cec5SDimitry Andric newArgs.clear(); // for the next iteration 5316*0b57cec5SDimitry Andric 5317*0b57cec5SDimitry Andric if (!newCall->getType()->isVoidTy()) 5318*0b57cec5SDimitry Andric newCall->takeName(callSite); 5319349cc55cSDimitry Andric newCall->setAttributes( 5320349cc55cSDimitry Andric llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(), 5321349cc55cSDimitry Andric oldAttrs.getRetAttrs(), newArgAttrs)); 5322*0b57cec5SDimitry Andric newCall->setCallingConv(callSite->getCallingConv()); 5323*0b57cec5SDimitry Andric 5324*0b57cec5SDimitry Andric // Finally, remove the old call, replacing any uses with the new one. 5325*0b57cec5SDimitry Andric if (!callSite->use_empty()) 5326*0b57cec5SDimitry Andric callSite->replaceAllUsesWith(newCall); 5327*0b57cec5SDimitry Andric 5328*0b57cec5SDimitry Andric // Copy debug location attached to CI. 5329*0b57cec5SDimitry Andric if (callSite->getDebugLoc()) 5330*0b57cec5SDimitry Andric newCall->setDebugLoc(callSite->getDebugLoc()); 5331*0b57cec5SDimitry Andric 5332*0b57cec5SDimitry Andric callSite->eraseFromParent(); 5333*0b57cec5SDimitry Andric } 5334*0b57cec5SDimitry Andric } 5335*0b57cec5SDimitry Andric 5336*0b57cec5SDimitry Andric /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 5337*0b57cec5SDimitry Andric /// implement a function with no prototype, e.g. "int foo() {}". If there are 5338*0b57cec5SDimitry Andric /// existing call uses of the old function in the module, this adjusts them to 5339*0b57cec5SDimitry Andric /// call the new function directly. 5340*0b57cec5SDimitry Andric /// 5341*0b57cec5SDimitry Andric /// This is not just a cleanup: the always_inline pass requires direct calls to 5342*0b57cec5SDimitry Andric /// functions to be able to inline them. If there is a bitcast in the way, it 5343*0b57cec5SDimitry Andric /// won't inline them. Instcombine normally deletes these calls, but it isn't 5344*0b57cec5SDimitry Andric /// run at -O0. 5345*0b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 5346*0b57cec5SDimitry Andric llvm::Function *NewFn) { 5347*0b57cec5SDimitry Andric // If we're redefining a global as a function, don't transform it. 5348*0b57cec5SDimitry Andric if (!isa<llvm::Function>(Old)) return; 5349*0b57cec5SDimitry Andric 5350*0b57cec5SDimitry Andric replaceUsesOfNonProtoConstant(Old, NewFn); 5351*0b57cec5SDimitry Andric } 5352*0b57cec5SDimitry Andric 5353*0b57cec5SDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 5354*0b57cec5SDimitry Andric auto DK = VD->isThisDeclarationADefinition(); 5355*0b57cec5SDimitry Andric if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) 5356*0b57cec5SDimitry Andric return; 5357*0b57cec5SDimitry Andric 5358*0b57cec5SDimitry Andric TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 5359*0b57cec5SDimitry Andric // If we have a definition, this might be a deferred decl. If the 5360*0b57cec5SDimitry Andric // instantiation is explicit, make sure we emit it at the end. 5361*0b57cec5SDimitry Andric if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 5362*0b57cec5SDimitry Andric GetAddrOfGlobalVar(VD); 5363*0b57cec5SDimitry Andric 5364*0b57cec5SDimitry Andric EmitTopLevelDecl(VD); 5365*0b57cec5SDimitry Andric } 5366*0b57cec5SDimitry Andric 5367*0b57cec5SDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 5368*0b57cec5SDimitry Andric llvm::GlobalValue *GV) { 5369*0b57cec5SDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 5370*0b57cec5SDimitry Andric 5371*0b57cec5SDimitry Andric // Compute the function info and LLVM type. 5372*0b57cec5SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 5373*0b57cec5SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 5374*0b57cec5SDimitry Andric 5375*0b57cec5SDimitry Andric // Get or create the prototype for the function. 53765ffd83dbSDimitry Andric if (!GV || (GV->getValueType() != Ty)) 5377*0b57cec5SDimitry Andric GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 5378*0b57cec5SDimitry Andric /*DontDefer=*/true, 5379*0b57cec5SDimitry Andric ForDefinition)); 5380*0b57cec5SDimitry Andric 5381*0b57cec5SDimitry Andric // Already emitted. 5382*0b57cec5SDimitry Andric if (!GV->isDeclaration()) 5383*0b57cec5SDimitry Andric return; 5384*0b57cec5SDimitry Andric 5385*0b57cec5SDimitry Andric // We need to set linkage and visibility on the function before 5386*0b57cec5SDimitry Andric // generating code for it because various parts of IR generation 5387*0b57cec5SDimitry Andric // want to propagate this information down (e.g. to local static 5388*0b57cec5SDimitry Andric // declarations). 5389*0b57cec5SDimitry Andric auto *Fn = cast<llvm::Function>(GV); 5390*0b57cec5SDimitry Andric setFunctionLinkage(GD, Fn); 5391*0b57cec5SDimitry Andric 5392*0b57cec5SDimitry Andric // FIXME: this is redundant with part of setFunctionDefinitionAttributes 5393*0b57cec5SDimitry Andric setGVProperties(Fn, GD); 5394*0b57cec5SDimitry Andric 5395*0b57cec5SDimitry Andric MaybeHandleStaticInExternC(D, Fn); 5396*0b57cec5SDimitry Andric 5397*0b57cec5SDimitry Andric maybeSetTrivialComdat(*D, *Fn); 5398*0b57cec5SDimitry Andric 5399e8d8bef9SDimitry Andric // Set CodeGen attributes that represent floating point environment. 5400e8d8bef9SDimitry Andric setLLVMFunctionFEnvAttributes(D, Fn); 5401e8d8bef9SDimitry Andric 54025ffd83dbSDimitry Andric CodeGenFunction(*this).GenerateCode(GD, Fn, FI); 5403*0b57cec5SDimitry Andric 5404*0b57cec5SDimitry Andric setNonAliasAttributes(GD, Fn); 5405*0b57cec5SDimitry Andric SetLLVMFunctionAttributesForDefinition(D, Fn); 5406*0b57cec5SDimitry Andric 5407*0b57cec5SDimitry Andric if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 5408*0b57cec5SDimitry Andric AddGlobalCtor(Fn, CA->getPriority()); 5409*0b57cec5SDimitry Andric if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 5410e8d8bef9SDimitry Andric AddGlobalDtor(Fn, DA->getPriority(), true); 5411*0b57cec5SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 5412*0b57cec5SDimitry Andric AddGlobalAnnotations(D, Fn); 5413*0b57cec5SDimitry Andric } 5414*0b57cec5SDimitry Andric 5415*0b57cec5SDimitry Andric void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 5416*0b57cec5SDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 5417*0b57cec5SDimitry Andric const AliasAttr *AA = D->getAttr<AliasAttr>(); 5418*0b57cec5SDimitry Andric assert(AA && "Not an alias?"); 5419*0b57cec5SDimitry Andric 5420*0b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 5421*0b57cec5SDimitry Andric 5422*0b57cec5SDimitry Andric if (AA->getAliasee() == MangledName) { 5423*0b57cec5SDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 5424*0b57cec5SDimitry Andric return; 5425*0b57cec5SDimitry Andric } 5426*0b57cec5SDimitry Andric 5427*0b57cec5SDimitry Andric // If there is a definition in the module, then it wins over the alias. 5428*0b57cec5SDimitry Andric // This is dubious, but allow it to be safe. Just ignore the alias. 5429*0b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 5430*0b57cec5SDimitry Andric if (Entry && !Entry->isDeclaration()) 5431*0b57cec5SDimitry Andric return; 5432*0b57cec5SDimitry Andric 5433*0b57cec5SDimitry Andric Aliases.push_back(GD); 5434*0b57cec5SDimitry Andric 5435*0b57cec5SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 5436*0b57cec5SDimitry Andric 5437*0b57cec5SDimitry Andric // Create a reference to the named value. This ensures that it is emitted 5438*0b57cec5SDimitry Andric // if a deferred decl. 5439*0b57cec5SDimitry Andric llvm::Constant *Aliasee; 5440*0b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes LT; 5441*0b57cec5SDimitry Andric if (isa<llvm::FunctionType>(DeclTy)) { 5442*0b57cec5SDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 5443*0b57cec5SDimitry Andric /*ForVTable=*/false); 5444*0b57cec5SDimitry Andric LT = getFunctionLinkage(GD); 5445*0b57cec5SDimitry Andric } else { 5446349cc55cSDimitry Andric Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 5447*0b57cec5SDimitry Andric /*D=*/nullptr); 5448e8d8bef9SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl())) 5449e8d8bef9SDimitry Andric LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified()); 5450e8d8bef9SDimitry Andric else 5451e8d8bef9SDimitry Andric LT = getFunctionLinkage(GD); 5452*0b57cec5SDimitry Andric } 5453*0b57cec5SDimitry Andric 5454*0b57cec5SDimitry Andric // Create the new alias itself, but don't set a name yet. 54555ffd83dbSDimitry Andric unsigned AS = Aliasee->getType()->getPointerAddressSpace(); 5456*0b57cec5SDimitry Andric auto *GA = 54575ffd83dbSDimitry Andric llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule()); 5458*0b57cec5SDimitry Andric 5459*0b57cec5SDimitry Andric if (Entry) { 5460*0b57cec5SDimitry Andric if (GA->getAliasee() == Entry) { 5461*0b57cec5SDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 5462*0b57cec5SDimitry Andric return; 5463*0b57cec5SDimitry Andric } 5464*0b57cec5SDimitry Andric 5465*0b57cec5SDimitry Andric assert(Entry->isDeclaration()); 5466*0b57cec5SDimitry Andric 5467*0b57cec5SDimitry Andric // If there is a declaration in the module, then we had an extern followed 5468*0b57cec5SDimitry Andric // by the alias, as in: 5469*0b57cec5SDimitry Andric // extern int test6(); 5470*0b57cec5SDimitry Andric // ... 5471*0b57cec5SDimitry Andric // int test6() __attribute__((alias("test7"))); 5472*0b57cec5SDimitry Andric // 5473*0b57cec5SDimitry Andric // Remove it and replace uses of it with the alias. 5474*0b57cec5SDimitry Andric GA->takeName(Entry); 5475*0b57cec5SDimitry Andric 5476*0b57cec5SDimitry Andric Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 5477*0b57cec5SDimitry Andric Entry->getType())); 5478*0b57cec5SDimitry Andric Entry->eraseFromParent(); 5479*0b57cec5SDimitry Andric } else { 5480*0b57cec5SDimitry Andric GA->setName(MangledName); 5481*0b57cec5SDimitry Andric } 5482*0b57cec5SDimitry Andric 5483*0b57cec5SDimitry Andric // Set attributes which are particular to an alias; this is a 5484*0b57cec5SDimitry Andric // specialization of the attributes which may be set on a global 5485*0b57cec5SDimitry Andric // variable/function. 5486*0b57cec5SDimitry Andric if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 5487*0b57cec5SDimitry Andric D->isWeakImported()) { 5488*0b57cec5SDimitry Andric GA->setLinkage(llvm::Function::WeakAnyLinkage); 5489*0b57cec5SDimitry Andric } 5490*0b57cec5SDimitry Andric 5491*0b57cec5SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 5492*0b57cec5SDimitry Andric if (VD->getTLSKind()) 5493*0b57cec5SDimitry Andric setTLSMode(GA, *VD); 5494*0b57cec5SDimitry Andric 5495*0b57cec5SDimitry Andric SetCommonAttributes(GD, GA); 549681ad6265SDimitry Andric 549781ad6265SDimitry Andric // Emit global alias debug information. 549881ad6265SDimitry Andric if (isa<VarDecl>(D)) 549981ad6265SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 5500bdd1243dSDimitry Andric DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD); 5501*0b57cec5SDimitry Andric } 5502*0b57cec5SDimitry Andric 5503*0b57cec5SDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 5504*0b57cec5SDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 5505*0b57cec5SDimitry Andric const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 5506*0b57cec5SDimitry Andric assert(IFA && "Not an ifunc?"); 5507*0b57cec5SDimitry Andric 5508*0b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 5509*0b57cec5SDimitry Andric 5510*0b57cec5SDimitry Andric if (IFA->getResolver() == MangledName) { 5511*0b57cec5SDimitry Andric Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 5512*0b57cec5SDimitry Andric return; 5513*0b57cec5SDimitry Andric } 5514*0b57cec5SDimitry Andric 5515*0b57cec5SDimitry Andric // Report an error if some definition overrides ifunc. 5516*0b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 5517*0b57cec5SDimitry Andric if (Entry && !Entry->isDeclaration()) { 5518*0b57cec5SDimitry Andric GlobalDecl OtherGD; 5519*0b57cec5SDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 5520*0b57cec5SDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 5521*0b57cec5SDimitry Andric Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name) 5522*0b57cec5SDimitry Andric << MangledName; 5523*0b57cec5SDimitry Andric Diags.Report(OtherGD.getDecl()->getLocation(), 5524*0b57cec5SDimitry Andric diag::note_previous_definition); 5525*0b57cec5SDimitry Andric } 5526*0b57cec5SDimitry Andric return; 5527*0b57cec5SDimitry Andric } 5528*0b57cec5SDimitry Andric 5529*0b57cec5SDimitry Andric Aliases.push_back(GD); 5530*0b57cec5SDimitry Andric 5531*0b57cec5SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 5532349cc55cSDimitry Andric llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy); 5533*0b57cec5SDimitry Andric llvm::Constant *Resolver = 5534349cc55cSDimitry Andric GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {}, 5535*0b57cec5SDimitry Andric /*ForVTable=*/false); 5536*0b57cec5SDimitry Andric llvm::GlobalIFunc *GIF = 5537*0b57cec5SDimitry Andric llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 5538*0b57cec5SDimitry Andric "", Resolver, &getModule()); 5539*0b57cec5SDimitry Andric if (Entry) { 5540*0b57cec5SDimitry Andric if (GIF->getResolver() == Entry) { 5541*0b57cec5SDimitry Andric Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 5542*0b57cec5SDimitry Andric return; 5543*0b57cec5SDimitry Andric } 5544*0b57cec5SDimitry Andric assert(Entry->isDeclaration()); 5545*0b57cec5SDimitry Andric 5546*0b57cec5SDimitry Andric // If there is a declaration in the module, then we had an extern followed 5547*0b57cec5SDimitry Andric // by the ifunc, as in: 5548*0b57cec5SDimitry Andric // extern int test(); 5549*0b57cec5SDimitry Andric // ... 5550*0b57cec5SDimitry Andric // int test() __attribute__((ifunc("resolver"))); 5551*0b57cec5SDimitry Andric // 5552*0b57cec5SDimitry Andric // Remove it and replace uses of it with the ifunc. 5553*0b57cec5SDimitry Andric GIF->takeName(Entry); 5554*0b57cec5SDimitry Andric 5555*0b57cec5SDimitry Andric Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF, 5556*0b57cec5SDimitry Andric Entry->getType())); 5557*0b57cec5SDimitry Andric Entry->eraseFromParent(); 5558*0b57cec5SDimitry Andric } else 5559*0b57cec5SDimitry Andric GIF->setName(MangledName); 5560*0b57cec5SDimitry Andric 5561*0b57cec5SDimitry Andric SetCommonAttributes(GD, GIF); 5562*0b57cec5SDimitry Andric } 5563*0b57cec5SDimitry Andric 5564*0b57cec5SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 5565*0b57cec5SDimitry Andric ArrayRef<llvm::Type*> Tys) { 5566*0b57cec5SDimitry Andric return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 5567*0b57cec5SDimitry Andric Tys); 5568*0b57cec5SDimitry Andric } 5569*0b57cec5SDimitry Andric 5570*0b57cec5SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> & 5571*0b57cec5SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 5572*0b57cec5SDimitry Andric const StringLiteral *Literal, bool TargetIsLSB, 5573*0b57cec5SDimitry Andric bool &IsUTF16, unsigned &StringLength) { 5574*0b57cec5SDimitry Andric StringRef String = Literal->getString(); 5575*0b57cec5SDimitry Andric unsigned NumBytes = String.size(); 5576*0b57cec5SDimitry Andric 5577*0b57cec5SDimitry Andric // Check for simple case. 5578*0b57cec5SDimitry Andric if (!Literal->containsNonAsciiOrNull()) { 5579*0b57cec5SDimitry Andric StringLength = NumBytes; 5580*0b57cec5SDimitry Andric return *Map.insert(std::make_pair(String, nullptr)).first; 5581*0b57cec5SDimitry Andric } 5582*0b57cec5SDimitry Andric 5583*0b57cec5SDimitry Andric // Otherwise, convert the UTF8 literals into a string of shorts. 5584*0b57cec5SDimitry Andric IsUTF16 = true; 5585*0b57cec5SDimitry Andric 5586*0b57cec5SDimitry Andric SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 5587*0b57cec5SDimitry Andric const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5588*0b57cec5SDimitry Andric llvm::UTF16 *ToPtr = &ToBuf[0]; 5589*0b57cec5SDimitry Andric 5590*0b57cec5SDimitry Andric (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5591*0b57cec5SDimitry Andric ToPtr + NumBytes, llvm::strictConversion); 5592*0b57cec5SDimitry Andric 5593*0b57cec5SDimitry Andric // ConvertUTF8toUTF16 returns the length in ToPtr. 5594*0b57cec5SDimitry Andric StringLength = ToPtr - &ToBuf[0]; 5595*0b57cec5SDimitry Andric 5596*0b57cec5SDimitry Andric // Add an explicit null. 5597*0b57cec5SDimitry Andric *ToPtr = 0; 5598*0b57cec5SDimitry Andric return *Map.insert(std::make_pair( 5599*0b57cec5SDimitry Andric StringRef(reinterpret_cast<const char *>(ToBuf.data()), 5600*0b57cec5SDimitry Andric (StringLength + 1) * 2), 5601*0b57cec5SDimitry Andric nullptr)).first; 5602*0b57cec5SDimitry Andric } 5603*0b57cec5SDimitry Andric 5604*0b57cec5SDimitry Andric ConstantAddress 5605*0b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 5606*0b57cec5SDimitry Andric unsigned StringLength = 0; 5607*0b57cec5SDimitry Andric bool isUTF16 = false; 5608*0b57cec5SDimitry Andric llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 5609*0b57cec5SDimitry Andric GetConstantCFStringEntry(CFConstantStringMap, Literal, 5610*0b57cec5SDimitry Andric getDataLayout().isLittleEndian(), isUTF16, 5611*0b57cec5SDimitry Andric StringLength); 5612*0b57cec5SDimitry Andric 5613*0b57cec5SDimitry Andric if (auto *C = Entry.second) 56140eae32dcSDimitry Andric return ConstantAddress( 56150eae32dcSDimitry Andric C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment())); 5616*0b57cec5SDimitry Andric 5617*0b57cec5SDimitry Andric llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 5618*0b57cec5SDimitry Andric llvm::Constant *Zeros[] = { Zero, Zero }; 5619*0b57cec5SDimitry Andric 5620*0b57cec5SDimitry Andric const ASTContext &Context = getContext(); 5621*0b57cec5SDimitry Andric const llvm::Triple &Triple = getTriple(); 5622*0b57cec5SDimitry Andric 5623*0b57cec5SDimitry Andric const auto CFRuntime = getLangOpts().CFRuntime; 5624*0b57cec5SDimitry Andric const bool IsSwiftABI = 5625*0b57cec5SDimitry Andric static_cast<unsigned>(CFRuntime) >= 5626*0b57cec5SDimitry Andric static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift); 5627*0b57cec5SDimitry Andric const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1; 5628*0b57cec5SDimitry Andric 5629*0b57cec5SDimitry Andric // If we don't already have it, get __CFConstantStringClassReference. 5630*0b57cec5SDimitry Andric if (!CFConstantStringClassRef) { 5631*0b57cec5SDimitry Andric const char *CFConstantStringClassName = "__CFConstantStringClassReference"; 5632*0b57cec5SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 5633*0b57cec5SDimitry Andric Ty = llvm::ArrayType::get(Ty, 0); 5634*0b57cec5SDimitry Andric 5635*0b57cec5SDimitry Andric switch (CFRuntime) { 5636*0b57cec5SDimitry Andric default: break; 5637bdd1243dSDimitry Andric case LangOptions::CoreFoundationABI::Swift: [[fallthrough]]; 5638*0b57cec5SDimitry Andric case LangOptions::CoreFoundationABI::Swift5_0: 5639*0b57cec5SDimitry Andric CFConstantStringClassName = 5640*0b57cec5SDimitry Andric Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN" 5641*0b57cec5SDimitry Andric : "$s10Foundation19_NSCFConstantStringCN"; 5642*0b57cec5SDimitry Andric Ty = IntPtrTy; 5643*0b57cec5SDimitry Andric break; 5644*0b57cec5SDimitry Andric case LangOptions::CoreFoundationABI::Swift4_2: 5645*0b57cec5SDimitry Andric CFConstantStringClassName = 5646*0b57cec5SDimitry Andric Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN" 5647*0b57cec5SDimitry Andric : "$S10Foundation19_NSCFConstantStringCN"; 5648*0b57cec5SDimitry Andric Ty = IntPtrTy; 5649*0b57cec5SDimitry Andric break; 5650*0b57cec5SDimitry Andric case LangOptions::CoreFoundationABI::Swift4_1: 5651*0b57cec5SDimitry Andric CFConstantStringClassName = 5652*0b57cec5SDimitry Andric Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN" 5653*0b57cec5SDimitry Andric : "__T010Foundation19_NSCFConstantStringCN"; 5654*0b57cec5SDimitry Andric Ty = IntPtrTy; 5655*0b57cec5SDimitry Andric break; 5656*0b57cec5SDimitry Andric } 5657*0b57cec5SDimitry Andric 5658*0b57cec5SDimitry Andric llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName); 5659*0b57cec5SDimitry Andric 5660*0b57cec5SDimitry Andric if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) { 5661*0b57cec5SDimitry Andric llvm::GlobalValue *GV = nullptr; 5662*0b57cec5SDimitry Andric 5663*0b57cec5SDimitry Andric if ((GV = dyn_cast<llvm::GlobalValue>(C))) { 5664*0b57cec5SDimitry Andric IdentifierInfo &II = Context.Idents.get(GV->getName()); 5665*0b57cec5SDimitry Andric TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl(); 5666*0b57cec5SDimitry Andric DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 5667*0b57cec5SDimitry Andric 5668*0b57cec5SDimitry Andric const VarDecl *VD = nullptr; 5669fe6060f1SDimitry Andric for (const auto *Result : DC->lookup(&II)) 5670*0b57cec5SDimitry Andric if ((VD = dyn_cast<VarDecl>(Result))) 5671*0b57cec5SDimitry Andric break; 5672*0b57cec5SDimitry Andric 5673*0b57cec5SDimitry Andric if (Triple.isOSBinFormatELF()) { 5674*0b57cec5SDimitry Andric if (!VD) 5675*0b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 5676*0b57cec5SDimitry Andric } else { 5677*0b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 5678*0b57cec5SDimitry Andric if (!VD || !VD->hasAttr<DLLExportAttr>()) 5679*0b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 5680*0b57cec5SDimitry Andric else 5681*0b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 5682*0b57cec5SDimitry Andric } 5683*0b57cec5SDimitry Andric 5684*0b57cec5SDimitry Andric setDSOLocal(GV); 5685*0b57cec5SDimitry Andric } 5686*0b57cec5SDimitry Andric } 5687*0b57cec5SDimitry Andric 5688*0b57cec5SDimitry Andric // Decay array -> ptr 5689*0b57cec5SDimitry Andric CFConstantStringClassRef = 5690*0b57cec5SDimitry Andric IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) 5691*0b57cec5SDimitry Andric : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros); 5692*0b57cec5SDimitry Andric } 5693*0b57cec5SDimitry Andric 5694*0b57cec5SDimitry Andric QualType CFTy = Context.getCFConstantStringType(); 5695*0b57cec5SDimitry Andric 5696*0b57cec5SDimitry Andric auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 5697*0b57cec5SDimitry Andric 5698*0b57cec5SDimitry Andric ConstantInitBuilder Builder(*this); 5699*0b57cec5SDimitry Andric auto Fields = Builder.beginStruct(STy); 5700*0b57cec5SDimitry Andric 5701*0b57cec5SDimitry Andric // Class pointer. 570281ad6265SDimitry Andric Fields.add(cast<llvm::Constant>(CFConstantStringClassRef)); 5703*0b57cec5SDimitry Andric 5704*0b57cec5SDimitry Andric // Flags. 5705*0b57cec5SDimitry Andric if (IsSwiftABI) { 5706*0b57cec5SDimitry Andric Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01); 5707*0b57cec5SDimitry Andric Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8); 5708*0b57cec5SDimitry Andric } else { 5709*0b57cec5SDimitry Andric Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); 5710*0b57cec5SDimitry Andric } 5711*0b57cec5SDimitry Andric 5712*0b57cec5SDimitry Andric // String pointer. 5713*0b57cec5SDimitry Andric llvm::Constant *C = nullptr; 5714*0b57cec5SDimitry Andric if (isUTF16) { 5715bdd1243dSDimitry Andric auto Arr = llvm::ArrayRef( 5716*0b57cec5SDimitry Andric reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 5717*0b57cec5SDimitry Andric Entry.first().size() / 2); 5718*0b57cec5SDimitry Andric C = llvm::ConstantDataArray::get(VMContext, Arr); 5719*0b57cec5SDimitry Andric } else { 5720*0b57cec5SDimitry Andric C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 5721*0b57cec5SDimitry Andric } 5722*0b57cec5SDimitry Andric 5723*0b57cec5SDimitry Andric // Note: -fwritable-strings doesn't make the backing store strings of 5724*0b57cec5SDimitry Andric // CFStrings writable. (See <rdar://problem/10657500>) 5725*0b57cec5SDimitry Andric auto *GV = 5726*0b57cec5SDimitry Andric new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 5727*0b57cec5SDimitry Andric llvm::GlobalValue::PrivateLinkage, C, ".str"); 5728*0b57cec5SDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 5729*0b57cec5SDimitry Andric // Don't enforce the target's minimum global alignment, since the only use 5730*0b57cec5SDimitry Andric // of the string is via this class initializer. 5731*0b57cec5SDimitry Andric CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy) 5732*0b57cec5SDimitry Andric : Context.getTypeAlignInChars(Context.CharTy); 5733a7dea167SDimitry Andric GV->setAlignment(Align.getAsAlign()); 5734*0b57cec5SDimitry Andric 5735*0b57cec5SDimitry Andric // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 5736*0b57cec5SDimitry Andric // Without it LLVM can merge the string with a non unnamed_addr one during 5737*0b57cec5SDimitry Andric // LTO. Doing that changes the section it ends in, which surprises ld64. 5738*0b57cec5SDimitry Andric if (Triple.isOSBinFormatMachO()) 5739*0b57cec5SDimitry Andric GV->setSection(isUTF16 ? "__TEXT,__ustring" 5740*0b57cec5SDimitry Andric : "__TEXT,__cstring,cstring_literals"); 5741*0b57cec5SDimitry Andric // Make sure the literal ends up in .rodata to allow for safe ICF and for 5742*0b57cec5SDimitry Andric // the static linker to adjust permissions to read-only later on. 5743*0b57cec5SDimitry Andric else if (Triple.isOSBinFormatELF()) 5744*0b57cec5SDimitry Andric GV->setSection(".rodata"); 5745*0b57cec5SDimitry Andric 5746*0b57cec5SDimitry Andric // String. 5747*0b57cec5SDimitry Andric llvm::Constant *Str = 5748*0b57cec5SDimitry Andric llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 5749*0b57cec5SDimitry Andric 5750*0b57cec5SDimitry Andric if (isUTF16) 5751*0b57cec5SDimitry Andric // Cast the UTF16 string to the correct type. 5752*0b57cec5SDimitry Andric Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy); 5753*0b57cec5SDimitry Andric Fields.add(Str); 5754*0b57cec5SDimitry Andric 5755*0b57cec5SDimitry Andric // String length. 5756*0b57cec5SDimitry Andric llvm::IntegerType *LengthTy = 5757*0b57cec5SDimitry Andric llvm::IntegerType::get(getModule().getContext(), 5758*0b57cec5SDimitry Andric Context.getTargetInfo().getLongWidth()); 5759*0b57cec5SDimitry Andric if (IsSwiftABI) { 5760*0b57cec5SDimitry Andric if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 5761*0b57cec5SDimitry Andric CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 5762*0b57cec5SDimitry Andric LengthTy = Int32Ty; 5763*0b57cec5SDimitry Andric else 5764*0b57cec5SDimitry Andric LengthTy = IntPtrTy; 5765*0b57cec5SDimitry Andric } 5766*0b57cec5SDimitry Andric Fields.addInt(LengthTy, StringLength); 5767*0b57cec5SDimitry Andric 5768a7dea167SDimitry Andric // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is 5769a7dea167SDimitry Andric // properly aligned on 32-bit platforms. 5770a7dea167SDimitry Andric CharUnits Alignment = 5771a7dea167SDimitry Andric IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign(); 5772*0b57cec5SDimitry Andric 5773*0b57cec5SDimitry Andric // The struct. 5774*0b57cec5SDimitry Andric GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, 5775*0b57cec5SDimitry Andric /*isConstant=*/false, 5776*0b57cec5SDimitry Andric llvm::GlobalVariable::PrivateLinkage); 5777*0b57cec5SDimitry Andric GV->addAttribute("objc_arc_inert"); 5778*0b57cec5SDimitry Andric switch (Triple.getObjectFormat()) { 5779*0b57cec5SDimitry Andric case llvm::Triple::UnknownObjectFormat: 5780*0b57cec5SDimitry Andric llvm_unreachable("unknown file format"); 578181ad6265SDimitry Andric case llvm::Triple::DXContainer: 5782e8d8bef9SDimitry Andric case llvm::Triple::GOFF: 578381ad6265SDimitry Andric case llvm::Triple::SPIRV: 5784*0b57cec5SDimitry Andric case llvm::Triple::XCOFF: 578581ad6265SDimitry Andric llvm_unreachable("unimplemented"); 5786*0b57cec5SDimitry Andric case llvm::Triple::COFF: 5787*0b57cec5SDimitry Andric case llvm::Triple::ELF: 5788*0b57cec5SDimitry Andric case llvm::Triple::Wasm: 5789*0b57cec5SDimitry Andric GV->setSection("cfstring"); 5790*0b57cec5SDimitry Andric break; 5791*0b57cec5SDimitry Andric case llvm::Triple::MachO: 5792*0b57cec5SDimitry Andric GV->setSection("__DATA,__cfstring"); 5793*0b57cec5SDimitry Andric break; 5794*0b57cec5SDimitry Andric } 5795*0b57cec5SDimitry Andric Entry.second = GV; 5796*0b57cec5SDimitry Andric 57970eae32dcSDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 5798*0b57cec5SDimitry Andric } 5799*0b57cec5SDimitry Andric 5800*0b57cec5SDimitry Andric bool CodeGenModule::getExpressionLocationsEnabled() const { 5801*0b57cec5SDimitry Andric return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo; 5802*0b57cec5SDimitry Andric } 5803*0b57cec5SDimitry Andric 5804*0b57cec5SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() { 5805*0b57cec5SDimitry Andric if (ObjCFastEnumerationStateType.isNull()) { 5806*0b57cec5SDimitry Andric RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 5807*0b57cec5SDimitry Andric D->startDefinition(); 5808*0b57cec5SDimitry Andric 5809*0b57cec5SDimitry Andric QualType FieldTypes[] = { 5810*0b57cec5SDimitry Andric Context.UnsignedLongTy, 5811*0b57cec5SDimitry Andric Context.getPointerType(Context.getObjCIdType()), 5812*0b57cec5SDimitry Andric Context.getPointerType(Context.UnsignedLongTy), 5813*0b57cec5SDimitry Andric Context.getConstantArrayType(Context.UnsignedLongTy, 5814a7dea167SDimitry Andric llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0) 5815*0b57cec5SDimitry Andric }; 5816*0b57cec5SDimitry Andric 5817*0b57cec5SDimitry Andric for (size_t i = 0; i < 4; ++i) { 5818*0b57cec5SDimitry Andric FieldDecl *Field = FieldDecl::Create(Context, 5819*0b57cec5SDimitry Andric D, 5820*0b57cec5SDimitry Andric SourceLocation(), 5821*0b57cec5SDimitry Andric SourceLocation(), nullptr, 5822*0b57cec5SDimitry Andric FieldTypes[i], /*TInfo=*/nullptr, 5823*0b57cec5SDimitry Andric /*BitWidth=*/nullptr, 5824*0b57cec5SDimitry Andric /*Mutable=*/false, 5825*0b57cec5SDimitry Andric ICIS_NoInit); 5826*0b57cec5SDimitry Andric Field->setAccess(AS_public); 5827*0b57cec5SDimitry Andric D->addDecl(Field); 5828*0b57cec5SDimitry Andric } 5829*0b57cec5SDimitry Andric 5830*0b57cec5SDimitry Andric D->completeDefinition(); 5831*0b57cec5SDimitry Andric ObjCFastEnumerationStateType = Context.getTagDeclType(D); 5832*0b57cec5SDimitry Andric } 5833*0b57cec5SDimitry Andric 5834*0b57cec5SDimitry Andric return ObjCFastEnumerationStateType; 5835*0b57cec5SDimitry Andric } 5836*0b57cec5SDimitry Andric 5837*0b57cec5SDimitry Andric llvm::Constant * 5838*0b57cec5SDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 5839*0b57cec5SDimitry Andric assert(!E->getType()->isPointerType() && "Strings are always arrays"); 5840*0b57cec5SDimitry Andric 5841*0b57cec5SDimitry Andric // Don't emit it as the address of the string, emit the string data itself 5842*0b57cec5SDimitry Andric // as an inline array. 5843*0b57cec5SDimitry Andric if (E->getCharByteWidth() == 1) { 5844*0b57cec5SDimitry Andric SmallString<64> Str(E->getString()); 5845*0b57cec5SDimitry Andric 5846*0b57cec5SDimitry Andric // Resize the string to the right size, which is indicated by its type. 5847*0b57cec5SDimitry Andric const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 5848*0b57cec5SDimitry Andric Str.resize(CAT->getSize().getZExtValue()); 5849*0b57cec5SDimitry Andric return llvm::ConstantDataArray::getString(VMContext, Str, false); 5850*0b57cec5SDimitry Andric } 5851*0b57cec5SDimitry Andric 5852*0b57cec5SDimitry Andric auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 5853*0b57cec5SDimitry Andric llvm::Type *ElemTy = AType->getElementType(); 5854*0b57cec5SDimitry Andric unsigned NumElements = AType->getNumElements(); 5855*0b57cec5SDimitry Andric 5856*0b57cec5SDimitry Andric // Wide strings have either 2-byte or 4-byte elements. 5857*0b57cec5SDimitry Andric if (ElemTy->getPrimitiveSizeInBits() == 16) { 5858*0b57cec5SDimitry Andric SmallVector<uint16_t, 32> Elements; 5859*0b57cec5SDimitry Andric Elements.reserve(NumElements); 5860*0b57cec5SDimitry Andric 5861*0b57cec5SDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 5862*0b57cec5SDimitry Andric Elements.push_back(E->getCodeUnit(i)); 5863*0b57cec5SDimitry Andric Elements.resize(NumElements); 5864*0b57cec5SDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 5865*0b57cec5SDimitry Andric } 5866*0b57cec5SDimitry Andric 5867*0b57cec5SDimitry Andric assert(ElemTy->getPrimitiveSizeInBits() == 32); 5868*0b57cec5SDimitry Andric SmallVector<uint32_t, 32> Elements; 5869*0b57cec5SDimitry Andric Elements.reserve(NumElements); 5870*0b57cec5SDimitry Andric 5871*0b57cec5SDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 5872*0b57cec5SDimitry Andric Elements.push_back(E->getCodeUnit(i)); 5873*0b57cec5SDimitry Andric Elements.resize(NumElements); 5874*0b57cec5SDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 5875*0b57cec5SDimitry Andric } 5876*0b57cec5SDimitry Andric 5877*0b57cec5SDimitry Andric static llvm::GlobalVariable * 5878*0b57cec5SDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 5879*0b57cec5SDimitry Andric CodeGenModule &CGM, StringRef GlobalName, 5880*0b57cec5SDimitry Andric CharUnits Alignment) { 5881*0b57cec5SDimitry Andric unsigned AddrSpace = CGM.getContext().getTargetAddressSpace( 5882fe6060f1SDimitry Andric CGM.GetGlobalConstantAddressSpace()); 5883*0b57cec5SDimitry Andric 5884*0b57cec5SDimitry Andric llvm::Module &M = CGM.getModule(); 5885*0b57cec5SDimitry Andric // Create a global variable for this string 5886*0b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 5887*0b57cec5SDimitry Andric M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 5888*0b57cec5SDimitry Andric nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 5889a7dea167SDimitry Andric GV->setAlignment(Alignment.getAsAlign()); 5890*0b57cec5SDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 5891*0b57cec5SDimitry Andric if (GV->isWeakForLinker()) { 5892*0b57cec5SDimitry Andric assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 5893*0b57cec5SDimitry Andric GV->setComdat(M.getOrInsertComdat(GV->getName())); 5894*0b57cec5SDimitry Andric } 5895*0b57cec5SDimitry Andric CGM.setDSOLocal(GV); 5896*0b57cec5SDimitry Andric 5897*0b57cec5SDimitry Andric return GV; 5898*0b57cec5SDimitry Andric } 5899*0b57cec5SDimitry Andric 5900*0b57cec5SDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 5901*0b57cec5SDimitry Andric /// constant array for the given string literal. 5902*0b57cec5SDimitry Andric ConstantAddress 5903*0b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 5904*0b57cec5SDimitry Andric StringRef Name) { 5905*0b57cec5SDimitry Andric CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 5906*0b57cec5SDimitry Andric 5907*0b57cec5SDimitry Andric llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 5908*0b57cec5SDimitry Andric llvm::GlobalVariable **Entry = nullptr; 5909*0b57cec5SDimitry Andric if (!LangOpts.WritableStrings) { 5910*0b57cec5SDimitry Andric Entry = &ConstantStringMap[C]; 5911*0b57cec5SDimitry Andric if (auto GV = *Entry) { 5912349cc55cSDimitry Andric if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 5913a7dea167SDimitry Andric GV->setAlignment(Alignment.getAsAlign()); 5914*0b57cec5SDimitry Andric return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 59150eae32dcSDimitry Andric GV->getValueType(), Alignment); 5916*0b57cec5SDimitry Andric } 5917*0b57cec5SDimitry Andric } 5918*0b57cec5SDimitry Andric 5919*0b57cec5SDimitry Andric SmallString<256> MangledNameBuffer; 5920*0b57cec5SDimitry Andric StringRef GlobalVariableName; 5921*0b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes LT; 5922*0b57cec5SDimitry Andric 5923*0b57cec5SDimitry Andric // Mangle the string literal if that's how the ABI merges duplicate strings. 5924*0b57cec5SDimitry Andric // Don't do it if they are writable, since we don't want writes in one TU to 5925*0b57cec5SDimitry Andric // affect strings in another. 5926*0b57cec5SDimitry Andric if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) && 5927*0b57cec5SDimitry Andric !LangOpts.WritableStrings) { 5928*0b57cec5SDimitry Andric llvm::raw_svector_ostream Out(MangledNameBuffer); 5929*0b57cec5SDimitry Andric getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 5930*0b57cec5SDimitry Andric LT = llvm::GlobalValue::LinkOnceODRLinkage; 5931*0b57cec5SDimitry Andric GlobalVariableName = MangledNameBuffer; 5932*0b57cec5SDimitry Andric } else { 5933*0b57cec5SDimitry Andric LT = llvm::GlobalValue::PrivateLinkage; 5934*0b57cec5SDimitry Andric GlobalVariableName = Name; 5935*0b57cec5SDimitry Andric } 5936*0b57cec5SDimitry Andric 5937*0b57cec5SDimitry Andric auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 593881ad6265SDimitry Andric 593981ad6265SDimitry Andric CGDebugInfo *DI = getModuleDebugInfo(); 594081ad6265SDimitry Andric if (DI && getCodeGenOpts().hasReducedDebugInfo()) 594181ad6265SDimitry Andric DI->AddStringLiteralDebugInfo(GV, S); 594281ad6265SDimitry Andric 5943*0b57cec5SDimitry Andric if (Entry) 5944*0b57cec5SDimitry Andric *Entry = GV; 5945*0b57cec5SDimitry Andric 594681ad6265SDimitry Andric SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0), "<string literal>"); 5947*0b57cec5SDimitry Andric 5948*0b57cec5SDimitry Andric return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 59490eae32dcSDimitry Andric GV->getValueType(), Alignment); 5950*0b57cec5SDimitry Andric } 5951*0b57cec5SDimitry Andric 5952*0b57cec5SDimitry Andric /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 5953*0b57cec5SDimitry Andric /// array for the given ObjCEncodeExpr node. 5954*0b57cec5SDimitry Andric ConstantAddress 5955*0b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 5956*0b57cec5SDimitry Andric std::string Str; 5957*0b57cec5SDimitry Andric getContext().getObjCEncodingForType(E->getEncodedType(), Str); 5958*0b57cec5SDimitry Andric 5959*0b57cec5SDimitry Andric return GetAddrOfConstantCString(Str); 5960*0b57cec5SDimitry Andric } 5961*0b57cec5SDimitry Andric 5962*0b57cec5SDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing 5963*0b57cec5SDimitry Andric /// the literal and a terminating '\0' character. 5964*0b57cec5SDimitry Andric /// The result has pointer to array type. 5965*0b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString( 5966*0b57cec5SDimitry Andric const std::string &Str, const char *GlobalName) { 5967*0b57cec5SDimitry Andric StringRef StrWithNull(Str.c_str(), Str.size() + 1); 5968*0b57cec5SDimitry Andric CharUnits Alignment = 5969*0b57cec5SDimitry Andric getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 5970*0b57cec5SDimitry Andric 5971*0b57cec5SDimitry Andric llvm::Constant *C = 5972*0b57cec5SDimitry Andric llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 5973*0b57cec5SDimitry Andric 5974*0b57cec5SDimitry Andric // Don't share any string literals if strings aren't constant. 5975*0b57cec5SDimitry Andric llvm::GlobalVariable **Entry = nullptr; 5976*0b57cec5SDimitry Andric if (!LangOpts.WritableStrings) { 5977*0b57cec5SDimitry Andric Entry = &ConstantStringMap[C]; 5978*0b57cec5SDimitry Andric if (auto GV = *Entry) { 5979349cc55cSDimitry Andric if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 5980a7dea167SDimitry Andric GV->setAlignment(Alignment.getAsAlign()); 5981*0b57cec5SDimitry Andric return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 59820eae32dcSDimitry Andric GV->getValueType(), Alignment); 5983*0b57cec5SDimitry Andric } 5984*0b57cec5SDimitry Andric } 5985*0b57cec5SDimitry Andric 5986*0b57cec5SDimitry Andric // Get the default prefix if a name wasn't specified. 5987*0b57cec5SDimitry Andric if (!GlobalName) 5988*0b57cec5SDimitry Andric GlobalName = ".str"; 5989*0b57cec5SDimitry Andric // Create a global variable for this. 5990*0b57cec5SDimitry Andric auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 5991*0b57cec5SDimitry Andric GlobalName, Alignment); 5992*0b57cec5SDimitry Andric if (Entry) 5993*0b57cec5SDimitry Andric *Entry = GV; 5994*0b57cec5SDimitry Andric 5995*0b57cec5SDimitry Andric return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 59960eae32dcSDimitry Andric GV->getValueType(), Alignment); 5997*0b57cec5SDimitry Andric } 5998*0b57cec5SDimitry Andric 5999*0b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 6000*0b57cec5SDimitry Andric const MaterializeTemporaryExpr *E, const Expr *Init) { 6001*0b57cec5SDimitry Andric assert((E->getStorageDuration() == SD_Static || 6002*0b57cec5SDimitry Andric E->getStorageDuration() == SD_Thread) && "not a global temporary"); 6003*0b57cec5SDimitry Andric const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 6004*0b57cec5SDimitry Andric 6005*0b57cec5SDimitry Andric // If we're not materializing a subobject of the temporary, keep the 6006*0b57cec5SDimitry Andric // cv-qualifiers from the type of the MaterializeTemporaryExpr. 6007*0b57cec5SDimitry Andric QualType MaterializedType = Init->getType(); 6008480093f4SDimitry Andric if (Init == E->getSubExpr()) 6009*0b57cec5SDimitry Andric MaterializedType = E->getType(); 6010*0b57cec5SDimitry Andric 6011*0b57cec5SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 6012*0b57cec5SDimitry Andric 6013fe6060f1SDimitry Andric auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr}); 6014fe6060f1SDimitry Andric if (!InsertResult.second) { 6015fe6060f1SDimitry Andric // We've seen this before: either we already created it or we're in the 6016fe6060f1SDimitry Andric // process of doing so. 6017fe6060f1SDimitry Andric if (!InsertResult.first->second) { 6018fe6060f1SDimitry Andric // We recursively re-entered this function, probably during emission of 6019fe6060f1SDimitry Andric // the initializer. Create a placeholder. We'll clean this up in the 6020fe6060f1SDimitry Andric // outer call, at the end of this function. 6021fe6060f1SDimitry Andric llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType); 6022fe6060f1SDimitry Andric InsertResult.first->second = new llvm::GlobalVariable( 6023fe6060f1SDimitry Andric getModule(), Type, false, llvm::GlobalVariable::InternalLinkage, 6024fe6060f1SDimitry Andric nullptr); 6025fe6060f1SDimitry Andric } 602681ad6265SDimitry Andric return ConstantAddress(InsertResult.first->second, 602781ad6265SDimitry Andric llvm::cast<llvm::GlobalVariable>( 602881ad6265SDimitry Andric InsertResult.first->second->stripPointerCasts()) 602981ad6265SDimitry Andric ->getValueType(), 603081ad6265SDimitry Andric Align); 6031fe6060f1SDimitry Andric } 6032*0b57cec5SDimitry Andric 6033*0b57cec5SDimitry Andric // FIXME: If an externally-visible declaration extends multiple temporaries, 6034*0b57cec5SDimitry Andric // we need to give each temporary the same name in every translation unit (and 6035*0b57cec5SDimitry Andric // we also need to make the temporaries externally-visible). 6036*0b57cec5SDimitry Andric SmallString<256> Name; 6037*0b57cec5SDimitry Andric llvm::raw_svector_ostream Out(Name); 6038*0b57cec5SDimitry Andric getCXXABI().getMangleContext().mangleReferenceTemporary( 6039*0b57cec5SDimitry Andric VD, E->getManglingNumber(), Out); 6040*0b57cec5SDimitry Andric 6041*0b57cec5SDimitry Andric APValue *Value = nullptr; 6042a7dea167SDimitry Andric if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) { 6043a7dea167SDimitry Andric // If the initializer of the extending declaration is a constant 6044a7dea167SDimitry Andric // initializer, we should have a cached constant initializer for this 6045a7dea167SDimitry Andric // temporary. Note that this might have a different value from the value 6046a7dea167SDimitry Andric // computed by evaluating the initializer if the surrounding constant 6047a7dea167SDimitry Andric // expression modifies the temporary. 6048480093f4SDimitry Andric Value = E->getOrCreateValue(false); 6049*0b57cec5SDimitry Andric } 6050*0b57cec5SDimitry Andric 6051*0b57cec5SDimitry Andric // Try evaluating it now, it might have a constant initializer. 6052*0b57cec5SDimitry Andric Expr::EvalResult EvalResult; 6053*0b57cec5SDimitry Andric if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 6054*0b57cec5SDimitry Andric !EvalResult.hasSideEffects()) 6055*0b57cec5SDimitry Andric Value = &EvalResult.Val; 6056*0b57cec5SDimitry Andric 6057*0b57cec5SDimitry Andric LangAS AddrSpace = 6058*0b57cec5SDimitry Andric VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace(); 6059*0b57cec5SDimitry Andric 6060bdd1243dSDimitry Andric std::optional<ConstantEmitter> emitter; 6061*0b57cec5SDimitry Andric llvm::Constant *InitialValue = nullptr; 6062*0b57cec5SDimitry Andric bool Constant = false; 6063*0b57cec5SDimitry Andric llvm::Type *Type; 6064*0b57cec5SDimitry Andric if (Value) { 6065*0b57cec5SDimitry Andric // The temporary has a constant initializer, use it. 6066*0b57cec5SDimitry Andric emitter.emplace(*this); 6067*0b57cec5SDimitry Andric InitialValue = emitter->emitForInitializer(*Value, AddrSpace, 6068*0b57cec5SDimitry Andric MaterializedType); 6069*0b57cec5SDimitry Andric Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 6070*0b57cec5SDimitry Andric Type = InitialValue->getType(); 6071*0b57cec5SDimitry Andric } else { 6072*0b57cec5SDimitry Andric // No initializer, the initialization will be provided when we 6073*0b57cec5SDimitry Andric // initialize the declaration which performed lifetime extension. 6074*0b57cec5SDimitry Andric Type = getTypes().ConvertTypeForMem(MaterializedType); 6075*0b57cec5SDimitry Andric } 6076*0b57cec5SDimitry Andric 6077*0b57cec5SDimitry Andric // Create a global variable for this lifetime-extended temporary. 6078*0b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 6079*0b57cec5SDimitry Andric getLLVMLinkageVarDefinition(VD, Constant); 6080*0b57cec5SDimitry Andric if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 6081*0b57cec5SDimitry Andric const VarDecl *InitVD; 6082*0b57cec5SDimitry Andric if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 6083*0b57cec5SDimitry Andric isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 6084*0b57cec5SDimitry Andric // Temporaries defined inside a class get linkonce_odr linkage because the 6085*0b57cec5SDimitry Andric // class can be defined in multiple translation units. 6086*0b57cec5SDimitry Andric Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 6087*0b57cec5SDimitry Andric } else { 6088*0b57cec5SDimitry Andric // There is no need for this temporary to have external linkage if the 6089*0b57cec5SDimitry Andric // VarDecl has external linkage. 6090*0b57cec5SDimitry Andric Linkage = llvm::GlobalVariable::InternalLinkage; 6091*0b57cec5SDimitry Andric } 6092*0b57cec5SDimitry Andric } 6093*0b57cec5SDimitry Andric auto TargetAS = getContext().getTargetAddressSpace(AddrSpace); 6094*0b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 6095*0b57cec5SDimitry Andric getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 6096*0b57cec5SDimitry Andric /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); 6097*0b57cec5SDimitry Andric if (emitter) emitter->finalize(GV); 6098bdd1243dSDimitry Andric // Don't assign dllimport or dllexport to local linkage globals. 6099bdd1243dSDimitry Andric if (!llvm::GlobalValue::isLocalLinkage(Linkage)) { 6100*0b57cec5SDimitry Andric setGVProperties(GV, VD); 610181ad6265SDimitry Andric if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass) 610281ad6265SDimitry Andric // The reference temporary should never be dllexport. 610381ad6265SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 6104bdd1243dSDimitry Andric } 6105a7dea167SDimitry Andric GV->setAlignment(Align.getAsAlign()); 6106*0b57cec5SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker()) 6107*0b57cec5SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 6108*0b57cec5SDimitry Andric if (VD->getTLSKind()) 6109*0b57cec5SDimitry Andric setTLSMode(GV, *VD); 6110*0b57cec5SDimitry Andric llvm::Constant *CV = GV; 6111*0b57cec5SDimitry Andric if (AddrSpace != LangAS::Default) 6112*0b57cec5SDimitry Andric CV = getTargetCodeGenInfo().performAddrSpaceCast( 6113*0b57cec5SDimitry Andric *this, GV, AddrSpace, LangAS::Default, 6114*0b57cec5SDimitry Andric Type->getPointerTo( 6115*0b57cec5SDimitry Andric getContext().getTargetAddressSpace(LangAS::Default))); 6116fe6060f1SDimitry Andric 6117fe6060f1SDimitry Andric // Update the map with the new temporary. If we created a placeholder above, 6118fe6060f1SDimitry Andric // replace it with the new global now. 6119fe6060f1SDimitry Andric llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E]; 6120fe6060f1SDimitry Andric if (Entry) { 6121fe6060f1SDimitry Andric Entry->replaceAllUsesWith( 6122fe6060f1SDimitry Andric llvm::ConstantExpr::getBitCast(CV, Entry->getType())); 6123fe6060f1SDimitry Andric llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent(); 6124fe6060f1SDimitry Andric } 6125fe6060f1SDimitry Andric Entry = CV; 6126fe6060f1SDimitry Andric 61270eae32dcSDimitry Andric return ConstantAddress(CV, Type, Align); 6128*0b57cec5SDimitry Andric } 6129*0b57cec5SDimitry Andric 6130*0b57cec5SDimitry Andric /// EmitObjCPropertyImplementations - Emit information for synthesized 6131*0b57cec5SDimitry Andric /// properties for an implementation. 6132*0b57cec5SDimitry Andric void CodeGenModule::EmitObjCPropertyImplementations(const 6133*0b57cec5SDimitry Andric ObjCImplementationDecl *D) { 6134*0b57cec5SDimitry Andric for (const auto *PID : D->property_impls()) { 6135*0b57cec5SDimitry Andric // Dynamic is just for type-checking. 6136*0b57cec5SDimitry Andric if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 6137*0b57cec5SDimitry Andric ObjCPropertyDecl *PD = PID->getPropertyDecl(); 6138*0b57cec5SDimitry Andric 6139*0b57cec5SDimitry Andric // Determine which methods need to be implemented, some may have 6140*0b57cec5SDimitry Andric // been overridden. Note that ::isPropertyAccessor is not the method 6141*0b57cec5SDimitry Andric // we want, that just indicates if the decl came from a 6142*0b57cec5SDimitry Andric // property. What we want to know is if the method is defined in 6143*0b57cec5SDimitry Andric // this implementation. 6144480093f4SDimitry Andric auto *Getter = PID->getGetterMethodDecl(); 6145480093f4SDimitry Andric if (!Getter || Getter->isSynthesizedAccessorStub()) 6146*0b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCGetter( 6147*0b57cec5SDimitry Andric const_cast<ObjCImplementationDecl *>(D), PID); 6148480093f4SDimitry Andric auto *Setter = PID->getSetterMethodDecl(); 6149480093f4SDimitry Andric if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub())) 6150*0b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCSetter( 6151*0b57cec5SDimitry Andric const_cast<ObjCImplementationDecl *>(D), PID); 6152*0b57cec5SDimitry Andric } 6153*0b57cec5SDimitry Andric } 6154*0b57cec5SDimitry Andric } 6155*0b57cec5SDimitry Andric 6156*0b57cec5SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) { 6157*0b57cec5SDimitry Andric const ObjCInterfaceDecl *iface = impl->getClassInterface(); 6158*0b57cec5SDimitry Andric for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 6159*0b57cec5SDimitry Andric ivar; ivar = ivar->getNextIvar()) 6160*0b57cec5SDimitry Andric if (ivar->getType().isDestructedType()) 6161*0b57cec5SDimitry Andric return true; 6162*0b57cec5SDimitry Andric 6163*0b57cec5SDimitry Andric return false; 6164*0b57cec5SDimitry Andric } 6165*0b57cec5SDimitry Andric 6166*0b57cec5SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM, 6167*0b57cec5SDimitry Andric ObjCImplementationDecl *D) { 6168*0b57cec5SDimitry Andric CodeGenFunction CGF(CGM); 6169*0b57cec5SDimitry Andric for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 6170*0b57cec5SDimitry Andric E = D->init_end(); B != E; ++B) { 6171*0b57cec5SDimitry Andric CXXCtorInitializer *CtorInitExp = *B; 6172*0b57cec5SDimitry Andric Expr *Init = CtorInitExp->getInit(); 6173*0b57cec5SDimitry Andric if (!CGF.isTrivialInitializer(Init)) 6174*0b57cec5SDimitry Andric return false; 6175*0b57cec5SDimitry Andric } 6176*0b57cec5SDimitry Andric return true; 6177*0b57cec5SDimitry Andric } 6178*0b57cec5SDimitry Andric 6179*0b57cec5SDimitry Andric /// EmitObjCIvarInitializations - Emit information for ivar initialization 6180*0b57cec5SDimitry Andric /// for an implementation. 6181*0b57cec5SDimitry Andric void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 6182*0b57cec5SDimitry Andric // We might need a .cxx_destruct even if we don't have any ivar initializers. 6183*0b57cec5SDimitry Andric if (needsDestructMethod(D)) { 6184*0b57cec5SDimitry Andric IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 6185*0b57cec5SDimitry Andric Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 6186480093f4SDimitry Andric ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create( 6187480093f4SDimitry Andric getContext(), D->getLocation(), D->getLocation(), cxxSelector, 6188480093f4SDimitry Andric getContext().VoidTy, nullptr, D, 6189*0b57cec5SDimitry Andric /*isInstance=*/true, /*isVariadic=*/false, 6190480093f4SDimitry Andric /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 6191480093f4SDimitry Andric /*isImplicitlyDeclared=*/true, 6192*0b57cec5SDimitry Andric /*isDefined=*/false, ObjCMethodDecl::Required); 6193*0b57cec5SDimitry Andric D->addInstanceMethod(DTORMethod); 6194*0b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 6195*0b57cec5SDimitry Andric D->setHasDestructors(true); 6196*0b57cec5SDimitry Andric } 6197*0b57cec5SDimitry Andric 6198*0b57cec5SDimitry Andric // If the implementation doesn't have any ivar initializers, we don't need 6199*0b57cec5SDimitry Andric // a .cxx_construct. 6200*0b57cec5SDimitry Andric if (D->getNumIvarInitializers() == 0 || 6201*0b57cec5SDimitry Andric AllTrivialInitializers(*this, D)) 6202*0b57cec5SDimitry Andric return; 6203*0b57cec5SDimitry Andric 6204*0b57cec5SDimitry Andric IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 6205*0b57cec5SDimitry Andric Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 6206*0b57cec5SDimitry Andric // The constructor returns 'self'. 6207480093f4SDimitry Andric ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create( 6208480093f4SDimitry Andric getContext(), D->getLocation(), D->getLocation(), cxxSelector, 6209480093f4SDimitry Andric getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true, 6210*0b57cec5SDimitry Andric /*isVariadic=*/false, 6211480093f4SDimitry Andric /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 6212*0b57cec5SDimitry Andric /*isImplicitlyDeclared=*/true, 6213480093f4SDimitry Andric /*isDefined=*/false, ObjCMethodDecl::Required); 6214*0b57cec5SDimitry Andric D->addInstanceMethod(CTORMethod); 6215*0b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 6216*0b57cec5SDimitry Andric D->setHasNonZeroConstructors(true); 6217*0b57cec5SDimitry Andric } 6218*0b57cec5SDimitry Andric 6219*0b57cec5SDimitry Andric // EmitLinkageSpec - Emit all declarations in a linkage spec. 6220*0b57cec5SDimitry Andric void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 6221*0b57cec5SDimitry Andric if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 6222480093f4SDimitry Andric LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 6223*0b57cec5SDimitry Andric ErrorUnsupported(LSD, "linkage spec"); 6224*0b57cec5SDimitry Andric return; 6225*0b57cec5SDimitry Andric } 6226*0b57cec5SDimitry Andric 6227*0b57cec5SDimitry Andric EmitDeclContext(LSD); 6228*0b57cec5SDimitry Andric } 6229*0b57cec5SDimitry Andric 6230bdd1243dSDimitry Andric void CodeGenModule::EmitTopLevelStmt(const TopLevelStmtDecl *D) { 6231bdd1243dSDimitry Andric std::unique_ptr<CodeGenFunction> &CurCGF = 6232bdd1243dSDimitry Andric GlobalTopLevelStmtBlockInFlight.first; 6233bdd1243dSDimitry Andric 6234bdd1243dSDimitry Andric // We emitted a top-level stmt but after it there is initialization. 6235bdd1243dSDimitry Andric // Stop squashing the top-level stmts into a single function. 6236bdd1243dSDimitry Andric if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) { 6237bdd1243dSDimitry Andric CurCGF->FinishFunction(D->getEndLoc()); 6238bdd1243dSDimitry Andric CurCGF = nullptr; 6239bdd1243dSDimitry Andric } 6240bdd1243dSDimitry Andric 6241bdd1243dSDimitry Andric if (!CurCGF) { 6242bdd1243dSDimitry Andric // void __stmts__N(void) 6243bdd1243dSDimitry Andric // FIXME: Ask the ABI name mangler to pick a name. 6244bdd1243dSDimitry Andric std::string Name = "__stmts__" + llvm::utostr(CXXGlobalInits.size()); 6245bdd1243dSDimitry Andric FunctionArgList Args; 6246bdd1243dSDimitry Andric QualType RetTy = getContext().VoidTy; 6247bdd1243dSDimitry Andric const CGFunctionInfo &FnInfo = 6248bdd1243dSDimitry Andric getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args); 6249bdd1243dSDimitry Andric llvm::FunctionType *FnTy = getTypes().GetFunctionType(FnInfo); 6250bdd1243dSDimitry Andric llvm::Function *Fn = llvm::Function::Create( 6251bdd1243dSDimitry Andric FnTy, llvm::GlobalValue::InternalLinkage, Name, &getModule()); 6252bdd1243dSDimitry Andric 6253bdd1243dSDimitry Andric CurCGF.reset(new CodeGenFunction(*this)); 6254bdd1243dSDimitry Andric GlobalTopLevelStmtBlockInFlight.second = D; 6255bdd1243dSDimitry Andric CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args, 6256bdd1243dSDimitry Andric D->getBeginLoc(), D->getBeginLoc()); 6257bdd1243dSDimitry Andric CXXGlobalInits.push_back(Fn); 6258bdd1243dSDimitry Andric } 6259bdd1243dSDimitry Andric 6260bdd1243dSDimitry Andric CurCGF->EmitStmt(D->getStmt()); 6261bdd1243dSDimitry Andric } 6262bdd1243dSDimitry Andric 6263*0b57cec5SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) { 6264*0b57cec5SDimitry Andric for (auto *I : DC->decls()) { 6265*0b57cec5SDimitry Andric // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope 6266*0b57cec5SDimitry Andric // are themselves considered "top-level", so EmitTopLevelDecl on an 6267*0b57cec5SDimitry Andric // ObjCImplDecl does not recursively visit them. We need to do that in 6268*0b57cec5SDimitry Andric // case they're nested inside another construct (LinkageSpecDecl / 6269*0b57cec5SDimitry Andric // ExportDecl) that does stop them from being considered "top-level". 6270*0b57cec5SDimitry Andric if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 6271*0b57cec5SDimitry Andric for (auto *M : OID->methods()) 6272*0b57cec5SDimitry Andric EmitTopLevelDecl(M); 6273*0b57cec5SDimitry Andric } 6274*0b57cec5SDimitry Andric 6275*0b57cec5SDimitry Andric EmitTopLevelDecl(I); 6276*0b57cec5SDimitry Andric } 6277*0b57cec5SDimitry Andric } 6278*0b57cec5SDimitry Andric 6279*0b57cec5SDimitry Andric /// EmitTopLevelDecl - Emit code for a single top level declaration. 6280*0b57cec5SDimitry Andric void CodeGenModule::EmitTopLevelDecl(Decl *D) { 6281*0b57cec5SDimitry Andric // Ignore dependent declarations. 6282*0b57cec5SDimitry Andric if (D->isTemplated()) 6283*0b57cec5SDimitry Andric return; 6284*0b57cec5SDimitry Andric 62855ffd83dbSDimitry Andric // Consteval function shouldn't be emitted. 62865ffd83dbSDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) 62875ffd83dbSDimitry Andric if (FD->isConsteval()) 62885ffd83dbSDimitry Andric return; 62895ffd83dbSDimitry Andric 6290*0b57cec5SDimitry Andric switch (D->getKind()) { 6291*0b57cec5SDimitry Andric case Decl::CXXConversion: 6292*0b57cec5SDimitry Andric case Decl::CXXMethod: 6293*0b57cec5SDimitry Andric case Decl::Function: 6294*0b57cec5SDimitry Andric EmitGlobal(cast<FunctionDecl>(D)); 6295*0b57cec5SDimitry Andric // Always provide some coverage mapping 6296*0b57cec5SDimitry Andric // even for the functions that aren't emitted. 6297*0b57cec5SDimitry Andric AddDeferredUnusedCoverageMapping(D); 6298*0b57cec5SDimitry Andric break; 6299*0b57cec5SDimitry Andric 6300*0b57cec5SDimitry Andric case Decl::CXXDeductionGuide: 6301*0b57cec5SDimitry Andric // Function-like, but does not result in code emission. 6302*0b57cec5SDimitry Andric break; 6303*0b57cec5SDimitry Andric 6304*0b57cec5SDimitry Andric case Decl::Var: 6305*0b57cec5SDimitry Andric case Decl::Decomposition: 6306*0b57cec5SDimitry Andric case Decl::VarTemplateSpecialization: 6307*0b57cec5SDimitry Andric EmitGlobal(cast<VarDecl>(D)); 6308*0b57cec5SDimitry Andric if (auto *DD = dyn_cast<DecompositionDecl>(D)) 6309*0b57cec5SDimitry Andric for (auto *B : DD->bindings()) 6310*0b57cec5SDimitry Andric if (auto *HD = B->getHoldingVar()) 6311*0b57cec5SDimitry Andric EmitGlobal(HD); 6312*0b57cec5SDimitry Andric break; 6313*0b57cec5SDimitry Andric 6314*0b57cec5SDimitry Andric // Indirect fields from global anonymous structs and unions can be 6315*0b57cec5SDimitry Andric // ignored; only the actual variable requires IR gen support. 6316*0b57cec5SDimitry Andric case Decl::IndirectField: 6317*0b57cec5SDimitry Andric break; 6318*0b57cec5SDimitry Andric 6319*0b57cec5SDimitry Andric // C++ Decls 6320*0b57cec5SDimitry Andric case Decl::Namespace: 6321*0b57cec5SDimitry Andric EmitDeclContext(cast<NamespaceDecl>(D)); 6322*0b57cec5SDimitry Andric break; 6323*0b57cec5SDimitry Andric case Decl::ClassTemplateSpecialization: { 6324*0b57cec5SDimitry Andric const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 63255ffd83dbSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 63265ffd83dbSDimitry Andric if (Spec->getSpecializationKind() == 63275ffd83dbSDimitry Andric TSK_ExplicitInstantiationDefinition && 6328*0b57cec5SDimitry Andric Spec->hasDefinition()) 63295ffd83dbSDimitry Andric DI->completeTemplateDefinition(*Spec); 6330bdd1243dSDimitry Andric } [[fallthrough]]; 6331e8d8bef9SDimitry Andric case Decl::CXXRecord: { 6332e8d8bef9SDimitry Andric CXXRecordDecl *CRD = cast<CXXRecordDecl>(D); 6333e8d8bef9SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) { 6334e8d8bef9SDimitry Andric if (CRD->hasDefinition()) 6335e8d8bef9SDimitry Andric DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 6336*0b57cec5SDimitry Andric if (auto *ES = D->getASTContext().getExternalSource()) 6337*0b57cec5SDimitry Andric if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) 6338e8d8bef9SDimitry Andric DI->completeUnusedClass(*CRD); 6339e8d8bef9SDimitry Andric } 6340*0b57cec5SDimitry Andric // Emit any static data members, they may be definitions. 6341e8d8bef9SDimitry Andric for (auto *I : CRD->decls()) 6342*0b57cec5SDimitry Andric if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) 6343*0b57cec5SDimitry Andric EmitTopLevelDecl(I); 6344*0b57cec5SDimitry Andric break; 6345e8d8bef9SDimitry Andric } 6346*0b57cec5SDimitry Andric // No code generation needed. 6347*0b57cec5SDimitry Andric case Decl::UsingShadow: 6348*0b57cec5SDimitry Andric case Decl::ClassTemplate: 6349*0b57cec5SDimitry Andric case Decl::VarTemplate: 6350*0b57cec5SDimitry Andric case Decl::Concept: 6351*0b57cec5SDimitry Andric case Decl::VarTemplatePartialSpecialization: 6352*0b57cec5SDimitry Andric case Decl::FunctionTemplate: 6353*0b57cec5SDimitry Andric case Decl::TypeAliasTemplate: 6354*0b57cec5SDimitry Andric case Decl::Block: 6355*0b57cec5SDimitry Andric case Decl::Empty: 6356*0b57cec5SDimitry Andric case Decl::Binding: 6357*0b57cec5SDimitry Andric break; 6358*0b57cec5SDimitry Andric case Decl::Using: // using X; [C++] 6359*0b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6360*0b57cec5SDimitry Andric DI->EmitUsingDecl(cast<UsingDecl>(*D)); 63615ffd83dbSDimitry Andric break; 6362fe6060f1SDimitry Andric case Decl::UsingEnum: // using enum X; [C++] 6363fe6060f1SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6364fe6060f1SDimitry Andric DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D)); 6365fe6060f1SDimitry Andric break; 6366*0b57cec5SDimitry Andric case Decl::NamespaceAlias: 6367*0b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6368*0b57cec5SDimitry Andric DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 63695ffd83dbSDimitry Andric break; 6370*0b57cec5SDimitry Andric case Decl::UsingDirective: // using namespace X; [C++] 6371*0b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6372*0b57cec5SDimitry Andric DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 63735ffd83dbSDimitry Andric break; 6374*0b57cec5SDimitry Andric case Decl::CXXConstructor: 6375*0b57cec5SDimitry Andric getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 6376*0b57cec5SDimitry Andric break; 6377*0b57cec5SDimitry Andric case Decl::CXXDestructor: 6378*0b57cec5SDimitry Andric getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 6379*0b57cec5SDimitry Andric break; 6380*0b57cec5SDimitry Andric 6381*0b57cec5SDimitry Andric case Decl::StaticAssert: 6382*0b57cec5SDimitry Andric // Nothing to do. 6383*0b57cec5SDimitry Andric break; 6384*0b57cec5SDimitry Andric 6385*0b57cec5SDimitry Andric // Objective-C Decls 6386*0b57cec5SDimitry Andric 6387*0b57cec5SDimitry Andric // Forward declarations, no (immediate) code generation. 6388*0b57cec5SDimitry Andric case Decl::ObjCInterface: 6389*0b57cec5SDimitry Andric case Decl::ObjCCategory: 6390*0b57cec5SDimitry Andric break; 6391*0b57cec5SDimitry Andric 6392*0b57cec5SDimitry Andric case Decl::ObjCProtocol: { 6393*0b57cec5SDimitry Andric auto *Proto = cast<ObjCProtocolDecl>(D); 6394*0b57cec5SDimitry Andric if (Proto->isThisDeclarationADefinition()) 6395*0b57cec5SDimitry Andric ObjCRuntime->GenerateProtocol(Proto); 6396*0b57cec5SDimitry Andric break; 6397*0b57cec5SDimitry Andric } 6398*0b57cec5SDimitry Andric 6399*0b57cec5SDimitry Andric case Decl::ObjCCategoryImpl: 6400*0b57cec5SDimitry Andric // Categories have properties but don't support synthesize so we 6401*0b57cec5SDimitry Andric // can ignore them here. 6402*0b57cec5SDimitry Andric ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 6403*0b57cec5SDimitry Andric break; 6404*0b57cec5SDimitry Andric 6405*0b57cec5SDimitry Andric case Decl::ObjCImplementation: { 6406*0b57cec5SDimitry Andric auto *OMD = cast<ObjCImplementationDecl>(D); 6407*0b57cec5SDimitry Andric EmitObjCPropertyImplementations(OMD); 6408*0b57cec5SDimitry Andric EmitObjCIvarInitializations(OMD); 6409*0b57cec5SDimitry Andric ObjCRuntime->GenerateClass(OMD); 6410*0b57cec5SDimitry Andric // Emit global variable debug information. 6411*0b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6412480093f4SDimitry Andric if (getCodeGenOpts().hasReducedDebugInfo()) 6413*0b57cec5SDimitry Andric DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 6414*0b57cec5SDimitry Andric OMD->getClassInterface()), OMD->getLocation()); 6415*0b57cec5SDimitry Andric break; 6416*0b57cec5SDimitry Andric } 6417*0b57cec5SDimitry Andric case Decl::ObjCMethod: { 6418*0b57cec5SDimitry Andric auto *OMD = cast<ObjCMethodDecl>(D); 6419*0b57cec5SDimitry Andric // If this is not a prototype, emit the body. 6420*0b57cec5SDimitry Andric if (OMD->getBody()) 6421*0b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCMethod(OMD); 6422*0b57cec5SDimitry Andric break; 6423*0b57cec5SDimitry Andric } 6424*0b57cec5SDimitry Andric case Decl::ObjCCompatibleAlias: 6425*0b57cec5SDimitry Andric ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 6426*0b57cec5SDimitry Andric break; 6427*0b57cec5SDimitry Andric 6428*0b57cec5SDimitry Andric case Decl::PragmaComment: { 6429*0b57cec5SDimitry Andric const auto *PCD = cast<PragmaCommentDecl>(D); 6430*0b57cec5SDimitry Andric switch (PCD->getCommentKind()) { 6431*0b57cec5SDimitry Andric case PCK_Unknown: 6432*0b57cec5SDimitry Andric llvm_unreachable("unexpected pragma comment kind"); 6433*0b57cec5SDimitry Andric case PCK_Linker: 6434*0b57cec5SDimitry Andric AppendLinkerOptions(PCD->getArg()); 6435*0b57cec5SDimitry Andric break; 6436*0b57cec5SDimitry Andric case PCK_Lib: 6437*0b57cec5SDimitry Andric AddDependentLib(PCD->getArg()); 6438*0b57cec5SDimitry Andric break; 6439*0b57cec5SDimitry Andric case PCK_Compiler: 6440*0b57cec5SDimitry Andric case PCK_ExeStr: 6441*0b57cec5SDimitry Andric case PCK_User: 6442*0b57cec5SDimitry Andric break; // We ignore all of these. 6443*0b57cec5SDimitry Andric } 6444*0b57cec5SDimitry Andric break; 6445*0b57cec5SDimitry Andric } 6446*0b57cec5SDimitry Andric 6447*0b57cec5SDimitry Andric case Decl::PragmaDetectMismatch: { 6448*0b57cec5SDimitry Andric const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 6449*0b57cec5SDimitry Andric AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 6450*0b57cec5SDimitry Andric break; 6451*0b57cec5SDimitry Andric } 6452*0b57cec5SDimitry Andric 6453*0b57cec5SDimitry Andric case Decl::LinkageSpec: 6454*0b57cec5SDimitry Andric EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 6455*0b57cec5SDimitry Andric break; 6456*0b57cec5SDimitry Andric 6457*0b57cec5SDimitry Andric case Decl::FileScopeAsm: { 6458*0b57cec5SDimitry Andric // File-scope asm is ignored during device-side CUDA compilation. 6459*0b57cec5SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 6460*0b57cec5SDimitry Andric break; 6461*0b57cec5SDimitry Andric // File-scope asm is ignored during device-side OpenMP compilation. 6462*0b57cec5SDimitry Andric if (LangOpts.OpenMPIsDevice) 6463*0b57cec5SDimitry Andric break; 6464fe6060f1SDimitry Andric // File-scope asm is ignored during device-side SYCL compilation. 6465fe6060f1SDimitry Andric if (LangOpts.SYCLIsDevice) 6466fe6060f1SDimitry Andric break; 6467*0b57cec5SDimitry Andric auto *AD = cast<FileScopeAsmDecl>(D); 6468*0b57cec5SDimitry Andric getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 6469*0b57cec5SDimitry Andric break; 6470*0b57cec5SDimitry Andric } 6471*0b57cec5SDimitry Andric 6472bdd1243dSDimitry Andric case Decl::TopLevelStmt: 6473bdd1243dSDimitry Andric EmitTopLevelStmt(cast<TopLevelStmtDecl>(D)); 6474bdd1243dSDimitry Andric break; 6475bdd1243dSDimitry Andric 6476*0b57cec5SDimitry Andric case Decl::Import: { 6477*0b57cec5SDimitry Andric auto *Import = cast<ImportDecl>(D); 6478*0b57cec5SDimitry Andric 6479*0b57cec5SDimitry Andric // If we've already imported this module, we're done. 6480*0b57cec5SDimitry Andric if (!ImportedModules.insert(Import->getImportedModule())) 6481*0b57cec5SDimitry Andric break; 6482*0b57cec5SDimitry Andric 6483*0b57cec5SDimitry Andric // Emit debug information for direct imports. 6484*0b57cec5SDimitry Andric if (!Import->getImportedOwningModule()) { 6485*0b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6486*0b57cec5SDimitry Andric DI->EmitImportDecl(*Import); 6487*0b57cec5SDimitry Andric } 6488*0b57cec5SDimitry Andric 6489fcaf7f86SDimitry Andric // For C++ standard modules we are done - we will call the module 6490fcaf7f86SDimitry Andric // initializer for imported modules, and that will likewise call those for 6491fcaf7f86SDimitry Andric // any imports it has. 6492fcaf7f86SDimitry Andric if (CXX20ModuleInits && Import->getImportedOwningModule() && 6493fcaf7f86SDimitry Andric !Import->getImportedOwningModule()->isModuleMapModule()) 6494fcaf7f86SDimitry Andric break; 6495fcaf7f86SDimitry Andric 6496fcaf7f86SDimitry Andric // For clang C++ module map modules the initializers for sub-modules are 6497fcaf7f86SDimitry Andric // emitted here. 6498fcaf7f86SDimitry Andric 6499*0b57cec5SDimitry Andric // Find all of the submodules and emit the module initializers. 6500*0b57cec5SDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 6501*0b57cec5SDimitry Andric SmallVector<clang::Module *, 16> Stack; 6502*0b57cec5SDimitry Andric Visited.insert(Import->getImportedModule()); 6503*0b57cec5SDimitry Andric Stack.push_back(Import->getImportedModule()); 6504*0b57cec5SDimitry Andric 6505*0b57cec5SDimitry Andric while (!Stack.empty()) { 6506*0b57cec5SDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 6507*0b57cec5SDimitry Andric if (!EmittedModuleInitializers.insert(Mod).second) 6508*0b57cec5SDimitry Andric continue; 6509*0b57cec5SDimitry Andric 6510*0b57cec5SDimitry Andric for (auto *D : Context.getModuleInitializers(Mod)) 6511*0b57cec5SDimitry Andric EmitTopLevelDecl(D); 6512*0b57cec5SDimitry Andric 6513*0b57cec5SDimitry Andric // Visit the submodules of this module. 6514*0b57cec5SDimitry Andric for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 6515*0b57cec5SDimitry Andric SubEnd = Mod->submodule_end(); 6516*0b57cec5SDimitry Andric Sub != SubEnd; ++Sub) { 6517*0b57cec5SDimitry Andric // Skip explicit children; they need to be explicitly imported to emit 6518*0b57cec5SDimitry Andric // the initializers. 6519*0b57cec5SDimitry Andric if ((*Sub)->IsExplicit) 6520*0b57cec5SDimitry Andric continue; 6521*0b57cec5SDimitry Andric 6522*0b57cec5SDimitry Andric if (Visited.insert(*Sub).second) 6523*0b57cec5SDimitry Andric Stack.push_back(*Sub); 6524*0b57cec5SDimitry Andric } 6525*0b57cec5SDimitry Andric } 6526*0b57cec5SDimitry Andric break; 6527*0b57cec5SDimitry Andric } 6528*0b57cec5SDimitry Andric 6529*0b57cec5SDimitry Andric case Decl::Export: 6530*0b57cec5SDimitry Andric EmitDeclContext(cast<ExportDecl>(D)); 6531*0b57cec5SDimitry Andric break; 6532*0b57cec5SDimitry Andric 6533*0b57cec5SDimitry Andric case Decl::OMPThreadPrivate: 6534*0b57cec5SDimitry Andric EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 6535*0b57cec5SDimitry Andric break; 6536*0b57cec5SDimitry Andric 6537*0b57cec5SDimitry Andric case Decl::OMPAllocate: 6538fe6060f1SDimitry Andric EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D)); 6539*0b57cec5SDimitry Andric break; 6540*0b57cec5SDimitry Andric 6541*0b57cec5SDimitry Andric case Decl::OMPDeclareReduction: 6542*0b57cec5SDimitry Andric EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 6543*0b57cec5SDimitry Andric break; 6544*0b57cec5SDimitry Andric 6545*0b57cec5SDimitry Andric case Decl::OMPDeclareMapper: 6546*0b57cec5SDimitry Andric EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D)); 6547*0b57cec5SDimitry Andric break; 6548*0b57cec5SDimitry Andric 6549*0b57cec5SDimitry Andric case Decl::OMPRequires: 6550*0b57cec5SDimitry Andric EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D)); 6551*0b57cec5SDimitry Andric break; 6552*0b57cec5SDimitry Andric 6553e8d8bef9SDimitry Andric case Decl::Typedef: 6554e8d8bef9SDimitry Andric case Decl::TypeAlias: // using foo = bar; [C++11] 6555e8d8bef9SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6556e8d8bef9SDimitry Andric DI->EmitAndRetainType( 6557e8d8bef9SDimitry Andric getContext().getTypedefType(cast<TypedefNameDecl>(D))); 6558e8d8bef9SDimitry Andric break; 6559e8d8bef9SDimitry Andric 6560e8d8bef9SDimitry Andric case Decl::Record: 6561e8d8bef9SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6562e8d8bef9SDimitry Andric if (cast<RecordDecl>(D)->getDefinition()) 6563e8d8bef9SDimitry Andric DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 6564e8d8bef9SDimitry Andric break; 6565e8d8bef9SDimitry Andric 6566e8d8bef9SDimitry Andric case Decl::Enum: 6567e8d8bef9SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6568e8d8bef9SDimitry Andric if (cast<EnumDecl>(D)->getDefinition()) 6569e8d8bef9SDimitry Andric DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D))); 6570e8d8bef9SDimitry Andric break; 6571e8d8bef9SDimitry Andric 6572bdd1243dSDimitry Andric case Decl::HLSLBuffer: 6573bdd1243dSDimitry Andric getHLSLRuntime().addBuffer(cast<HLSLBufferDecl>(D)); 6574bdd1243dSDimitry Andric break; 6575bdd1243dSDimitry Andric 6576*0b57cec5SDimitry Andric default: 6577*0b57cec5SDimitry Andric // Make sure we handled everything we should, every other kind is a 6578*0b57cec5SDimitry Andric // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 6579*0b57cec5SDimitry Andric // function. Need to recode Decl::Kind to do that easily. 6580*0b57cec5SDimitry Andric assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 6581*0b57cec5SDimitry Andric break; 6582*0b57cec5SDimitry Andric } 6583*0b57cec5SDimitry Andric } 6584*0b57cec5SDimitry Andric 6585*0b57cec5SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 6586*0b57cec5SDimitry Andric // Do we need to generate coverage mapping? 6587*0b57cec5SDimitry Andric if (!CodeGenOpts.CoverageMapping) 6588*0b57cec5SDimitry Andric return; 6589*0b57cec5SDimitry Andric switch (D->getKind()) { 6590*0b57cec5SDimitry Andric case Decl::CXXConversion: 6591*0b57cec5SDimitry Andric case Decl::CXXMethod: 6592*0b57cec5SDimitry Andric case Decl::Function: 6593*0b57cec5SDimitry Andric case Decl::ObjCMethod: 6594*0b57cec5SDimitry Andric case Decl::CXXConstructor: 6595*0b57cec5SDimitry Andric case Decl::CXXDestructor: { 6596*0b57cec5SDimitry Andric if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 65975ffd83dbSDimitry Andric break; 6598*0b57cec5SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 6599*0b57cec5SDimitry Andric if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc())) 66005ffd83dbSDimitry Andric break; 6601*0b57cec5SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 6602*0b57cec5SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 6603*0b57cec5SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = true; 6604*0b57cec5SDimitry Andric break; 6605*0b57cec5SDimitry Andric } 6606*0b57cec5SDimitry Andric default: 6607*0b57cec5SDimitry Andric break; 6608*0b57cec5SDimitry Andric }; 6609*0b57cec5SDimitry Andric } 6610*0b57cec5SDimitry Andric 6611*0b57cec5SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 6612*0b57cec5SDimitry Andric // Do we need to generate coverage mapping? 6613*0b57cec5SDimitry Andric if (!CodeGenOpts.CoverageMapping) 6614*0b57cec5SDimitry Andric return; 6615*0b57cec5SDimitry Andric if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 6616*0b57cec5SDimitry Andric if (Fn->isTemplateInstantiation()) 6617*0b57cec5SDimitry Andric ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 6618*0b57cec5SDimitry Andric } 6619*0b57cec5SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 6620*0b57cec5SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 6621*0b57cec5SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = false; 6622*0b57cec5SDimitry Andric else 6623*0b57cec5SDimitry Andric I->second = false; 6624*0b57cec5SDimitry Andric } 6625*0b57cec5SDimitry Andric 6626*0b57cec5SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 6627*0b57cec5SDimitry Andric // We call takeVector() here to avoid use-after-free. 6628*0b57cec5SDimitry Andric // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because 6629*0b57cec5SDimitry Andric // we deserialize function bodies to emit coverage info for them, and that 6630*0b57cec5SDimitry Andric // deserializes more declarations. How should we handle that case? 6631*0b57cec5SDimitry Andric for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) { 6632*0b57cec5SDimitry Andric if (!Entry.second) 6633*0b57cec5SDimitry Andric continue; 6634*0b57cec5SDimitry Andric const Decl *D = Entry.first; 6635*0b57cec5SDimitry Andric switch (D->getKind()) { 6636*0b57cec5SDimitry Andric case Decl::CXXConversion: 6637*0b57cec5SDimitry Andric case Decl::CXXMethod: 6638*0b57cec5SDimitry Andric case Decl::Function: 6639*0b57cec5SDimitry Andric case Decl::ObjCMethod: { 6640*0b57cec5SDimitry Andric CodeGenPGO PGO(*this); 6641*0b57cec5SDimitry Andric GlobalDecl GD(cast<FunctionDecl>(D)); 6642*0b57cec5SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6643*0b57cec5SDimitry Andric getFunctionLinkage(GD)); 6644*0b57cec5SDimitry Andric break; 6645*0b57cec5SDimitry Andric } 6646*0b57cec5SDimitry Andric case Decl::CXXConstructor: { 6647*0b57cec5SDimitry Andric CodeGenPGO PGO(*this); 6648*0b57cec5SDimitry Andric GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 6649*0b57cec5SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6650*0b57cec5SDimitry Andric getFunctionLinkage(GD)); 6651*0b57cec5SDimitry Andric break; 6652*0b57cec5SDimitry Andric } 6653*0b57cec5SDimitry Andric case Decl::CXXDestructor: { 6654*0b57cec5SDimitry Andric CodeGenPGO PGO(*this); 6655*0b57cec5SDimitry Andric GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 6656*0b57cec5SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6657*0b57cec5SDimitry Andric getFunctionLinkage(GD)); 6658*0b57cec5SDimitry Andric break; 6659*0b57cec5SDimitry Andric } 6660*0b57cec5SDimitry Andric default: 6661*0b57cec5SDimitry Andric break; 6662*0b57cec5SDimitry Andric }; 6663*0b57cec5SDimitry Andric } 6664*0b57cec5SDimitry Andric } 6665*0b57cec5SDimitry Andric 66665ffd83dbSDimitry Andric void CodeGenModule::EmitMainVoidAlias() { 66675ffd83dbSDimitry Andric // In order to transition away from "__original_main" gracefully, emit an 66685ffd83dbSDimitry Andric // alias for "main" in the no-argument case so that libc can detect when 66695ffd83dbSDimitry Andric // new-style no-argument main is in used. 66705ffd83dbSDimitry Andric if (llvm::Function *F = getModule().getFunction("main")) { 66715ffd83dbSDimitry Andric if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() && 667281ad6265SDimitry Andric F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) { 667381ad6265SDimitry Andric auto *GA = llvm::GlobalAlias::create("__main_void", F); 667481ad6265SDimitry Andric GA->setVisibility(llvm::GlobalValue::HiddenVisibility); 667581ad6265SDimitry Andric } 66765ffd83dbSDimitry Andric } 66775ffd83dbSDimitry Andric } 66785ffd83dbSDimitry Andric 6679*0b57cec5SDimitry Andric /// Turns the given pointer into a constant. 6680*0b57cec5SDimitry Andric static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 6681*0b57cec5SDimitry Andric const void *Ptr) { 6682*0b57cec5SDimitry Andric uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 6683*0b57cec5SDimitry Andric llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 6684*0b57cec5SDimitry Andric return llvm::ConstantInt::get(i64, PtrInt); 6685*0b57cec5SDimitry Andric } 6686*0b57cec5SDimitry Andric 6687*0b57cec5SDimitry Andric static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 6688*0b57cec5SDimitry Andric llvm::NamedMDNode *&GlobalMetadata, 6689*0b57cec5SDimitry Andric GlobalDecl D, 6690*0b57cec5SDimitry Andric llvm::GlobalValue *Addr) { 6691*0b57cec5SDimitry Andric if (!GlobalMetadata) 6692*0b57cec5SDimitry Andric GlobalMetadata = 6693*0b57cec5SDimitry Andric CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 6694*0b57cec5SDimitry Andric 6695*0b57cec5SDimitry Andric // TODO: should we report variant information for ctors/dtors? 6696*0b57cec5SDimitry Andric llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 6697*0b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(GetPointerConstant( 6698*0b57cec5SDimitry Andric CGM.getLLVMContext(), D.getDecl()))}; 6699*0b57cec5SDimitry Andric GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 6700*0b57cec5SDimitry Andric } 6701*0b57cec5SDimitry Andric 670281ad6265SDimitry Andric bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem, 670381ad6265SDimitry Andric llvm::GlobalValue *CppFunc) { 670481ad6265SDimitry Andric // Store the list of ifuncs we need to replace uses in. 670581ad6265SDimitry Andric llvm::SmallVector<llvm::GlobalIFunc *> IFuncs; 670681ad6265SDimitry Andric // List of ConstantExprs that we should be able to delete when we're done 670781ad6265SDimitry Andric // here. 670881ad6265SDimitry Andric llvm::SmallVector<llvm::ConstantExpr *> CEs; 670981ad6265SDimitry Andric 671081ad6265SDimitry Andric // It isn't valid to replace the extern-C ifuncs if all we find is itself! 671181ad6265SDimitry Andric if (Elem == CppFunc) 671281ad6265SDimitry Andric return false; 671381ad6265SDimitry Andric 671481ad6265SDimitry Andric // First make sure that all users of this are ifuncs (or ifuncs via a 671581ad6265SDimitry Andric // bitcast), and collect the list of ifuncs and CEs so we can work on them 671681ad6265SDimitry Andric // later. 671781ad6265SDimitry Andric for (llvm::User *User : Elem->users()) { 671881ad6265SDimitry Andric // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an 671981ad6265SDimitry Andric // ifunc directly. In any other case, just give up, as we don't know what we 672081ad6265SDimitry Andric // could break by changing those. 672181ad6265SDimitry Andric if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) { 672281ad6265SDimitry Andric if (ConstExpr->getOpcode() != llvm::Instruction::BitCast) 672381ad6265SDimitry Andric return false; 672481ad6265SDimitry Andric 672581ad6265SDimitry Andric for (llvm::User *CEUser : ConstExpr->users()) { 672681ad6265SDimitry Andric if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) { 672781ad6265SDimitry Andric IFuncs.push_back(IFunc); 672881ad6265SDimitry Andric } else { 672981ad6265SDimitry Andric return false; 673081ad6265SDimitry Andric } 673181ad6265SDimitry Andric } 673281ad6265SDimitry Andric CEs.push_back(ConstExpr); 673381ad6265SDimitry Andric } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) { 673481ad6265SDimitry Andric IFuncs.push_back(IFunc); 673581ad6265SDimitry Andric } else { 673681ad6265SDimitry Andric // This user is one we don't know how to handle, so fail redirection. This 673781ad6265SDimitry Andric // will result in an ifunc retaining a resolver name that will ultimately 673881ad6265SDimitry Andric // fail to be resolved to a defined function. 673981ad6265SDimitry Andric return false; 674081ad6265SDimitry Andric } 674181ad6265SDimitry Andric } 674281ad6265SDimitry Andric 674381ad6265SDimitry Andric // Now we know this is a valid case where we can do this alias replacement, we 674481ad6265SDimitry Andric // need to remove all of the references to Elem (and the bitcasts!) so we can 674581ad6265SDimitry Andric // delete it. 674681ad6265SDimitry Andric for (llvm::GlobalIFunc *IFunc : IFuncs) 674781ad6265SDimitry Andric IFunc->setResolver(nullptr); 674881ad6265SDimitry Andric for (llvm::ConstantExpr *ConstExpr : CEs) 674981ad6265SDimitry Andric ConstExpr->destroyConstant(); 675081ad6265SDimitry Andric 675181ad6265SDimitry Andric // We should now be out of uses for the 'old' version of this function, so we 675281ad6265SDimitry Andric // can erase it as well. 675381ad6265SDimitry Andric Elem->eraseFromParent(); 675481ad6265SDimitry Andric 675581ad6265SDimitry Andric for (llvm::GlobalIFunc *IFunc : IFuncs) { 675681ad6265SDimitry Andric // The type of the resolver is always just a function-type that returns the 675781ad6265SDimitry Andric // type of the IFunc, so create that here. If the type of the actual 675881ad6265SDimitry Andric // resolver doesn't match, it just gets bitcast to the right thing. 675981ad6265SDimitry Andric auto *ResolverTy = 676081ad6265SDimitry Andric llvm::FunctionType::get(IFunc->getType(), /*isVarArg*/ false); 676181ad6265SDimitry Andric llvm::Constant *Resolver = GetOrCreateLLVMFunction( 676281ad6265SDimitry Andric CppFunc->getName(), ResolverTy, {}, /*ForVTable*/ false); 676381ad6265SDimitry Andric IFunc->setResolver(Resolver); 676481ad6265SDimitry Andric } 676581ad6265SDimitry Andric return true; 676681ad6265SDimitry Andric } 676781ad6265SDimitry Andric 6768*0b57cec5SDimitry Andric /// For each function which is declared within an extern "C" region and marked 6769*0b57cec5SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled 6770*0b57cec5SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer 6771*0b57cec5SDimitry Andric /// to such functions with an unmangled name from inline assembly within the 6772*0b57cec5SDimitry Andric /// same translation unit. 6773*0b57cec5SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() { 6774*0b57cec5SDimitry Andric if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases()) 6775*0b57cec5SDimitry Andric return; 6776*0b57cec5SDimitry Andric for (auto &I : StaticExternCValues) { 6777*0b57cec5SDimitry Andric IdentifierInfo *Name = I.first; 6778*0b57cec5SDimitry Andric llvm::GlobalValue *Val = I.second; 677981ad6265SDimitry Andric 678081ad6265SDimitry Andric // If Val is null, that implies there were multiple declarations that each 678181ad6265SDimitry Andric // had a claim to the unmangled name. In this case, generation of the alias 678281ad6265SDimitry Andric // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC. 678381ad6265SDimitry Andric if (!Val) 678481ad6265SDimitry Andric break; 678581ad6265SDimitry Andric 678681ad6265SDimitry Andric llvm::GlobalValue *ExistingElem = 678781ad6265SDimitry Andric getModule().getNamedValue(Name->getName()); 678881ad6265SDimitry Andric 678981ad6265SDimitry Andric // If there is either not something already by this name, or we were able to 679081ad6265SDimitry Andric // replace all uses from IFuncs, create the alias. 679181ad6265SDimitry Andric if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val)) 6792fe6060f1SDimitry Andric addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 6793*0b57cec5SDimitry Andric } 6794*0b57cec5SDimitry Andric } 6795*0b57cec5SDimitry Andric 6796*0b57cec5SDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 6797*0b57cec5SDimitry Andric GlobalDecl &Result) const { 6798*0b57cec5SDimitry Andric auto Res = Manglings.find(MangledName); 6799*0b57cec5SDimitry Andric if (Res == Manglings.end()) 6800*0b57cec5SDimitry Andric return false; 6801*0b57cec5SDimitry Andric Result = Res->getValue(); 6802*0b57cec5SDimitry Andric return true; 6803*0b57cec5SDimitry Andric } 6804*0b57cec5SDimitry Andric 6805*0b57cec5SDimitry Andric /// Emits metadata nodes associating all the global values in the 6806*0b57cec5SDimitry Andric /// current module with the Decls they came from. This is useful for 6807*0b57cec5SDimitry Andric /// projects using IR gen as a subroutine. 6808*0b57cec5SDimitry Andric /// 6809*0b57cec5SDimitry Andric /// Since there's currently no way to associate an MDNode directly 6810*0b57cec5SDimitry Andric /// with an llvm::GlobalValue, we create a global named metadata 6811*0b57cec5SDimitry Andric /// with the name 'clang.global.decl.ptrs'. 6812*0b57cec5SDimitry Andric void CodeGenModule::EmitDeclMetadata() { 6813*0b57cec5SDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 6814*0b57cec5SDimitry Andric 6815*0b57cec5SDimitry Andric for (auto &I : MangledDeclNames) { 6816*0b57cec5SDimitry Andric llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 6817*0b57cec5SDimitry Andric // Some mangled names don't necessarily have an associated GlobalValue 6818*0b57cec5SDimitry Andric // in this module, e.g. if we mangled it for DebugInfo. 6819*0b57cec5SDimitry Andric if (Addr) 6820*0b57cec5SDimitry Andric EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 6821*0b57cec5SDimitry Andric } 6822*0b57cec5SDimitry Andric } 6823*0b57cec5SDimitry Andric 6824*0b57cec5SDimitry Andric /// Emits metadata nodes for all the local variables in the current 6825*0b57cec5SDimitry Andric /// function. 6826*0b57cec5SDimitry Andric void CodeGenFunction::EmitDeclMetadata() { 6827*0b57cec5SDimitry Andric if (LocalDeclMap.empty()) return; 6828*0b57cec5SDimitry Andric 6829*0b57cec5SDimitry Andric llvm::LLVMContext &Context = getLLVMContext(); 6830*0b57cec5SDimitry Andric 6831*0b57cec5SDimitry Andric // Find the unique metadata ID for this name. 6832*0b57cec5SDimitry Andric unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 6833*0b57cec5SDimitry Andric 6834*0b57cec5SDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 6835*0b57cec5SDimitry Andric 6836*0b57cec5SDimitry Andric for (auto &I : LocalDeclMap) { 6837*0b57cec5SDimitry Andric const Decl *D = I.first; 6838*0b57cec5SDimitry Andric llvm::Value *Addr = I.second.getPointer(); 6839*0b57cec5SDimitry Andric if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 6840*0b57cec5SDimitry Andric llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 6841*0b57cec5SDimitry Andric Alloca->setMetadata( 6842*0b57cec5SDimitry Andric DeclPtrKind, llvm::MDNode::get( 6843*0b57cec5SDimitry Andric Context, llvm::ValueAsMetadata::getConstant(DAddr))); 6844*0b57cec5SDimitry Andric } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 6845*0b57cec5SDimitry Andric GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 6846*0b57cec5SDimitry Andric EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 6847*0b57cec5SDimitry Andric } 6848*0b57cec5SDimitry Andric } 6849*0b57cec5SDimitry Andric } 6850*0b57cec5SDimitry Andric 6851*0b57cec5SDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() { 6852*0b57cec5SDimitry Andric llvm::NamedMDNode *IdentMetadata = 6853*0b57cec5SDimitry Andric TheModule.getOrInsertNamedMetadata("llvm.ident"); 6854*0b57cec5SDimitry Andric std::string Version = getClangFullVersion(); 6855*0b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 6856*0b57cec5SDimitry Andric 6857*0b57cec5SDimitry Andric llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 6858*0b57cec5SDimitry Andric IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 6859*0b57cec5SDimitry Andric } 6860*0b57cec5SDimitry Andric 6861*0b57cec5SDimitry Andric void CodeGenModule::EmitCommandLineMetadata() { 6862*0b57cec5SDimitry Andric llvm::NamedMDNode *CommandLineMetadata = 6863*0b57cec5SDimitry Andric TheModule.getOrInsertNamedMetadata("llvm.commandline"); 6864*0b57cec5SDimitry Andric std::string CommandLine = getCodeGenOpts().RecordCommandLine; 6865*0b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 6866*0b57cec5SDimitry Andric 6867*0b57cec5SDimitry Andric llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)}; 6868*0b57cec5SDimitry Andric CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode)); 6869*0b57cec5SDimitry Andric } 6870*0b57cec5SDimitry Andric 6871*0b57cec5SDimitry Andric void CodeGenModule::EmitCoverageFile() { 6872*0b57cec5SDimitry Andric if (getCodeGenOpts().CoverageDataFile.empty() && 6873*0b57cec5SDimitry Andric getCodeGenOpts().CoverageNotesFile.empty()) 6874*0b57cec5SDimitry Andric return; 6875*0b57cec5SDimitry Andric 6876*0b57cec5SDimitry Andric llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); 6877*0b57cec5SDimitry Andric if (!CUNode) 6878*0b57cec5SDimitry Andric return; 6879*0b57cec5SDimitry Andric 6880*0b57cec5SDimitry Andric llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 6881*0b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 6882*0b57cec5SDimitry Andric auto *CoverageDataFile = 6883*0b57cec5SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); 6884*0b57cec5SDimitry Andric auto *CoverageNotesFile = 6885*0b57cec5SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); 6886*0b57cec5SDimitry Andric for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 6887*0b57cec5SDimitry Andric llvm::MDNode *CU = CUNode->getOperand(i); 6888*0b57cec5SDimitry Andric llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; 6889*0b57cec5SDimitry Andric GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 6890*0b57cec5SDimitry Andric } 6891*0b57cec5SDimitry Andric } 6892*0b57cec5SDimitry Andric 6893*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 6894*0b57cec5SDimitry Andric bool ForEH) { 6895*0b57cec5SDimitry Andric // Return a bogus pointer if RTTI is disabled, unless it's for EH. 6896*0b57cec5SDimitry Andric // FIXME: should we even be calling this method if RTTI is disabled 6897*0b57cec5SDimitry Andric // and it's not for EH? 68985ffd83dbSDimitry Andric if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice || 68995ffd83dbSDimitry Andric (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 69005ffd83dbSDimitry Andric getTriple().isNVPTX())) 6901*0b57cec5SDimitry Andric return llvm::Constant::getNullValue(Int8PtrTy); 6902*0b57cec5SDimitry Andric 6903*0b57cec5SDimitry Andric if (ForEH && Ty->isObjCObjectPointerType() && 6904*0b57cec5SDimitry Andric LangOpts.ObjCRuntime.isGNUFamily()) 6905*0b57cec5SDimitry Andric return ObjCRuntime->GetEHType(Ty); 6906*0b57cec5SDimitry Andric 6907*0b57cec5SDimitry Andric return getCXXABI().getAddrOfRTTIDescriptor(Ty); 6908*0b57cec5SDimitry Andric } 6909*0b57cec5SDimitry Andric 6910*0b57cec5SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 6911*0b57cec5SDimitry Andric // Do not emit threadprivates in simd-only mode. 6912*0b57cec5SDimitry Andric if (LangOpts.OpenMP && LangOpts.OpenMPSimd) 6913*0b57cec5SDimitry Andric return; 6914*0b57cec5SDimitry Andric for (auto RefExpr : D->varlists()) { 6915*0b57cec5SDimitry Andric auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 6916*0b57cec5SDimitry Andric bool PerformInit = 6917*0b57cec5SDimitry Andric VD->getAnyInitializer() && 6918*0b57cec5SDimitry Andric !VD->getAnyInitializer()->isConstantInitializer(getContext(), 6919*0b57cec5SDimitry Andric /*ForRef=*/false); 6920*0b57cec5SDimitry Andric 692181ad6265SDimitry Andric Address Addr(GetAddrOfGlobalVar(VD), 692281ad6265SDimitry Andric getTypes().ConvertTypeForMem(VD->getType()), 692381ad6265SDimitry Andric getContext().getDeclAlign(VD)); 6924*0b57cec5SDimitry Andric if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 6925*0b57cec5SDimitry Andric VD, Addr, RefExpr->getBeginLoc(), PerformInit)) 6926*0b57cec5SDimitry Andric CXXGlobalInits.push_back(InitFunction); 6927*0b57cec5SDimitry Andric } 6928*0b57cec5SDimitry Andric } 6929*0b57cec5SDimitry Andric 6930*0b57cec5SDimitry Andric llvm::Metadata * 6931*0b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, 6932*0b57cec5SDimitry Andric StringRef Suffix) { 69330eae32dcSDimitry Andric if (auto *FnType = T->getAs<FunctionProtoType>()) 69340eae32dcSDimitry Andric T = getContext().getFunctionType( 69350eae32dcSDimitry Andric FnType->getReturnType(), FnType->getParamTypes(), 69360eae32dcSDimitry Andric FnType->getExtProtoInfo().withExceptionSpec(EST_None)); 69370eae32dcSDimitry Andric 6938*0b57cec5SDimitry Andric llvm::Metadata *&InternalId = Map[T.getCanonicalType()]; 6939*0b57cec5SDimitry Andric if (InternalId) 6940*0b57cec5SDimitry Andric return InternalId; 6941*0b57cec5SDimitry Andric 6942*0b57cec5SDimitry Andric if (isExternallyVisible(T->getLinkage())) { 6943*0b57cec5SDimitry Andric std::string OutName; 6944*0b57cec5SDimitry Andric llvm::raw_string_ostream Out(OutName); 6945*0b57cec5SDimitry Andric getCXXABI().getMangleContext().mangleTypeName(T, Out); 6946*0b57cec5SDimitry Andric Out << Suffix; 6947*0b57cec5SDimitry Andric 6948*0b57cec5SDimitry Andric InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 6949*0b57cec5SDimitry Andric } else { 6950*0b57cec5SDimitry Andric InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 6951*0b57cec5SDimitry Andric llvm::ArrayRef<llvm::Metadata *>()); 6952*0b57cec5SDimitry Andric } 6953*0b57cec5SDimitry Andric 6954*0b57cec5SDimitry Andric return InternalId; 6955*0b57cec5SDimitry Andric } 6956*0b57cec5SDimitry Andric 6957*0b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 6958*0b57cec5SDimitry Andric return CreateMetadataIdentifierImpl(T, MetadataIdMap, ""); 6959*0b57cec5SDimitry Andric } 6960*0b57cec5SDimitry Andric 6961*0b57cec5SDimitry Andric llvm::Metadata * 6962*0b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) { 6963*0b57cec5SDimitry Andric return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual"); 6964*0b57cec5SDimitry Andric } 6965*0b57cec5SDimitry Andric 6966*0b57cec5SDimitry Andric // Generalize pointer types to a void pointer with the qualifiers of the 6967*0b57cec5SDimitry Andric // originally pointed-to type, e.g. 'const char *' and 'char * const *' 6968*0b57cec5SDimitry Andric // generalize to 'const void *' while 'char *' and 'const char **' generalize to 6969*0b57cec5SDimitry Andric // 'void *'. 6970*0b57cec5SDimitry Andric static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) { 6971*0b57cec5SDimitry Andric if (!Ty->isPointerType()) 6972*0b57cec5SDimitry Andric return Ty; 6973*0b57cec5SDimitry Andric 6974*0b57cec5SDimitry Andric return Ctx.getPointerType( 6975*0b57cec5SDimitry Andric QualType(Ctx.VoidTy).withCVRQualifiers( 6976*0b57cec5SDimitry Andric Ty->getPointeeType().getCVRQualifiers())); 6977*0b57cec5SDimitry Andric } 6978*0b57cec5SDimitry Andric 6979*0b57cec5SDimitry Andric // Apply type generalization to a FunctionType's return and argument types 6980*0b57cec5SDimitry Andric static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) { 6981*0b57cec5SDimitry Andric if (auto *FnType = Ty->getAs<FunctionProtoType>()) { 6982*0b57cec5SDimitry Andric SmallVector<QualType, 8> GeneralizedParams; 6983*0b57cec5SDimitry Andric for (auto &Param : FnType->param_types()) 6984*0b57cec5SDimitry Andric GeneralizedParams.push_back(GeneralizeType(Ctx, Param)); 6985*0b57cec5SDimitry Andric 6986*0b57cec5SDimitry Andric return Ctx.getFunctionType( 6987*0b57cec5SDimitry Andric GeneralizeType(Ctx, FnType->getReturnType()), 6988*0b57cec5SDimitry Andric GeneralizedParams, FnType->getExtProtoInfo()); 6989*0b57cec5SDimitry Andric } 6990*0b57cec5SDimitry Andric 6991*0b57cec5SDimitry Andric if (auto *FnType = Ty->getAs<FunctionNoProtoType>()) 6992*0b57cec5SDimitry Andric return Ctx.getFunctionNoProtoType( 6993*0b57cec5SDimitry Andric GeneralizeType(Ctx, FnType->getReturnType())); 6994*0b57cec5SDimitry Andric 6995*0b57cec5SDimitry Andric llvm_unreachable("Encountered unknown FunctionType"); 6996*0b57cec5SDimitry Andric } 6997*0b57cec5SDimitry Andric 6998*0b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) { 6999*0b57cec5SDimitry Andric return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T), 7000*0b57cec5SDimitry Andric GeneralizedMetadataIdMap, ".generalized"); 7001*0b57cec5SDimitry Andric } 7002*0b57cec5SDimitry Andric 7003*0b57cec5SDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier. 7004*0b57cec5SDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const { 7005*0b57cec5SDimitry Andric // Returns true if at least one of vtable-based CFI checkers is enabled and 7006*0b57cec5SDimitry Andric // is not in the trapping mode. 7007*0b57cec5SDimitry Andric return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 7008*0b57cec5SDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 7009*0b57cec5SDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 7010*0b57cec5SDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 7011*0b57cec5SDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 7012*0b57cec5SDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 7013*0b57cec5SDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 7014*0b57cec5SDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 7015*0b57cec5SDimitry Andric } 7016*0b57cec5SDimitry Andric 7017*0b57cec5SDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 7018*0b57cec5SDimitry Andric CharUnits Offset, 7019*0b57cec5SDimitry Andric const CXXRecordDecl *RD) { 7020*0b57cec5SDimitry Andric llvm::Metadata *MD = 7021*0b57cec5SDimitry Andric CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 7022*0b57cec5SDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), MD); 7023*0b57cec5SDimitry Andric 7024*0b57cec5SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 7025*0b57cec5SDimitry Andric if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 7026*0b57cec5SDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), 7027*0b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 7028*0b57cec5SDimitry Andric 7029*0b57cec5SDimitry Andric if (NeedAllVtablesTypeId()) { 7030*0b57cec5SDimitry Andric llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 7031*0b57cec5SDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), MD); 7032*0b57cec5SDimitry Andric } 7033*0b57cec5SDimitry Andric } 7034*0b57cec5SDimitry Andric 7035*0b57cec5SDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 7036*0b57cec5SDimitry Andric if (!SanStats) 7037a7dea167SDimitry Andric SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule()); 7038*0b57cec5SDimitry Andric 7039*0b57cec5SDimitry Andric return *SanStats; 7040*0b57cec5SDimitry Andric } 704123408297SDimitry Andric 7042*0b57cec5SDimitry Andric llvm::Value * 7043*0b57cec5SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, 7044*0b57cec5SDimitry Andric CodeGenFunction &CGF) { 7045*0b57cec5SDimitry Andric llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType()); 704623408297SDimitry Andric auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr()); 704723408297SDimitry Andric auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); 7048fe6060f1SDimitry Andric auto *Call = CGF.EmitRuntimeCall( 704923408297SDimitry Andric CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C}); 705023408297SDimitry Andric return Call; 7051*0b57cec5SDimitry Andric } 70525ffd83dbSDimitry Andric 70535ffd83dbSDimitry Andric CharUnits CodeGenModule::getNaturalPointeeTypeAlignment( 70545ffd83dbSDimitry Andric QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) { 70555ffd83dbSDimitry Andric return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo, 70565ffd83dbSDimitry Andric /* forPointeeType= */ true); 70575ffd83dbSDimitry Andric } 70585ffd83dbSDimitry Andric 70595ffd83dbSDimitry Andric CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T, 70605ffd83dbSDimitry Andric LValueBaseInfo *BaseInfo, 70615ffd83dbSDimitry Andric TBAAAccessInfo *TBAAInfo, 70625ffd83dbSDimitry Andric bool forPointeeType) { 70635ffd83dbSDimitry Andric if (TBAAInfo) 70645ffd83dbSDimitry Andric *TBAAInfo = getTBAAAccessInfo(T); 70655ffd83dbSDimitry Andric 70665ffd83dbSDimitry Andric // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But 70675ffd83dbSDimitry Andric // that doesn't return the information we need to compute BaseInfo. 70685ffd83dbSDimitry Andric 70695ffd83dbSDimitry Andric // Honor alignment typedef attributes even on incomplete types. 70705ffd83dbSDimitry Andric // We also honor them straight for C++ class types, even as pointees; 70715ffd83dbSDimitry Andric // there's an expressivity gap here. 70725ffd83dbSDimitry Andric if (auto TT = T->getAs<TypedefType>()) { 70735ffd83dbSDimitry Andric if (auto Align = TT->getDecl()->getMaxAlignment()) { 70745ffd83dbSDimitry Andric if (BaseInfo) 70755ffd83dbSDimitry Andric *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType); 70765ffd83dbSDimitry Andric return getContext().toCharUnitsFromBits(Align); 70775ffd83dbSDimitry Andric } 70785ffd83dbSDimitry Andric } 70795ffd83dbSDimitry Andric 70805ffd83dbSDimitry Andric bool AlignForArray = T->isArrayType(); 70815ffd83dbSDimitry Andric 70825ffd83dbSDimitry Andric // Analyze the base element type, so we don't get confused by incomplete 70835ffd83dbSDimitry Andric // array types. 70845ffd83dbSDimitry Andric T = getContext().getBaseElementType(T); 70855ffd83dbSDimitry Andric 70865ffd83dbSDimitry Andric if (T->isIncompleteType()) { 70875ffd83dbSDimitry Andric // We could try to replicate the logic from 70885ffd83dbSDimitry Andric // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the 70895ffd83dbSDimitry Andric // type is incomplete, so it's impossible to test. We could try to reuse 70905ffd83dbSDimitry Andric // getTypeAlignIfKnown, but that doesn't return the information we need 70915ffd83dbSDimitry Andric // to set BaseInfo. So just ignore the possibility that the alignment is 70925ffd83dbSDimitry Andric // greater than one. 70935ffd83dbSDimitry Andric if (BaseInfo) 70945ffd83dbSDimitry Andric *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 70955ffd83dbSDimitry Andric return CharUnits::One(); 70965ffd83dbSDimitry Andric } 70975ffd83dbSDimitry Andric 70985ffd83dbSDimitry Andric if (BaseInfo) 70995ffd83dbSDimitry Andric *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 71005ffd83dbSDimitry Andric 71015ffd83dbSDimitry Andric CharUnits Alignment; 7102e8d8bef9SDimitry Andric const CXXRecordDecl *RD; 7103e8d8bef9SDimitry Andric if (T.getQualifiers().hasUnaligned()) { 7104e8d8bef9SDimitry Andric Alignment = CharUnits::One(); 7105e8d8bef9SDimitry Andric } else if (forPointeeType && !AlignForArray && 7106e8d8bef9SDimitry Andric (RD = T->getAsCXXRecordDecl())) { 71075ffd83dbSDimitry Andric // For C++ class pointees, we don't know whether we're pointing at a 71085ffd83dbSDimitry Andric // base or a complete object, so we generally need to use the 71095ffd83dbSDimitry Andric // non-virtual alignment. 71105ffd83dbSDimitry Andric Alignment = getClassPointerAlignment(RD); 71115ffd83dbSDimitry Andric } else { 71125ffd83dbSDimitry Andric Alignment = getContext().getTypeAlignInChars(T); 71135ffd83dbSDimitry Andric } 71145ffd83dbSDimitry Andric 71155ffd83dbSDimitry Andric // Cap to the global maximum type alignment unless the alignment 71165ffd83dbSDimitry Andric // was somehow explicit on the type. 71175ffd83dbSDimitry Andric if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { 71185ffd83dbSDimitry Andric if (Alignment.getQuantity() > MaxAlign && 71195ffd83dbSDimitry Andric !getContext().isAlignmentRequired(T)) 71205ffd83dbSDimitry Andric Alignment = CharUnits::fromQuantity(MaxAlign); 71215ffd83dbSDimitry Andric } 71225ffd83dbSDimitry Andric return Alignment; 71235ffd83dbSDimitry Andric } 71245ffd83dbSDimitry Andric 71255ffd83dbSDimitry Andric bool CodeGenModule::stopAutoInit() { 71265ffd83dbSDimitry Andric unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter; 71275ffd83dbSDimitry Andric if (StopAfter) { 71285ffd83dbSDimitry Andric // This number is positive only when -ftrivial-auto-var-init-stop-after=* is 71295ffd83dbSDimitry Andric // used 71305ffd83dbSDimitry Andric if (NumAutoVarInit >= StopAfter) { 71315ffd83dbSDimitry Andric return true; 71325ffd83dbSDimitry Andric } 71335ffd83dbSDimitry Andric if (!NumAutoVarInit) { 71345ffd83dbSDimitry Andric unsigned DiagID = getDiags().getCustomDiagID( 71355ffd83dbSDimitry Andric DiagnosticsEngine::Warning, 71365ffd83dbSDimitry Andric "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the " 71375ffd83dbSDimitry Andric "number of times ftrivial-auto-var-init=%1 gets applied."); 71385ffd83dbSDimitry Andric getDiags().Report(DiagID) 71395ffd83dbSDimitry Andric << StopAfter 71405ffd83dbSDimitry Andric << (getContext().getLangOpts().getTrivialAutoVarInit() == 71415ffd83dbSDimitry Andric LangOptions::TrivialAutoVarInitKind::Zero 71425ffd83dbSDimitry Andric ? "zero" 71435ffd83dbSDimitry Andric : "pattern"); 71445ffd83dbSDimitry Andric } 71455ffd83dbSDimitry Andric ++NumAutoVarInit; 71465ffd83dbSDimitry Andric } 71475ffd83dbSDimitry Andric return false; 71485ffd83dbSDimitry Andric } 7149fe6060f1SDimitry Andric 71502a66634dSDimitry Andric void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS, 71512a66634dSDimitry Andric const Decl *D) const { 71522a66634dSDimitry Andric // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers 71532a66634dSDimitry Andric // postfix beginning with '.' since the symbol name can be demangled. 71542a66634dSDimitry Andric if (LangOpts.HIP) 715581ad6265SDimitry Andric OS << (isa<VarDecl>(D) ? ".static." : ".intern."); 71562a66634dSDimitry Andric else 715781ad6265SDimitry Andric OS << (isa<VarDecl>(D) ? "__static__" : "__intern__"); 715881ad6265SDimitry Andric 715981ad6265SDimitry Andric // If the CUID is not specified we try to generate a unique postfix. 716081ad6265SDimitry Andric if (getLangOpts().CUID.empty()) { 716181ad6265SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 716281ad6265SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation()); 716381ad6265SDimitry Andric assert(PLoc.isValid() && "Source location is expected to be valid."); 716481ad6265SDimitry Andric 716581ad6265SDimitry Andric // Get the hash of the user defined macros. 716681ad6265SDimitry Andric llvm::MD5 Hash; 716781ad6265SDimitry Andric llvm::MD5::MD5Result Result; 716881ad6265SDimitry Andric for (const auto &Arg : PreprocessorOpts.Macros) 716981ad6265SDimitry Andric Hash.update(Arg.first); 717081ad6265SDimitry Andric Hash.final(Result); 717181ad6265SDimitry Andric 717281ad6265SDimitry Andric // Get the UniqueID for the file containing the decl. 717381ad6265SDimitry Andric llvm::sys::fs::UniqueID ID; 717481ad6265SDimitry Andric if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) { 717581ad6265SDimitry Andric PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false); 717681ad6265SDimitry Andric assert(PLoc.isValid() && "Source location is expected to be valid."); 717781ad6265SDimitry Andric if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) 717881ad6265SDimitry Andric SM.getDiagnostics().Report(diag::err_cannot_open_file) 717981ad6265SDimitry Andric << PLoc.getFilename() << EC.message(); 718081ad6265SDimitry Andric } 718181ad6265SDimitry Andric OS << llvm::format("%x", ID.getFile()) << llvm::format("%x", ID.getDevice()) 718281ad6265SDimitry Andric << "_" << llvm::utohexstr(Result.low(), /*LowerCase=*/true, /*Width=*/8); 718381ad6265SDimitry Andric } else { 718481ad6265SDimitry Andric OS << getContext().getCUIDHash(); 718581ad6265SDimitry Andric } 7186fe6060f1SDimitry Andric } 7187fcaf7f86SDimitry Andric 7188fcaf7f86SDimitry Andric void CodeGenModule::moveLazyEmissionStates(CodeGenModule *NewBuilder) { 7189fcaf7f86SDimitry Andric assert(DeferredDeclsToEmit.empty() && 7190fcaf7f86SDimitry Andric "Should have emitted all decls deferred to emit."); 7191fcaf7f86SDimitry Andric assert(NewBuilder->DeferredDecls.empty() && 7192fcaf7f86SDimitry Andric "Newly created module should not have deferred decls"); 7193fcaf7f86SDimitry Andric NewBuilder->DeferredDecls = std::move(DeferredDecls); 7194fcaf7f86SDimitry Andric 7195fcaf7f86SDimitry Andric assert(NewBuilder->DeferredVTables.empty() && 7196fcaf7f86SDimitry Andric "Newly created module should not have deferred vtables"); 7197fcaf7f86SDimitry Andric NewBuilder->DeferredVTables = std::move(DeferredVTables); 7198fcaf7f86SDimitry Andric 7199fcaf7f86SDimitry Andric assert(NewBuilder->MangledDeclNames.empty() && 7200fcaf7f86SDimitry Andric "Newly created module should not have mangled decl names"); 7201fcaf7f86SDimitry Andric assert(NewBuilder->Manglings.empty() && 7202fcaf7f86SDimitry Andric "Newly created module should not have manglings"); 7203fcaf7f86SDimitry Andric NewBuilder->Manglings = std::move(Manglings); 7204fcaf7f86SDimitry Andric 7205fcaf7f86SDimitry Andric assert(WeakRefReferences.empty() && "Not all WeakRefRefs have been applied"); 7206fcaf7f86SDimitry Andric NewBuilder->WeakRefReferences = std::move(WeakRefReferences); 7207fcaf7f86SDimitry Andric 7208fcaf7f86SDimitry Andric NewBuilder->TBAA = std::move(TBAA); 7209fcaf7f86SDimitry Andric 7210fcaf7f86SDimitry Andric assert(NewBuilder->EmittedDeferredDecls.empty() && 7211fcaf7f86SDimitry Andric "Still have (unmerged) EmittedDeferredDecls deferred decls"); 7212fcaf7f86SDimitry Andric 7213fcaf7f86SDimitry Andric NewBuilder->EmittedDeferredDecls = std::move(EmittedDeferredDecls); 7214972a253aSDimitry Andric 7215972a253aSDimitry Andric NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx); 7216fcaf7f86SDimitry Andric } 7217