10b57cec5SDimitry Andric //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // This coordinates the per-module state used while generating code. 100b57cec5SDimitry Andric // 110b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 120b57cec5SDimitry Andric 130b57cec5SDimitry Andric #include "CodeGenModule.h" 14fcaf7f86SDimitry Andric #include "ABIInfo.h" 150b57cec5SDimitry Andric #include "CGBlocks.h" 160b57cec5SDimitry Andric #include "CGCUDARuntime.h" 170b57cec5SDimitry Andric #include "CGCXXABI.h" 180b57cec5SDimitry Andric #include "CGCall.h" 190b57cec5SDimitry Andric #include "CGDebugInfo.h" 2081ad6265SDimitry Andric #include "CGHLSLRuntime.h" 210b57cec5SDimitry Andric #include "CGObjCRuntime.h" 220b57cec5SDimitry Andric #include "CGOpenCLRuntime.h" 230b57cec5SDimitry Andric #include "CGOpenMPRuntime.h" 24349cc55cSDimitry Andric #include "CGOpenMPRuntimeGPU.h" 250b57cec5SDimitry Andric #include "CodeGenFunction.h" 260b57cec5SDimitry Andric #include "CodeGenPGO.h" 270b57cec5SDimitry Andric #include "ConstantEmitter.h" 280b57cec5SDimitry Andric #include "CoverageMappingGen.h" 290b57cec5SDimitry Andric #include "TargetInfo.h" 300b57cec5SDimitry Andric #include "clang/AST/ASTContext.h" 310b57cec5SDimitry Andric #include "clang/AST/CharUnits.h" 320b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h" 330b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h" 340b57cec5SDimitry Andric #include "clang/AST/DeclTemplate.h" 350b57cec5SDimitry Andric #include "clang/AST/Mangle.h" 360b57cec5SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h" 370b57cec5SDimitry Andric #include "clang/AST/StmtVisitor.h" 380b57cec5SDimitry Andric #include "clang/Basic/Builtins.h" 390b57cec5SDimitry Andric #include "clang/Basic/CharInfo.h" 400b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h" 410b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h" 425ffd83dbSDimitry Andric #include "clang/Basic/FileManager.h" 430b57cec5SDimitry Andric #include "clang/Basic/Module.h" 440b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h" 450b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h" 460b57cec5SDimitry Andric #include "clang/Basic/Version.h" 4781ad6265SDimitry Andric #include "clang/CodeGen/BackendUtil.h" 480b57cec5SDimitry Andric #include "clang/CodeGen/ConstantInitBuilder.h" 490b57cec5SDimitry Andric #include "clang/Frontend/FrontendDiagnostic.h" 50*bdd1243dSDimitry Andric #include "llvm/ADT/STLExtras.h" 51*bdd1243dSDimitry Andric #include "llvm/ADT/StringExtras.h" 520b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h" 530b57cec5SDimitry Andric #include "llvm/ADT/Triple.h" 540b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h" 55480093f4SDimitry Andric #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 560b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h" 570b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h" 580b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h" 590b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h" 600b57cec5SDimitry Andric #include "llvm/IR/Module.h" 610b57cec5SDimitry Andric #include "llvm/IR/ProfileSummary.h" 620b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfReader.h" 63*bdd1243dSDimitry Andric #include "llvm/ProfileData/SampleProf.h" 64fcaf7f86SDimitry Andric #include "llvm/Support/CRC.h" 650b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h" 66480093f4SDimitry Andric #include "llvm/Support/CommandLine.h" 670b57cec5SDimitry Andric #include "llvm/Support/ConvertUTF.h" 680b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h" 690b57cec5SDimitry Andric #include "llvm/Support/TimeProfiler.h" 70349cc55cSDimitry Andric #include "llvm/Support/X86TargetParser.h" 71*bdd1243dSDimitry Andric #include "llvm/Support/xxhash.h" 72*bdd1243dSDimitry Andric #include <optional> 730b57cec5SDimitry Andric 740b57cec5SDimitry Andric using namespace clang; 750b57cec5SDimitry Andric using namespace CodeGen; 760b57cec5SDimitry Andric 770b57cec5SDimitry 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)")); 800b57cec5SDimitry Andric 810b57cec5SDimitry Andric static const char AnnotationSection[] = "llvm.metadata"; 820b57cec5SDimitry Andric 830b57cec5SDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) { 84fe6060f1SDimitry Andric switch (CGM.getContext().getCXXABIKind()) { 85e8d8bef9SDimitry Andric case TargetCXXABI::AppleARM64: 86480093f4SDimitry Andric case TargetCXXABI::Fuchsia: 870b57cec5SDimitry Andric case TargetCXXABI::GenericAArch64: 880b57cec5SDimitry Andric case TargetCXXABI::GenericARM: 890b57cec5SDimitry Andric case TargetCXXABI::iOS: 900b57cec5SDimitry Andric case TargetCXXABI::WatchOS: 910b57cec5SDimitry Andric case TargetCXXABI::GenericMIPS: 920b57cec5SDimitry Andric case TargetCXXABI::GenericItanium: 930b57cec5SDimitry Andric case TargetCXXABI::WebAssembly: 945ffd83dbSDimitry Andric case TargetCXXABI::XL: 950b57cec5SDimitry Andric return CreateItaniumCXXABI(CGM); 960b57cec5SDimitry Andric case TargetCXXABI::Microsoft: 970b57cec5SDimitry Andric return CreateMicrosoftCXXABI(CGM); 980b57cec5SDimitry Andric } 990b57cec5SDimitry Andric 1000b57cec5SDimitry Andric llvm_unreachable("invalid C++ ABI kind"); 1010b57cec5SDimitry Andric } 1020b57cec5SDimitry Andric 103972a253aSDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, 104972a253aSDimitry Andric IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS, 105972a253aSDimitry Andric const HeaderSearchOptions &HSO, 1060b57cec5SDimitry Andric const PreprocessorOptions &PPO, 1070b57cec5SDimitry Andric const CodeGenOptions &CGO, llvm::Module &M, 1080b57cec5SDimitry Andric DiagnosticsEngine &diags, 1090b57cec5SDimitry 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)) { 1150b57cec5SDimitry Andric 1160b57cec5SDimitry Andric // Initialize the type cache. 1170b57cec5SDimitry Andric llvm::LLVMContext &LLVMContext = M.getContext(); 1180b57cec5SDimitry Andric VoidTy = llvm::Type::getVoidTy(LLVMContext); 1190b57cec5SDimitry Andric Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 1200b57cec5SDimitry Andric Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 1210b57cec5SDimitry Andric Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 1220b57cec5SDimitry Andric Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 1230b57cec5SDimitry Andric HalfTy = llvm::Type::getHalfTy(LLVMContext); 1245ffd83dbSDimitry Andric BFloatTy = llvm::Type::getBFloatTy(LLVMContext); 1250b57cec5SDimitry Andric FloatTy = llvm::Type::getFloatTy(LLVMContext); 1260b57cec5SDimitry Andric DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 127*bdd1243dSDimitry Andric PointerWidthInBits = C.getTargetInfo().getPointerWidth(LangAS::Default); 1280b57cec5SDimitry Andric PointerAlignInBytes = 129*bdd1243dSDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(LangAS::Default)) 130*bdd1243dSDimitry Andric .getQuantity(); 1310b57cec5SDimitry Andric SizeSizeInBytes = 1320b57cec5SDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity(); 1330b57cec5SDimitry Andric IntAlignInBytes = 1340b57cec5SDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity(); 135e8d8bef9SDimitry Andric CharTy = 136e8d8bef9SDimitry Andric llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth()); 1370b57cec5SDimitry Andric IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 1380b57cec5SDimitry Andric IntPtrTy = llvm::IntegerType::get(LLVMContext, 1390b57cec5SDimitry Andric C.getTargetInfo().getMaxPointerWidth()); 1400b57cec5SDimitry Andric Int8PtrTy = Int8Ty->getPointerTo(0); 1410b57cec5SDimitry 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()); 145*bdd1243dSDimitry Andric ConstGlobalsPtrTy = Int8Ty->getPointerTo( 146*bdd1243dSDimitry Andric C.getTargetAddressSpace(GetGlobalConstantAddressSpace())); 1470b57cec5SDimitry Andric ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace(); 1480b57cec5SDimitry 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 1560b57cec5SDimitry Andric RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 1570b57cec5SDimitry Andric 1580b57cec5SDimitry Andric if (LangOpts.ObjC) 1590b57cec5SDimitry Andric createObjCRuntime(); 1600b57cec5SDimitry Andric if (LangOpts.OpenCL) 1610b57cec5SDimitry Andric createOpenCLRuntime(); 1620b57cec5SDimitry Andric if (LangOpts.OpenMP) 1630b57cec5SDimitry Andric createOpenMPRuntime(); 1640b57cec5SDimitry Andric if (LangOpts.CUDA) 1650b57cec5SDimitry Andric createCUDARuntime(); 16681ad6265SDimitry Andric if (LangOpts.HLSL) 16781ad6265SDimitry Andric createHLSLRuntime(); 1680b57cec5SDimitry Andric 1690b57cec5SDimitry Andric // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 1700b57cec5SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::Thread) || 1710b57cec5SDimitry Andric (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 1720b57cec5SDimitry Andric TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(), 1730b57cec5SDimitry Andric getCXXABI().getMangleContext())); 1740b57cec5SDimitry Andric 1750b57cec5SDimitry Andric // If debug info or coverage generation is enabled, create the CGDebugInfo 1760b57cec5SDimitry Andric // object. 1770b57cec5SDimitry Andric if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo || 1780b57cec5SDimitry Andric CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) 1790b57cec5SDimitry Andric DebugInfo.reset(new CGDebugInfo(*this)); 1800b57cec5SDimitry Andric 1810b57cec5SDimitry Andric Block.GlobalUniqueCount = 0; 1820b57cec5SDimitry Andric 1830b57cec5SDimitry Andric if (C.getLangOpts().ObjC) 1840b57cec5SDimitry Andric ObjCData.reset(new ObjCEntrypoints()); 1850b57cec5SDimitry Andric 1860b57cec5SDimitry Andric if (CodeGenOpts.hasProfileClangUse()) { 1870b57cec5SDimitry Andric auto ReaderOrErr = llvm::IndexedInstrProfReader::create( 1880b57cec5SDimitry Andric CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile); 189*bdd1243dSDimitry Andric // We're checking for profile read errors in CompilerInvocation, so if 190*bdd1243dSDimitry Andric // there was an error it should've already been caught. If it hasn't been 191*bdd1243dSDimitry Andric // somehow, trip an assertion. 192*bdd1243dSDimitry Andric assert(ReaderOrErr); 1930b57cec5SDimitry Andric PGOReader = std::move(ReaderOrErr.get()); 1940b57cec5SDimitry Andric } 1950b57cec5SDimitry Andric 1960b57cec5SDimitry Andric // If coverage mapping generation is enabled, create the 1970b57cec5SDimitry Andric // CoverageMappingModuleGen object. 1980b57cec5SDimitry Andric if (CodeGenOpts.CoverageMapping) 1990b57cec5SDimitry 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 } 211*bdd1243dSDimitry Andric ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path); 212fe6060f1SDimitry Andric } 2130b57cec5SDimitry Andric } 2140b57cec5SDimitry Andric 2150b57cec5SDimitry Andric CodeGenModule::~CodeGenModule() {} 2160b57cec5SDimitry Andric 2170b57cec5SDimitry Andric void CodeGenModule::createObjCRuntime() { 2180b57cec5SDimitry Andric // This is just isGNUFamily(), but we want to force implementors of 2190b57cec5SDimitry Andric // new ABIs to decide how best to do this. 2200b57cec5SDimitry Andric switch (LangOpts.ObjCRuntime.getKind()) { 2210b57cec5SDimitry Andric case ObjCRuntime::GNUstep: 2220b57cec5SDimitry Andric case ObjCRuntime::GCC: 2230b57cec5SDimitry Andric case ObjCRuntime::ObjFW: 2240b57cec5SDimitry Andric ObjCRuntime.reset(CreateGNUObjCRuntime(*this)); 2250b57cec5SDimitry Andric return; 2260b57cec5SDimitry Andric 2270b57cec5SDimitry Andric case ObjCRuntime::FragileMacOSX: 2280b57cec5SDimitry Andric case ObjCRuntime::MacOSX: 2290b57cec5SDimitry Andric case ObjCRuntime::iOS: 2300b57cec5SDimitry Andric case ObjCRuntime::WatchOS: 2310b57cec5SDimitry Andric ObjCRuntime.reset(CreateMacObjCRuntime(*this)); 2320b57cec5SDimitry Andric return; 2330b57cec5SDimitry Andric } 2340b57cec5SDimitry Andric llvm_unreachable("bad runtime kind"); 2350b57cec5SDimitry Andric } 2360b57cec5SDimitry Andric 2370b57cec5SDimitry Andric void CodeGenModule::createOpenCLRuntime() { 2380b57cec5SDimitry Andric OpenCLRuntime.reset(new CGOpenCLRuntime(*this)); 2390b57cec5SDimitry Andric } 2400b57cec5SDimitry Andric 2410b57cec5SDimitry Andric void CodeGenModule::createOpenMPRuntime() { 2420b57cec5SDimitry Andric // Select a specialized code generation class based on the target, if any. 2430b57cec5SDimitry Andric // If it does not exist use the default implementation. 2440b57cec5SDimitry Andric switch (getTriple().getArch()) { 2450b57cec5SDimitry Andric case llvm::Triple::nvptx: 2460b57cec5SDimitry 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; 2520b57cec5SDimitry Andric default: 2530b57cec5SDimitry Andric if (LangOpts.OpenMPSimd) 2540b57cec5SDimitry Andric OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this)); 2550b57cec5SDimitry Andric else 2560b57cec5SDimitry Andric OpenMPRuntime.reset(new CGOpenMPRuntime(*this)); 2570b57cec5SDimitry Andric break; 2580b57cec5SDimitry Andric } 2590b57cec5SDimitry Andric } 2600b57cec5SDimitry Andric 2610b57cec5SDimitry Andric void CodeGenModule::createCUDARuntime() { 2620b57cec5SDimitry Andric CUDARuntime.reset(CreateNVCUDARuntime(*this)); 2630b57cec5SDimitry Andric } 2640b57cec5SDimitry Andric 26581ad6265SDimitry Andric void CodeGenModule::createHLSLRuntime() { 26681ad6265SDimitry Andric HLSLRuntime.reset(new CGHLSLRuntime(*this)); 26781ad6265SDimitry Andric } 26881ad6265SDimitry Andric 2690b57cec5SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { 2700b57cec5SDimitry Andric Replacements[Name] = C; 2710b57cec5SDimitry Andric } 2720b57cec5SDimitry Andric 2730b57cec5SDimitry Andric void CodeGenModule::applyReplacements() { 2740b57cec5SDimitry Andric for (auto &I : Replacements) { 2750b57cec5SDimitry Andric StringRef MangledName = I.first(); 2760b57cec5SDimitry Andric llvm::Constant *Replacement = I.second; 2770b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2780b57cec5SDimitry Andric if (!Entry) 2790b57cec5SDimitry Andric continue; 2800b57cec5SDimitry Andric auto *OldF = cast<llvm::Function>(Entry); 2810b57cec5SDimitry Andric auto *NewF = dyn_cast<llvm::Function>(Replacement); 2820b57cec5SDimitry Andric if (!NewF) { 2830b57cec5SDimitry Andric if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 2840b57cec5SDimitry Andric NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 2850b57cec5SDimitry Andric } else { 2860b57cec5SDimitry Andric auto *CE = cast<llvm::ConstantExpr>(Replacement); 2870b57cec5SDimitry Andric assert(CE->getOpcode() == llvm::Instruction::BitCast || 2880b57cec5SDimitry Andric CE->getOpcode() == llvm::Instruction::GetElementPtr); 2890b57cec5SDimitry Andric NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 2900b57cec5SDimitry Andric } 2910b57cec5SDimitry Andric } 2920b57cec5SDimitry Andric 2930b57cec5SDimitry Andric // Replace old with new, but keep the old order. 2940b57cec5SDimitry Andric OldF->replaceAllUsesWith(Replacement); 2950b57cec5SDimitry Andric if (NewF) { 2960b57cec5SDimitry Andric NewF->removeFromParent(); 2970b57cec5SDimitry Andric OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(), 2980b57cec5SDimitry Andric NewF); 2990b57cec5SDimitry Andric } 3000b57cec5SDimitry Andric OldF->eraseFromParent(); 3010b57cec5SDimitry Andric } 3020b57cec5SDimitry Andric } 3030b57cec5SDimitry Andric 3040b57cec5SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { 3050b57cec5SDimitry Andric GlobalValReplacements.push_back(std::make_pair(GV, C)); 3060b57cec5SDimitry Andric } 3070b57cec5SDimitry Andric 3080b57cec5SDimitry Andric void CodeGenModule::applyGlobalValReplacements() { 3090b57cec5SDimitry Andric for (auto &I : GlobalValReplacements) { 3100b57cec5SDimitry Andric llvm::GlobalValue *GV = I.first; 3110b57cec5SDimitry Andric llvm::Constant *C = I.second; 3120b57cec5SDimitry Andric 3130b57cec5SDimitry Andric GV->replaceAllUsesWith(C); 3140b57cec5SDimitry Andric GV->eraseFromParent(); 3150b57cec5SDimitry Andric } 3160b57cec5SDimitry Andric } 3170b57cec5SDimitry Andric 3180b57cec5SDimitry Andric // This is only used in aliases that we created and we know they have a 3190b57cec5SDimitry 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) 3310b57cec5SDimitry Andric return nullptr; 332349cc55cSDimitry Andric 333349cc55cSDimitry Andric const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject(); 334349cc55cSDimitry Andric if (FinalGV == GV) 3350b57cec5SDimitry Andric return nullptr; 336349cc55cSDimitry Andric 337349cc55cSDimitry Andric return FinalGV; 3380b57cec5SDimitry 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; 3720b57cec5SDimitry Andric } 3730b57cec5SDimitry Andric 3740b57cec5SDimitry Andric void CodeGenModule::checkAliases() { 3750b57cec5SDimitry Andric // Check if the constructed aliases are well formed. It is really unfortunate 3760b57cec5SDimitry Andric // that we have to do this in CodeGen, but we only construct mangled names 3770b57cec5SDimitry Andric // and aliases during codegen. 3780b57cec5SDimitry Andric bool Error = false; 3790b57cec5SDimitry Andric DiagnosticsEngine &Diags = getDiags(); 3800b57cec5SDimitry Andric for (const GlobalDecl &GD : Aliases) { 3810b57cec5SDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 3820b57cec5SDimitry Andric SourceLocation Location; 3830b57cec5SDimitry Andric bool IsIFunc = D->hasAttr<IFuncAttr>(); 3840b57cec5SDimitry Andric if (const Attr *A = D->getDefiningAttr()) 3850b57cec5SDimitry Andric Location = A->getLocation(); 3860b57cec5SDimitry Andric else 3870b57cec5SDimitry Andric llvm_unreachable("Not an alias or ifunc?"); 388349cc55cSDimitry Andric 3890b57cec5SDimitry 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)) { 3930b57cec5SDimitry Andric Error = true; 394349cc55cSDimitry Andric continue; 3950b57cec5SDimitry Andric } 3960b57cec5SDimitry Andric 397349cc55cSDimitry Andric llvm::Constant *Aliasee = 398349cc55cSDimitry Andric IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver() 399349cc55cSDimitry Andric : cast<llvm::GlobalAlias>(Alias)->getAliasee(); 400349cc55cSDimitry Andric 4010b57cec5SDimitry Andric llvm::GlobalValue *AliaseeGV; 4020b57cec5SDimitry Andric if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 4030b57cec5SDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 4040b57cec5SDimitry Andric else 4050b57cec5SDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 4060b57cec5SDimitry Andric 4070b57cec5SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 4080b57cec5SDimitry Andric StringRef AliasSection = SA->getName(); 4090b57cec5SDimitry Andric if (AliasSection != AliaseeGV->getSection()) 4100b57cec5SDimitry Andric Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 4110b57cec5SDimitry Andric << AliasSection << IsIFunc << IsIFunc; 4120b57cec5SDimitry Andric } 4130b57cec5SDimitry Andric 4140b57cec5SDimitry Andric // We have to handle alias to weak aliases in here. LLVM itself disallows 4150b57cec5SDimitry Andric // this since the object semantics would not match the IL one. For 4160b57cec5SDimitry Andric // compatibility with gcc we implement it by just pointing the alias 4170b57cec5SDimitry Andric // to its aliasee's aliasee. We also warn, since the user is probably 4180b57cec5SDimitry Andric // expecting the link to be weak. 419349cc55cSDimitry Andric if (auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) { 4200b57cec5SDimitry Andric if (GA->isInterposable()) { 4210b57cec5SDimitry Andric Diags.Report(Location, diag::warn_alias_to_weak_alias) 4220b57cec5SDimitry Andric << GV->getName() << GA->getName() << IsIFunc; 4230b57cec5SDimitry 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); 4300b57cec5SDimitry Andric } 4310b57cec5SDimitry Andric } 4320b57cec5SDimitry Andric } 4330b57cec5SDimitry Andric if (!Error) 4340b57cec5SDimitry Andric return; 4350b57cec5SDimitry Andric 4360b57cec5SDimitry Andric for (const GlobalDecl &GD : Aliases) { 4370b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 438349cc55cSDimitry Andric llvm::GlobalValue *Alias = GetGlobalValue(MangledName); 4390b57cec5SDimitry Andric Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 4400b57cec5SDimitry Andric Alias->eraseFromParent(); 4410b57cec5SDimitry Andric } 4420b57cec5SDimitry Andric } 4430b57cec5SDimitry Andric 4440b57cec5SDimitry Andric void CodeGenModule::clear() { 4450b57cec5SDimitry Andric DeferredDeclsToEmit.clear(); 446753f127fSDimitry Andric EmittedDeferredDecls.clear(); 4470b57cec5SDimitry Andric if (OpenMPRuntime) 4480b57cec5SDimitry Andric OpenMPRuntime->clear(); 4490b57cec5SDimitry Andric } 4500b57cec5SDimitry Andric 4510b57cec5SDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 4520b57cec5SDimitry Andric StringRef MainFile) { 4530b57cec5SDimitry Andric if (!hasDiagnostics()) 4540b57cec5SDimitry Andric return; 4550b57cec5SDimitry Andric if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 4560b57cec5SDimitry Andric if (MainFile.empty()) 4570b57cec5SDimitry Andric MainFile = "<stdin>"; 4580b57cec5SDimitry Andric Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 4590b57cec5SDimitry Andric } else { 4600b57cec5SDimitry Andric if (Mismatched > 0) 4610b57cec5SDimitry Andric Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched; 4620b57cec5SDimitry Andric 4630b57cec5SDimitry Andric if (Missing > 0) 4640b57cec5SDimitry Andric Diags.Report(diag::warn_profile_data_missing) << Visited << Missing; 4650b57cec5SDimitry Andric } 4660b57cec5SDimitry Andric } 4670b57cec5SDimitry 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 5100b57cec5SDimitry Andric void CodeGenModule::Release() { 511fcaf7f86SDimitry Andric Module *Primary = getContext().getModuleForCodeGen(); 51261cfbce3SDimitry Andric if (CXX20ModuleInits && Primary && !Primary->isHeaderLikeModule()) 513fcaf7f86SDimitry Andric EmitModuleInitializers(Primary); 5140b57cec5SDimitry Andric EmitDeferred(); 515753f127fSDimitry Andric DeferredDecls.insert(EmittedDeferredDecls.begin(), 516753f127fSDimitry Andric EmittedDeferredDecls.end()); 517753f127fSDimitry Andric EmittedDeferredDecls.clear(); 5180b57cec5SDimitry Andric EmitVTablesOpportunistically(); 5190b57cec5SDimitry Andric applyGlobalValReplacements(); 5200b57cec5SDimitry Andric applyReplacements(); 5210b57cec5SDimitry Andric emitMultiVersionFunctions(); 522*bdd1243dSDimitry Andric 523*bdd1243dSDimitry Andric if (Context.getLangOpts().IncrementalExtensions && 524*bdd1243dSDimitry Andric GlobalTopLevelStmtBlockInFlight.first) { 525*bdd1243dSDimitry Andric const TopLevelStmtDecl *TLSD = GlobalTopLevelStmtBlockInFlight.second; 526*bdd1243dSDimitry Andric GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->getEndLoc()); 527*bdd1243dSDimitry Andric GlobalTopLevelStmtBlockInFlight = {nullptr, nullptr}; 528*bdd1243dSDimitry Andric } 529*bdd1243dSDimitry Andric 530fcaf7f86SDimitry Andric if (CXX20ModuleInits && Primary && Primary->isInterfaceOrPartition()) 531fcaf7f86SDimitry Andric EmitCXXModuleInitFunc(Primary); 532fcaf7f86SDimitry Andric else 5330b57cec5SDimitry Andric EmitCXXGlobalInitFunc(); 5345ffd83dbSDimitry Andric EmitCXXGlobalCleanUpFunc(); 5350b57cec5SDimitry Andric registerGlobalDtorsWithAtExit(); 5360b57cec5SDimitry Andric EmitCXXThreadLocalInitFunc(); 5370b57cec5SDimitry Andric if (ObjCRuntime) 5380b57cec5SDimitry Andric if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 5390b57cec5SDimitry Andric AddGlobalCtor(ObjCInitFunction); 540fe6060f1SDimitry Andric if (Context.getLangOpts().CUDA && CUDARuntime) { 541fe6060f1SDimitry Andric if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule()) 5420b57cec5SDimitry Andric AddGlobalCtor(CudaCtorFunction); 5430b57cec5SDimitry Andric } 5440b57cec5SDimitry Andric if (OpenMPRuntime) { 5450b57cec5SDimitry Andric if (llvm::Function *OpenMPRequiresDirectiveRegFun = 5460b57cec5SDimitry Andric OpenMPRuntime->emitRequiresDirectiveRegFun()) { 5470b57cec5SDimitry Andric AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0); 5480b57cec5SDimitry Andric } 549a7dea167SDimitry Andric OpenMPRuntime->createOffloadEntriesAndInfoMetadata(); 5500b57cec5SDimitry Andric OpenMPRuntime->clear(); 5510b57cec5SDimitry Andric } 5520b57cec5SDimitry Andric if (PGOReader) { 5530b57cec5SDimitry Andric getModule().setProfileSummary( 5540b57cec5SDimitry Andric PGOReader->getSummary(/* UseCS */ false).getMD(VMContext), 5550b57cec5SDimitry Andric llvm::ProfileSummary::PSK_Instr); 5560b57cec5SDimitry Andric if (PGOStats.hasDiagnostics()) 5570b57cec5SDimitry Andric PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 5580b57cec5SDimitry Andric } 559*bdd1243dSDimitry Andric llvm::stable_sort(GlobalCtors, [](const Structor &L, const Structor &R) { 560*bdd1243dSDimitry Andric return L.LexOrder < R.LexOrder; 561*bdd1243dSDimitry Andric }); 5620b57cec5SDimitry Andric EmitCtorList(GlobalCtors, "llvm.global_ctors"); 5630b57cec5SDimitry Andric EmitCtorList(GlobalDtors, "llvm.global_dtors"); 5640b57cec5SDimitry Andric EmitGlobalAnnotations(); 5650b57cec5SDimitry Andric EmitStaticExternCAliases(); 56681ad6265SDimitry Andric checkAliases(); 5670b57cec5SDimitry Andric EmitDeferredUnusedCoverageMappings(); 568fe6060f1SDimitry Andric CodeGenPGO(*this).setValueProfilingFlag(getModule()); 5690b57cec5SDimitry Andric if (CoverageMapping) 5700b57cec5SDimitry Andric CoverageMapping->emit(); 5710b57cec5SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 5720b57cec5SDimitry Andric CodeGenFunction(*this).EmitCfiCheckFail(); 5730b57cec5SDimitry Andric CodeGenFunction(*this).EmitCfiCheckStub(); 5740b57cec5SDimitry Andric } 575*bdd1243dSDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) 576*bdd1243dSDimitry Andric finalizeKCFITypes(); 5770b57cec5SDimitry 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. 598*bdd1243dSDimitry Andric if (getTarget().getTargetOpts().CodeObjectVersion != 599*bdd1243dSDimitry 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 6300b57cec5SDimitry Andric emitLLVMUsed(); 6310b57cec5SDimitry Andric if (SanStats) 6320b57cec5SDimitry Andric SanStats->finish(); 6330b57cec5SDimitry Andric 6340b57cec5SDimitry Andric if (CodeGenOpts.Autolink && 6350b57cec5SDimitry Andric (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 6360b57cec5SDimitry Andric EmitModuleLinkOptions(); 6370b57cec5SDimitry Andric } 6380b57cec5SDimitry Andric 6390b57cec5SDimitry Andric // On ELF we pass the dependent library specifiers directly to the linker 6400b57cec5SDimitry Andric // without manipulating them. This is in contrast to other platforms where 6410b57cec5SDimitry Andric // they are mapped to a specific linker option by the compiler. This 6420b57cec5SDimitry Andric // difference is a result of the greater variety of ELF linkers and the fact 6430b57cec5SDimitry Andric // that ELF linkers tend to handle libraries in a more complicated fashion 6440b57cec5SDimitry Andric // than on other platforms. This forces us to defer handling the dependent 6450b57cec5SDimitry Andric // libs to the linker. 6460b57cec5SDimitry Andric // 6470b57cec5SDimitry Andric // CUDA/HIP device and host libraries are different. Currently there is no 6480b57cec5SDimitry Andric // way to differentiate dependent libraries for host or device. Existing 6490b57cec5SDimitry Andric // usage of #pragma comment(lib, *) is intended for host libraries on 6500b57cec5SDimitry Andric // Windows. Therefore emit llvm.dependent-libraries only for host. 6510b57cec5SDimitry Andric if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) { 6520b57cec5SDimitry Andric auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries"); 6530b57cec5SDimitry Andric for (auto *MD : ELFDependentLibraries) 6540b57cec5SDimitry Andric NMD->addOperand(MD); 6550b57cec5SDimitry Andric } 6560b57cec5SDimitry Andric 6570b57cec5SDimitry Andric // Record mregparm value now so it is visible through rest of codegen. 6580b57cec5SDimitry Andric if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) 6590b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters", 6600b57cec5SDimitry Andric CodeGenOpts.NumRegisterParameters); 6610b57cec5SDimitry Andric 6620b57cec5SDimitry Andric if (CodeGenOpts.DwarfVersion) { 663480093f4SDimitry Andric getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version", 6640b57cec5SDimitry Andric CodeGenOpts.DwarfVersion); 6650b57cec5SDimitry 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 6740b57cec5SDimitry Andric if (CodeGenOpts.EmitCodeView) { 6750b57cec5SDimitry Andric // Indicate that we want CodeView in the metadata. 6760b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); 6770b57cec5SDimitry Andric } 6780b57cec5SDimitry Andric if (CodeGenOpts.CodeViewGHash) { 6790b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1); 6800b57cec5SDimitry Andric } 6810b57cec5SDimitry 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); 6870b57cec5SDimitry 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 } 692*bdd1243dSDimitry Andric if (Context.getLangOpts().Kernel) { 693*bdd1243dSDimitry Andric // Note if we are compiling with /kernel. 694*bdd1243dSDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "ms-kernel", 1); 695*bdd1243dSDimitry Andric } 6960b57cec5SDimitry Andric if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { 6970b57cec5SDimitry Andric // We don't support LTO with 2 with different StrictVTablePointers 6980b57cec5SDimitry Andric // FIXME: we could support it by stripping all the information introduced 6990b57cec5SDimitry Andric // by StrictVTablePointers. 7000b57cec5SDimitry Andric 7010b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); 7020b57cec5SDimitry Andric 7030b57cec5SDimitry Andric llvm::Metadata *Ops[2] = { 7040b57cec5SDimitry Andric llvm::MDString::get(VMContext, "StrictVTablePointers"), 7050b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 7060b57cec5SDimitry Andric llvm::Type::getInt32Ty(VMContext), 1))}; 7070b57cec5SDimitry Andric 7080b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Require, 7090b57cec5SDimitry Andric "StrictVTablePointersRequirement", 7100b57cec5SDimitry Andric llvm::MDNode::get(VMContext, Ops)); 7110b57cec5SDimitry Andric } 7125ffd83dbSDimitry Andric if (getModuleDebugInfo()) 7130b57cec5SDimitry Andric // We support a single version in the linked module. The LLVM 7140b57cec5SDimitry Andric // parser will drop debug info with a different version number 7150b57cec5SDimitry Andric // (and warn about it, too). 7160b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 7170b57cec5SDimitry Andric llvm::DEBUG_METADATA_VERSION); 7180b57cec5SDimitry Andric 7190b57cec5SDimitry Andric // We need to record the widths of enums and wchar_t, so that we can generate 7200b57cec5SDimitry Andric // the correct build attributes in the ARM backend. wchar_size is also used by 7210b57cec5SDimitry Andric // TargetLibraryInfo. 7220b57cec5SDimitry Andric uint64_t WCharWidth = 7230b57cec5SDimitry Andric Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 7240b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 7250b57cec5SDimitry Andric 7260b57cec5SDimitry Andric llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 7270b57cec5SDimitry Andric if ( Arch == llvm::Triple::arm 7280b57cec5SDimitry Andric || Arch == llvm::Triple::armeb 7290b57cec5SDimitry Andric || Arch == llvm::Triple::thumb 7300b57cec5SDimitry Andric || Arch == llvm::Triple::thumbeb) { 7310b57cec5SDimitry Andric // The minimum width of an enum in bytes 7320b57cec5SDimitry Andric uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 7330b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 7340b57cec5SDimitry Andric } 7350b57cec5SDimitry 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 7430b57cec5SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 7440b57cec5SDimitry Andric // Indicate that we want cross-DSO control flow integrity checks. 7450b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); 7460b57cec5SDimitry Andric } 7470b57cec5SDimitry 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 762*bdd1243dSDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) { 763*bdd1243dSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "kcfi", 1); 764*bdd1243dSDimitry Andric // KCFI assumes patchable-function-prefix is the same for all indirectly 765*bdd1243dSDimitry Andric // called functions. Store the expected offset for code generation. 766*bdd1243dSDimitry Andric if (CodeGenOpts.PatchableFunctionEntryOffset) 767*bdd1243dSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "kcfi-offset", 768*bdd1243dSDimitry Andric CodeGenOpts.PatchableFunctionEntryOffset); 769*bdd1243dSDimitry Andric } 770*bdd1243dSDimitry Andric 7710b57cec5SDimitry Andric if (CodeGenOpts.CFProtectionReturn && 7720b57cec5SDimitry Andric Target.checkCFProtectionReturnSupported(getDiags())) { 7730b57cec5SDimitry Andric // Indicate that we want to instrument return control flow protection. 774fcaf7f86SDimitry Andric getModule().addModuleFlag(llvm::Module::Min, "cf-protection-return", 7750b57cec5SDimitry Andric 1); 7760b57cec5SDimitry Andric } 7770b57cec5SDimitry Andric 7780b57cec5SDimitry Andric if (CodeGenOpts.CFProtectionBranch && 7790b57cec5SDimitry Andric Target.checkCFProtectionBranchSupported(getDiags())) { 7800b57cec5SDimitry Andric // Indicate that we want to instrument branch control flow protection. 781fcaf7f86SDimitry Andric getModule().addModuleFlag(llvm::Module::Min, "cf-protection-branch", 7820b57cec5SDimitry Andric 1); 7830b57cec5SDimitry Andric } 7840b57cec5SDimitry Andric 785fcaf7f86SDimitry Andric if (CodeGenOpts.FunctionReturnThunks) 786fcaf7f86SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "function_return_thunk_extern", 1); 78704eeddc0SDimitry Andric 788*bdd1243dSDimitry Andric if (CodeGenOpts.IndirectBranchCSPrefix) 789*bdd1243dSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "indirect_branch_cs_prefix", 1); 790*bdd1243dSDimitry 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 8330b57cec5SDimitry Andric if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) { 8340b57cec5SDimitry Andric // Indicate whether __nvvm_reflect should be configured to flush denormal 8350b57cec5SDimitry Andric // floating point values to 0. (This corresponds to its "__CUDA_FTZ" 8360b57cec5SDimitry Andric // property.) 8370b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", 8385ffd83dbSDimitry Andric CodeGenOpts.FP32DenormalMode.Output != 8395ffd83dbSDimitry Andric llvm::DenormalMode::IEEE); 8400b57cec5SDimitry Andric } 8410b57cec5SDimitry 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 8520b57cec5SDimitry Andric // Emit OpenCL specific module metadata: OpenCL/SPIR version. 85381ad6265SDimitry Andric if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice && getTriple().isSPIRV())) { 8540b57cec5SDimitry Andric EmitOpenCLMetadata(); 8550b57cec5SDimitry Andric // Emit SPIR version. 8560b57cec5SDimitry Andric if (getTriple().isSPIR()) { 8570b57cec5SDimitry Andric // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the 8580b57cec5SDimitry 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(); 8620b57cec5SDimitry Andric llvm::Metadata *SPIRVerElts[] = { 8630b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 8640b57cec5SDimitry Andric Int32Ty, Version / 100)), 8650b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 8660b57cec5SDimitry Andric Int32Ty, (Version / 100 > 1) ? 0 : 2))}; 8670b57cec5SDimitry Andric llvm::NamedMDNode *SPIRVerMD = 8680b57cec5SDimitry Andric TheModule.getOrInsertNamedMetadata("opencl.spir.version"); 8690b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 8700b57cec5SDimitry Andric SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts)); 8710b57cec5SDimitry Andric } 8720b57cec5SDimitry Andric } 8730b57cec5SDimitry Andric 87481ad6265SDimitry Andric // HLSL related end of code gen work items. 87581ad6265SDimitry Andric if (LangOpts.HLSL) 87681ad6265SDimitry Andric getHLSLRuntime().finishCodeGen(); 87781ad6265SDimitry Andric 8780b57cec5SDimitry Andric if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 8790b57cec5SDimitry Andric assert(PLevel < 3 && "Invalid PIC Level"); 8800b57cec5SDimitry Andric getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel)); 8810b57cec5SDimitry Andric if (Context.getLangOpts().PIE) 8820b57cec5SDimitry Andric getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel)); 8830b57cec5SDimitry Andric } 8840b57cec5SDimitry Andric 8850b57cec5SDimitry Andric if (getCodeGenOpts().CodeModel.size() > 0) { 8860b57cec5SDimitry Andric unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel) 8870b57cec5SDimitry Andric .Case("tiny", llvm::CodeModel::Tiny) 8880b57cec5SDimitry Andric .Case("small", llvm::CodeModel::Small) 8890b57cec5SDimitry Andric .Case("kernel", llvm::CodeModel::Kernel) 8900b57cec5SDimitry Andric .Case("medium", llvm::CodeModel::Medium) 8910b57cec5SDimitry Andric .Case("large", llvm::CodeModel::Large) 8920b57cec5SDimitry Andric .Default(~0u); 8930b57cec5SDimitry Andric if (CM != ~0u) { 8940b57cec5SDimitry Andric llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM); 8950b57cec5SDimitry Andric getModule().setCodeModel(codeModel); 8960b57cec5SDimitry Andric } 8970b57cec5SDimitry Andric } 8980b57cec5SDimitry Andric 8990b57cec5SDimitry Andric if (CodeGenOpts.NoPLT) 9000b57cec5SDimitry 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 } 9150b57cec5SDimitry Andric 9160b57cec5SDimitry Andric SimplifyPersonality(); 9170b57cec5SDimitry Andric 9180b57cec5SDimitry Andric if (getCodeGenOpts().EmitDeclMetadata) 9190b57cec5SDimitry Andric EmitDeclMetadata(); 9200b57cec5SDimitry Andric 9210b57cec5SDimitry Andric if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 9220b57cec5SDimitry Andric EmitCoverageFile(); 9230b57cec5SDimitry Andric 9245ffd83dbSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 9255ffd83dbSDimitry Andric DI->finalize(); 9260b57cec5SDimitry Andric 9270b57cec5SDimitry Andric if (getCodeGenOpts().EmitVersionIdentMetadata) 9280b57cec5SDimitry Andric EmitVersionIdentMetadata(); 9290b57cec5SDimitry Andric 9300b57cec5SDimitry Andric if (!getCodeGenOpts().RecordCommandLine.empty()) 9310b57cec5SDimitry Andric EmitCommandLineMetadata(); 9320b57cec5SDimitry 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()); 9610b57cec5SDimitry Andric } 9620b57cec5SDimitry Andric 9630b57cec5SDimitry Andric void CodeGenModule::EmitOpenCLMetadata() { 9640b57cec5SDimitry Andric // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the 9650b57cec5SDimitry 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(); 9680b57cec5SDimitry Andric llvm::Metadata *OCLVerElts[] = { 9690b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 9700b57cec5SDimitry Andric Int32Ty, Version / 100)), 9710b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 9720b57cec5SDimitry Andric Int32Ty, (Version % 100) / 10))}; 9730b57cec5SDimitry Andric llvm::NamedMDNode *OCLVerMD = 9740b57cec5SDimitry Andric TheModule.getOrInsertNamedMetadata("opencl.ocl.version"); 9750b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 9760b57cec5SDimitry Andric OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts)); 9770b57cec5SDimitry Andric } 9780b57cec5SDimitry Andric 9795ffd83dbSDimitry Andric void CodeGenModule::EmitBackendOptionsMetadata( 9805ffd83dbSDimitry Andric const CodeGenOptions CodeGenOpts) { 981*bdd1243dSDimitry Andric if (getTriple().isRISCV()) { 9825ffd83dbSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "SmallDataLimit", 9835ffd83dbSDimitry Andric CodeGenOpts.SmallDataLimit); 9845ffd83dbSDimitry Andric } 9855ffd83dbSDimitry Andric } 9865ffd83dbSDimitry Andric 9870b57cec5SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 9880b57cec5SDimitry Andric // Make sure that this type is translated. 9890b57cec5SDimitry Andric Types.UpdateCompletedType(TD); 9900b57cec5SDimitry Andric } 9910b57cec5SDimitry Andric 9920b57cec5SDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { 9930b57cec5SDimitry Andric // Make sure that this type is translated. 9940b57cec5SDimitry Andric Types.RefreshTypeCacheForClass(RD); 9950b57cec5SDimitry Andric } 9960b57cec5SDimitry Andric 9970b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) { 9980b57cec5SDimitry Andric if (!TBAA) 9990b57cec5SDimitry Andric return nullptr; 10000b57cec5SDimitry Andric return TBAA->getTypeInfo(QTy); 10010b57cec5SDimitry Andric } 10020b57cec5SDimitry Andric 10030b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) { 10040b57cec5SDimitry Andric if (!TBAA) 10050b57cec5SDimitry 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 } 10190b57cec5SDimitry Andric return TBAA->getAccessInfo(AccessType); 10200b57cec5SDimitry Andric } 10210b57cec5SDimitry Andric 10220b57cec5SDimitry Andric TBAAAccessInfo 10230b57cec5SDimitry Andric CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) { 10240b57cec5SDimitry Andric if (!TBAA) 10250b57cec5SDimitry Andric return TBAAAccessInfo(); 10260b57cec5SDimitry Andric return TBAA->getVTablePtrAccessInfo(VTablePtrType); 10270b57cec5SDimitry Andric } 10280b57cec5SDimitry Andric 10290b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 10300b57cec5SDimitry Andric if (!TBAA) 10310b57cec5SDimitry Andric return nullptr; 10320b57cec5SDimitry Andric return TBAA->getTBAAStructInfo(QTy); 10330b57cec5SDimitry Andric } 10340b57cec5SDimitry Andric 10350b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) { 10360b57cec5SDimitry Andric if (!TBAA) 10370b57cec5SDimitry Andric return nullptr; 10380b57cec5SDimitry Andric return TBAA->getBaseTypeInfo(QTy); 10390b57cec5SDimitry Andric } 10400b57cec5SDimitry Andric 10410b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) { 10420b57cec5SDimitry Andric if (!TBAA) 10430b57cec5SDimitry Andric return nullptr; 10440b57cec5SDimitry Andric return TBAA->getAccessTagInfo(Info); 10450b57cec5SDimitry Andric } 10460b57cec5SDimitry Andric 10470b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, 10480b57cec5SDimitry Andric TBAAAccessInfo TargetInfo) { 10490b57cec5SDimitry Andric if (!TBAA) 10500b57cec5SDimitry Andric return TBAAAccessInfo(); 10510b57cec5SDimitry Andric return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo); 10520b57cec5SDimitry Andric } 10530b57cec5SDimitry Andric 10540b57cec5SDimitry Andric TBAAAccessInfo 10550b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, 10560b57cec5SDimitry Andric TBAAAccessInfo InfoB) { 10570b57cec5SDimitry Andric if (!TBAA) 10580b57cec5SDimitry Andric return TBAAAccessInfo(); 10590b57cec5SDimitry Andric return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB); 10600b57cec5SDimitry Andric } 10610b57cec5SDimitry Andric 10620b57cec5SDimitry Andric TBAAAccessInfo 10630b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, 10640b57cec5SDimitry Andric TBAAAccessInfo SrcInfo) { 10650b57cec5SDimitry Andric if (!TBAA) 10660b57cec5SDimitry Andric return TBAAAccessInfo(); 10670b57cec5SDimitry Andric return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo); 10680b57cec5SDimitry Andric } 10690b57cec5SDimitry Andric 10700b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, 10710b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo) { 10720b57cec5SDimitry Andric if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo)) 10730b57cec5SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag); 10740b57cec5SDimitry Andric } 10750b57cec5SDimitry Andric 10760b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup( 10770b57cec5SDimitry Andric llvm::Instruction *I, const CXXRecordDecl *RD) { 10780b57cec5SDimitry Andric I->setMetadata(llvm::LLVMContext::MD_invariant_group, 10790b57cec5SDimitry Andric llvm::MDNode::get(getLLVMContext(), {})); 10800b57cec5SDimitry Andric } 10810b57cec5SDimitry Andric 10820b57cec5SDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) { 10830b57cec5SDimitry Andric unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 10840b57cec5SDimitry Andric getDiags().Report(Context.getFullLoc(loc), diagID) << message; 10850b57cec5SDimitry Andric } 10860b57cec5SDimitry Andric 10870b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the 10880b57cec5SDimitry Andric /// specified stmt yet. 10890b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 10900b57cec5SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 10910b57cec5SDimitry Andric "cannot compile this %0 yet"); 10920b57cec5SDimitry Andric std::string Msg = Type; 10930b57cec5SDimitry Andric getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID) 10940b57cec5SDimitry Andric << Msg << S->getSourceRange(); 10950b57cec5SDimitry Andric } 10960b57cec5SDimitry Andric 10970b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the 10980b57cec5SDimitry Andric /// specified decl yet. 10990b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 11000b57cec5SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 11010b57cec5SDimitry Andric "cannot compile this %0 yet"); 11020b57cec5SDimitry Andric std::string Msg = Type; 11030b57cec5SDimitry Andric getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 11040b57cec5SDimitry Andric } 11050b57cec5SDimitry Andric 11060b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 11070b57cec5SDimitry Andric return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 11080b57cec5SDimitry Andric } 11090b57cec5SDimitry Andric 11100b57cec5SDimitry Andric void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 11110b57cec5SDimitry Andric const NamedDecl *D) const { 11120b57cec5SDimitry Andric // Internal definitions always have default visibility. 11130b57cec5SDimitry Andric if (GV->hasLocalLinkage()) { 11140b57cec5SDimitry Andric GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 11150b57cec5SDimitry Andric return; 11160b57cec5SDimitry Andric } 11170b57cec5SDimitry Andric if (!D) 11180b57cec5SDimitry Andric return; 11190b57cec5SDimitry Andric // Set visibility for definitions, and for declarations if requested globally 11200b57cec5SDimitry Andric // or set explicitly. 11210b57cec5SDimitry Andric LinkageInfo LV = D->getLinkageAndVisibility(); 1122*bdd1243dSDimitry Andric if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) { 1123*bdd1243dSDimitry Andric // Reject incompatible dlllstorage and visibility annotations. 1124*bdd1243dSDimitry Andric if (!LV.isVisibilityExplicit()) 1125*bdd1243dSDimitry Andric return; 1126*bdd1243dSDimitry Andric if (GV->hasDLLExportStorageClass()) { 1127*bdd1243dSDimitry Andric if (LV.getVisibility() == HiddenVisibility) 1128*bdd1243dSDimitry Andric getDiags().Report(D->getLocation(), 1129*bdd1243dSDimitry Andric diag::err_hidden_visibility_dllexport); 1130*bdd1243dSDimitry Andric } else if (LV.getVisibility() != DefaultVisibility) { 1131*bdd1243dSDimitry Andric getDiags().Report(D->getLocation(), 1132*bdd1243dSDimitry Andric diag::err_non_default_visibility_dllimport); 1133*bdd1243dSDimitry Andric } 1134*bdd1243dSDimitry Andric return; 1135*bdd1243dSDimitry Andric } 1136*bdd1243dSDimitry Andric 11370b57cec5SDimitry Andric if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls || 11380b57cec5SDimitry Andric !GV->isDeclarationForLinker()) 11390b57cec5SDimitry Andric GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 11400b57cec5SDimitry Andric } 11410b57cec5SDimitry Andric 11420b57cec5SDimitry Andric static bool shouldAssumeDSOLocal(const CodeGenModule &CGM, 11430b57cec5SDimitry Andric llvm::GlobalValue *GV) { 11440b57cec5SDimitry Andric if (GV->hasLocalLinkage()) 11450b57cec5SDimitry Andric return true; 11460b57cec5SDimitry Andric 11470b57cec5SDimitry Andric if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()) 11480b57cec5SDimitry Andric return true; 11490b57cec5SDimitry Andric 11500b57cec5SDimitry Andric // DLLImport explicitly marks the GV as external. 11510b57cec5SDimitry Andric if (GV->hasDLLImportStorageClass()) 11520b57cec5SDimitry Andric return false; 11530b57cec5SDimitry Andric 11540b57cec5SDimitry Andric const llvm::Triple &TT = CGM.getTriple(); 11550b57cec5SDimitry Andric if (TT.isWindowsGNUEnvironment()) { 11560b57cec5SDimitry Andric // In MinGW, variables without DLLImport can still be automatically 11570b57cec5SDimitry Andric // imported from a DLL by the linker; don't mark variables that 11580b57cec5SDimitry 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.) 11640b57cec5SDimitry Andric if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) && 1165fe6060f1SDimitry Andric (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS)) 11660b57cec5SDimitry Andric return false; 11670b57cec5SDimitry Andric } 11680b57cec5SDimitry Andric 11690b57cec5SDimitry Andric // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols 11700b57cec5SDimitry Andric // remain unresolved in the link, they can be resolved to zero, which is 11710b57cec5SDimitry Andric // outside the current DSO. 11720b57cec5SDimitry Andric if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage()) 11730b57cec5SDimitry Andric return false; 11740b57cec5SDimitry Andric 11750b57cec5SDimitry Andric // Every other GV is local on COFF. 11760b57cec5SDimitry Andric // Make an exception for windows OS in the triple: Some firmware builds use 11770b57cec5SDimitry Andric // *-win32-macho triples. This (accidentally?) produced windows relocations 11780b57cec5SDimitry Andric // without GOT tables in older clang versions; Keep this behaviour. 11790b57cec5SDimitry Andric // FIXME: even thread local variables? 11800b57cec5SDimitry Andric if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO())) 11810b57cec5SDimitry Andric return true; 11820b57cec5SDimitry Andric 11830b57cec5SDimitry Andric // Only handle COFF and ELF for now. 11840b57cec5SDimitry Andric if (!TT.isOSBinFormatELF()) 11850b57cec5SDimitry Andric return false; 11860b57cec5SDimitry 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())) 11980b57cec5SDimitry Andric return false; 1199e8d8bef9SDimitry Andric return !(CGM.getLangOpts().SemanticInterposition || 1200e8d8bef9SDimitry Andric CGM.getLangOpts().HalfNoSemanticInterposition); 1201e8d8bef9SDimitry Andric } 12020b57cec5SDimitry Andric 12030b57cec5SDimitry Andric // A definition cannot be preempted from an executable. 12040b57cec5SDimitry Andric if (!GV->isDeclarationForLinker()) 12050b57cec5SDimitry Andric return true; 12060b57cec5SDimitry Andric 12070b57cec5SDimitry Andric // Most PIC code sequences that assume that a symbol is local cannot produce a 12080b57cec5SDimitry Andric // 0 if it turns out the symbol is undefined. While this is ABI and relocation 12090b57cec5SDimitry Andric // depended, it seems worth it to handle it here. 12100b57cec5SDimitry Andric if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage()) 12110b57cec5SDimitry Andric return false; 12120b57cec5SDimitry Andric 1213e8d8bef9SDimitry Andric // PowerPC64 prefers TOC indirection to avoid copy relocations. 1214e8d8bef9SDimitry Andric if (TT.isPPC64()) 12150b57cec5SDimitry Andric return false; 12160b57cec5SDimitry 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. 12230b57cec5SDimitry Andric if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV)) 1224e8d8bef9SDimitry Andric if (!Var->isThreadLocal()) 12250b57cec5SDimitry Andric return true; 12260b57cec5SDimitry 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. 12330b57cec5SDimitry Andric if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static) 12340b57cec5SDimitry Andric return true; 1235e8d8bef9SDimitry Andric } 1236e8d8bef9SDimitry Andric 1237e8d8bef9SDimitry Andric // If we can use copy relocations we can assume it is local. 12380b57cec5SDimitry Andric 12395ffd83dbSDimitry Andric // Otherwise don't assume it is local. 12400b57cec5SDimitry Andric return false; 12410b57cec5SDimitry Andric } 12420b57cec5SDimitry Andric 12430b57cec5SDimitry Andric void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const { 12440b57cec5SDimitry Andric GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV)); 12450b57cec5SDimitry Andric } 12460b57cec5SDimitry Andric 12470b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 12480b57cec5SDimitry Andric GlobalDecl GD) const { 12490b57cec5SDimitry Andric const auto *D = dyn_cast<NamedDecl>(GD.getDecl()); 12500b57cec5SDimitry Andric // C++ destructors have a few C++ ABI specific special cases. 12510b57cec5SDimitry Andric if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) { 12520b57cec5SDimitry Andric getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType()); 12530b57cec5SDimitry Andric return; 12540b57cec5SDimitry Andric } 12550b57cec5SDimitry Andric setDLLImportDLLExport(GV, D); 12560b57cec5SDimitry Andric } 12570b57cec5SDimitry Andric 12580b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 12590b57cec5SDimitry Andric const NamedDecl *D) const { 12600b57cec5SDimitry Andric if (D && D->isExternallyVisible()) { 12610b57cec5SDimitry Andric if (D->hasAttr<DLLImportAttr>()) 12620b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 126381ad6265SDimitry Andric else if ((D->hasAttr<DLLExportAttr>() || 126481ad6265SDimitry Andric shouldMapVisibilityToDLLExport(D)) && 126581ad6265SDimitry Andric !GV->isDeclarationForLinker()) 12660b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 12670b57cec5SDimitry Andric } 12680b57cec5SDimitry Andric } 12690b57cec5SDimitry Andric 12700b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 12710b57cec5SDimitry Andric GlobalDecl GD) const { 12720b57cec5SDimitry Andric setDLLImportDLLExport(GV, GD); 12730b57cec5SDimitry Andric setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl())); 12740b57cec5SDimitry Andric } 12750b57cec5SDimitry Andric 12760b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 12770b57cec5SDimitry Andric const NamedDecl *D) const { 12780b57cec5SDimitry Andric setDLLImportDLLExport(GV, D); 12790b57cec5SDimitry Andric setGVPropertiesAux(GV, D); 12800b57cec5SDimitry Andric } 12810b57cec5SDimitry Andric 12820b57cec5SDimitry Andric void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV, 12830b57cec5SDimitry Andric const NamedDecl *D) const { 12840b57cec5SDimitry Andric setGlobalVisibility(GV, D); 12850b57cec5SDimitry Andric setDSOLocal(GV); 12860b57cec5SDimitry Andric GV->setPartition(CodeGenOpts.SymbolPartition); 12870b57cec5SDimitry Andric } 12880b57cec5SDimitry Andric 12890b57cec5SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 12900b57cec5SDimitry Andric return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 12910b57cec5SDimitry Andric .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 12920b57cec5SDimitry Andric .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 12930b57cec5SDimitry Andric .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 12940b57cec5SDimitry Andric .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 12950b57cec5SDimitry Andric } 12960b57cec5SDimitry Andric 12975ffd83dbSDimitry Andric llvm::GlobalVariable::ThreadLocalMode 12985ffd83dbSDimitry Andric CodeGenModule::GetDefaultLLVMTLSModel() const { 12995ffd83dbSDimitry Andric switch (CodeGenOpts.getDefaultTLSModel()) { 13000b57cec5SDimitry Andric case CodeGenOptions::GeneralDynamicTLSModel: 13010b57cec5SDimitry Andric return llvm::GlobalVariable::GeneralDynamicTLSModel; 13020b57cec5SDimitry Andric case CodeGenOptions::LocalDynamicTLSModel: 13030b57cec5SDimitry Andric return llvm::GlobalVariable::LocalDynamicTLSModel; 13040b57cec5SDimitry Andric case CodeGenOptions::InitialExecTLSModel: 13050b57cec5SDimitry Andric return llvm::GlobalVariable::InitialExecTLSModel; 13060b57cec5SDimitry Andric case CodeGenOptions::LocalExecTLSModel: 13070b57cec5SDimitry Andric return llvm::GlobalVariable::LocalExecTLSModel; 13080b57cec5SDimitry Andric } 13090b57cec5SDimitry Andric llvm_unreachable("Invalid TLS model!"); 13100b57cec5SDimitry Andric } 13110b57cec5SDimitry Andric 13120b57cec5SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 13130b57cec5SDimitry Andric assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 13140b57cec5SDimitry Andric 13150b57cec5SDimitry Andric llvm::GlobalValue::ThreadLocalMode TLM; 13165ffd83dbSDimitry Andric TLM = GetDefaultLLVMTLSModel(); 13170b57cec5SDimitry Andric 13180b57cec5SDimitry Andric // Override the TLS model if it is explicitly specified. 13190b57cec5SDimitry Andric if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 13200b57cec5SDimitry Andric TLM = GetLLVMTLSModel(Attr->getModel()); 13210b57cec5SDimitry Andric } 13220b57cec5SDimitry Andric 13230b57cec5SDimitry Andric GV->setThreadLocalMode(TLM); 13240b57cec5SDimitry Andric } 13250b57cec5SDimitry Andric 13260b57cec5SDimitry Andric static std::string getCPUSpecificMangling(const CodeGenModule &CGM, 13270b57cec5SDimitry Andric StringRef Name) { 13280b57cec5SDimitry Andric const TargetInfo &Target = CGM.getTarget(); 13290b57cec5SDimitry Andric return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str(); 13300b57cec5SDimitry Andric } 13310b57cec5SDimitry Andric 13320b57cec5SDimitry Andric static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, 13330b57cec5SDimitry Andric const CPUSpecificAttr *Attr, 13340b57cec5SDimitry Andric unsigned CPUIndex, 13350b57cec5SDimitry Andric raw_ostream &Out) { 13360b57cec5SDimitry Andric // cpu_specific gets the current name, dispatch gets the resolver if IFunc is 13370b57cec5SDimitry Andric // supported. 13380b57cec5SDimitry Andric if (Attr) 13390b57cec5SDimitry Andric Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName()); 13400b57cec5SDimitry Andric else if (CGM.getTarget().supportsIFunc()) 13410b57cec5SDimitry Andric Out << ".resolver"; 13420b57cec5SDimitry Andric } 13430b57cec5SDimitry Andric 1344*bdd1243dSDimitry Andric static void AppendTargetVersionMangling(const CodeGenModule &CGM, 1345*bdd1243dSDimitry Andric const TargetVersionAttr *Attr, 1346*bdd1243dSDimitry Andric raw_ostream &Out) { 1347*bdd1243dSDimitry Andric if (Attr->isDefaultVersion()) 1348*bdd1243dSDimitry Andric return; 1349*bdd1243dSDimitry Andric Out << "._"; 1350*bdd1243dSDimitry Andric llvm::SmallVector<StringRef, 8> Feats; 1351*bdd1243dSDimitry Andric Attr->getFeatures(Feats); 1352*bdd1243dSDimitry Andric for (const auto &Feat : Feats) { 1353*bdd1243dSDimitry Andric Out << 'M'; 1354*bdd1243dSDimitry Andric Out << Feat; 1355*bdd1243dSDimitry Andric } 1356*bdd1243dSDimitry Andric } 1357*bdd1243dSDimitry Andric 13580b57cec5SDimitry Andric static void AppendTargetMangling(const CodeGenModule &CGM, 13590b57cec5SDimitry Andric const TargetAttr *Attr, raw_ostream &Out) { 13600b57cec5SDimitry Andric if (Attr->isDefaultVersion()) 13610b57cec5SDimitry Andric return; 13620b57cec5SDimitry Andric 13630b57cec5SDimitry Andric Out << '.'; 13640b57cec5SDimitry Andric const TargetInfo &Target = CGM.getTarget(); 1365*bdd1243dSDimitry Andric ParsedTargetAttr Info = Target.parseTargetAttr(Attr->getFeaturesStr()); 1366*bdd1243dSDimitry Andric llvm::sort(Info.Features, [&Target](StringRef LHS, StringRef RHS) { 13670b57cec5SDimitry Andric // Multiversioning doesn't allow "no-${feature}", so we can 13680b57cec5SDimitry Andric // only have "+" prefixes here. 13690b57cec5SDimitry Andric assert(LHS.startswith("+") && RHS.startswith("+") && 13700b57cec5SDimitry Andric "Features should always have a prefix."); 13710b57cec5SDimitry Andric return Target.multiVersionSortPriority(LHS.substr(1)) > 13720b57cec5SDimitry Andric Target.multiVersionSortPriority(RHS.substr(1)); 13730b57cec5SDimitry Andric }); 13740b57cec5SDimitry Andric 13750b57cec5SDimitry Andric bool IsFirst = true; 13760b57cec5SDimitry Andric 1377*bdd1243dSDimitry Andric if (!Info.CPU.empty()) { 13780b57cec5SDimitry Andric IsFirst = false; 1379*bdd1243dSDimitry Andric Out << "arch_" << Info.CPU; 13800b57cec5SDimitry Andric } 13810b57cec5SDimitry Andric 13820b57cec5SDimitry Andric for (StringRef Feat : Info.Features) { 13830b57cec5SDimitry Andric if (!IsFirst) 13840b57cec5SDimitry Andric Out << '_'; 13850b57cec5SDimitry Andric IsFirst = false; 13860b57cec5SDimitry Andric Out << Feat.substr(1); 13870b57cec5SDimitry Andric } 13880b57cec5SDimitry Andric } 13890b57cec5SDimitry 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) { 1403*bdd1243dSDimitry Andric if (CGM.getTarget().getTriple().isAArch64()) { 1404*bdd1243dSDimitry Andric StringRef FeatureStr = Attr->getFeatureStr(VersionIndex); 1405*bdd1243dSDimitry Andric if (FeatureStr == "default") 1406*bdd1243dSDimitry Andric return; 1407*bdd1243dSDimitry Andric Out << "._"; 1408*bdd1243dSDimitry Andric SmallVector<StringRef, 8> Features; 1409*bdd1243dSDimitry Andric FeatureStr.split(Features, "+"); 1410*bdd1243dSDimitry Andric for (auto &Feat : Features) { 1411*bdd1243dSDimitry Andric Out << 'M'; 1412*bdd1243dSDimitry Andric Out << Feat; 1413*bdd1243dSDimitry Andric } 1414*bdd1243dSDimitry 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 } 1424*bdd1243dSDimitry Andric } 14254824e7fdSDimitry Andric 1426fe6060f1SDimitry Andric static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD, 14270b57cec5SDimitry Andric const NamedDecl *ND, 14280b57cec5SDimitry Andric bool OmitMultiVersionMangling = false) { 14290b57cec5SDimitry Andric SmallString<256> Buffer; 14300b57cec5SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 14310b57cec5SDimitry 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 { 14380b57cec5SDimitry Andric IdentifierInfo *II = ND->getIdentifier(); 14390b57cec5SDimitry Andric assert(II && "Attempt to mangle unnamed decl."); 14400b57cec5SDimitry Andric const auto *FD = dyn_cast<FunctionDecl>(ND); 14410b57cec5SDimitry Andric 14420b57cec5SDimitry Andric if (FD && 14430b57cec5SDimitry Andric FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { 14440b57cec5SDimitry 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(); 14480b57cec5SDimitry Andric } else { 14490b57cec5SDimitry Andric Out << II->getName(); 14500b57cec5SDimitry Andric } 14510b57cec5SDimitry Andric } 14520b57cec5SDimitry 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 14670b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 14680b57cec5SDimitry Andric if (FD->isMultiVersion() && !OmitMultiVersionMangling) { 14690b57cec5SDimitry Andric switch (FD->getMultiVersionKind()) { 14700b57cec5SDimitry Andric case MultiVersionKind::CPUDispatch: 14710b57cec5SDimitry Andric case MultiVersionKind::CPUSpecific: 14720b57cec5SDimitry Andric AppendCPUSpecificCPUDispatchMangling(CGM, 14730b57cec5SDimitry Andric FD->getAttr<CPUSpecificAttr>(), 14740b57cec5SDimitry Andric GD.getMultiVersionIndex(), Out); 14750b57cec5SDimitry Andric break; 14760b57cec5SDimitry Andric case MultiVersionKind::Target: 14770b57cec5SDimitry Andric AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out); 14780b57cec5SDimitry Andric break; 1479*bdd1243dSDimitry Andric case MultiVersionKind::TargetVersion: 1480*bdd1243dSDimitry Andric AppendTargetVersionMangling(CGM, FD->getAttr<TargetVersionAttr>(), Out); 1481*bdd1243dSDimitry Andric break; 14824824e7fdSDimitry Andric case MultiVersionKind::TargetClones: 14834824e7fdSDimitry Andric AppendTargetClonesMangling(CGM, FD->getAttr<TargetClonesAttr>(), 14844824e7fdSDimitry Andric GD.getMultiVersionIndex(), Out); 14854824e7fdSDimitry Andric break; 14860b57cec5SDimitry Andric case MultiVersionKind::None: 14870b57cec5SDimitry Andric llvm_unreachable("None multiversion type isn't valid here"); 14880b57cec5SDimitry Andric } 14890b57cec5SDimitry Andric } 14900b57cec5SDimitry 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()); 14980b57cec5SDimitry Andric } 14990b57cec5SDimitry Andric 15000b57cec5SDimitry Andric void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD, 150104eeddc0SDimitry Andric const FunctionDecl *FD, 150204eeddc0SDimitry Andric StringRef &CurName) { 15030b57cec5SDimitry Andric if (!FD->isMultiVersion()) 15040b57cec5SDimitry Andric return; 15050b57cec5SDimitry Andric 15060b57cec5SDimitry Andric // Get the name of what this would be without the 'target' attribute. This 15070b57cec5SDimitry Andric // allows us to lookup the version that was emitted when this wasn't a 15080b57cec5SDimitry Andric // multiversion function. 15090b57cec5SDimitry Andric std::string NonTargetName = 15100b57cec5SDimitry Andric getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 15110b57cec5SDimitry Andric GlobalDecl OtherGD; 15120b57cec5SDimitry Andric if (lookupRepresentativeDecl(NonTargetName, OtherGD)) { 15130b57cec5SDimitry Andric assert(OtherGD.getCanonicalDecl() 15140b57cec5SDimitry Andric .getDecl() 15150b57cec5SDimitry Andric ->getAsFunction() 15160b57cec5SDimitry Andric ->isMultiVersion() && 15170b57cec5SDimitry Andric "Other GD should now be a multiversioned function"); 15180b57cec5SDimitry Andric // OtherFD is the version of this function that was mangled BEFORE 15190b57cec5SDimitry Andric // becoming a MultiVersion function. It potentially needs to be updated. 15200b57cec5SDimitry Andric const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl() 15210b57cec5SDimitry Andric .getDecl() 15220b57cec5SDimitry Andric ->getAsFunction() 15230b57cec5SDimitry Andric ->getMostRecentDecl(); 15240b57cec5SDimitry Andric std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD); 15250b57cec5SDimitry Andric // This is so that if the initial version was already the 'default' 15260b57cec5SDimitry Andric // version, we don't try to update it. 15270b57cec5SDimitry Andric if (OtherName != NonTargetName) { 15280b57cec5SDimitry Andric // Remove instead of erase, since others may have stored the StringRef 15290b57cec5SDimitry Andric // to this. 15300b57cec5SDimitry Andric const auto ExistingRecord = Manglings.find(NonTargetName); 15310b57cec5SDimitry Andric if (ExistingRecord != std::end(Manglings)) 15320b57cec5SDimitry Andric Manglings.remove(&(*ExistingRecord)); 15330b57cec5SDimitry 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; 15390b57cec5SDimitry Andric if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName)) 15400b57cec5SDimitry Andric Entry->setName(OtherName); 15410b57cec5SDimitry Andric } 15420b57cec5SDimitry Andric } 15430b57cec5SDimitry Andric } 15440b57cec5SDimitry Andric 15450b57cec5SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 15460b57cec5SDimitry Andric GlobalDecl CanonicalGD = GD.getCanonicalDecl(); 15470b57cec5SDimitry Andric 15480b57cec5SDimitry Andric // Some ABIs don't have constructor variants. Make sure that base and 15490b57cec5SDimitry Andric // complete constructors get mangled the same. 15500b57cec5SDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { 15510b57cec5SDimitry Andric if (!getTarget().getCXXABI().hasConstructorVariants()) { 15520b57cec5SDimitry Andric CXXCtorType OrigCtorType = GD.getCtorType(); 15530b57cec5SDimitry Andric assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); 15540b57cec5SDimitry Andric if (OrigCtorType == Ctor_Base) 15550b57cec5SDimitry Andric CanonicalGD = GlobalDecl(CD, Ctor_Complete); 15560b57cec5SDimitry Andric } 15570b57cec5SDimitry Andric } 15580b57cec5SDimitry 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())) { 15640b57cec5SDimitry Andric auto FoundName = MangledDeclNames.find(CanonicalGD); 15650b57cec5SDimitry Andric if (FoundName != MangledDeclNames.end()) 15660b57cec5SDimitry Andric return FoundName->second; 1567fe6060f1SDimitry Andric } 15680b57cec5SDimitry Andric 15690b57cec5SDimitry Andric // Keep the first result in the case of a mangling collision. 15700b57cec5SDimitry Andric const auto *ND = cast<NamedDecl>(GD.getDecl()); 15710b57cec5SDimitry Andric std::string MangledName = getMangledNameImpl(*this, GD, ND); 15720b57cec5SDimitry 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)); 15920b57cec5SDimitry Andric 15930b57cec5SDimitry Andric auto Result = Manglings.insert(std::make_pair(MangledName, GD)); 15940b57cec5SDimitry Andric return MangledDeclNames[CanonicalGD] = Result.first->first(); 15950b57cec5SDimitry Andric } 15960b57cec5SDimitry Andric 15970b57cec5SDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 15980b57cec5SDimitry Andric const BlockDecl *BD) { 15990b57cec5SDimitry Andric MangleContext &MangleCtx = getCXXABI().getMangleContext(); 16000b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 16010b57cec5SDimitry Andric 16020b57cec5SDimitry Andric SmallString<256> Buffer; 16030b57cec5SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 16040b57cec5SDimitry Andric if (!D) 16050b57cec5SDimitry Andric MangleCtx.mangleGlobalBlock(BD, 16060b57cec5SDimitry Andric dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 16070b57cec5SDimitry Andric else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 16080b57cec5SDimitry Andric MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 16090b57cec5SDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 16100b57cec5SDimitry Andric MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 16110b57cec5SDimitry Andric else 16120b57cec5SDimitry Andric MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 16130b57cec5SDimitry Andric 16140b57cec5SDimitry Andric auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 16150b57cec5SDimitry Andric return Result.first->first(); 16160b57cec5SDimitry Andric } 16170b57cec5SDimitry 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 16280b57cec5SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 16290b57cec5SDimitry Andric return getModule().getNamedValue(Name); 16300b57cec5SDimitry Andric } 16310b57cec5SDimitry Andric 16320b57cec5SDimitry Andric /// AddGlobalCtor - Add a function to the list that will be called before 16330b57cec5SDimitry Andric /// main() runs. 16340b57cec5SDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 1635*bdd1243dSDimitry Andric unsigned LexOrder, 16360b57cec5SDimitry Andric llvm::Constant *AssociatedData) { 16370b57cec5SDimitry Andric // FIXME: Type coercion of void()* types. 1638*bdd1243dSDimitry Andric GlobalCtors.push_back(Structor(Priority, LexOrder, Ctor, AssociatedData)); 16390b57cec5SDimitry Andric } 16400b57cec5SDimitry Andric 16410b57cec5SDimitry Andric /// AddGlobalDtor - Add a function to the list that will be called 16420b57cec5SDimitry 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)) { 16470b57cec5SDimitry Andric DtorsUsingAtExit[Priority].push_back(Dtor); 16480b57cec5SDimitry Andric return; 16490b57cec5SDimitry Andric } 16500b57cec5SDimitry Andric 16510b57cec5SDimitry Andric // FIXME: Type coercion of void()* types. 1652*bdd1243dSDimitry Andric GlobalDtors.push_back(Structor(Priority, ~0U, Dtor, nullptr)); 16530b57cec5SDimitry Andric } 16540b57cec5SDimitry Andric 16550b57cec5SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { 16560b57cec5SDimitry Andric if (Fns.empty()) return; 16570b57cec5SDimitry Andric 16580b57cec5SDimitry Andric // Ctor function type is void()*. 16590b57cec5SDimitry Andric llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 16600b57cec5SDimitry Andric llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy, 16610b57cec5SDimitry Andric TheModule.getDataLayout().getProgramAddressSpace()); 16620b57cec5SDimitry Andric 16630b57cec5SDimitry Andric // Get the type of a ctor entry, { i32, void ()*, i8* }. 16640b57cec5SDimitry Andric llvm::StructType *CtorStructTy = llvm::StructType::get( 16650b57cec5SDimitry Andric Int32Ty, CtorPFTy, VoidPtrTy); 16660b57cec5SDimitry Andric 16670b57cec5SDimitry Andric // Construct the constructor and destructor arrays. 16680b57cec5SDimitry Andric ConstantInitBuilder builder(*this); 16690b57cec5SDimitry Andric auto ctors = builder.beginArray(CtorStructTy); 16700b57cec5SDimitry Andric for (const auto &I : Fns) { 16710b57cec5SDimitry Andric auto ctor = ctors.beginStruct(CtorStructTy); 16720b57cec5SDimitry Andric ctor.addInt(Int32Ty, I.Priority); 16730b57cec5SDimitry Andric ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy)); 16740b57cec5SDimitry Andric if (I.AssociatedData) 16750b57cec5SDimitry Andric ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)); 16760b57cec5SDimitry Andric else 16770b57cec5SDimitry Andric ctor.addNullPointer(VoidPtrTy); 16780b57cec5SDimitry Andric ctor.finishAndAddTo(ctors); 16790b57cec5SDimitry Andric } 16800b57cec5SDimitry Andric 16810b57cec5SDimitry Andric auto list = 16820b57cec5SDimitry Andric ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(), 16830b57cec5SDimitry Andric /*constant*/ false, 16840b57cec5SDimitry Andric llvm::GlobalValue::AppendingLinkage); 16850b57cec5SDimitry Andric 16860b57cec5SDimitry Andric // The LTO linker doesn't seem to like it when we set an alignment 16870b57cec5SDimitry Andric // on appending variables. Take it off as a workaround. 1688*bdd1243dSDimitry Andric list->setAlignment(std::nullopt); 16890b57cec5SDimitry Andric 16900b57cec5SDimitry Andric Fns.clear(); 16910b57cec5SDimitry Andric } 16920b57cec5SDimitry Andric 16930b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes 16940b57cec5SDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 16950b57cec5SDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 16960b57cec5SDimitry Andric 16970b57cec5SDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 16980b57cec5SDimitry Andric 16990b57cec5SDimitry Andric if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D)) 17000b57cec5SDimitry Andric return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType()); 17010b57cec5SDimitry Andric 17020b57cec5SDimitry Andric if (isa<CXXConstructorDecl>(D) && 17030b57cec5SDimitry Andric cast<CXXConstructorDecl>(D)->isInheritingConstructor() && 17040b57cec5SDimitry Andric Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17050b57cec5SDimitry Andric // Our approach to inheriting constructors is fundamentally different from 17060b57cec5SDimitry Andric // that used by the MS ABI, so keep our inheriting constructor thunks 17070b57cec5SDimitry Andric // internal rather than trying to pick an unambiguous mangling for them. 17080b57cec5SDimitry Andric return llvm::GlobalValue::InternalLinkage; 17090b57cec5SDimitry Andric } 17100b57cec5SDimitry Andric 17110b57cec5SDimitry Andric return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false); 17120b57cec5SDimitry Andric } 17130b57cec5SDimitry Andric 17140b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { 17150b57cec5SDimitry Andric llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 17160b57cec5SDimitry Andric if (!MDS) return nullptr; 17170b57cec5SDimitry Andric 17180b57cec5SDimitry Andric return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString())); 17190b57cec5SDimitry Andric } 17200b57cec5SDimitry Andric 1721*bdd1243dSDimitry Andric llvm::ConstantInt *CodeGenModule::CreateKCFITypeId(QualType T) { 1722*bdd1243dSDimitry Andric if (auto *FnType = T->getAs<FunctionProtoType>()) 1723*bdd1243dSDimitry Andric T = getContext().getFunctionType( 1724*bdd1243dSDimitry Andric FnType->getReturnType(), FnType->getParamTypes(), 1725*bdd1243dSDimitry Andric FnType->getExtProtoInfo().withExceptionSpec(EST_None)); 1726*bdd1243dSDimitry Andric 1727*bdd1243dSDimitry Andric std::string OutName; 1728*bdd1243dSDimitry Andric llvm::raw_string_ostream Out(OutName); 1729*bdd1243dSDimitry Andric getCXXABI().getMangleContext().mangleTypeName(T, Out); 1730*bdd1243dSDimitry Andric 1731*bdd1243dSDimitry Andric return llvm::ConstantInt::get(Int32Ty, 1732*bdd1243dSDimitry Andric static_cast<uint32_t>(llvm::xxHash64(OutName))); 1733*bdd1243dSDimitry Andric } 1734*bdd1243dSDimitry Andric 17350b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD, 17360b57cec5SDimitry Andric const CGFunctionInfo &Info, 1737fe6060f1SDimitry Andric llvm::Function *F, bool IsThunk) { 17380b57cec5SDimitry Andric unsigned CallingConv; 17390b57cec5SDimitry Andric llvm::AttributeList PAL; 1740fe6060f1SDimitry Andric ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, 1741fe6060f1SDimitry Andric /*AttrOnCallSite=*/false, IsThunk); 17420b57cec5SDimitry Andric F->setAttributes(PAL); 17430b57cec5SDimitry Andric F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 17440b57cec5SDimitry Andric } 17450b57cec5SDimitry Andric 17460b57cec5SDimitry Andric static void removeImageAccessQualifier(std::string& TyName) { 17470b57cec5SDimitry Andric std::string ReadOnlyQual("__read_only"); 17480b57cec5SDimitry Andric std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual); 17490b57cec5SDimitry Andric if (ReadOnlyPos != std::string::npos) 17500b57cec5SDimitry Andric // "+ 1" for the space after access qualifier. 17510b57cec5SDimitry Andric TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1); 17520b57cec5SDimitry Andric else { 17530b57cec5SDimitry Andric std::string WriteOnlyQual("__write_only"); 17540b57cec5SDimitry Andric std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual); 17550b57cec5SDimitry Andric if (WriteOnlyPos != std::string::npos) 17560b57cec5SDimitry Andric TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1); 17570b57cec5SDimitry Andric else { 17580b57cec5SDimitry Andric std::string ReadWriteQual("__read_write"); 17590b57cec5SDimitry Andric std::string::size_type ReadWritePos = TyName.find(ReadWriteQual); 17600b57cec5SDimitry Andric if (ReadWritePos != std::string::npos) 17610b57cec5SDimitry Andric TyName.erase(ReadWritePos, ReadWriteQual.size() + 1); 17620b57cec5SDimitry Andric } 17630b57cec5SDimitry Andric } 17640b57cec5SDimitry Andric } 17650b57cec5SDimitry Andric 17660b57cec5SDimitry Andric // Returns the address space id that should be produced to the 17670b57cec5SDimitry Andric // kernel_arg_addr_space metadata. This is always fixed to the ids 17680b57cec5SDimitry Andric // as specified in the SPIR 2.0 specification in order to differentiate 17690b57cec5SDimitry Andric // for example in clGetKernelArgInfo() implementation between the address 17700b57cec5SDimitry Andric // spaces with targets without unique mapping to the OpenCL address spaces 17710b57cec5SDimitry Andric // (basically all single AS CPUs). 17720b57cec5SDimitry Andric static unsigned ArgInfoAddressSpace(LangAS AS) { 17730b57cec5SDimitry 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; 17860b57cec5SDimitry Andric default: 17870b57cec5SDimitry Andric return 0; // Assume private. 17880b57cec5SDimitry Andric } 17890b57cec5SDimitry Andric } 17900b57cec5SDimitry Andric 179181ad6265SDimitry Andric void CodeGenModule::GenKernelArgMetadata(llvm::Function *Fn, 17920b57cec5SDimitry Andric const FunctionDecl *FD, 17930b57cec5SDimitry Andric CodeGenFunction *CGF) { 17940b57cec5SDimitry Andric assert(((FD && CGF) || (!FD && !CGF)) && 17950b57cec5SDimitry Andric "Incorrect use - FD and CGF should either be both null or not!"); 17960b57cec5SDimitry Andric // Create MDNodes that represent the kernel arg metadata. 17970b57cec5SDimitry Andric // Each MDNode is a list in the form of "key", N number of values which is 17980b57cec5SDimitry Andric // the same number of values as their are kernel arguments. 17990b57cec5SDimitry Andric 18000b57cec5SDimitry Andric const PrintingPolicy &Policy = Context.getPrintingPolicy(); 18010b57cec5SDimitry Andric 18020b57cec5SDimitry Andric // MDNode for the kernel argument address space qualifiers. 18030b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> addressQuals; 18040b57cec5SDimitry Andric 18050b57cec5SDimitry Andric // MDNode for the kernel argument access qualifiers (images only). 18060b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> accessQuals; 18070b57cec5SDimitry Andric 18080b57cec5SDimitry Andric // MDNode for the kernel argument type names. 18090b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> argTypeNames; 18100b57cec5SDimitry Andric 18110b57cec5SDimitry Andric // MDNode for the kernel argument base type names. 18120b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> argBaseTypeNames; 18130b57cec5SDimitry Andric 18140b57cec5SDimitry Andric // MDNode for the kernel argument type qualifiers. 18150b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> argTypeQuals; 18160b57cec5SDimitry Andric 18170b57cec5SDimitry Andric // MDNode for the kernel argument names. 18180b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> argNames; 18190b57cec5SDimitry Andric 18200b57cec5SDimitry Andric if (FD && CGF) 18210b57cec5SDimitry Andric for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { 18220b57cec5SDimitry 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; 18280b57cec5SDimitry Andric QualType ty = parm->getType(); 18290b57cec5SDimitry Andric std::string typeQuals; 18300b57cec5SDimitry Andric 1831fe6060f1SDimitry Andric // Get image and pipe access qualifier: 1832fe6060f1SDimitry Andric if (ty->isImageType() || ty->isPipeType()) { 1833fe6060f1SDimitry Andric const Decl *PDecl = parm; 1834*bdd1243dSDimitry 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 18610b57cec5SDimitry Andric if (ty->isPointerType()) { 18620b57cec5SDimitry Andric QualType pointeeTy = ty->getPointeeType(); 18630b57cec5SDimitry Andric 18640b57cec5SDimitry Andric // Get address qualifier. 18650b57cec5SDimitry Andric addressQuals.push_back( 18660b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(CGF->Builder.getInt32( 18670b57cec5SDimitry Andric ArgInfoAddressSpace(pointeeTy.getAddressSpace())))); 18680b57cec5SDimitry Andric 18690b57cec5SDimitry Andric // Get argument type name. 1870fe6060f1SDimitry Andric std::string typeName = getTypeSpelling(pointeeTy) + "*"; 18710b57cec5SDimitry Andric std::string baseTypeName = 1872fe6060f1SDimitry Andric getTypeSpelling(pointeeTy.getCanonicalType()) + "*"; 1873fe6060f1SDimitry Andric argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 18740b57cec5SDimitry Andric argBaseTypeNames.push_back( 18750b57cec5SDimitry Andric llvm::MDString::get(VMContext, baseTypeName)); 18760b57cec5SDimitry Andric 18770b57cec5SDimitry Andric // Get argument type qualifiers: 18780b57cec5SDimitry Andric if (ty.isRestrictQualified()) 18790b57cec5SDimitry Andric typeQuals = "restrict"; 18800b57cec5SDimitry Andric if (pointeeTy.isConstQualified() || 18810b57cec5SDimitry Andric (pointeeTy.getAddressSpace() == LangAS::opencl_constant)) 18820b57cec5SDimitry Andric typeQuals += typeQuals.empty() ? "const" : " const"; 18830b57cec5SDimitry Andric if (pointeeTy.isVolatileQualified()) 18840b57cec5SDimitry Andric typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 18850b57cec5SDimitry Andric } else { 18860b57cec5SDimitry Andric uint32_t AddrSpc = 0; 18870b57cec5SDimitry Andric bool isPipe = ty->isPipeType(); 18880b57cec5SDimitry Andric if (ty->isImageType() || isPipe) 18890b57cec5SDimitry Andric AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global); 18900b57cec5SDimitry Andric 18910b57cec5SDimitry Andric addressQuals.push_back( 18920b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc))); 18930b57cec5SDimitry Andric 18940b57cec5SDimitry 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()); 18980b57cec5SDimitry Andric 18990b57cec5SDimitry Andric // Remove access qualifiers on images 19000b57cec5SDimitry Andric // (as they are inseparable from type in clang implementation, 19010b57cec5SDimitry Andric // but OpenCL spec provides a special query to get access qualifier 19020b57cec5SDimitry Andric // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER): 19030b57cec5SDimitry Andric if (ty->isImageType()) { 19040b57cec5SDimitry Andric removeImageAccessQualifier(typeName); 19050b57cec5SDimitry Andric removeImageAccessQualifier(baseTypeName); 19060b57cec5SDimitry Andric } 19070b57cec5SDimitry Andric 19080b57cec5SDimitry Andric argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 19090b57cec5SDimitry Andric argBaseTypeNames.push_back( 19100b57cec5SDimitry Andric llvm::MDString::get(VMContext, baseTypeName)); 19110b57cec5SDimitry Andric 19120b57cec5SDimitry Andric if (isPipe) 19130b57cec5SDimitry Andric typeQuals = "pipe"; 19140b57cec5SDimitry Andric } 19150b57cec5SDimitry Andric argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals)); 19160b57cec5SDimitry Andric } 19170b57cec5SDimitry Andric 191881ad6265SDimitry Andric if (getLangOpts().OpenCL) { 19190b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_addr_space", 19200b57cec5SDimitry Andric llvm::MDNode::get(VMContext, addressQuals)); 19210b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_access_qual", 19220b57cec5SDimitry Andric llvm::MDNode::get(VMContext, accessQuals)); 19230b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_type", 19240b57cec5SDimitry Andric llvm::MDNode::get(VMContext, argTypeNames)); 19250b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_base_type", 19260b57cec5SDimitry Andric llvm::MDNode::get(VMContext, argBaseTypeNames)); 19270b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_type_qual", 19280b57cec5SDimitry Andric llvm::MDNode::get(VMContext, argTypeQuals)); 192981ad6265SDimitry Andric } 193081ad6265SDimitry Andric if (getCodeGenOpts().EmitOpenCLArgMetadata || 193181ad6265SDimitry Andric getCodeGenOpts().HIPSaveKernelArgName) 19320b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_name", 19330b57cec5SDimitry Andric llvm::MDNode::get(VMContext, argNames)); 19340b57cec5SDimitry Andric } 19350b57cec5SDimitry Andric 19360b57cec5SDimitry Andric /// Determines whether the language options require us to model 19370b57cec5SDimitry Andric /// unwind exceptions. We treat -fexceptions as mandating this 19380b57cec5SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions 19390b57cec5SDimitry Andric /// enabled. This means, for example, that C with -fexceptions 19400b57cec5SDimitry Andric /// enables this. 19410b57cec5SDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) { 19420b57cec5SDimitry Andric // If exceptions are completely disabled, obviously this is false. 19430b57cec5SDimitry Andric if (!LangOpts.Exceptions) return false; 19440b57cec5SDimitry Andric 19450b57cec5SDimitry Andric // If C++ exceptions are enabled, this is true. 19460b57cec5SDimitry Andric if (LangOpts.CXXExceptions) return true; 19470b57cec5SDimitry Andric 19480b57cec5SDimitry Andric // If ObjC exceptions are enabled, this depends on the ABI. 19490b57cec5SDimitry Andric if (LangOpts.ObjCExceptions) { 19500b57cec5SDimitry Andric return LangOpts.ObjCRuntime.hasUnwindExceptions(); 19510b57cec5SDimitry Andric } 19520b57cec5SDimitry Andric 19530b57cec5SDimitry Andric return true; 19540b57cec5SDimitry Andric } 19550b57cec5SDimitry Andric 19560b57cec5SDimitry Andric static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, 19570b57cec5SDimitry Andric const CXXMethodDecl *MD) { 19580b57cec5SDimitry Andric // Check that the type metadata can ever actually be used by a call. 19590b57cec5SDimitry Andric if (!CGM.getCodeGenOpts().LTOUnit || 19600b57cec5SDimitry Andric !CGM.HasHiddenLTOVisibility(MD->getParent())) 19610b57cec5SDimitry Andric return false; 19620b57cec5SDimitry Andric 19630b57cec5SDimitry Andric // Only functions whose address can be taken with a member function pointer 19640b57cec5SDimitry Andric // need this sort of type metadata. 19650b57cec5SDimitry Andric return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) && 19660b57cec5SDimitry Andric !isa<CXXDestructorDecl>(MD); 19670b57cec5SDimitry Andric } 19680b57cec5SDimitry Andric 19690b57cec5SDimitry Andric std::vector<const CXXRecordDecl *> 19700b57cec5SDimitry Andric CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) { 19710b57cec5SDimitry Andric llvm::SetVector<const CXXRecordDecl *> MostBases; 19720b57cec5SDimitry Andric 19730b57cec5SDimitry Andric std::function<void (const CXXRecordDecl *)> CollectMostBases; 19740b57cec5SDimitry Andric CollectMostBases = [&](const CXXRecordDecl *RD) { 19750b57cec5SDimitry Andric if (RD->getNumBases() == 0) 19760b57cec5SDimitry Andric MostBases.insert(RD); 19770b57cec5SDimitry Andric for (const CXXBaseSpecifier &B : RD->bases()) 19780b57cec5SDimitry Andric CollectMostBases(B.getType()->getAsCXXRecordDecl()); 19790b57cec5SDimitry Andric }; 19800b57cec5SDimitry Andric CollectMostBases(RD); 19810b57cec5SDimitry Andric return MostBases.takeVector(); 19820b57cec5SDimitry Andric } 19830b57cec5SDimitry 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 20000b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 20010b57cec5SDimitry Andric llvm::Function *F) { 200204eeddc0SDimitry Andric llvm::AttrBuilder B(F->getContext()); 20030b57cec5SDimitry Andric 2004*bdd1243dSDimitry Andric if ((!D || !D->hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables) 200581ad6265SDimitry Andric B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables)); 20060b57cec5SDimitry Andric 20075ffd83dbSDimitry Andric if (CodeGenOpts.StackClashProtector) 20085ffd83dbSDimitry Andric B.addAttribute("probe-stack", "inline-asm"); 20095ffd83dbSDimitry Andric 20100b57cec5SDimitry Andric if (!hasUnwindExceptions(LangOpts)) 20110b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoUnwind); 20120b57cec5SDimitry Andric 2013*bdd1243dSDimitry Andric if (D && D->hasAttr<NoStackProtectorAttr>()) 2014*bdd1243dSDimitry Andric ; // Do nothing. 2015*bdd1243dSDimitry Andric else if (D && D->hasAttr<StrictGuardStackCheckAttr>() && 2016*bdd1243dSDimitry Andric LangOpts.getStackProtector() == LangOptions::SSPOn) 2017*bdd1243dSDimitry Andric B.addAttribute(llvm::Attribute::StackProtectStrong); 2018*bdd1243dSDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPOn) 20190b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::StackProtect); 20200b57cec5SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 20210b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectStrong); 20220b57cec5SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 20230b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectReq); 20240b57cec5SDimitry Andric 20250b57cec5SDimitry Andric if (!D) { 20260b57cec5SDimitry Andric // If we don't have a declaration to control inlining, the function isn't 20270b57cec5SDimitry Andric // explicitly marked as alwaysinline for semantic reasons, and inlining is 20280b57cec5SDimitry Andric // disabled, mark the function as noinline. 20290b57cec5SDimitry Andric if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 20300b57cec5SDimitry Andric CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) 20310b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 20320b57cec5SDimitry Andric 2033349cc55cSDimitry Andric F->addFnAttrs(B); 20340b57cec5SDimitry Andric return; 20350b57cec5SDimitry Andric } 20360b57cec5SDimitry Andric 20370b57cec5SDimitry Andric // Track whether we need to add the optnone LLVM attribute, 20380b57cec5SDimitry Andric // starting with the default for this optimization level. 20390b57cec5SDimitry Andric bool ShouldAddOptNone = 20400b57cec5SDimitry Andric !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0; 20410b57cec5SDimitry Andric // We can't add optnone in the following cases, it won't pass the verifier. 20420b57cec5SDimitry Andric ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>(); 20430b57cec5SDimitry Andric ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>(); 20440b57cec5SDimitry 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)) { 20480b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::OptimizeNone); 20490b57cec5SDimitry Andric 20500b57cec5SDimitry Andric // OptimizeNone implies noinline; we should not be inlining such functions. 20510b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 20520b57cec5SDimitry Andric 20530b57cec5SDimitry Andric // We still need to handle naked functions even though optnone subsumes 20540b57cec5SDimitry Andric // much of their semantics. 20550b57cec5SDimitry Andric if (D->hasAttr<NakedAttr>()) 20560b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::Naked); 20570b57cec5SDimitry Andric 20580b57cec5SDimitry Andric // OptimizeNone wins over OptimizeForSize and MinSize. 20590b57cec5SDimitry Andric F->removeFnAttr(llvm::Attribute::OptimizeForSize); 20600b57cec5SDimitry Andric F->removeFnAttr(llvm::Attribute::MinSize); 20610b57cec5SDimitry Andric } else if (D->hasAttr<NakedAttr>()) { 20620b57cec5SDimitry Andric // Naked implies noinline: we should not be inlining such functions. 20630b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::Naked); 20640b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 20650b57cec5SDimitry Andric } else if (D->hasAttr<NoDuplicateAttr>()) { 20660b57cec5SDimitry 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. 20690b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 20700b57cec5SDimitry Andric } else if (D->hasAttr<AlwaysInlineAttr>() && 20710b57cec5SDimitry Andric !F->hasFnAttribute(llvm::Attribute::NoInline)) { 20720b57cec5SDimitry Andric // (noinline wins over always_inline, and we can't specify both in IR) 20730b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::AlwaysInline); 20740b57cec5SDimitry Andric } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { 20750b57cec5SDimitry Andric // If we're not inlining, then force everything that isn't always_inline to 20760b57cec5SDimitry Andric // carry an explicit noinline attribute. 20770b57cec5SDimitry Andric if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) 20780b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 20790b57cec5SDimitry Andric } else { 20800b57cec5SDimitry Andric // Otherwise, propagate the inline hint attribute and potentially use its 20810b57cec5SDimitry Andric // absence to mark things as noinline. 20820b57cec5SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) { 20830b57cec5SDimitry Andric // Search function and template pattern redeclarations for inline. 20840b57cec5SDimitry Andric auto CheckForInline = [](const FunctionDecl *FD) { 20850b57cec5SDimitry Andric auto CheckRedeclForInline = [](const FunctionDecl *Redecl) { 20860b57cec5SDimitry Andric return Redecl->isInlineSpecified(); 20870b57cec5SDimitry Andric }; 20880b57cec5SDimitry Andric if (any_of(FD->redecls(), CheckRedeclForInline)) 20890b57cec5SDimitry Andric return true; 20900b57cec5SDimitry Andric const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern(); 20910b57cec5SDimitry Andric if (!Pattern) 20920b57cec5SDimitry Andric return false; 20930b57cec5SDimitry Andric return any_of(Pattern->redecls(), CheckRedeclForInline); 20940b57cec5SDimitry Andric }; 20950b57cec5SDimitry Andric if (CheckForInline(FD)) { 20960b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::InlineHint); 20970b57cec5SDimitry Andric } else if (CodeGenOpts.getInlining() == 20980b57cec5SDimitry Andric CodeGenOptions::OnlyHintInlining && 20990b57cec5SDimitry Andric !FD->isInlined() && 21000b57cec5SDimitry Andric !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 21010b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 21020b57cec5SDimitry Andric } 21030b57cec5SDimitry Andric } 21040b57cec5SDimitry Andric } 21050b57cec5SDimitry Andric 21060b57cec5SDimitry Andric // Add other optimization related attributes if we are optimizing this 21070b57cec5SDimitry Andric // function. 21080b57cec5SDimitry Andric if (!D->hasAttr<OptimizeNoneAttr>()) { 21090b57cec5SDimitry Andric if (D->hasAttr<ColdAttr>()) { 21100b57cec5SDimitry Andric if (!ShouldAddOptNone) 21110b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::OptimizeForSize); 21120b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::Cold); 21130b57cec5SDimitry Andric } 2114e8d8bef9SDimitry Andric if (D->hasAttr<HotAttr>()) 2115e8d8bef9SDimitry Andric B.addAttribute(llvm::Attribute::Hot); 21160b57cec5SDimitry Andric if (D->hasAttr<MinSizeAttr>()) 21170b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::MinSize); 21180b57cec5SDimitry Andric } 21190b57cec5SDimitry Andric 2120349cc55cSDimitry Andric F->addFnAttrs(B); 21210b57cec5SDimitry Andric 21220b57cec5SDimitry Andric unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 21230b57cec5SDimitry Andric if (alignment) 2124a7dea167SDimitry Andric F->setAlignment(llvm::Align(alignment)); 21250b57cec5SDimitry Andric 21260b57cec5SDimitry Andric if (!D->hasAttr<AlignedAttr>()) 21270b57cec5SDimitry Andric if (LangOpts.FunctionAlignment) 2128a7dea167SDimitry Andric F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment)); 21290b57cec5SDimitry Andric 21300b57cec5SDimitry Andric // Some C++ ABIs require 2-byte alignment for member functions, in order to 21310b57cec5SDimitry Andric // reserve a bit for differentiating between virtual and non-virtual member 21320b57cec5SDimitry Andric // functions. If the current target's C++ ABI requires this and this is a 21330b57cec5SDimitry Andric // member function, set its alignment accordingly. 21340b57cec5SDimitry Andric if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 21350b57cec5SDimitry Andric if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 2136a7dea167SDimitry Andric F->setAlignment(llvm::Align(2)); 21370b57cec5SDimitry Andric } 21380b57cec5SDimitry 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) 21470b57cec5SDimitry Andric CreateFunctionTypeMetadataForIcall(FD, F); 2148a7dea167SDimitry Andric } 2149a7dea167SDimitry Andric } 21500b57cec5SDimitry Andric 21510b57cec5SDimitry Andric // Emit type metadata on member functions for member function pointer checks. 21520b57cec5SDimitry Andric // These are only ever necessary on definitions; we're guaranteed that the 21530b57cec5SDimitry Andric // definition will be present in the LTO unit as a result of LTO visibility. 21540b57cec5SDimitry Andric auto *MD = dyn_cast<CXXMethodDecl>(D); 21550b57cec5SDimitry Andric if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) { 21560b57cec5SDimitry Andric for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) { 21570b57cec5SDimitry Andric llvm::Metadata *Id = 21580b57cec5SDimitry Andric CreateMetadataIdentifierForType(Context.getMemberPointerType( 21590b57cec5SDimitry Andric MD->getType(), Context.getRecordType(Base).getTypePtr())); 21600b57cec5SDimitry Andric F->addTypeMetadata(0, Id); 21610b57cec5SDimitry Andric } 21620b57cec5SDimitry Andric } 21630b57cec5SDimitry Andric } 21640b57cec5SDimitry 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 21740b57cec5SDimitry Andric void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) { 21750b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 2176349cc55cSDimitry Andric if (isa_and_nonnull<NamedDecl>(D)) 21770b57cec5SDimitry Andric setGVProperties(GV, GD); 21780b57cec5SDimitry Andric else 21790b57cec5SDimitry Andric GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 21800b57cec5SDimitry Andric 21810b57cec5SDimitry Andric if (D && D->hasAttr<UsedAttr>()) 2182fe6060f1SDimitry Andric addUsedOrCompilerUsedGlobal(GV); 21830b57cec5SDimitry Andric 21840b57cec5SDimitry Andric if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) { 21850b57cec5SDimitry Andric const auto *VD = cast<VarDecl>(D); 21860b57cec5SDimitry Andric if (VD->getType().isConstQualified() && 21870b57cec5SDimitry Andric VD->getStorageDuration() == SD_Static) 2188fe6060f1SDimitry Andric addUsedOrCompilerUsedGlobal(GV); 21890b57cec5SDimitry Andric } 21900b57cec5SDimitry Andric } 21910b57cec5SDimitry Andric 21920b57cec5SDimitry Andric bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD, 21930b57cec5SDimitry Andric llvm::AttrBuilder &Attrs) { 21940b57cec5SDimitry Andric // Add target-cpu and target-features attributes to functions. If 21950b57cec5SDimitry Andric // we have a decl for the function and it has a target attribute then 21960b57cec5SDimitry Andric // parse that and add it to the feature set. 21970b57cec5SDimitry Andric StringRef TargetCPU = getTarget().getTargetOpts().CPU; 2198e8d8bef9SDimitry Andric StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU; 21990b57cec5SDimitry Andric std::vector<std::string> Features; 22000b57cec5SDimitry Andric const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl()); 22010b57cec5SDimitry Andric FD = FD ? FD->getMostRecentDecl() : FD; 22020b57cec5SDimitry Andric const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr; 2203*bdd1243dSDimitry Andric const auto *TV = FD ? FD->getAttr<TargetVersionAttr>() : nullptr; 2204*bdd1243dSDimitry Andric assert((!TD || !TV) && "both target_version and target specified"); 22050b57cec5SDimitry Andric const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr; 22064824e7fdSDimitry Andric const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr; 22070b57cec5SDimitry Andric bool AddedAttr = false; 2208*bdd1243dSDimitry Andric if (TD || TV || SD || TC) { 22090b57cec5SDimitry Andric llvm::StringMap<bool> FeatureMap; 2210480093f4SDimitry Andric getContext().getFunctionFeatureMap(FeatureMap, GD); 22110b57cec5SDimitry Andric 22120b57cec5SDimitry Andric // Produce the canonical string for this set of features. 22130b57cec5SDimitry Andric for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap) 22140b57cec5SDimitry Andric Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str()); 22150b57cec5SDimitry Andric 22160b57cec5SDimitry Andric // Now add the target-cpu and target-features to the function. 22170b57cec5SDimitry Andric // While we populated the feature map above, we still need to 22180b57cec5SDimitry Andric // get and parse the target attribute so we can get the cpu for 22190b57cec5SDimitry Andric // the function. 22200b57cec5SDimitry Andric if (TD) { 2221*bdd1243dSDimitry Andric ParsedTargetAttr ParsedAttr = 2222*bdd1243dSDimitry Andric Target.parseTargetAttr(TD->getFeaturesStr()); 2223*bdd1243dSDimitry Andric if (!ParsedAttr.CPU.empty() && 2224*bdd1243dSDimitry Andric getTarget().isValidCPUName(ParsedAttr.CPU)) { 2225*bdd1243dSDimitry 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; 22310b57cec5SDimitry 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 } 22390b57cec5SDimitry Andric } else { 22400b57cec5SDimitry Andric // Otherwise just add the existing target cpu and target features to the 22410b57cec5SDimitry Andric // function. 22420b57cec5SDimitry Andric Features = getTarget().getTargetOpts().Features; 22430b57cec5SDimitry Andric } 22440b57cec5SDimitry Andric 2245e8d8bef9SDimitry Andric if (!TargetCPU.empty()) { 22460b57cec5SDimitry Andric Attrs.addAttribute("target-cpu", TargetCPU); 22470b57cec5SDimitry Andric AddedAttr = true; 22480b57cec5SDimitry Andric } 2249e8d8bef9SDimitry Andric if (!TuneCPU.empty()) { 2250e8d8bef9SDimitry Andric Attrs.addAttribute("tune-cpu", TuneCPU); 2251e8d8bef9SDimitry Andric AddedAttr = true; 2252e8d8bef9SDimitry Andric } 22530b57cec5SDimitry Andric if (!Features.empty()) { 22540b57cec5SDimitry Andric llvm::sort(Features); 22550b57cec5SDimitry Andric Attrs.addAttribute("target-features", llvm::join(Features, ",")); 22560b57cec5SDimitry Andric AddedAttr = true; 22570b57cec5SDimitry Andric } 22580b57cec5SDimitry Andric 22590b57cec5SDimitry Andric return AddedAttr; 22600b57cec5SDimitry Andric } 22610b57cec5SDimitry Andric 22620b57cec5SDimitry Andric void CodeGenModule::setNonAliasAttributes(GlobalDecl GD, 22630b57cec5SDimitry Andric llvm::GlobalObject *GO) { 22640b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 22650b57cec5SDimitry Andric SetCommonAttributes(GD, GO); 22660b57cec5SDimitry Andric 22670b57cec5SDimitry Andric if (D) { 22680b57cec5SDimitry Andric if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) { 2269fe6060f1SDimitry Andric if (D->hasAttr<RetainAttr>()) 2270fe6060f1SDimitry Andric addUsedGlobal(GV); 22710b57cec5SDimitry Andric if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) 22720b57cec5SDimitry Andric GV->addAttribute("bss-section", SA->getName()); 22730b57cec5SDimitry Andric if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) 22740b57cec5SDimitry Andric GV->addAttribute("data-section", SA->getName()); 22750b57cec5SDimitry Andric if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) 22760b57cec5SDimitry Andric GV->addAttribute("rodata-section", SA->getName()); 2277a7dea167SDimitry Andric if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>()) 2278a7dea167SDimitry Andric GV->addAttribute("relro-section", SA->getName()); 22790b57cec5SDimitry Andric } 22800b57cec5SDimitry Andric 22810b57cec5SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(GO)) { 2282fe6060f1SDimitry Andric if (D->hasAttr<RetainAttr>()) 2283fe6060f1SDimitry Andric addUsedGlobal(F); 22840b57cec5SDimitry Andric if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) 22850b57cec5SDimitry Andric if (!D->getAttr<SectionAttr>()) 22860b57cec5SDimitry Andric F->addFnAttr("implicit-section-name", SA->getName()); 22870b57cec5SDimitry Andric 228804eeddc0SDimitry Andric llvm::AttrBuilder Attrs(F->getContext()); 22890b57cec5SDimitry Andric if (GetCPUAndFeaturesAttributes(GD, Attrs)) { 22900b57cec5SDimitry Andric // We know that GetCPUAndFeaturesAttributes will always have the 22910b57cec5SDimitry Andric // newest set, since it has the newest possible FunctionDecl, so the 22920b57cec5SDimitry 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); 22990b57cec5SDimitry Andric } 23000b57cec5SDimitry Andric } 23010b57cec5SDimitry Andric 23020b57cec5SDimitry Andric if (const auto *CSA = D->getAttr<CodeSegAttr>()) 23030b57cec5SDimitry Andric GO->setSection(CSA->getName()); 23040b57cec5SDimitry Andric else if (const auto *SA = D->getAttr<SectionAttr>()) 23050b57cec5SDimitry Andric GO->setSection(SA->getName()); 23060b57cec5SDimitry Andric } 23070b57cec5SDimitry Andric 23080b57cec5SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 23090b57cec5SDimitry Andric } 23100b57cec5SDimitry Andric 23110b57cec5SDimitry Andric void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD, 23120b57cec5SDimitry Andric llvm::Function *F, 23130b57cec5SDimitry Andric const CGFunctionInfo &FI) { 23140b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 2315fe6060f1SDimitry Andric SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false); 23160b57cec5SDimitry Andric SetLLVMFunctionAttributesForDefinition(D, F); 23170b57cec5SDimitry Andric 23180b57cec5SDimitry Andric F->setLinkage(llvm::Function::InternalLinkage); 23190b57cec5SDimitry Andric 23200b57cec5SDimitry Andric setNonAliasAttributes(GD, F); 23210b57cec5SDimitry Andric } 23220b57cec5SDimitry Andric 23230b57cec5SDimitry Andric static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) { 23240b57cec5SDimitry Andric // Set linkage and visibility in case we never see a definition. 23250b57cec5SDimitry Andric LinkageInfo LV = ND->getLinkageAndVisibility(); 23260b57cec5SDimitry Andric // Don't set internal linkage on declarations. 23270b57cec5SDimitry Andric // "extern_weak" is overloaded in LLVM; we probably should have 23280b57cec5SDimitry Andric // separate linkage types for this. 23290b57cec5SDimitry Andric if (isExternallyVisible(LV.getLinkage()) && 23300b57cec5SDimitry Andric (ND->hasAttr<WeakAttr>() || ND->isWeakImported())) 23310b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 23320b57cec5SDimitry Andric } 23330b57cec5SDimitry Andric 23340b57cec5SDimitry Andric void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, 23350b57cec5SDimitry Andric llvm::Function *F) { 23360b57cec5SDimitry Andric // Only if we are checking indirect calls. 23370b57cec5SDimitry Andric if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 23380b57cec5SDimitry Andric return; 23390b57cec5SDimitry Andric 23400b57cec5SDimitry Andric // Non-static class methods are handled via vtable or member function pointer 23410b57cec5SDimitry Andric // checks elsewhere. 23420b57cec5SDimitry Andric if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 23430b57cec5SDimitry Andric return; 23440b57cec5SDimitry Andric 23450b57cec5SDimitry Andric llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 23460b57cec5SDimitry Andric F->addTypeMetadata(0, MD); 23470b57cec5SDimitry Andric F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType())); 23480b57cec5SDimitry Andric 23490b57cec5SDimitry Andric // Emit a hash-based bit set entry for cross-DSO calls. 23500b57cec5SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 23510b57cec5SDimitry Andric if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 23520b57cec5SDimitry Andric F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 23530b57cec5SDimitry Andric } 23540b57cec5SDimitry Andric 2355*bdd1243dSDimitry Andric void CodeGenModule::setKCFIType(const FunctionDecl *FD, llvm::Function *F) { 2356*bdd1243dSDimitry Andric if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 2357*bdd1243dSDimitry Andric return; 2358*bdd1243dSDimitry Andric 2359*bdd1243dSDimitry Andric llvm::LLVMContext &Ctx = F->getContext(); 2360*bdd1243dSDimitry Andric llvm::MDBuilder MDB(Ctx); 2361*bdd1243dSDimitry Andric F->setMetadata(llvm::LLVMContext::MD_kcfi_type, 2362*bdd1243dSDimitry Andric llvm::MDNode::get( 2363*bdd1243dSDimitry Andric Ctx, MDB.createConstant(CreateKCFITypeId(FD->getType())))); 2364*bdd1243dSDimitry Andric } 2365*bdd1243dSDimitry Andric 2366*bdd1243dSDimitry Andric static bool allowKCFIIdentifier(StringRef Name) { 2367*bdd1243dSDimitry Andric // KCFI type identifier constants are only necessary for external assembly 2368*bdd1243dSDimitry Andric // functions, which means it's safe to skip unusual names. Subset of 2369*bdd1243dSDimitry Andric // MCAsmInfo::isAcceptableChar() and MCAsmInfoXCOFF::isAcceptableChar(). 2370*bdd1243dSDimitry Andric return llvm::all_of(Name, [](const char &C) { 2371*bdd1243dSDimitry Andric return llvm::isAlnum(C) || C == '_' || C == '.'; 2372*bdd1243dSDimitry Andric }); 2373*bdd1243dSDimitry Andric } 2374*bdd1243dSDimitry Andric 2375*bdd1243dSDimitry Andric void CodeGenModule::finalizeKCFITypes() { 2376*bdd1243dSDimitry Andric llvm::Module &M = getModule(); 2377*bdd1243dSDimitry Andric for (auto &F : M.functions()) { 2378*bdd1243dSDimitry Andric // Remove KCFI type metadata from non-address-taken local functions. 2379*bdd1243dSDimitry Andric bool AddressTaken = F.hasAddressTaken(); 2380*bdd1243dSDimitry Andric if (!AddressTaken && F.hasLocalLinkage()) 2381*bdd1243dSDimitry Andric F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type); 2382*bdd1243dSDimitry Andric 2383*bdd1243dSDimitry Andric // Generate a constant with the expected KCFI type identifier for all 2384*bdd1243dSDimitry Andric // address-taken function declarations to support annotating indirectly 2385*bdd1243dSDimitry Andric // called assembly functions. 2386*bdd1243dSDimitry Andric if (!AddressTaken || !F.isDeclaration()) 2387*bdd1243dSDimitry Andric continue; 2388*bdd1243dSDimitry Andric 2389*bdd1243dSDimitry Andric const llvm::ConstantInt *Type; 2390*bdd1243dSDimitry Andric if (const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type)) 2391*bdd1243dSDimitry Andric Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0)); 2392*bdd1243dSDimitry Andric else 2393*bdd1243dSDimitry Andric continue; 2394*bdd1243dSDimitry Andric 2395*bdd1243dSDimitry Andric StringRef Name = F.getName(); 2396*bdd1243dSDimitry Andric if (!allowKCFIIdentifier(Name)) 2397*bdd1243dSDimitry Andric continue; 2398*bdd1243dSDimitry Andric 2399*bdd1243dSDimitry Andric std::string Asm = (".weak __kcfi_typeid_" + Name + "\n.set __kcfi_typeid_" + 2400*bdd1243dSDimitry Andric Name + ", " + Twine(Type->getZExtValue()) + "\n") 2401*bdd1243dSDimitry Andric .str(); 2402*bdd1243dSDimitry Andric M.appendModuleInlineAsm(Asm); 2403*bdd1243dSDimitry Andric } 2404*bdd1243dSDimitry Andric } 2405*bdd1243dSDimitry Andric 24060b57cec5SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 24070b57cec5SDimitry Andric bool IsIncompleteFunction, 24080b57cec5SDimitry Andric bool IsThunk) { 24090b57cec5SDimitry Andric 24100b57cec5SDimitry Andric if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 24110b57cec5SDimitry Andric // If this is an intrinsic function, set the function's attributes 24120b57cec5SDimitry Andric // to the intrinsic's attributes. 24130b57cec5SDimitry Andric F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 24140b57cec5SDimitry Andric return; 24150b57cec5SDimitry Andric } 24160b57cec5SDimitry Andric 24170b57cec5SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 24180b57cec5SDimitry Andric 24190b57cec5SDimitry Andric if (!IsIncompleteFunction) 2420fe6060f1SDimitry Andric SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F, 2421fe6060f1SDimitry Andric IsThunk); 24220b57cec5SDimitry Andric 24230b57cec5SDimitry Andric // Add the Returned attribute for "this", except for iOS 5 and earlier 24240b57cec5SDimitry Andric // where substantial code, including the libstdc++ dylib, was compiled with 24250b57cec5SDimitry Andric // GCC and does not actually return "this". 24260b57cec5SDimitry Andric if (!IsThunk && getCXXABI().HasThisReturn(GD) && 24270b57cec5SDimitry Andric !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { 24280b57cec5SDimitry Andric assert(!F->arg_empty() && 24290b57cec5SDimitry Andric F->arg_begin()->getType() 24300b57cec5SDimitry Andric ->canLosslesslyBitCastTo(F->getReturnType()) && 24310b57cec5SDimitry Andric "unexpected this return"); 2432349cc55cSDimitry Andric F->addParamAttr(0, llvm::Attribute::Returned); 24330b57cec5SDimitry Andric } 24340b57cec5SDimitry Andric 24350b57cec5SDimitry Andric // Only a few attributes are set on declarations; these may later be 24360b57cec5SDimitry Andric // overridden by a definition. 24370b57cec5SDimitry Andric 24380b57cec5SDimitry Andric setLinkageForGV(F, FD); 24390b57cec5SDimitry Andric setGVProperties(F, FD); 24400b57cec5SDimitry Andric 24410b57cec5SDimitry Andric // Setup target-specific attributes. 24420b57cec5SDimitry Andric if (!IsIncompleteFunction && F->isDeclaration()) 24430b57cec5SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(FD, F, *this); 24440b57cec5SDimitry Andric 24450b57cec5SDimitry Andric if (const auto *CSA = FD->getAttr<CodeSegAttr>()) 24460b57cec5SDimitry Andric F->setSection(CSA->getName()); 24470b57cec5SDimitry Andric else if (const auto *SA = FD->getAttr<SectionAttr>()) 24480b57cec5SDimitry Andric F->setSection(SA->getName()); 24490b57cec5SDimitry 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 24680b57cec5SDimitry Andric if (FD->isReplaceableGlobalAllocationFunction()) { 24690b57cec5SDimitry Andric // A replaceable global allocation function does not act like a builtin by 24700b57cec5SDimitry Andric // default, only if it is invoked by a new-expression or delete-expression. 2471349cc55cSDimitry Andric F->addFnAttr(llvm::Attribute::NoBuiltin); 24720b57cec5SDimitry Andric } 24730b57cec5SDimitry Andric 24740b57cec5SDimitry Andric if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 24750b57cec5SDimitry Andric F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 24760b57cec5SDimitry Andric else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 24770b57cec5SDimitry Andric if (MD->isVirtual()) 24780b57cec5SDimitry Andric F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 24790b57cec5SDimitry Andric 24800b57cec5SDimitry 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) 24860b57cec5SDimitry Andric CreateFunctionTypeMetadataForIcall(FD, F); 24870b57cec5SDimitry Andric 2488*bdd1243dSDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) 2489*bdd1243dSDimitry Andric setKCFIType(FD, F); 2490*bdd1243dSDimitry Andric 24910b57cec5SDimitry Andric if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) 24920b57cec5SDimitry Andric getOpenMPRuntime().emitDeclareSimdFunction(FD, F); 24930b57cec5SDimitry Andric 2494*bdd1243dSDimitry Andric if (CodeGenOpts.InlineMaxStackSize != UINT_MAX) 2495*bdd1243dSDimitry Andric F->addFnAttr("inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize)); 2496*bdd1243dSDimitry Andric 24970b57cec5SDimitry Andric if (const auto *CB = FD->getAttr<CallbackAttr>()) { 24980b57cec5SDimitry Andric // Annotate the callback behavior as metadata: 24990b57cec5SDimitry Andric // - The callback callee (as argument number). 25000b57cec5SDimitry Andric // - The callback payloads (as argument numbers). 25010b57cec5SDimitry Andric llvm::LLVMContext &Ctx = F->getContext(); 25020b57cec5SDimitry Andric llvm::MDBuilder MDB(Ctx); 25030b57cec5SDimitry Andric 25040b57cec5SDimitry Andric // The payload indices are all but the first one in the encoding. The first 25050b57cec5SDimitry Andric // identifies the callback callee. 25060b57cec5SDimitry Andric int CalleeIdx = *CB->encoding_begin(); 25070b57cec5SDimitry Andric ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end()); 25080b57cec5SDimitry Andric F->addMetadata(llvm::LLVMContext::MD_callback, 25090b57cec5SDimitry Andric *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding( 25100b57cec5SDimitry Andric CalleeIdx, PayloadIndices, 25110b57cec5SDimitry Andric /* VarArgsArePassed */ false)})); 25120b57cec5SDimitry Andric } 25130b57cec5SDimitry Andric } 25140b57cec5SDimitry Andric 25150b57cec5SDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 2516e8d8bef9SDimitry Andric assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 25170b57cec5SDimitry Andric "Only globals with definition can force usage."); 25180b57cec5SDimitry Andric LLVMUsed.emplace_back(GV); 25190b57cec5SDimitry Andric } 25200b57cec5SDimitry Andric 25210b57cec5SDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 25220b57cec5SDimitry Andric assert(!GV->isDeclaration() && 25230b57cec5SDimitry Andric "Only globals with definition can force usage."); 25240b57cec5SDimitry Andric LLVMCompilerUsed.emplace_back(GV); 25250b57cec5SDimitry Andric } 25260b57cec5SDimitry 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 25360b57cec5SDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name, 25370b57cec5SDimitry Andric std::vector<llvm::WeakTrackingVH> &List) { 25380b57cec5SDimitry Andric // Don't create llvm.used if there is no need. 25390b57cec5SDimitry Andric if (List.empty()) 25400b57cec5SDimitry Andric return; 25410b57cec5SDimitry Andric 25420b57cec5SDimitry Andric // Convert List to what ConstantArray needs. 25430b57cec5SDimitry Andric SmallVector<llvm::Constant*, 8> UsedArray; 25440b57cec5SDimitry Andric UsedArray.resize(List.size()); 25450b57cec5SDimitry Andric for (unsigned i = 0, e = List.size(); i != e; ++i) { 25460b57cec5SDimitry Andric UsedArray[i] = 25470b57cec5SDimitry Andric llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 25480b57cec5SDimitry Andric cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 25490b57cec5SDimitry Andric } 25500b57cec5SDimitry Andric 25510b57cec5SDimitry Andric if (UsedArray.empty()) 25520b57cec5SDimitry Andric return; 25530b57cec5SDimitry Andric llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 25540b57cec5SDimitry Andric 25550b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 25560b57cec5SDimitry Andric CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 25570b57cec5SDimitry Andric llvm::ConstantArray::get(ATy, UsedArray), Name); 25580b57cec5SDimitry Andric 25590b57cec5SDimitry Andric GV->setSection("llvm.metadata"); 25600b57cec5SDimitry Andric } 25610b57cec5SDimitry Andric 25620b57cec5SDimitry Andric void CodeGenModule::emitLLVMUsed() { 25630b57cec5SDimitry Andric emitUsed(*this, "llvm.used", LLVMUsed); 25640b57cec5SDimitry Andric emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 25650b57cec5SDimitry Andric } 25660b57cec5SDimitry Andric 25670b57cec5SDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 25680b57cec5SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 25690b57cec5SDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 25700b57cec5SDimitry Andric } 25710b57cec5SDimitry Andric 25720b57cec5SDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 25730b57cec5SDimitry Andric llvm::SmallString<32> Opt; 25740b57cec5SDimitry Andric getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 2575480093f4SDimitry Andric if (Opt.empty()) 2576480093f4SDimitry Andric return; 25770b57cec5SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 25780b57cec5SDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 25790b57cec5SDimitry Andric } 25800b57cec5SDimitry Andric 25810b57cec5SDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) { 25820b57cec5SDimitry Andric auto &C = getLLVMContext(); 25830b57cec5SDimitry Andric if (getTarget().getTriple().isOSBinFormatELF()) { 25840b57cec5SDimitry Andric ELFDependentLibraries.push_back( 25850b57cec5SDimitry Andric llvm::MDNode::get(C, llvm::MDString::get(C, Lib))); 25860b57cec5SDimitry Andric return; 25870b57cec5SDimitry Andric } 25880b57cec5SDimitry Andric 25890b57cec5SDimitry Andric llvm::SmallString<24> Opt; 25900b57cec5SDimitry Andric getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 25910b57cec5SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 25920b57cec5SDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts)); 25930b57cec5SDimitry Andric } 25940b57cec5SDimitry Andric 25950b57cec5SDimitry Andric /// Add link options implied by the given module, including modules 25960b57cec5SDimitry Andric /// it depends on, using a postorder walk. 25970b57cec5SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 25980b57cec5SDimitry Andric SmallVectorImpl<llvm::MDNode *> &Metadata, 25990b57cec5SDimitry Andric llvm::SmallPtrSet<Module *, 16> &Visited) { 26000b57cec5SDimitry Andric // Import this module's parent. 26010b57cec5SDimitry Andric if (Mod->Parent && Visited.insert(Mod->Parent).second) { 26020b57cec5SDimitry Andric addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 26030b57cec5SDimitry Andric } 26040b57cec5SDimitry Andric 26050b57cec5SDimitry 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); 26090b57cec5SDimitry Andric } 26100b57cec5SDimitry Andric 26110b57cec5SDimitry Andric // Add linker options to link against the libraries/frameworks 26120b57cec5SDimitry Andric // described by this module. 26130b57cec5SDimitry Andric llvm::LLVMContext &Context = CGM.getLLVMContext(); 26140b57cec5SDimitry Andric bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF(); 26150b57cec5SDimitry Andric 26160b57cec5SDimitry Andric // For modules that use export_as for linking, use that module 26170b57cec5SDimitry Andric // name instead. 26180b57cec5SDimitry Andric if (Mod->UseExportAsModuleLinkName) 26190b57cec5SDimitry Andric return; 26200b57cec5SDimitry Andric 2621349cc55cSDimitry Andric for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) { 26220b57cec5SDimitry Andric // Link against a framework. Frameworks are currently Darwin only, so we 26230b57cec5SDimitry 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)}; 26270b57cec5SDimitry Andric 26280b57cec5SDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, Args)); 26290b57cec5SDimitry Andric continue; 26300b57cec5SDimitry Andric } 26310b57cec5SDimitry Andric 26320b57cec5SDimitry Andric // Link against a library. 26330b57cec5SDimitry Andric if (IsELF) { 26340b57cec5SDimitry Andric llvm::Metadata *Args[2] = { 26350b57cec5SDimitry Andric llvm::MDString::get(Context, "lib"), 2636349cc55cSDimitry Andric llvm::MDString::get(Context, LL.Library), 26370b57cec5SDimitry Andric }; 26380b57cec5SDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, Args)); 26390b57cec5SDimitry Andric } else { 26400b57cec5SDimitry Andric llvm::SmallString<24> Opt; 2641349cc55cSDimitry Andric CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt); 26420b57cec5SDimitry Andric auto *OptString = llvm::MDString::get(Context, Opt); 26430b57cec5SDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, OptString)); 26440b57cec5SDimitry Andric } 26450b57cec5SDimitry Andric } 26460b57cec5SDimitry Andric } 26470b57cec5SDimitry 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 26750b57cec5SDimitry Andric void CodeGenModule::EmitModuleLinkOptions() { 26760b57cec5SDimitry Andric // Collect the set of all of the modules we want to visit to emit link 26770b57cec5SDimitry Andric // options, which is essentially the imported modules and all of their 26780b57cec5SDimitry Andric // non-explicit child modules. 26790b57cec5SDimitry Andric llvm::SetVector<clang::Module *> LinkModules; 26800b57cec5SDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 26810b57cec5SDimitry Andric SmallVector<clang::Module *, 16> Stack; 26820b57cec5SDimitry Andric 26830b57cec5SDimitry Andric // Seed the stack with imported modules. 26840b57cec5SDimitry Andric for (Module *M : ImportedModules) { 26850b57cec5SDimitry Andric // Do not add any link flags when an implementation TU of a module imports 26860b57cec5SDimitry Andric // a header of that same module. 26870b57cec5SDimitry Andric if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && 26880b57cec5SDimitry Andric !getLangOpts().isCompilingModule()) 26890b57cec5SDimitry Andric continue; 26900b57cec5SDimitry Andric if (Visited.insert(M).second) 26910b57cec5SDimitry Andric Stack.push_back(M); 26920b57cec5SDimitry Andric } 26930b57cec5SDimitry Andric 26940b57cec5SDimitry Andric // Find all of the modules to import, making a little effort to prune 26950b57cec5SDimitry Andric // non-leaf modules. 26960b57cec5SDimitry Andric while (!Stack.empty()) { 26970b57cec5SDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 26980b57cec5SDimitry Andric 26990b57cec5SDimitry Andric bool AnyChildren = false; 27000b57cec5SDimitry Andric 27010b57cec5SDimitry Andric // Visit the submodules of this module. 27020b57cec5SDimitry Andric for (const auto &SM : Mod->submodules()) { 27030b57cec5SDimitry Andric // Skip explicit children; they need to be explicitly imported to be 27040b57cec5SDimitry Andric // linked against. 27050b57cec5SDimitry Andric if (SM->IsExplicit) 27060b57cec5SDimitry Andric continue; 27070b57cec5SDimitry Andric 27080b57cec5SDimitry Andric if (Visited.insert(SM).second) { 27090b57cec5SDimitry Andric Stack.push_back(SM); 27100b57cec5SDimitry Andric AnyChildren = true; 27110b57cec5SDimitry Andric } 27120b57cec5SDimitry Andric } 27130b57cec5SDimitry Andric 27140b57cec5SDimitry Andric // We didn't find any children, so add this module to the list of 27150b57cec5SDimitry Andric // modules to link against. 27160b57cec5SDimitry Andric if (!AnyChildren) { 27170b57cec5SDimitry Andric LinkModules.insert(Mod); 27180b57cec5SDimitry Andric } 27190b57cec5SDimitry Andric } 27200b57cec5SDimitry Andric 27210b57cec5SDimitry Andric // Add link options for all of the imported modules in reverse topological 27220b57cec5SDimitry Andric // order. We don't do anything to try to order import link flags with respect 27230b57cec5SDimitry Andric // to linker options inserted by things like #pragma comment(). 27240b57cec5SDimitry Andric SmallVector<llvm::MDNode *, 16> MetadataArgs; 27250b57cec5SDimitry Andric Visited.clear(); 27260b57cec5SDimitry Andric for (Module *M : LinkModules) 27270b57cec5SDimitry Andric if (Visited.insert(M).second) 27280b57cec5SDimitry Andric addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 27290b57cec5SDimitry Andric std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 27300b57cec5SDimitry Andric LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 27310b57cec5SDimitry Andric 27320b57cec5SDimitry Andric // Add the linker options metadata flag. 27330b57cec5SDimitry Andric auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options"); 27340b57cec5SDimitry Andric for (auto *MD : LinkerOptionsMetadata) 27350b57cec5SDimitry Andric NMD->addOperand(MD); 27360b57cec5SDimitry Andric } 27370b57cec5SDimitry Andric 27380b57cec5SDimitry Andric void CodeGenModule::EmitDeferred() { 27390b57cec5SDimitry Andric // Emit deferred declare target declarations. 27400b57cec5SDimitry Andric if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 27410b57cec5SDimitry Andric getOpenMPRuntime().emitDeferredTargetDecls(); 27420b57cec5SDimitry Andric 27430b57cec5SDimitry Andric // Emit code for any potentially referenced deferred decls. Since a 27440b57cec5SDimitry Andric // previously unused static decl may become used during the generation of code 27450b57cec5SDimitry Andric // for a static function, iterate until no changes are made. 27460b57cec5SDimitry Andric 27470b57cec5SDimitry Andric if (!DeferredVTables.empty()) { 27480b57cec5SDimitry Andric EmitDeferredVTables(); 27490b57cec5SDimitry Andric 27500b57cec5SDimitry Andric // Emitting a vtable doesn't directly cause more vtables to 27510b57cec5SDimitry Andric // become deferred, although it can cause functions to be 27520b57cec5SDimitry Andric // emitted that then need those vtables. 27530b57cec5SDimitry Andric assert(DeferredVTables.empty()); 27540b57cec5SDimitry Andric } 27550b57cec5SDimitry 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 27630b57cec5SDimitry Andric // Stop if we're out of both deferred vtables and deferred declarations. 27640b57cec5SDimitry Andric if (DeferredDeclsToEmit.empty()) 27650b57cec5SDimitry Andric return; 27660b57cec5SDimitry Andric 27670b57cec5SDimitry Andric // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 27680b57cec5SDimitry Andric // work, it will not interfere with this. 27690b57cec5SDimitry Andric std::vector<GlobalDecl> CurDeclsToEmit; 27700b57cec5SDimitry Andric CurDeclsToEmit.swap(DeferredDeclsToEmit); 27710b57cec5SDimitry Andric 27720b57cec5SDimitry Andric for (GlobalDecl &D : CurDeclsToEmit) { 27730b57cec5SDimitry Andric // We should call GetAddrOfGlobal with IsForDefinition set to true in order 27740b57cec5SDimitry Andric // to get GlobalValue with exactly the type we need, not something that 27750b57cec5SDimitry Andric // might had been created for another decl with the same mangled name but 27760b57cec5SDimitry Andric // different type. 27770b57cec5SDimitry Andric llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 27780b57cec5SDimitry Andric GetAddrOfGlobal(D, ForDefinition)); 27790b57cec5SDimitry Andric 27800b57cec5SDimitry Andric // In case of different address spaces, we may still get a cast, even with 27810b57cec5SDimitry Andric // IsForDefinition equal to true. Query mangled names table to get 27820b57cec5SDimitry Andric // GlobalValue. 27830b57cec5SDimitry Andric if (!GV) 27840b57cec5SDimitry Andric GV = GetGlobalValue(getMangledName(D)); 27850b57cec5SDimitry Andric 27860b57cec5SDimitry Andric // Make sure GetGlobalValue returned non-null. 27870b57cec5SDimitry Andric assert(GV); 27880b57cec5SDimitry Andric 27890b57cec5SDimitry Andric // Check to see if we've already emitted this. This is necessary 27900b57cec5SDimitry Andric // for a couple of reasons: first, decls can end up in the 27910b57cec5SDimitry Andric // deferred-decls queue multiple times, and second, decls can end 27920b57cec5SDimitry Andric // up with definitions in unusual ways (e.g. by an extern inline 27930b57cec5SDimitry Andric // function acquiring a strong function redefinition). Just 27940b57cec5SDimitry Andric // ignore these cases. 27950b57cec5SDimitry Andric if (!GV->isDeclaration()) 27960b57cec5SDimitry Andric continue; 27970b57cec5SDimitry 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 28020b57cec5SDimitry Andric // Otherwise, emit the definition and move on to the next one. 28030b57cec5SDimitry Andric EmitGlobalDefinition(D, GV); 28040b57cec5SDimitry Andric 28050b57cec5SDimitry Andric // If we found out that we need to emit more decls, do that recursively. 28060b57cec5SDimitry Andric // This has the advantage that the decls are emitted in a DFS and related 28070b57cec5SDimitry Andric // ones are close together, which is convenient for testing. 28080b57cec5SDimitry Andric if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 28090b57cec5SDimitry Andric EmitDeferred(); 28100b57cec5SDimitry Andric assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 28110b57cec5SDimitry Andric } 28120b57cec5SDimitry Andric } 28130b57cec5SDimitry Andric } 28140b57cec5SDimitry Andric 28150b57cec5SDimitry Andric void CodeGenModule::EmitVTablesOpportunistically() { 28160b57cec5SDimitry Andric // Try to emit external vtables as available_externally if they have emitted 28170b57cec5SDimitry Andric // all inlined virtual functions. It runs after EmitDeferred() and therefore 28180b57cec5SDimitry Andric // is not allowed to create new references to things that need to be emitted 28190b57cec5SDimitry Andric // lazily. Note that it also uses fact that we eagerly emitting RTTI. 28200b57cec5SDimitry Andric 28210b57cec5SDimitry Andric assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) 28220b57cec5SDimitry Andric && "Only emit opportunistic vtables with optimizations"); 28230b57cec5SDimitry Andric 28240b57cec5SDimitry Andric for (const CXXRecordDecl *RD : OpportunisticVTables) { 28250b57cec5SDimitry Andric assert(getVTables().isVTableExternal(RD) && 28260b57cec5SDimitry Andric "This queue should only contain external vtables"); 28270b57cec5SDimitry Andric if (getCXXABI().canSpeculativelyEmitVTable(RD)) 28280b57cec5SDimitry Andric VTables.GenerateClassData(RD); 28290b57cec5SDimitry Andric } 28300b57cec5SDimitry Andric OpportunisticVTables.clear(); 28310b57cec5SDimitry Andric } 28320b57cec5SDimitry Andric 28330b57cec5SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() { 28340b57cec5SDimitry Andric if (Annotations.empty()) 28350b57cec5SDimitry Andric return; 28360b57cec5SDimitry Andric 28370b57cec5SDimitry Andric // Create a new global variable for the ConstantStruct in the Module. 28380b57cec5SDimitry Andric llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 28390b57cec5SDimitry Andric Annotations[0]->getType(), Annotations.size()), Annotations); 28400b57cec5SDimitry Andric auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 28410b57cec5SDimitry Andric llvm::GlobalValue::AppendingLinkage, 28420b57cec5SDimitry Andric Array, "llvm.global.annotations"); 28430b57cec5SDimitry Andric gv->setSection(AnnotationSection); 28440b57cec5SDimitry Andric } 28450b57cec5SDimitry Andric 28460b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 28470b57cec5SDimitry Andric llvm::Constant *&AStr = AnnotationStrings[Str]; 28480b57cec5SDimitry Andric if (AStr) 28490b57cec5SDimitry Andric return AStr; 28500b57cec5SDimitry Andric 28510b57cec5SDimitry Andric // Not found yet, create a new global. 28520b57cec5SDimitry Andric llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 2853*bdd1243dSDimitry Andric auto *gv = new llvm::GlobalVariable( 2854*bdd1243dSDimitry Andric getModule(), s->getType(), true, llvm::GlobalValue::PrivateLinkage, s, 2855*bdd1243dSDimitry Andric ".str", nullptr, llvm::GlobalValue::NotThreadLocal, 2856*bdd1243dSDimitry Andric ConstGlobalsPtrTy->getAddressSpace()); 28570b57cec5SDimitry Andric gv->setSection(AnnotationSection); 28580b57cec5SDimitry Andric gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 28590b57cec5SDimitry Andric AStr = gv; 28600b57cec5SDimitry Andric return gv; 28610b57cec5SDimitry Andric } 28620b57cec5SDimitry Andric 28630b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 28640b57cec5SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 28650b57cec5SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(Loc); 28660b57cec5SDimitry Andric if (PLoc.isValid()) 28670b57cec5SDimitry Andric return EmitAnnotationString(PLoc.getFilename()); 28680b57cec5SDimitry Andric return EmitAnnotationString(SM.getBufferName(Loc)); 28690b57cec5SDimitry Andric } 28700b57cec5SDimitry Andric 28710b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 28720b57cec5SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 28730b57cec5SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(L); 28740b57cec5SDimitry Andric unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 28750b57cec5SDimitry Andric SM.getExpansionLineNumber(L); 28760b57cec5SDimitry Andric return llvm::ConstantInt::get(Int32Ty, LineNo); 28770b57cec5SDimitry Andric } 28780b57cec5SDimitry 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()) 2882*bdd1243dSDimitry 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 29120b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 29130b57cec5SDimitry Andric const AnnotateAttr *AA, 29140b57cec5SDimitry Andric SourceLocation L) { 29150b57cec5SDimitry Andric // Get the globals for file name, annotation, and the line number. 29160b57cec5SDimitry Andric llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 29170b57cec5SDimitry Andric *UnitGV = EmitAnnotationUnit(L), 2918e8d8bef9SDimitry Andric *LineNoCst = EmitAnnotationLineNo(L), 2919e8d8bef9SDimitry Andric *Args = EmitAnnotationArgs(AA); 29200b57cec5SDimitry 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 29290b57cec5SDimitry Andric // Create the ConstantStruct for the global annotation. 2930e8d8bef9SDimitry Andric llvm::Constant *Fields[] = { 2931349cc55cSDimitry Andric llvm::ConstantExpr::getBitCast(GVInGlobalsAS, GlobalsInt8PtrTy), 2932*bdd1243dSDimitry Andric llvm::ConstantExpr::getBitCast(AnnoGV, ConstGlobalsPtrTy), 2933*bdd1243dSDimitry Andric llvm::ConstantExpr::getBitCast(UnitGV, ConstGlobalsPtrTy), 2934e8d8bef9SDimitry Andric LineNoCst, 2935e8d8bef9SDimitry Andric Args, 29360b57cec5SDimitry Andric }; 29370b57cec5SDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 29380b57cec5SDimitry Andric } 29390b57cec5SDimitry Andric 29400b57cec5SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 29410b57cec5SDimitry Andric llvm::GlobalValue *GV) { 29420b57cec5SDimitry Andric assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 29430b57cec5SDimitry Andric // Get the struct elements for these annotations. 29440b57cec5SDimitry Andric for (const auto *I : D->specific_attrs<AnnotateAttr>()) 29450b57cec5SDimitry Andric Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 29460b57cec5SDimitry Andric } 29470b57cec5SDimitry Andric 2948fe6060f1SDimitry Andric bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, 29490b57cec5SDimitry 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())) 29530b57cec5SDimitry 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. 29610b57cec5SDimitry Andric if (Loc.isValid()) 2962fe6060f1SDimitry Andric return NoSanitizeL.containsLocation(Kind, Loc); 29630b57cec5SDimitry Andric // If location is unknown, this may be a compiler-generated function. Assume 29640b57cec5SDimitry Andric // it's located in the main file. 2965fcaf7f86SDimitry Andric return NoSanitizeL.containsFile(Kind, MainFile.getName()); 29660b57cec5SDimitry Andric } 29670b57cec5SDimitry Andric 296881ad6265SDimitry Andric bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, 296981ad6265SDimitry Andric llvm::GlobalVariable *GV, 29700b57cec5SDimitry Andric SourceLocation Loc, QualType Ty, 29710b57cec5SDimitry Andric StringRef Category) const { 2972fe6060f1SDimitry Andric const auto &NoSanitizeL = getContext().getNoSanitizeList(); 297381ad6265SDimitry Andric if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category)) 29740b57cec5SDimitry 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)) 29800b57cec5SDimitry Andric return true; 2981fcaf7f86SDimitry Andric 29820b57cec5SDimitry Andric // Check global type. 29830b57cec5SDimitry Andric if (!Ty.isNull()) { 29840b57cec5SDimitry 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. 29860b57cec5SDimitry Andric while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 29870b57cec5SDimitry Andric Ty = AT->getElementType(); 29880b57cec5SDimitry Andric Ty = Ty.getCanonicalType().getUnqualifiedType(); 2989fe6060f1SDimitry Andric // Only record types (classes, structs etc.) are ignored. 29900b57cec5SDimitry Andric if (Ty->isRecordType()) { 29910b57cec5SDimitry Andric std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 299281ad6265SDimitry Andric if (NoSanitizeL.containsType(Kind, TypeStr, Category)) 29930b57cec5SDimitry Andric return true; 29940b57cec5SDimitry Andric } 29950b57cec5SDimitry Andric } 29960b57cec5SDimitry Andric return false; 29970b57cec5SDimitry Andric } 29980b57cec5SDimitry Andric 29990b57cec5SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 30000b57cec5SDimitry Andric StringRef Category) const { 30010b57cec5SDimitry Andric const auto &XRayFilter = getContext().getXRayFilter(); 30020b57cec5SDimitry Andric using ImbueAttr = XRayFunctionFilter::ImbueAttribute; 30030b57cec5SDimitry Andric auto Attr = ImbueAttr::NONE; 30040b57cec5SDimitry Andric if (Loc.isValid()) 30050b57cec5SDimitry Andric Attr = XRayFilter.shouldImbueLocation(Loc, Category); 30060b57cec5SDimitry Andric if (Attr == ImbueAttr::NONE) 30070b57cec5SDimitry Andric Attr = XRayFilter.shouldImbueFunction(Fn->getName()); 30080b57cec5SDimitry Andric switch (Attr) { 30090b57cec5SDimitry Andric case ImbueAttr::NONE: 30100b57cec5SDimitry Andric return false; 30110b57cec5SDimitry Andric case ImbueAttr::ALWAYS: 30120b57cec5SDimitry Andric Fn->addFnAttr("function-instrument", "xray-always"); 30130b57cec5SDimitry Andric break; 30140b57cec5SDimitry Andric case ImbueAttr::ALWAYS_ARG1: 30150b57cec5SDimitry Andric Fn->addFnAttr("function-instrument", "xray-always"); 30160b57cec5SDimitry Andric Fn->addFnAttr("xray-log-args", "1"); 30170b57cec5SDimitry Andric break; 30180b57cec5SDimitry Andric case ImbueAttr::NEVER: 30190b57cec5SDimitry Andric Fn->addFnAttr("function-instrument", "xray-never"); 30200b57cec5SDimitry Andric break; 30210b57cec5SDimitry Andric } 30220b57cec5SDimitry Andric return true; 30230b57cec5SDimitry Andric } 30240b57cec5SDimitry Andric 3025*bdd1243dSDimitry Andric ProfileList::ExclusionType 3026*bdd1243dSDimitry 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()) 3031*bdd1243dSDimitry Andric return ProfileList::Allow; 3032e8d8bef9SDimitry Andric CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr(); 3033e8d8bef9SDimitry Andric // First, check the function name. 3034*bdd1243dSDimitry Andric if (auto V = ProfileList.isFunctionExcluded(Fn->getName(), Kind)) 3035e8d8bef9SDimitry Andric return *V; 3036e8d8bef9SDimitry Andric // Next, check the source location. 3037*bdd1243dSDimitry Andric if (Loc.isValid()) 3038*bdd1243dSDimitry 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(); 3043*bdd1243dSDimitry Andric if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) 3044*bdd1243dSDimitry Andric if (auto V = ProfileList.isFileExcluded(MainFile->getName(), Kind)) 3045e8d8bef9SDimitry Andric return *V; 3046*bdd1243dSDimitry Andric return ProfileList.getDefault(Kind); 3047e8d8bef9SDimitry Andric } 3048e8d8bef9SDimitry Andric 3049*bdd1243dSDimitry Andric ProfileList::ExclusionType 3050*bdd1243dSDimitry Andric CodeGenModule::isFunctionBlockedFromProfileInstr(llvm::Function *Fn, 3051*bdd1243dSDimitry Andric SourceLocation Loc) const { 3052*bdd1243dSDimitry Andric auto V = isFunctionBlockedByProfileList(Fn, Loc); 3053*bdd1243dSDimitry Andric if (V != ProfileList::Allow) 3054*bdd1243dSDimitry 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) 3060*bdd1243dSDimitry Andric return ProfileList::Skip; 3061fcaf7f86SDimitry Andric } 3062*bdd1243dSDimitry Andric return ProfileList::Allow; 3063fcaf7f86SDimitry Andric } 3064fcaf7f86SDimitry Andric 30650b57cec5SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 30660b57cec5SDimitry Andric // Never defer when EmitAllDecls is specified. 30670b57cec5SDimitry Andric if (LangOpts.EmitAllDecls) 30680b57cec5SDimitry Andric return true; 30690b57cec5SDimitry Andric 30700b57cec5SDimitry Andric if (CodeGenOpts.KeepStaticConsts) { 30710b57cec5SDimitry Andric const auto *VD = dyn_cast<VarDecl>(Global); 30720b57cec5SDimitry Andric if (VD && VD->getType().isConstQualified() && 30730b57cec5SDimitry Andric VD->getStorageDuration() == SD_Static) 30740b57cec5SDimitry Andric return true; 30750b57cec5SDimitry Andric } 30760b57cec5SDimitry Andric 30770b57cec5SDimitry Andric return getContext().DeclMustBeEmitted(Global); 30780b57cec5SDimitry Andric } 30790b57cec5SDimitry Andric 30800b57cec5SDimitry 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) { 3088*bdd1243dSDimitry 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)) { 30950b57cec5SDimitry Andric if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 30960b57cec5SDimitry Andric // Implicit template instantiations may change linkage if they are later 30970b57cec5SDimitry Andric // explicitly instantiated, so they should not be emitted eagerly. 30980b57cec5SDimitry Andric return false; 3099a7dea167SDimitry Andric } 3100fcaf7f86SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(Global)) { 31010b57cec5SDimitry Andric if (Context.getInlineVariableDefinitionKind(VD) == 31020b57cec5SDimitry Andric ASTContext::InlineVariableDefinitionKind::WeakUnknown) 31030b57cec5SDimitry Andric // A definition of an inline constexpr static data member may change 31040b57cec5SDimitry Andric // linkage later if it's redeclared outside the class. 31050b57cec5SDimitry 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 } 31140b57cec5SDimitry Andric // If OpenMP is enabled and threadprivates must be generated like TLS, delay 31150b57cec5SDimitry Andric // codegen for global variables, because they may be marked as threadprivate. 31160b57cec5SDimitry Andric if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 31170b57cec5SDimitry Andric getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) && 31180b57cec5SDimitry Andric !isTypeConstant(Global->getType(), false) && 31190b57cec5SDimitry Andric !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global)) 31200b57cec5SDimitry Andric return false; 31210b57cec5SDimitry Andric 31220b57cec5SDimitry Andric return true; 31230b57cec5SDimitry Andric } 31240b57cec5SDimitry Andric 31255ffd83dbSDimitry Andric ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) { 31265ffd83dbSDimitry Andric StringRef Name = getMangledName(GD); 31270b57cec5SDimitry Andric 31280b57cec5SDimitry Andric // The UUID descriptor should be pointer aligned. 31290b57cec5SDimitry Andric CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 31300b57cec5SDimitry Andric 31310b57cec5SDimitry Andric // Look for an existing global. 31320b57cec5SDimitry Andric if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 31330eae32dcSDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 31340b57cec5SDimitry 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 } 31590b57cec5SDimitry Andric 31600b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 31610b57cec5SDimitry Andric getModule(), Init->getType(), 31620b57cec5SDimitry Andric /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 31630b57cec5SDimitry Andric if (supportsCOMDAT()) 31640b57cec5SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 31650b57cec5SDimitry 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); 31760b57cec5SDimitry Andric } 31770b57cec5SDimitry 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 32360b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 32370b57cec5SDimitry Andric const AliasAttr *AA = VD->getAttr<AliasAttr>(); 32380b57cec5SDimitry Andric assert(AA && "No alias?"); 32390b57cec5SDimitry Andric 32400b57cec5SDimitry Andric CharUnits Alignment = getContext().getDeclAlign(VD); 32410b57cec5SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 32420b57cec5SDimitry Andric 32430b57cec5SDimitry Andric // See if there is already something with the target's name in the module. 32440b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 32450b57cec5SDimitry Andric if (Entry) { 3246*bdd1243dSDimitry Andric unsigned AS = getTypes().getTargetAddressSpace(VD->getType()); 32470b57cec5SDimitry Andric auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 32480eae32dcSDimitry Andric return ConstantAddress(Ptr, DeclTy, Alignment); 32490b57cec5SDimitry Andric } 32500b57cec5SDimitry Andric 32510b57cec5SDimitry Andric llvm::Constant *Aliasee; 32520b57cec5SDimitry Andric if (isa<llvm::FunctionType>(DeclTy)) 32530b57cec5SDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 32540b57cec5SDimitry Andric GlobalDecl(cast<FunctionDecl>(VD)), 32550b57cec5SDimitry Andric /*ForVTable=*/false); 32560b57cec5SDimitry Andric else 3257349cc55cSDimitry Andric Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 3258349cc55cSDimitry Andric nullptr); 32590b57cec5SDimitry Andric 32600b57cec5SDimitry Andric auto *F = cast<llvm::GlobalValue>(Aliasee); 32610b57cec5SDimitry Andric F->setLinkage(llvm::Function::ExternalWeakLinkage); 32620b57cec5SDimitry Andric WeakRefReferences.insert(F); 32630b57cec5SDimitry Andric 32640eae32dcSDimitry Andric return ConstantAddress(Aliasee, DeclTy, Alignment); 32650b57cec5SDimitry Andric } 32660b57cec5SDimitry Andric 32670b57cec5SDimitry Andric void CodeGenModule::EmitGlobal(GlobalDecl GD) { 32680b57cec5SDimitry Andric const auto *Global = cast<ValueDecl>(GD.getDecl()); 32690b57cec5SDimitry Andric 32700b57cec5SDimitry Andric // Weak references don't produce any output by themselves. 32710b57cec5SDimitry Andric if (Global->hasAttr<WeakRefAttr>()) 32720b57cec5SDimitry Andric return; 32730b57cec5SDimitry Andric 32740b57cec5SDimitry Andric // If this is an alias definition (which otherwise looks like a declaration) 32750b57cec5SDimitry Andric // emit it now. 32760b57cec5SDimitry Andric if (Global->hasAttr<AliasAttr>()) 32770b57cec5SDimitry Andric return EmitAliasDefinition(GD); 32780b57cec5SDimitry Andric 32790b57cec5SDimitry Andric // IFunc like an alias whose value is resolved at runtime by calling resolver. 32800b57cec5SDimitry Andric if (Global->hasAttr<IFuncAttr>()) 32810b57cec5SDimitry Andric return emitIFuncDefinition(GD); 32820b57cec5SDimitry Andric 32830b57cec5SDimitry Andric // If this is a cpu_dispatch multiversion function, emit the resolver. 32840b57cec5SDimitry Andric if (Global->hasAttr<CPUDispatchAttr>()) 32850b57cec5SDimitry Andric return emitCPUDispatchDefinition(GD); 32860b57cec5SDimitry Andric 32870b57cec5SDimitry Andric // If this is CUDA, be selective about which declarations we emit. 32880b57cec5SDimitry Andric if (LangOpts.CUDA) { 32890b57cec5SDimitry Andric if (LangOpts.CUDAIsDevice) { 32900b57cec5SDimitry Andric if (!Global->hasAttr<CUDADeviceAttr>() && 32910b57cec5SDimitry Andric !Global->hasAttr<CUDAGlobalAttr>() && 32920b57cec5SDimitry Andric !Global->hasAttr<CUDAConstantAttr>() && 32930b57cec5SDimitry Andric !Global->hasAttr<CUDASharedAttr>() && 32945ffd83dbSDimitry Andric !Global->getType()->isCUDADeviceBuiltinSurfaceType() && 32955ffd83dbSDimitry Andric !Global->getType()->isCUDADeviceBuiltinTextureType()) 32960b57cec5SDimitry Andric return; 32970b57cec5SDimitry Andric } else { 32980b57cec5SDimitry Andric // We need to emit host-side 'shadows' for all global 32990b57cec5SDimitry Andric // device-side variables because the CUDA runtime needs their 33000b57cec5SDimitry Andric // size and host-side address in order to provide access to 33010b57cec5SDimitry Andric // their device-side incarnations. 33020b57cec5SDimitry Andric 33030b57cec5SDimitry Andric // So device-only functions are the only things we skip. 33040b57cec5SDimitry Andric if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 33050b57cec5SDimitry Andric Global->hasAttr<CUDADeviceAttr>()) 33060b57cec5SDimitry Andric return; 33070b57cec5SDimitry Andric 33080b57cec5SDimitry Andric assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 33090b57cec5SDimitry Andric "Expected Variable or Function"); 33100b57cec5SDimitry Andric } 33110b57cec5SDimitry Andric } 33120b57cec5SDimitry Andric 33130b57cec5SDimitry Andric if (LangOpts.OpenMP) { 3314a7dea167SDimitry Andric // If this is OpenMP, check if it is legal to emit this global normally. 33150b57cec5SDimitry Andric if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 33160b57cec5SDimitry Andric return; 33170b57cec5SDimitry Andric if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 33180b57cec5SDimitry Andric if (MustBeEmitted(Global)) 33190b57cec5SDimitry Andric EmitOMPDeclareReduction(DRD); 33200b57cec5SDimitry Andric return; 33210b57cec5SDimitry Andric } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) { 33220b57cec5SDimitry Andric if (MustBeEmitted(Global)) 33230b57cec5SDimitry Andric EmitOMPDeclareMapper(DMD); 33240b57cec5SDimitry Andric return; 33250b57cec5SDimitry Andric } 33260b57cec5SDimitry Andric } 33270b57cec5SDimitry Andric 33280b57cec5SDimitry Andric // Ignore declarations, they will be emitted on their first use. 33290b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 33300b57cec5SDimitry Andric // Forward declarations are emitted lazily on first use. 33310b57cec5SDimitry Andric if (!FD->doesThisDeclarationHaveABody()) { 33320b57cec5SDimitry Andric if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 33330b57cec5SDimitry Andric return; 33340b57cec5SDimitry Andric 33350b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 33360b57cec5SDimitry Andric 33370b57cec5SDimitry Andric // Compute the function info and LLVM type. 33380b57cec5SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 33390b57cec5SDimitry Andric llvm::Type *Ty = getTypes().GetFunctionType(FI); 33400b57cec5SDimitry Andric 33410b57cec5SDimitry Andric GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 33420b57cec5SDimitry Andric /*DontDefer=*/false); 33430b57cec5SDimitry Andric return; 33440b57cec5SDimitry Andric } 33450b57cec5SDimitry Andric } else { 33460b57cec5SDimitry Andric const auto *VD = cast<VarDecl>(Global); 33470b57cec5SDimitry Andric assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 33480b57cec5SDimitry Andric if (VD->isThisDeclarationADefinition() != VarDecl::Definition && 33490b57cec5SDimitry Andric !Context.isMSStaticDataMemberInlineDefinition(VD)) { 33500b57cec5SDimitry Andric if (LangOpts.OpenMP) { 33510b57cec5SDimitry Andric // Emit declaration of the must-be-emitted declare target variable. 3352*bdd1243dSDimitry Andric if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 33530b57cec5SDimitry Andric OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 33540b57cec5SDimitry Andric bool UnifiedMemoryEnabled = 33550b57cec5SDimitry Andric getOpenMPRuntime().hasRequiresUnifiedSharedMemory(); 3356*bdd1243dSDimitry Andric if ((*Res == OMPDeclareTargetDeclAttr::MT_To || 3357*bdd1243dSDimitry Andric *Res == OMPDeclareTargetDeclAttr::MT_Enter) && 33580b57cec5SDimitry Andric !UnifiedMemoryEnabled) { 33590b57cec5SDimitry Andric (void)GetAddrOfGlobalVar(VD); 33600b57cec5SDimitry Andric } else { 33610b57cec5SDimitry Andric assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) || 3362*bdd1243dSDimitry Andric ((*Res == OMPDeclareTargetDeclAttr::MT_To || 3363*bdd1243dSDimitry Andric *Res == OMPDeclareTargetDeclAttr::MT_Enter) && 33640b57cec5SDimitry Andric UnifiedMemoryEnabled)) && 33650b57cec5SDimitry Andric "Link clause or to clause with unified memory expected."); 33660b57cec5SDimitry Andric (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD); 33670b57cec5SDimitry Andric } 33680b57cec5SDimitry Andric 33690b57cec5SDimitry Andric return; 33700b57cec5SDimitry Andric } 33710b57cec5SDimitry Andric } 33720b57cec5SDimitry Andric // If this declaration may have caused an inline variable definition to 33730b57cec5SDimitry Andric // change linkage, make sure that it's emitted. 33740b57cec5SDimitry Andric if (Context.getInlineVariableDefinitionKind(VD) == 33750b57cec5SDimitry Andric ASTContext::InlineVariableDefinitionKind::Strong) 33760b57cec5SDimitry Andric GetAddrOfGlobalVar(VD); 33770b57cec5SDimitry Andric return; 33780b57cec5SDimitry Andric } 33790b57cec5SDimitry Andric } 33800b57cec5SDimitry Andric 33810b57cec5SDimitry Andric // Defer code generation to first use when possible, e.g. if this is an inline 33820b57cec5SDimitry Andric // function. If the global must always be emitted, do it eagerly if possible 33830b57cec5SDimitry Andric // to benefit from cache locality. 33840b57cec5SDimitry Andric if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 33850b57cec5SDimitry Andric // Emit the definition if it can't be deferred. 33860b57cec5SDimitry Andric EmitGlobalDefinition(GD); 33870b57cec5SDimitry Andric return; 33880b57cec5SDimitry Andric } 33890b57cec5SDimitry Andric 33900b57cec5SDimitry Andric // If we're deferring emission of a C++ variable with an 33910b57cec5SDimitry Andric // initializer, remember the order in which it appeared in the file. 33920b57cec5SDimitry Andric if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 33930b57cec5SDimitry Andric cast<VarDecl>(Global)->hasInit()) { 33940b57cec5SDimitry Andric DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 33950b57cec5SDimitry Andric CXXGlobalInits.push_back(nullptr); 33960b57cec5SDimitry Andric } 33970b57cec5SDimitry Andric 33980b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 33990b57cec5SDimitry Andric if (GetGlobalValue(MangledName) != nullptr) { 34000b57cec5SDimitry Andric // The value has already been used and should therefore be emitted. 34010b57cec5SDimitry Andric addDeferredDeclToEmit(GD); 34020b57cec5SDimitry Andric } else if (MustBeEmitted(Global)) { 34030b57cec5SDimitry Andric // The value must be emitted, but cannot be emitted eagerly. 34040b57cec5SDimitry Andric assert(!MayBeEmittedEagerly(Global)); 34050b57cec5SDimitry Andric addDeferredDeclToEmit(GD); 3406*bdd1243dSDimitry Andric EmittedDeferredDecls[MangledName] = GD; 34070b57cec5SDimitry Andric } else { 34080b57cec5SDimitry Andric // Otherwise, remember that we saw a deferred decl with this name. The 34090b57cec5SDimitry Andric // first use of the mangled name will cause it to move into 34100b57cec5SDimitry Andric // DeferredDeclsToEmit. 34110b57cec5SDimitry Andric DeferredDecls[MangledName] = GD; 34120b57cec5SDimitry Andric } 34130b57cec5SDimitry Andric } 34140b57cec5SDimitry Andric 34150b57cec5SDimitry Andric // Check if T is a class type with a destructor that's not dllimport. 34160b57cec5SDimitry Andric static bool HasNonDllImportDtor(QualType T) { 34170b57cec5SDimitry Andric if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) 34180b57cec5SDimitry Andric if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 34190b57cec5SDimitry Andric if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) 34200b57cec5SDimitry Andric return true; 34210b57cec5SDimitry Andric 34220b57cec5SDimitry Andric return false; 34230b57cec5SDimitry Andric } 34240b57cec5SDimitry Andric 34250b57cec5SDimitry Andric namespace { 34260b57cec5SDimitry Andric struct FunctionIsDirectlyRecursive 34270b57cec5SDimitry Andric : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> { 34280b57cec5SDimitry Andric const StringRef Name; 34290b57cec5SDimitry Andric const Builtin::Context &BI; 34300b57cec5SDimitry Andric FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) 34310b57cec5SDimitry Andric : Name(N), BI(C) {} 34320b57cec5SDimitry Andric 34330b57cec5SDimitry Andric bool VisitCallExpr(const CallExpr *E) { 34340b57cec5SDimitry Andric const FunctionDecl *FD = E->getDirectCallee(); 34350b57cec5SDimitry Andric if (!FD) 34360b57cec5SDimitry Andric return false; 34370b57cec5SDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 34380b57cec5SDimitry Andric if (Attr && Name == Attr->getLabel()) 34390b57cec5SDimitry Andric return true; 34400b57cec5SDimitry Andric unsigned BuiltinID = FD->getBuiltinID(); 34410b57cec5SDimitry Andric if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 34420b57cec5SDimitry Andric return false; 34430b57cec5SDimitry Andric StringRef BuiltinName = BI.getName(BuiltinID); 34440b57cec5SDimitry Andric if (BuiltinName.startswith("__builtin_") && 34450b57cec5SDimitry Andric Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 34460b57cec5SDimitry Andric return true; 34470b57cec5SDimitry Andric } 34480b57cec5SDimitry Andric return false; 34490b57cec5SDimitry Andric } 34500b57cec5SDimitry Andric 34510b57cec5SDimitry Andric bool VisitStmt(const Stmt *S) { 34520b57cec5SDimitry Andric for (const Stmt *Child : S->children()) 34530b57cec5SDimitry Andric if (Child && this->Visit(Child)) 34540b57cec5SDimitry Andric return true; 34550b57cec5SDimitry Andric return false; 34560b57cec5SDimitry Andric } 34570b57cec5SDimitry Andric }; 34580b57cec5SDimitry Andric 34590b57cec5SDimitry Andric // Make sure we're not referencing non-imported vars or functions. 34600b57cec5SDimitry Andric struct DLLImportFunctionVisitor 34610b57cec5SDimitry Andric : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 34620b57cec5SDimitry Andric bool SafeToInline = true; 34630b57cec5SDimitry Andric 34640b57cec5SDimitry Andric bool shouldVisitImplicitCode() const { return true; } 34650b57cec5SDimitry Andric 34660b57cec5SDimitry Andric bool VisitVarDecl(VarDecl *VD) { 34670b57cec5SDimitry Andric if (VD->getTLSKind()) { 34680b57cec5SDimitry Andric // A thread-local variable cannot be imported. 34690b57cec5SDimitry Andric SafeToInline = false; 34700b57cec5SDimitry Andric return SafeToInline; 34710b57cec5SDimitry Andric } 34720b57cec5SDimitry Andric 34730b57cec5SDimitry Andric // A variable definition might imply a destructor call. 34740b57cec5SDimitry Andric if (VD->isThisDeclarationADefinition()) 34750b57cec5SDimitry Andric SafeToInline = !HasNonDllImportDtor(VD->getType()); 34760b57cec5SDimitry Andric 34770b57cec5SDimitry Andric return SafeToInline; 34780b57cec5SDimitry Andric } 34790b57cec5SDimitry Andric 34800b57cec5SDimitry Andric bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 34810b57cec5SDimitry Andric if (const auto *D = E->getTemporary()->getDestructor()) 34820b57cec5SDimitry Andric SafeToInline = D->hasAttr<DLLImportAttr>(); 34830b57cec5SDimitry Andric return SafeToInline; 34840b57cec5SDimitry Andric } 34850b57cec5SDimitry Andric 34860b57cec5SDimitry Andric bool VisitDeclRefExpr(DeclRefExpr *E) { 34870b57cec5SDimitry Andric ValueDecl *VD = E->getDecl(); 34880b57cec5SDimitry Andric if (isa<FunctionDecl>(VD)) 34890b57cec5SDimitry Andric SafeToInline = VD->hasAttr<DLLImportAttr>(); 34900b57cec5SDimitry Andric else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 34910b57cec5SDimitry Andric SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 34920b57cec5SDimitry Andric return SafeToInline; 34930b57cec5SDimitry Andric } 34940b57cec5SDimitry Andric 34950b57cec5SDimitry Andric bool VisitCXXConstructExpr(CXXConstructExpr *E) { 34960b57cec5SDimitry Andric SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); 34970b57cec5SDimitry Andric return SafeToInline; 34980b57cec5SDimitry Andric } 34990b57cec5SDimitry Andric 35000b57cec5SDimitry Andric bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 35010b57cec5SDimitry Andric CXXMethodDecl *M = E->getMethodDecl(); 35020b57cec5SDimitry Andric if (!M) { 35030b57cec5SDimitry Andric // Call through a pointer to member function. This is safe to inline. 35040b57cec5SDimitry Andric SafeToInline = true; 35050b57cec5SDimitry Andric } else { 35060b57cec5SDimitry Andric SafeToInline = M->hasAttr<DLLImportAttr>(); 35070b57cec5SDimitry Andric } 35080b57cec5SDimitry Andric return SafeToInline; 35090b57cec5SDimitry Andric } 35100b57cec5SDimitry Andric 35110b57cec5SDimitry Andric bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 35120b57cec5SDimitry Andric SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 35130b57cec5SDimitry Andric return SafeToInline; 35140b57cec5SDimitry Andric } 35150b57cec5SDimitry Andric 35160b57cec5SDimitry Andric bool VisitCXXNewExpr(CXXNewExpr *E) { 35170b57cec5SDimitry Andric SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 35180b57cec5SDimitry Andric return SafeToInline; 35190b57cec5SDimitry Andric } 35200b57cec5SDimitry Andric }; 35210b57cec5SDimitry Andric } 35220b57cec5SDimitry Andric 35230b57cec5SDimitry Andric // isTriviallyRecursive - Check if this function calls another 35240b57cec5SDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin, 35250b57cec5SDimitry Andric // ends up pointing to itself. 35260b57cec5SDimitry Andric bool 35270b57cec5SDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 35280b57cec5SDimitry Andric StringRef Name; 35290b57cec5SDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 35300b57cec5SDimitry Andric // asm labels are a special kind of mangling we have to support. 35310b57cec5SDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 35320b57cec5SDimitry Andric if (!Attr) 35330b57cec5SDimitry Andric return false; 35340b57cec5SDimitry Andric Name = Attr->getLabel(); 35350b57cec5SDimitry Andric } else { 35360b57cec5SDimitry Andric Name = FD->getName(); 35370b57cec5SDimitry Andric } 35380b57cec5SDimitry Andric 35390b57cec5SDimitry Andric FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 35400b57cec5SDimitry Andric const Stmt *Body = FD->getBody(); 35410b57cec5SDimitry Andric return Body ? Walker.Visit(Body) : false; 35420b57cec5SDimitry Andric } 35430b57cec5SDimitry Andric 35440b57cec5SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 35450b57cec5SDimitry Andric if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 35460b57cec5SDimitry Andric return true; 35470b57cec5SDimitry Andric const auto *F = cast<FunctionDecl>(GD.getDecl()); 35480b57cec5SDimitry Andric if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 35490b57cec5SDimitry Andric return false; 35500b57cec5SDimitry Andric 3551fe6060f1SDimitry Andric if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) { 35520b57cec5SDimitry Andric // Check whether it would be safe to inline this dllimport function. 35530b57cec5SDimitry Andric DLLImportFunctionVisitor Visitor; 35540b57cec5SDimitry Andric Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 35550b57cec5SDimitry Andric if (!Visitor.SafeToInline) 35560b57cec5SDimitry Andric return false; 35570b57cec5SDimitry Andric 35580b57cec5SDimitry Andric if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { 35590b57cec5SDimitry Andric // Implicit destructor invocations aren't captured in the AST, so the 35600b57cec5SDimitry Andric // check above can't see them. Check for them manually here. 35610b57cec5SDimitry Andric for (const Decl *Member : Dtor->getParent()->decls()) 35620b57cec5SDimitry Andric if (isa<FieldDecl>(Member)) 35630b57cec5SDimitry Andric if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) 35640b57cec5SDimitry Andric return false; 35650b57cec5SDimitry Andric for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) 35660b57cec5SDimitry Andric if (HasNonDllImportDtor(B.getType())) 35670b57cec5SDimitry Andric return false; 35680b57cec5SDimitry Andric } 35690b57cec5SDimitry Andric } 35700b57cec5SDimitry 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 35760b57cec5SDimitry Andric // PR9614. Avoid cases where the source code is lying to us. An available 35770b57cec5SDimitry 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. 35800b57cec5SDimitry Andric // This happens in glibc's btowc and in some configure checks. 35810b57cec5SDimitry Andric return !isTriviallyRecursive(F); 35820b57cec5SDimitry Andric } 35830b57cec5SDimitry Andric 35840b57cec5SDimitry Andric bool CodeGenModule::shouldOpportunisticallyEmitVTables() { 35850b57cec5SDimitry Andric return CodeGenOpts.OptimizationLevel > 0; 35860b57cec5SDimitry Andric } 35870b57cec5SDimitry Andric 35880b57cec5SDimitry Andric void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD, 35890b57cec5SDimitry Andric llvm::GlobalValue *GV) { 35900b57cec5SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 35910b57cec5SDimitry Andric 35920b57cec5SDimitry Andric if (FD->isCPUSpecificMultiVersion()) { 35930b57cec5SDimitry Andric auto *Spec = FD->getAttr<CPUSpecificAttr>(); 35940b57cec5SDimitry Andric for (unsigned I = 0; I < Spec->cpus_size(); ++I) 35950b57cec5SDimitry 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); 36030b57cec5SDimitry Andric } else 36040b57cec5SDimitry Andric EmitGlobalFunctionDefinition(GD, GV); 36050b57cec5SDimitry Andric } 36060b57cec5SDimitry Andric 36070b57cec5SDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 36080b57cec5SDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 36090b57cec5SDimitry Andric 36100b57cec5SDimitry Andric PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 36110b57cec5SDimitry Andric Context.getSourceManager(), 36120b57cec5SDimitry Andric "Generating code for declaration"); 36130b57cec5SDimitry Andric 36140b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 36150b57cec5SDimitry Andric // At -O0, don't generate IR for functions with available_externally 36160b57cec5SDimitry Andric // linkage. 36170b57cec5SDimitry Andric if (!shouldEmitFunction(GD)) 36180b57cec5SDimitry Andric return; 36190b57cec5SDimitry Andric 36200b57cec5SDimitry Andric llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() { 36210b57cec5SDimitry Andric std::string Name; 36220b57cec5SDimitry Andric llvm::raw_string_ostream OS(Name); 36230b57cec5SDimitry Andric FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(), 36240b57cec5SDimitry Andric /*Qualified=*/true); 36250b57cec5SDimitry Andric return Name; 36260b57cec5SDimitry Andric }); 36270b57cec5SDimitry Andric 36280b57cec5SDimitry Andric if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 36290b57cec5SDimitry Andric // Make sure to emit the definition(s) before we emit the thunks. 36300b57cec5SDimitry Andric // This is necessary for the generation of certain thunks. 36310b57cec5SDimitry Andric if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method)) 36320b57cec5SDimitry Andric ABI->emitCXXStructor(GD); 36330b57cec5SDimitry Andric else if (FD->isMultiVersion()) 36340b57cec5SDimitry Andric EmitMultiVersionFunctionDefinition(GD, GV); 36350b57cec5SDimitry Andric else 36360b57cec5SDimitry Andric EmitGlobalFunctionDefinition(GD, GV); 36370b57cec5SDimitry Andric 36380b57cec5SDimitry Andric if (Method->isVirtual()) 36390b57cec5SDimitry Andric getVTables().EmitThunks(GD); 36400b57cec5SDimitry Andric 36410b57cec5SDimitry Andric return; 36420b57cec5SDimitry Andric } 36430b57cec5SDimitry Andric 36440b57cec5SDimitry Andric if (FD->isMultiVersion()) 36450b57cec5SDimitry Andric return EmitMultiVersionFunctionDefinition(GD, GV); 36460b57cec5SDimitry Andric return EmitGlobalFunctionDefinition(GD, GV); 36470b57cec5SDimitry Andric } 36480b57cec5SDimitry Andric 36490b57cec5SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 36500b57cec5SDimitry Andric return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 36510b57cec5SDimitry Andric 36520b57cec5SDimitry Andric llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 36530b57cec5SDimitry Andric } 36540b57cec5SDimitry Andric 36550b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 36560b57cec5SDimitry Andric llvm::Function *NewFn); 36570b57cec5SDimitry Andric 36580b57cec5SDimitry Andric static unsigned 36590b57cec5SDimitry Andric TargetMVPriority(const TargetInfo &TI, 36600b57cec5SDimitry Andric const CodeGenFunction::MultiVersionResolverOption &RO) { 36610b57cec5SDimitry Andric unsigned Priority = 0; 3662*bdd1243dSDimitry Andric unsigned NumFeatures = 0; 3663*bdd1243dSDimitry Andric for (StringRef Feat : RO.Conditions.Features) { 36640b57cec5SDimitry Andric Priority = std::max(Priority, TI.multiVersionSortPriority(Feat)); 3665*bdd1243dSDimitry Andric NumFeatures++; 3666*bdd1243dSDimitry Andric } 36670b57cec5SDimitry Andric 36680b57cec5SDimitry Andric if (!RO.Conditions.Architecture.empty()) 36690b57cec5SDimitry Andric Priority = std::max( 36700b57cec5SDimitry Andric Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture)); 3671*bdd1243dSDimitry Andric 3672*bdd1243dSDimitry Andric Priority += TI.multiVersionFeatureCost() * NumFeatures; 3673*bdd1243dSDimitry Andric 36740b57cec5SDimitry Andric return Priority; 36750b57cec5SDimitry Andric } 36760b57cec5SDimitry 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 36900b57cec5SDimitry 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 36970b57cec5SDimitry Andric SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 369881ad6265SDimitry Andric if (FD->isTargetMultiVersion()) { 36990b57cec5SDimitry Andric getContext().forEachMultiversionedFunctionVersion( 37000b57cec5SDimitry Andric FD, [this, &GD, &Options](const FunctionDecl *CurFD) { 37010b57cec5SDimitry Andric GlobalDecl CurGD{ 37020b57cec5SDimitry Andric (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)}; 37030b57cec5SDimitry Andric StringRef MangledName = getMangledName(CurGD); 37040b57cec5SDimitry Andric llvm::Constant *Func = GetGlobalValue(MangledName); 37050b57cec5SDimitry Andric if (!Func) { 37060b57cec5SDimitry Andric if (CurFD->isDefined()) { 37070b57cec5SDimitry Andric EmitGlobalFunctionDefinition(CurGD, nullptr); 37080b57cec5SDimitry Andric Func = GetGlobalValue(MangledName); 37090b57cec5SDimitry Andric } else { 37100b57cec5SDimitry Andric const CGFunctionInfo &FI = 37110b57cec5SDimitry Andric getTypes().arrangeGlobalDeclaration(GD); 37120b57cec5SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 37130b57cec5SDimitry Andric Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, 37140b57cec5SDimitry Andric /*DontDefer=*/false, ForDefinition); 37150b57cec5SDimitry Andric } 37160b57cec5SDimitry Andric assert(Func && "This should have just been created"); 37170b57cec5SDimitry Andric } 3718*bdd1243dSDimitry Andric if (CurFD->getMultiVersionKind() == MultiVersionKind::Target) { 37190b57cec5SDimitry Andric const auto *TA = CurFD->getAttr<TargetAttr>(); 37200b57cec5SDimitry Andric llvm::SmallVector<StringRef, 8> Feats; 37210b57cec5SDimitry Andric TA->getAddedFeatures(Feats); 37220b57cec5SDimitry Andric Options.emplace_back(cast<llvm::Function>(Func), 37230b57cec5SDimitry Andric TA->getArchitecture(), Feats); 3724*bdd1243dSDimitry Andric } else { 3725*bdd1243dSDimitry Andric const auto *TVA = CurFD->getAttr<TargetVersionAttr>(); 3726*bdd1243dSDimitry Andric llvm::SmallVector<StringRef, 8> Feats; 3727*bdd1243dSDimitry Andric TVA->getFeatures(Feats); 3728*bdd1243dSDimitry Andric Options.emplace_back(cast<llvm::Function>(Func), 3729*bdd1243dSDimitry Andric /*Architecture*/ "", Feats); 3730*bdd1243dSDimitry Andric } 37310b57cec5SDimitry 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 3760*bdd1243dSDimitry Andric if (getTarget().getTriple().isAArch64()) { 3761*bdd1243dSDimitry Andric if (Version != "default") { 3762*bdd1243dSDimitry Andric llvm::SmallVector<StringRef, 8> VerFeats; 3763*bdd1243dSDimitry Andric Version.split(VerFeats, "+"); 3764*bdd1243dSDimitry Andric for (auto &CurFeat : VerFeats) 3765*bdd1243dSDimitry Andric Feature.push_back(CurFeat.trim()); 3766*bdd1243dSDimitry Andric } 3767*bdd1243dSDimitry 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); 3772*bdd1243dSDimitry 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)); 37870b57cec5SDimitry Andric 37880b57cec5SDimitry Andric if (supportsCOMDAT()) 37890b57cec5SDimitry Andric ResolverFunc->setComdat( 37900b57cec5SDimitry Andric getModule().getOrInsertComdat(ResolverFunc->getName())); 37910b57cec5SDimitry Andric 379281ad6265SDimitry Andric const TargetInfo &TI = getTarget(); 37930b57cec5SDimitry Andric llvm::stable_sort( 37940b57cec5SDimitry Andric Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS, 37950b57cec5SDimitry Andric const CodeGenFunction::MultiVersionResolverOption &RHS) { 37960b57cec5SDimitry Andric return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS); 37970b57cec5SDimitry Andric }); 37980b57cec5SDimitry Andric CodeGenFunction CGF(*this); 37990b57cec5SDimitry Andric CGF.EmitMultiVersionResolver(ResolverFunc, Options); 38000b57cec5SDimitry 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(); 38120b57cec5SDimitry Andric } 38130b57cec5SDimitry Andric 38140b57cec5SDimitry Andric void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) { 38150b57cec5SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 38160b57cec5SDimitry Andric assert(FD && "Not a FunctionDecl?"); 381704eeddc0SDimitry Andric assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?"); 38180b57cec5SDimitry Andric const auto *DD = FD->getAttr<CPUDispatchAttr>(); 38190b57cec5SDimitry Andric assert(DD && "Not a cpu_dispatch Function?"); 38200b57cec5SDimitry Andric 382181ad6265SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 382281ad6265SDimitry Andric llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI); 38230b57cec5SDimitry Andric 38240b57cec5SDimitry Andric StringRef ResolverName = getMangledName(GD); 382504eeddc0SDimitry Andric UpdateMultiVersionNames(GD, FD, ResolverName); 38260b57cec5SDimitry Andric 38270b57cec5SDimitry Andric llvm::Type *ResolverType; 38280b57cec5SDimitry Andric GlobalDecl ResolverGD; 382904eeddc0SDimitry Andric if (getTarget().supportsIFunc()) { 38300b57cec5SDimitry Andric ResolverType = llvm::FunctionType::get( 38310b57cec5SDimitry Andric llvm::PointerType::get(DeclTy, 3832*bdd1243dSDimitry Andric getTypes().getTargetAddressSpace(FD->getType())), 38330b57cec5SDimitry Andric false); 383404eeddc0SDimitry Andric } 38350b57cec5SDimitry Andric else { 38360b57cec5SDimitry Andric ResolverType = DeclTy; 38370b57cec5SDimitry Andric ResolverGD = GD; 38380b57cec5SDimitry Andric } 38390b57cec5SDimitry Andric 38400b57cec5SDimitry Andric auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction( 38410b57cec5SDimitry 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())); 38460b57cec5SDimitry Andric 38470b57cec5SDimitry Andric SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 38480b57cec5SDimitry Andric const TargetInfo &Target = getTarget(); 38490b57cec5SDimitry Andric unsigned Index = 0; 38500b57cec5SDimitry Andric for (const IdentifierInfo *II : DD->cpus()) { 38510b57cec5SDimitry Andric // Get the name of the target function so we can look it up/create it. 38520b57cec5SDimitry Andric std::string MangledName = getMangledNameImpl(*this, GD, FD, true) + 38530b57cec5SDimitry Andric getCPUSpecificMangling(*this, II->getName()); 38540b57cec5SDimitry Andric 38550b57cec5SDimitry Andric llvm::Constant *Func = GetGlobalValue(MangledName); 38560b57cec5SDimitry Andric 38570b57cec5SDimitry Andric if (!Func) { 38580b57cec5SDimitry Andric GlobalDecl ExistingDecl = Manglings.lookup(MangledName); 38590b57cec5SDimitry Andric if (ExistingDecl.getDecl() && 38600b57cec5SDimitry Andric ExistingDecl.getDecl()->getAsFunction()->isDefined()) { 38610b57cec5SDimitry Andric EmitGlobalFunctionDefinition(ExistingDecl, nullptr); 38620b57cec5SDimitry Andric Func = GetGlobalValue(MangledName); 38630b57cec5SDimitry Andric } else { 38640b57cec5SDimitry Andric if (!ExistingDecl.getDecl()) 38650b57cec5SDimitry Andric ExistingDecl = GD.getWithMultiVersionIndex(Index); 38660b57cec5SDimitry Andric 38670b57cec5SDimitry Andric Func = GetOrCreateLLVMFunction( 38680b57cec5SDimitry Andric MangledName, DeclTy, ExistingDecl, 38690b57cec5SDimitry Andric /*ForVTable=*/false, /*DontDefer=*/true, 38700b57cec5SDimitry Andric /*IsThunk=*/false, llvm::AttributeList(), ForDefinition); 38710b57cec5SDimitry Andric } 38720b57cec5SDimitry Andric } 38730b57cec5SDimitry Andric 38740b57cec5SDimitry Andric llvm::SmallVector<StringRef, 32> Features; 38750b57cec5SDimitry Andric Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features); 38760b57cec5SDimitry Andric llvm::transform(Features, Features.begin(), 38770b57cec5SDimitry Andric [](StringRef Str) { return Str.substr(1); }); 3878349cc55cSDimitry Andric llvm::erase_if(Features, [&Target](StringRef Feat) { 38790b57cec5SDimitry Andric return !Target.validateCpuSupports(Feat); 3880349cc55cSDimitry Andric }); 38810b57cec5SDimitry Andric Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features); 38820b57cec5SDimitry Andric ++Index; 38830b57cec5SDimitry Andric } 38840b57cec5SDimitry Andric 3885fe6060f1SDimitry Andric llvm::stable_sort( 38860b57cec5SDimitry Andric Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS, 38870b57cec5SDimitry Andric const CodeGenFunction::MultiVersionResolverOption &RHS) { 3888349cc55cSDimitry Andric return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) > 3889349cc55cSDimitry Andric llvm::X86::getCpuSupportsMask(RHS.Conditions.Features); 38900b57cec5SDimitry Andric }); 38910b57cec5SDimitry Andric 38920b57cec5SDimitry Andric // If the list contains multiple 'default' versions, such as when it contains 38930b57cec5SDimitry Andric // 'pentium' and 'generic', don't emit the call to the generic one (since we 38940b57cec5SDimitry Andric // always run on at least a 'pentium'). We do this by deleting the 'least 38950b57cec5SDimitry Andric // advanced' (read, lowest mangling letter). 38960b57cec5SDimitry Andric while (Options.size() > 1 && 3897349cc55cSDimitry Andric llvm::X86::getCpuSupportsMask( 38980b57cec5SDimitry Andric (Options.end() - 2)->Conditions.Features) == 0) { 38990b57cec5SDimitry Andric StringRef LHSName = (Options.end() - 2)->Function->getName(); 39000b57cec5SDimitry Andric StringRef RHSName = (Options.end() - 1)->Function->getName(); 39010b57cec5SDimitry Andric if (LHSName.compare(RHSName) < 0) 39020b57cec5SDimitry Andric Options.erase(Options.end() - 2); 39030b57cec5SDimitry Andric else 39040b57cec5SDimitry Andric Options.erase(Options.end() - 1); 39050b57cec5SDimitry Andric } 39060b57cec5SDimitry Andric 39070b57cec5SDimitry Andric CodeGenFunction CGF(*this); 39080b57cec5SDimitry 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 } 39350b57cec5SDimitry Andric } 39360b57cec5SDimitry Andric 39370b57cec5SDimitry Andric /// If a dispatcher for the specified mangled name is not in the module, create 39380b57cec5SDimitry 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 39430b57cec5SDimitry Andric std::string MangledName = 39440b57cec5SDimitry Andric getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 39450b57cec5SDimitry Andric 39460b57cec5SDimitry Andric // Holds the name of the resolver, in ifunc mode this is the ifunc (which has 39470b57cec5SDimitry Andric // a separate resolver). 39480b57cec5SDimitry Andric std::string ResolverName = MangledName; 39490b57cec5SDimitry Andric if (getTarget().supportsIFunc()) 39500b57cec5SDimitry Andric ResolverName += ".ifunc"; 39510b57cec5SDimitry Andric else if (FD->isTargetMultiVersion()) 39520b57cec5SDimitry Andric ResolverName += ".resolver"; 39530b57cec5SDimitry Andric 395481ad6265SDimitry Andric // If the resolver has already been created, just return it. 39550b57cec5SDimitry Andric if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName)) 39560b57cec5SDimitry Andric return ResolverGV; 39570b57cec5SDimitry Andric 395881ad6265SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 395981ad6265SDimitry Andric llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI); 39600b57cec5SDimitry 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()) { 39690b57cec5SDimitry Andric llvm::Type *ResolverType = llvm::FunctionType::get( 3970*bdd1243dSDimitry Andric llvm::PointerType::get(DeclTy, 3971*bdd1243dSDimitry Andric getTypes().getTargetAddressSpace(FD->getType())), 39720b57cec5SDimitry Andric false); 39730b57cec5SDimitry Andric llvm::Constant *Resolver = GetOrCreateLLVMFunction( 39740b57cec5SDimitry Andric MangledName + ".resolver", ResolverType, GlobalDecl{}, 39750b57cec5SDimitry Andric /*ForVTable=*/false); 3976349cc55cSDimitry Andric llvm::GlobalIFunc *GIF = 3977349cc55cSDimitry Andric llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD), 3978349cc55cSDimitry Andric "", Resolver, &getModule()); 39790b57cec5SDimitry Andric GIF->setName(ResolverName); 39800b57cec5SDimitry Andric SetCommonAttributes(FD, GIF); 39810b57cec5SDimitry Andric 39820b57cec5SDimitry Andric return GIF; 39830b57cec5SDimitry Andric } 39840b57cec5SDimitry Andric 39850b57cec5SDimitry Andric llvm::Constant *Resolver = GetOrCreateLLVMFunction( 39860b57cec5SDimitry Andric ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false); 39870b57cec5SDimitry Andric assert(isa<llvm::GlobalValue>(Resolver) && 39880b57cec5SDimitry Andric "Resolver should be created for the first time"); 39890b57cec5SDimitry Andric SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver)); 39900b57cec5SDimitry Andric return Resolver; 39910b57cec5SDimitry Andric } 39920b57cec5SDimitry Andric 39930b57cec5SDimitry Andric /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 39940b57cec5SDimitry Andric /// module, create and return an llvm Function with the specified type. If there 39950b57cec5SDimitry Andric /// is something in the module with the specified name, return it potentially 39960b57cec5SDimitry Andric /// bitcasted to the right type. 39970b57cec5SDimitry Andric /// 39980b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this. This is used 39990b57cec5SDimitry Andric /// to set the attributes on the function when it is first created. 40000b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( 40010b57cec5SDimitry Andric StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, 40020b57cec5SDimitry Andric bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, 40030b57cec5SDimitry Andric ForDefinition_t IsForDefinition) { 40040b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 40050b57cec5SDimitry Andric 40060b57cec5SDimitry Andric // Any attempts to use a MultiVersion function should result in retrieving 40070b57cec5SDimitry Andric // the iFunc instead. Name Mangling will handle the rest of the changes. 40080b57cec5SDimitry Andric if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) { 40090b57cec5SDimitry Andric // For the device mark the function as one that should be emitted. 40100b57cec5SDimitry Andric if (getLangOpts().OpenMPIsDevice && OpenMPRuntime && 40110b57cec5SDimitry Andric !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() && 40120b57cec5SDimitry Andric !DontDefer && !IsForDefinition) { 40130b57cec5SDimitry Andric if (const FunctionDecl *FDDef = FD->getDefinition()) { 40140b57cec5SDimitry Andric GlobalDecl GDDef; 40150b57cec5SDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef)) 40160b57cec5SDimitry Andric GDDef = GlobalDecl(CD, GD.getCtorType()); 40170b57cec5SDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef)) 40180b57cec5SDimitry Andric GDDef = GlobalDecl(DD, GD.getDtorType()); 40190b57cec5SDimitry Andric else 40200b57cec5SDimitry Andric GDDef = GlobalDecl(FDDef); 40210b57cec5SDimitry Andric EmitGlobal(GDDef); 40220b57cec5SDimitry Andric } 40230b57cec5SDimitry Andric } 40240b57cec5SDimitry Andric 40250b57cec5SDimitry Andric if (FD->isMultiVersion()) { 402604eeddc0SDimitry Andric UpdateMultiVersionNames(GD, FD, MangledName); 40270b57cec5SDimitry Andric if (!IsForDefinition) 402881ad6265SDimitry Andric return GetOrCreateMultiVersionResolver(GD); 40290b57cec5SDimitry Andric } 40300b57cec5SDimitry Andric } 40310b57cec5SDimitry Andric 40320b57cec5SDimitry Andric // Lookup the entry, lazily creating it if necessary. 40330b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 40340b57cec5SDimitry Andric if (Entry) { 40350b57cec5SDimitry Andric if (WeakRefReferences.erase(Entry)) { 40360b57cec5SDimitry Andric const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 40370b57cec5SDimitry Andric if (FD && !FD->hasAttr<WeakAttr>()) 40380b57cec5SDimitry Andric Entry->setLinkage(llvm::Function::ExternalLinkage); 40390b57cec5SDimitry Andric } 40400b57cec5SDimitry Andric 40410b57cec5SDimitry Andric // Handle dropped DLL attributes. 404281ad6265SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() && 404381ad6265SDimitry Andric !shouldMapVisibilityToDLLExport(cast_or_null<NamedDecl>(D))) { 40440b57cec5SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 40450b57cec5SDimitry Andric setDSOLocal(Entry); 40460b57cec5SDimitry Andric } 40470b57cec5SDimitry Andric 40480b57cec5SDimitry Andric // If there are two attempts to define the same mangled name, issue an 40490b57cec5SDimitry Andric // error. 40500b57cec5SDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 40510b57cec5SDimitry Andric GlobalDecl OtherGD; 40520b57cec5SDimitry Andric // Check that GD is not yet in DiagnosedConflictingDefinitions is required 40530b57cec5SDimitry Andric // to make sure that we issue an error only once. 40540b57cec5SDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 40550b57cec5SDimitry Andric (GD.getCanonicalDecl().getDecl() != 40560b57cec5SDimitry Andric OtherGD.getCanonicalDecl().getDecl()) && 40570b57cec5SDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 40580b57cec5SDimitry Andric getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 40590b57cec5SDimitry Andric << MangledName; 40600b57cec5SDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 40610b57cec5SDimitry Andric diag::note_previous_definition); 40620b57cec5SDimitry Andric } 40630b57cec5SDimitry Andric } 40640b57cec5SDimitry Andric 40650b57cec5SDimitry Andric if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 40665ffd83dbSDimitry Andric (Entry->getValueType() == Ty)) { 40670b57cec5SDimitry Andric return Entry; 40680b57cec5SDimitry Andric } 40690b57cec5SDimitry Andric 40700b57cec5SDimitry Andric // Make sure the result is of the correct type. 40710b57cec5SDimitry Andric // (If function is requested for a definition, we always need to create a new 40720b57cec5SDimitry Andric // function, not just return a bitcast.) 40730b57cec5SDimitry Andric if (!IsForDefinition) 4074*bdd1243dSDimitry Andric return llvm::ConstantExpr::getBitCast( 4075*bdd1243dSDimitry Andric Entry, Ty->getPointerTo(Entry->getAddressSpace())); 40760b57cec5SDimitry Andric } 40770b57cec5SDimitry Andric 40780b57cec5SDimitry Andric // This function doesn't have a complete type (for example, the return 40790b57cec5SDimitry Andric // type is an incomplete struct). Use a fake type instead, and make 40800b57cec5SDimitry Andric // sure not to try to set attributes. 40810b57cec5SDimitry Andric bool IsIncompleteFunction = false; 40820b57cec5SDimitry Andric 40830b57cec5SDimitry Andric llvm::FunctionType *FTy; 40840b57cec5SDimitry Andric if (isa<llvm::FunctionType>(Ty)) { 40850b57cec5SDimitry Andric FTy = cast<llvm::FunctionType>(Ty); 40860b57cec5SDimitry Andric } else { 40870b57cec5SDimitry Andric FTy = llvm::FunctionType::get(VoidTy, false); 40880b57cec5SDimitry Andric IsIncompleteFunction = true; 40890b57cec5SDimitry Andric } 40900b57cec5SDimitry Andric 40910b57cec5SDimitry Andric llvm::Function *F = 40920b57cec5SDimitry Andric llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 40930b57cec5SDimitry Andric Entry ? StringRef() : MangledName, &getModule()); 40940b57cec5SDimitry Andric 40950b57cec5SDimitry Andric // If we already created a function with the same mangled name (but different 40960b57cec5SDimitry Andric // type) before, take its name and add it to the list of functions to be 40970b57cec5SDimitry Andric // replaced with F at the end of CodeGen. 40980b57cec5SDimitry Andric // 40990b57cec5SDimitry Andric // This happens if there is a prototype for a function (e.g. "int f()") and 41000b57cec5SDimitry Andric // then a definition of a different type (e.g. "int f(int x)"). 41010b57cec5SDimitry Andric if (Entry) { 41020b57cec5SDimitry Andric F->takeName(Entry); 41030b57cec5SDimitry Andric 41040b57cec5SDimitry Andric // This might be an implementation of a function without a prototype, in 41050b57cec5SDimitry Andric // which case, try to do special replacement of calls which match the new 41060b57cec5SDimitry Andric // prototype. The really key thing here is that we also potentially drop 41070b57cec5SDimitry Andric // arguments from the call site so as to make a direct call, which makes the 41080b57cec5SDimitry Andric // inliner happier and suppresses a number of optimizer warnings (!) about 41090b57cec5SDimitry Andric // dropping arguments. 41100b57cec5SDimitry Andric if (!Entry->use_empty()) { 41110b57cec5SDimitry Andric ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 41120b57cec5SDimitry Andric Entry->removeDeadConstantUsers(); 41130b57cec5SDimitry Andric } 41140b57cec5SDimitry Andric 41150b57cec5SDimitry Andric llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 4116*bdd1243dSDimitry Andric F, Entry->getValueType()->getPointerTo(Entry->getAddressSpace())); 41170b57cec5SDimitry Andric addGlobalValReplacement(Entry, BC); 41180b57cec5SDimitry Andric } 41190b57cec5SDimitry Andric 41200b57cec5SDimitry Andric assert(F->getName() == MangledName && "name was uniqued!"); 41210b57cec5SDimitry Andric if (D) 41220b57cec5SDimitry 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); 41260b57cec5SDimitry Andric } 41270b57cec5SDimitry Andric 41280b57cec5SDimitry Andric if (!DontDefer) { 41290b57cec5SDimitry Andric // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 41300b57cec5SDimitry Andric // each other bottoming out with the base dtor. Therefore we emit non-base 41310b57cec5SDimitry Andric // dtors on usage, even if there is no dtor definition in the TU. 4132*bdd1243dSDimitry Andric if (isa_and_nonnull<CXXDestructorDecl>(D) && 41330b57cec5SDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 41340b57cec5SDimitry Andric GD.getDtorType())) 41350b57cec5SDimitry Andric addDeferredDeclToEmit(GD); 41360b57cec5SDimitry Andric 41370b57cec5SDimitry Andric // This is the first use or definition of a mangled name. If there is a 41380b57cec5SDimitry Andric // deferred decl with this name, remember that we need to emit it at the end 41390b57cec5SDimitry Andric // of the file. 41400b57cec5SDimitry Andric auto DDI = DeferredDecls.find(MangledName); 41410b57cec5SDimitry Andric if (DDI != DeferredDecls.end()) { 41420b57cec5SDimitry Andric // Move the potentially referenced deferred decl to the 41430b57cec5SDimitry Andric // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 41440b57cec5SDimitry Andric // don't need it anymore). 41450b57cec5SDimitry Andric addDeferredDeclToEmit(DDI->second); 4146*bdd1243dSDimitry Andric EmittedDeferredDecls[DDI->first] = DDI->second; 41470b57cec5SDimitry Andric DeferredDecls.erase(DDI); 41480b57cec5SDimitry Andric 41490b57cec5SDimitry Andric // Otherwise, there are cases we have to worry about where we're 41500b57cec5SDimitry Andric // using a declaration for which we must emit a definition but where 41510b57cec5SDimitry Andric // we might not find a top-level definition: 41520b57cec5SDimitry Andric // - member functions defined inline in their classes 41530b57cec5SDimitry Andric // - friend functions defined inline in some class 41540b57cec5SDimitry Andric // - special member functions with implicit definitions 41550b57cec5SDimitry Andric // If we ever change our AST traversal to walk into class methods, 41560b57cec5SDimitry Andric // this will be unnecessary. 41570b57cec5SDimitry Andric // 41580b57cec5SDimitry Andric // We also don't emit a definition for a function if it's going to be an 41590b57cec5SDimitry Andric // entry in a vtable, unless it's already marked as used. 41600b57cec5SDimitry Andric } else if (getLangOpts().CPlusPlus && D) { 41610b57cec5SDimitry Andric // Look for a declaration that's lexically in a record. 41620b57cec5SDimitry Andric for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 41630b57cec5SDimitry Andric FD = FD->getPreviousDecl()) { 41640b57cec5SDimitry Andric if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 41650b57cec5SDimitry Andric if (FD->doesThisDeclarationHaveABody()) { 41660b57cec5SDimitry Andric addDeferredDeclToEmit(GD.getWithDecl(FD)); 41670b57cec5SDimitry Andric break; 41680b57cec5SDimitry Andric } 41690b57cec5SDimitry Andric } 41700b57cec5SDimitry Andric } 41710b57cec5SDimitry Andric } 41720b57cec5SDimitry Andric } 41730b57cec5SDimitry Andric 41740b57cec5SDimitry Andric // Make sure the result is of the requested type. 41750b57cec5SDimitry Andric if (!IsIncompleteFunction) { 41765ffd83dbSDimitry Andric assert(F->getFunctionType() == Ty); 41770b57cec5SDimitry Andric return F; 41780b57cec5SDimitry Andric } 41790b57cec5SDimitry Andric 4180*bdd1243dSDimitry Andric return llvm::ConstantExpr::getBitCast(F, 4181*bdd1243dSDimitry Andric Ty->getPointerTo(F->getAddressSpace())); 41820b57cec5SDimitry Andric } 41830b57cec5SDimitry Andric 41840b57cec5SDimitry Andric /// GetAddrOfFunction - Return the address of the given function. If Ty is 41850b57cec5SDimitry Andric /// non-null, then this function will use the specified type if it has to 41860b57cec5SDimitry Andric /// create it (this occurs when we see a definition of the function). 41870b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 41880b57cec5SDimitry Andric llvm::Type *Ty, 41890b57cec5SDimitry Andric bool ForVTable, 41900b57cec5SDimitry Andric bool DontDefer, 41910b57cec5SDimitry Andric ForDefinition_t IsForDefinition) { 41925ffd83dbSDimitry Andric assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() && 41935ffd83dbSDimitry Andric "consteval function should never be emitted"); 41940b57cec5SDimitry Andric // If there was no specific requested type, just convert it now. 41950b57cec5SDimitry Andric if (!Ty) { 41960b57cec5SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 41970b57cec5SDimitry Andric Ty = getTypes().ConvertType(FD->getType()); 41980b57cec5SDimitry Andric } 41990b57cec5SDimitry Andric 42000b57cec5SDimitry Andric // Devirtualized destructor calls may come through here instead of via 42010b57cec5SDimitry Andric // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead 42020b57cec5SDimitry Andric // of the complete destructor when necessary. 42030b57cec5SDimitry Andric if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) { 42040b57cec5SDimitry Andric if (getTarget().getCXXABI().isMicrosoft() && 42050b57cec5SDimitry Andric GD.getDtorType() == Dtor_Complete && 42060b57cec5SDimitry Andric DD->getParent()->getNumVBases() == 0) 42070b57cec5SDimitry Andric GD = GlobalDecl(DD, Dtor_Base); 42080b57cec5SDimitry Andric } 42090b57cec5SDimitry Andric 42100b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 4211fe6060f1SDimitry Andric auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 42120b57cec5SDimitry Andric /*IsThunk=*/false, llvm::AttributeList(), 42130b57cec5SDimitry 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; 42240b57cec5SDimitry Andric } 42250b57cec5SDimitry 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 4230*bdd1243dSDimitry Andric return llvm::ConstantExpr::getBitCast( 4231*bdd1243dSDimitry Andric llvm::NoCFIValue::get(F), 4232*bdd1243dSDimitry Andric llvm::Type::getInt8PtrTy(VMContext, F->getAddressSpace())); 42330eae32dcSDimitry Andric } 42340eae32dcSDimitry Andric 42350b57cec5SDimitry Andric static const FunctionDecl * 42360b57cec5SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { 42370b57cec5SDimitry Andric TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 42380b57cec5SDimitry Andric DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 42390b57cec5SDimitry Andric 42400b57cec5SDimitry 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)) 42430b57cec5SDimitry Andric return FD; 42440b57cec5SDimitry Andric 42450b57cec5SDimitry Andric if (!C.getLangOpts().CPlusPlus) 42460b57cec5SDimitry Andric return nullptr; 42470b57cec5SDimitry Andric 42480b57cec5SDimitry Andric // Demangle the premangled name from getTerminateFn() 42490b57cec5SDimitry Andric IdentifierInfo &CXXII = 42500b57cec5SDimitry Andric (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ") 42510b57cec5SDimitry Andric ? C.Idents.get("terminate") 42520b57cec5SDimitry Andric : C.Idents.get(Name); 42530b57cec5SDimitry Andric 42540b57cec5SDimitry Andric for (const auto &N : {"__cxxabiv1", "std"}) { 42550b57cec5SDimitry 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)) 42600b57cec5SDimitry Andric if ((ND = dyn_cast<NamespaceDecl>(Result))) 42610b57cec5SDimitry Andric break; 42620b57cec5SDimitry Andric 42630b57cec5SDimitry Andric if (ND) 4264fe6060f1SDimitry Andric for (const auto *Result : ND->lookup(&CXXII)) 42650b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 42660b57cec5SDimitry Andric return FD; 42670b57cec5SDimitry Andric } 42680b57cec5SDimitry Andric } 42690b57cec5SDimitry Andric 42700b57cec5SDimitry Andric return nullptr; 42710b57cec5SDimitry Andric } 42720b57cec5SDimitry Andric 42730b57cec5SDimitry Andric /// CreateRuntimeFunction - Create a new runtime function with the specified 42740b57cec5SDimitry Andric /// type and name. 42750b57cec5SDimitry Andric llvm::FunctionCallee 42760b57cec5SDimitry 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 42840b57cec5SDimitry Andric llvm::Constant *C = 42850b57cec5SDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 42860b57cec5SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, 42870b57cec5SDimitry Andric ExtraAttrs); 42880b57cec5SDimitry Andric 42890b57cec5SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) { 42900b57cec5SDimitry Andric if (F->empty()) { 42910b57cec5SDimitry Andric F->setCallingConv(getRuntimeCC()); 42920b57cec5SDimitry Andric 42930b57cec5SDimitry Andric // In Windows Itanium environments, try to mark runtime functions 42940b57cec5SDimitry Andric // dllimport. For Mingw and MSVC, don't. We don't really know if the user 42950b57cec5SDimitry Andric // will link their standard library statically or dynamically. Marking 42960b57cec5SDimitry Andric // functions imported when they are not imported can cause linker errors 42970b57cec5SDimitry Andric // and warnings. 42980b57cec5SDimitry Andric if (!Local && getTriple().isWindowsItaniumEnvironment() && 42990b57cec5SDimitry Andric !getCodeGenOpts().LTOVisibilityPublicStd) { 43000b57cec5SDimitry Andric const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); 43010b57cec5SDimitry Andric if (!FD || FD->hasAttr<DLLImportAttr>()) { 43020b57cec5SDimitry Andric F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 43030b57cec5SDimitry Andric F->setLinkage(llvm::GlobalValue::ExternalLinkage); 43040b57cec5SDimitry Andric } 43050b57cec5SDimitry Andric } 43060b57cec5SDimitry Andric setDSOLocal(F); 43070b57cec5SDimitry Andric } 43080b57cec5SDimitry Andric } 43090b57cec5SDimitry Andric 43100b57cec5SDimitry Andric return {FTy, C}; 43110b57cec5SDimitry Andric } 43120b57cec5SDimitry Andric 43130b57cec5SDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted 43140b57cec5SDimitry Andric /// as a constant. 43150b57cec5SDimitry Andric /// 43160b57cec5SDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs 43170b57cec5SDimitry Andric /// will not be considered. The caller will need to verify that the object is 43180b57cec5SDimitry Andric /// not written to during its construction. 43190b57cec5SDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 43200b57cec5SDimitry Andric if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 43210b57cec5SDimitry Andric return false; 43220b57cec5SDimitry Andric 43230b57cec5SDimitry Andric if (Context.getLangOpts().CPlusPlus) { 43240b57cec5SDimitry Andric if (const CXXRecordDecl *Record 43250b57cec5SDimitry Andric = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 43260b57cec5SDimitry Andric return ExcludeCtor && !Record->hasMutableFields() && 43270b57cec5SDimitry Andric Record->hasTrivialDestructor(); 43280b57cec5SDimitry Andric } 43290b57cec5SDimitry Andric 43300b57cec5SDimitry Andric return true; 43310b57cec5SDimitry Andric } 43320b57cec5SDimitry Andric 43330b57cec5SDimitry 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. 43370b57cec5SDimitry Andric /// 43380b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this. This is used 43390b57cec5SDimitry Andric /// to set the attributes on the global when it is first created. 43400b57cec5SDimitry Andric /// 43410b57cec5SDimitry Andric /// If IsForDefinition is true, it is guaranteed that an actual global with 43420b57cec5SDimitry Andric /// type Ty will be returned, not conversion of a variable with the same 43430b57cec5SDimitry Andric /// mangled name but some other type. 43440b57cec5SDimitry Andric llvm::Constant * 4345fe6060f1SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, 4346349cc55cSDimitry Andric LangAS AddrSpace, const VarDecl *D, 43470b57cec5SDimitry Andric ForDefinition_t IsForDefinition) { 43480b57cec5SDimitry Andric // Lookup the entry, lazily creating it if necessary. 43490b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4350349cc55cSDimitry Andric unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace); 43510b57cec5SDimitry Andric if (Entry) { 43520b57cec5SDimitry Andric if (WeakRefReferences.erase(Entry)) { 43530b57cec5SDimitry Andric if (D && !D->hasAttr<WeakAttr>()) 43540b57cec5SDimitry Andric Entry->setLinkage(llvm::Function::ExternalLinkage); 43550b57cec5SDimitry Andric } 43560b57cec5SDimitry Andric 43570b57cec5SDimitry Andric // Handle dropped DLL attributes. 435881ad6265SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() && 435981ad6265SDimitry Andric !shouldMapVisibilityToDLLExport(D)) 43600b57cec5SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 43610b57cec5SDimitry Andric 43620b57cec5SDimitry Andric if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D) 43630b57cec5SDimitry Andric getOpenMPRuntime().registerTargetGlobalVariable(D, Entry); 43640b57cec5SDimitry Andric 4365349cc55cSDimitry Andric if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS) 43660b57cec5SDimitry Andric return Entry; 43670b57cec5SDimitry Andric 43680b57cec5SDimitry Andric // If there are two attempts to define the same mangled name, issue an 43690b57cec5SDimitry Andric // error. 43700b57cec5SDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 43710b57cec5SDimitry Andric GlobalDecl OtherGD; 43720b57cec5SDimitry Andric const VarDecl *OtherD; 43730b57cec5SDimitry Andric 43740b57cec5SDimitry Andric // Check that D is not yet in DiagnosedConflictingDefinitions is required 43750b57cec5SDimitry Andric // to make sure that we issue an error only once. 43760b57cec5SDimitry Andric if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 43770b57cec5SDimitry Andric (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 43780b57cec5SDimitry Andric (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 43790b57cec5SDimitry Andric OtherD->hasInit() && 43800b57cec5SDimitry Andric DiagnosedConflictingDefinitions.insert(D).second) { 43810b57cec5SDimitry Andric getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 43820b57cec5SDimitry Andric << MangledName; 43830b57cec5SDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 43840b57cec5SDimitry Andric diag::note_previous_definition); 43850b57cec5SDimitry Andric } 43860b57cec5SDimitry Andric } 43870b57cec5SDimitry Andric 43880b57cec5SDimitry 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 } 43930b57cec5SDimitry Andric 43940b57cec5SDimitry Andric // (If global is requested for a definition, we always need to create a new 43950b57cec5SDimitry Andric // global, not just return a bitcast.) 43960b57cec5SDimitry Andric if (!IsForDefinition) 4397349cc55cSDimitry Andric return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(TargetAS)); 43980b57cec5SDimitry Andric } 43990b57cec5SDimitry Andric 4400fe6060f1SDimitry Andric auto DAddrSpace = GetGlobalVarAddressSpace(D); 44010b57cec5SDimitry Andric 44020b57cec5SDimitry 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)); 44060b57cec5SDimitry Andric 44070b57cec5SDimitry Andric // If we already created a global with the same mangled name (but different 44080b57cec5SDimitry Andric // type) before, take its name and remove it from its parent. 44090b57cec5SDimitry Andric if (Entry) { 44100b57cec5SDimitry Andric GV->takeName(Entry); 44110b57cec5SDimitry Andric 44120b57cec5SDimitry Andric if (!Entry->use_empty()) { 44130b57cec5SDimitry Andric llvm::Constant *NewPtrForOldDecl = 44140b57cec5SDimitry Andric llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 44150b57cec5SDimitry Andric Entry->replaceAllUsesWith(NewPtrForOldDecl); 44160b57cec5SDimitry Andric } 44170b57cec5SDimitry Andric 44180b57cec5SDimitry Andric Entry->eraseFromParent(); 44190b57cec5SDimitry Andric } 44200b57cec5SDimitry Andric 44210b57cec5SDimitry Andric // This is the first use or definition of a mangled name. If there is a 44220b57cec5SDimitry Andric // deferred decl with this name, remember that we need to emit it at the end 44230b57cec5SDimitry Andric // of the file. 44240b57cec5SDimitry Andric auto DDI = DeferredDecls.find(MangledName); 44250b57cec5SDimitry Andric if (DDI != DeferredDecls.end()) { 44260b57cec5SDimitry Andric // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 44270b57cec5SDimitry Andric // list, and remove it from DeferredDecls (since we don't need it anymore). 44280b57cec5SDimitry Andric addDeferredDeclToEmit(DDI->second); 4429*bdd1243dSDimitry Andric EmittedDeferredDecls[DDI->first] = DDI->second; 44300b57cec5SDimitry Andric DeferredDecls.erase(DDI); 44310b57cec5SDimitry Andric } 44320b57cec5SDimitry Andric 44330b57cec5SDimitry Andric // Handle things which are present even on external declarations. 44340b57cec5SDimitry Andric if (D) { 44350b57cec5SDimitry Andric if (LangOpts.OpenMP && !LangOpts.OpenMPSimd) 44360b57cec5SDimitry Andric getOpenMPRuntime().registerTargetGlobalVariable(D, GV); 44370b57cec5SDimitry Andric 44380b57cec5SDimitry Andric // FIXME: This code is overly simple and should be merged with other global 44390b57cec5SDimitry Andric // handling. 44400b57cec5SDimitry Andric GV->setConstant(isTypeConstant(D->getType(), false)); 44410b57cec5SDimitry Andric 4442a7dea167SDimitry Andric GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); 44430b57cec5SDimitry Andric 44440b57cec5SDimitry Andric setLinkageForGV(GV, D); 44450b57cec5SDimitry Andric 44460b57cec5SDimitry Andric if (D->getTLSKind()) { 44470b57cec5SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 44480b57cec5SDimitry Andric CXXThreadLocals.push_back(D); 44490b57cec5SDimitry Andric setTLSMode(GV, *D); 44500b57cec5SDimitry Andric } 44510b57cec5SDimitry Andric 44520b57cec5SDimitry Andric setGVProperties(GV, D); 44530b57cec5SDimitry Andric 44540b57cec5SDimitry Andric // If required by the ABI, treat declarations of static data members with 44550b57cec5SDimitry Andric // inline initializers as definitions. 44560b57cec5SDimitry Andric if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 44570b57cec5SDimitry Andric EmitGlobalVarDefinition(D); 44580b57cec5SDimitry Andric } 44590b57cec5SDimitry Andric 44600b57cec5SDimitry Andric // Emit section information for extern variables. 44610b57cec5SDimitry Andric if (D->hasExternalStorage()) { 44620b57cec5SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 44630b57cec5SDimitry Andric GV->setSection(SA->getName()); 44640b57cec5SDimitry Andric } 44650b57cec5SDimitry Andric 44660b57cec5SDimitry Andric // Handle XCore specific ABI requirements. 44670b57cec5SDimitry Andric if (getTriple().getArch() == llvm::Triple::xcore && 44680b57cec5SDimitry Andric D->getLanguageLinkage() == CLanguageLinkage && 44690b57cec5SDimitry Andric D->getType().isConstant(Context) && 44700b57cec5SDimitry Andric isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 44710b57cec5SDimitry Andric GV->setSection(".cp.rodata"); 44720b57cec5SDimitry Andric 44730b57cec5SDimitry Andric // Check if we a have a const declaration with an initializer, we may be 44740b57cec5SDimitry Andric // able to emit it as available_externally to expose it's value to the 44750b57cec5SDimitry Andric // optimizer. 44760b57cec5SDimitry Andric if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() && 44770b57cec5SDimitry Andric D->getType().isConstQualified() && !GV->hasInitializer() && 44780b57cec5SDimitry Andric !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) { 44790b57cec5SDimitry Andric const auto *Record = 44800b57cec5SDimitry Andric Context.getBaseElementType(D->getType())->getAsCXXRecordDecl(); 44810b57cec5SDimitry Andric bool HasMutableFields = Record && Record->hasMutableFields(); 44820b57cec5SDimitry Andric if (!HasMutableFields) { 44830b57cec5SDimitry Andric const VarDecl *InitDecl; 44840b57cec5SDimitry Andric const Expr *InitExpr = D->getAnyInitializer(InitDecl); 44850b57cec5SDimitry Andric if (InitExpr) { 44860b57cec5SDimitry Andric ConstantEmitter emitter(*this); 44870b57cec5SDimitry Andric llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl); 44880b57cec5SDimitry Andric if (Init) { 44890b57cec5SDimitry Andric auto *InitType = Init->getType(); 44905ffd83dbSDimitry Andric if (GV->getValueType() != InitType) { 44910b57cec5SDimitry Andric // The type of the initializer does not match the definition. 44920b57cec5SDimitry Andric // This happens when an initializer has a different type from 44930b57cec5SDimitry Andric // the type of the global (because of padding at the end of a 44940b57cec5SDimitry Andric // structure for instance). 44950b57cec5SDimitry Andric GV->setName(StringRef()); 44960b57cec5SDimitry Andric // Make a new global with the correct type, this is now guaranteed 44970b57cec5SDimitry Andric // to work. 44980b57cec5SDimitry Andric auto *NewGV = cast<llvm::GlobalVariable>( 4499a7dea167SDimitry Andric GetAddrOfGlobalVar(D, InitType, IsForDefinition) 4500a7dea167SDimitry Andric ->stripPointerCasts()); 45010b57cec5SDimitry Andric 45020b57cec5SDimitry Andric // Erase the old global, since it is no longer used. 45030b57cec5SDimitry Andric GV->eraseFromParent(); 45040b57cec5SDimitry Andric GV = NewGV; 45050b57cec5SDimitry Andric } else { 45060b57cec5SDimitry Andric GV->setInitializer(Init); 45070b57cec5SDimitry Andric GV->setConstant(true); 45080b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 45090b57cec5SDimitry Andric } 45100b57cec5SDimitry Andric emitter.finalize(GV); 45110b57cec5SDimitry Andric } 45120b57cec5SDimitry Andric } 45130b57cec5SDimitry Andric } 45140b57cec5SDimitry Andric } 45150b57cec5SDimitry Andric } 45160b57cec5SDimitry 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 45290b57cec5SDimitry Andric LangAS ExpectedAS = 45300b57cec5SDimitry Andric D ? D->getType().getAddressSpace() 45310b57cec5SDimitry 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 } 45370b57cec5SDimitry Andric 45380b57cec5SDimitry Andric return GV; 45390b57cec5SDimitry Andric } 45400b57cec5SDimitry Andric 45410b57cec5SDimitry Andric llvm::Constant * 45425ffd83dbSDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) { 45430b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 45445ffd83dbSDimitry Andric 45450b57cec5SDimitry Andric if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 45460b57cec5SDimitry Andric return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr, 45470b57cec5SDimitry Andric /*DontDefer=*/false, IsForDefinition); 45485ffd83dbSDimitry Andric 45495ffd83dbSDimitry Andric if (isa<CXXMethodDecl>(D)) { 45505ffd83dbSDimitry Andric auto FInfo = 45515ffd83dbSDimitry Andric &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D)); 45520b57cec5SDimitry Andric auto Ty = getTypes().GetFunctionType(*FInfo); 45530b57cec5SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 45540b57cec5SDimitry Andric IsForDefinition); 45555ffd83dbSDimitry Andric } 45565ffd83dbSDimitry Andric 45575ffd83dbSDimitry Andric if (isa<FunctionDecl>(D)) { 45580b57cec5SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 45590b57cec5SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 45600b57cec5SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 45610b57cec5SDimitry Andric IsForDefinition); 45625ffd83dbSDimitry Andric } 45635ffd83dbSDimitry Andric 45645ffd83dbSDimitry Andric return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition); 45650b57cec5SDimitry Andric } 45660b57cec5SDimitry Andric 45670b57cec5SDimitry Andric llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable( 45680b57cec5SDimitry Andric StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, 4569*bdd1243dSDimitry Andric llvm::Align Alignment) { 45700b57cec5SDimitry Andric llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 45710b57cec5SDimitry Andric llvm::GlobalVariable *OldGV = nullptr; 45720b57cec5SDimitry Andric 45730b57cec5SDimitry Andric if (GV) { 45740b57cec5SDimitry Andric // Check if the variable has the right type. 45755ffd83dbSDimitry Andric if (GV->getValueType() == Ty) 45760b57cec5SDimitry Andric return GV; 45770b57cec5SDimitry Andric 45780b57cec5SDimitry Andric // Because C++ name mangling, the only way we can end up with an already 45790b57cec5SDimitry Andric // existing global with the same name is if it has been declared extern "C". 45800b57cec5SDimitry Andric assert(GV->isDeclaration() && "Declaration has wrong type!"); 45810b57cec5SDimitry Andric OldGV = GV; 45820b57cec5SDimitry Andric } 45830b57cec5SDimitry Andric 45840b57cec5SDimitry Andric // Create a new variable. 45850b57cec5SDimitry Andric GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 45860b57cec5SDimitry Andric Linkage, nullptr, Name); 45870b57cec5SDimitry Andric 45880b57cec5SDimitry Andric if (OldGV) { 45890b57cec5SDimitry Andric // Replace occurrences of the old variable if needed. 45900b57cec5SDimitry Andric GV->takeName(OldGV); 45910b57cec5SDimitry Andric 45920b57cec5SDimitry Andric if (!OldGV->use_empty()) { 45930b57cec5SDimitry Andric llvm::Constant *NewPtrForOldDecl = 45940b57cec5SDimitry Andric llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 45950b57cec5SDimitry Andric OldGV->replaceAllUsesWith(NewPtrForOldDecl); 45960b57cec5SDimitry Andric } 45970b57cec5SDimitry Andric 45980b57cec5SDimitry Andric OldGV->eraseFromParent(); 45990b57cec5SDimitry Andric } 46000b57cec5SDimitry Andric 46010b57cec5SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker() && 46020b57cec5SDimitry Andric !GV->hasAvailableExternallyLinkage()) 46030b57cec5SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 46040b57cec5SDimitry Andric 4605*bdd1243dSDimitry Andric GV->setAlignment(Alignment); 46060b57cec5SDimitry Andric 46070b57cec5SDimitry Andric return GV; 46080b57cec5SDimitry Andric } 46090b57cec5SDimitry Andric 46100b57cec5SDimitry Andric /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 46110b57cec5SDimitry Andric /// given global variable. If Ty is non-null and if the global doesn't exist, 46120b57cec5SDimitry Andric /// then it will be created with the specified type instead of whatever the 46130b57cec5SDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guaranteed 46140b57cec5SDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a 46150b57cec5SDimitry Andric /// variable with the same mangled name but some other type. 46160b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 46170b57cec5SDimitry Andric llvm::Type *Ty, 46180b57cec5SDimitry Andric ForDefinition_t IsForDefinition) { 46190b57cec5SDimitry Andric assert(D->hasGlobalStorage() && "Not a global variable"); 46200b57cec5SDimitry Andric QualType ASTTy = D->getType(); 46210b57cec5SDimitry Andric if (!Ty) 46220b57cec5SDimitry Andric Ty = getTypes().ConvertTypeForMem(ASTTy); 46230b57cec5SDimitry Andric 46240b57cec5SDimitry Andric StringRef MangledName = getMangledName(D); 4625349cc55cSDimitry Andric return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D, 4626fe6060f1SDimitry Andric IsForDefinition); 46270b57cec5SDimitry Andric } 46280b57cec5SDimitry Andric 46290b57cec5SDimitry Andric /// CreateRuntimeVariable - Create a new runtime global variable with the 46300b57cec5SDimitry Andric /// specified type and name. 46310b57cec5SDimitry Andric llvm::Constant * 46320b57cec5SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 46330b57cec5SDimitry 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); 46370b57cec5SDimitry Andric setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts())); 46380b57cec5SDimitry Andric return Ret; 46390b57cec5SDimitry Andric } 46400b57cec5SDimitry Andric 46410b57cec5SDimitry Andric void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 46420b57cec5SDimitry Andric assert(!D->getInit() && "Cannot emit definite definitions here!"); 46430b57cec5SDimitry Andric 46440b57cec5SDimitry Andric StringRef MangledName = getMangledName(D); 46450b57cec5SDimitry Andric llvm::GlobalValue *GV = GetGlobalValue(MangledName); 46460b57cec5SDimitry Andric 46470b57cec5SDimitry Andric // We already have a definition, not declaration, with the same mangled name. 46480b57cec5SDimitry Andric // Emitting of declaration is not required (and actually overwrites emitted 46490b57cec5SDimitry Andric // definition). 46500b57cec5SDimitry Andric if (GV && !GV->isDeclaration()) 46510b57cec5SDimitry Andric return; 46520b57cec5SDimitry Andric 46530b57cec5SDimitry Andric // If we have not seen a reference to this variable yet, place it into the 46540b57cec5SDimitry Andric // deferred declarations table to be emitted if needed later. 46550b57cec5SDimitry Andric if (!MustBeEmitted(D) && !GV) { 46560b57cec5SDimitry Andric DeferredDecls[MangledName] = D; 46570b57cec5SDimitry Andric return; 46580b57cec5SDimitry Andric } 46590b57cec5SDimitry Andric 46600b57cec5SDimitry Andric // The tentative definition is the only definition. 46610b57cec5SDimitry Andric EmitGlobalVarDefinition(D); 46620b57cec5SDimitry Andric } 46630b57cec5SDimitry Andric 4664480093f4SDimitry Andric void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) { 4665480093f4SDimitry Andric EmitExternalVarDeclaration(D); 4666480093f4SDimitry Andric } 4667480093f4SDimitry Andric 46680b57cec5SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 46690b57cec5SDimitry Andric return Context.toCharUnitsFromBits( 46700b57cec5SDimitry Andric getDataLayout().getTypeStoreSizeInBits(Ty)); 46710b57cec5SDimitry Andric } 46720b57cec5SDimitry Andric 46730b57cec5SDimitry Andric LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { 46740b57cec5SDimitry 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; 46830b57cec5SDimitry Andric } 46840b57cec5SDimitry Andric 4685fe6060f1SDimitry Andric if (LangOpts.SYCLIsDevice && 4686fe6060f1SDimitry Andric (!D || D->getType().getAddressSpace() == LangAS::Default)) 4687fe6060f1SDimitry Andric return LangAS::sycl_global; 4688fe6060f1SDimitry Andric 46890b57cec5SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { 46900b57cec5SDimitry Andric if (D && D->hasAttr<CUDAConstantAttr>()) 46910b57cec5SDimitry Andric return LangAS::cuda_constant; 46920b57cec5SDimitry Andric else if (D && D->hasAttr<CUDASharedAttr>()) 46930b57cec5SDimitry Andric return LangAS::cuda_shared; 46940b57cec5SDimitry Andric else if (D && D->hasAttr<CUDADeviceAttr>()) 46950b57cec5SDimitry Andric return LangAS::cuda_device; 46960b57cec5SDimitry Andric else if (D && D->getType().isConstQualified()) 46970b57cec5SDimitry Andric return LangAS::cuda_constant; 46980b57cec5SDimitry Andric else 46990b57cec5SDimitry Andric return LangAS::cuda_device; 47000b57cec5SDimitry Andric } 47010b57cec5SDimitry Andric 47020b57cec5SDimitry Andric if (LangOpts.OpenMP) { 47030b57cec5SDimitry Andric LangAS AS; 47040b57cec5SDimitry Andric if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS)) 47050b57cec5SDimitry Andric return AS; 47060b57cec5SDimitry Andric } 47070b57cec5SDimitry Andric return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D); 47080b57cec5SDimitry Andric } 47090b57cec5SDimitry Andric 4710fe6060f1SDimitry Andric LangAS CodeGenModule::GetGlobalConstantAddressSpace() const { 47110b57cec5SDimitry Andric // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 47120b57cec5SDimitry Andric if (LangOpts.OpenCL) 47130b57cec5SDimitry 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; 47240b57cec5SDimitry Andric if (auto AS = getTarget().getConstantAddressSpace()) 472581ad6265SDimitry Andric return *AS; 47260b57cec5SDimitry Andric return LangAS::Default; 47270b57cec5SDimitry Andric } 47280b57cec5SDimitry Andric 47290b57cec5SDimitry Andric // In address space agnostic languages, string literals are in default address 47300b57cec5SDimitry Andric // space in AST. However, certain targets (e.g. amdgcn) request them to be 47310b57cec5SDimitry Andric // emitted in constant address space in LLVM IR. To be consistent with other 47320b57cec5SDimitry Andric // parts of AST, string literal global variables in constant address space 47330b57cec5SDimitry Andric // need to be casted to default address space before being put into address 47340b57cec5SDimitry Andric // map and referenced by other part of CodeGen. 47350b57cec5SDimitry Andric // In OpenCL, string literals are in constant address space in AST, therefore 47360b57cec5SDimitry Andric // they should not be casted to default address space. 47370b57cec5SDimitry Andric static llvm::Constant * 47380b57cec5SDimitry Andric castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, 47390b57cec5SDimitry Andric llvm::GlobalVariable *GV) { 47400b57cec5SDimitry Andric llvm::Constant *Cast = GV; 47410b57cec5SDimitry Andric if (!CGM.getLangOpts().OpenCL) { 4742fe6060f1SDimitry Andric auto AS = CGM.GetGlobalConstantAddressSpace(); 47430b57cec5SDimitry Andric if (AS != LangAS::Default) 47440b57cec5SDimitry Andric Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast( 4745fe6060f1SDimitry Andric CGM, GV, AS, LangAS::Default, 47460b57cec5SDimitry Andric GV->getValueType()->getPointerTo( 47470b57cec5SDimitry Andric CGM.getContext().getTargetAddressSpace(LangAS::Default))); 47480b57cec5SDimitry Andric } 47490b57cec5SDimitry Andric return Cast; 47500b57cec5SDimitry Andric } 47510b57cec5SDimitry Andric 47520b57cec5SDimitry Andric template<typename SomeDecl> 47530b57cec5SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 47540b57cec5SDimitry Andric llvm::GlobalValue *GV) { 47550b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus) 47560b57cec5SDimitry Andric return; 47570b57cec5SDimitry Andric 47580b57cec5SDimitry Andric // Must have 'used' attribute, or else inline assembly can't rely on 47590b57cec5SDimitry Andric // the name existing. 47600b57cec5SDimitry Andric if (!D->template hasAttr<UsedAttr>()) 47610b57cec5SDimitry Andric return; 47620b57cec5SDimitry Andric 47630b57cec5SDimitry Andric // Must have internal linkage and an ordinary name. 47640b57cec5SDimitry Andric if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 47650b57cec5SDimitry Andric return; 47660b57cec5SDimitry Andric 47670b57cec5SDimitry Andric // Must be in an extern "C" context. Entities declared directly within 47680b57cec5SDimitry Andric // a record are not extern "C" even if the record is in such a context. 47690b57cec5SDimitry Andric const SomeDecl *First = D->getFirstDecl(); 47700b57cec5SDimitry Andric if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 47710b57cec5SDimitry Andric return; 47720b57cec5SDimitry Andric 47730b57cec5SDimitry Andric // OK, this is an internal linkage entity inside an extern "C" linkage 47740b57cec5SDimitry Andric // specification. Make a note of that so we can give it the "expected" 47750b57cec5SDimitry Andric // mangled name if nothing else is using that name. 47760b57cec5SDimitry Andric std::pair<StaticExternCMap::iterator, bool> R = 47770b57cec5SDimitry Andric StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 47780b57cec5SDimitry Andric 47790b57cec5SDimitry Andric // If we have multiple internal linkage entities with the same name 47800b57cec5SDimitry Andric // in extern "C" regions, none of them gets that name. 47810b57cec5SDimitry Andric if (!R.second) 47820b57cec5SDimitry Andric R.first->second = nullptr; 47830b57cec5SDimitry Andric } 47840b57cec5SDimitry Andric 47850b57cec5SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 47860b57cec5SDimitry Andric if (!CGM.supportsCOMDAT()) 47870b57cec5SDimitry Andric return false; 47880b57cec5SDimitry Andric 47890b57cec5SDimitry Andric if (D.hasAttr<SelectAnyAttr>()) 47900b57cec5SDimitry Andric return true; 47910b57cec5SDimitry Andric 47920b57cec5SDimitry Andric GVALinkage Linkage; 47930b57cec5SDimitry Andric if (auto *VD = dyn_cast<VarDecl>(&D)) 47940b57cec5SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 47950b57cec5SDimitry Andric else 47960b57cec5SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 47970b57cec5SDimitry Andric 47980b57cec5SDimitry Andric switch (Linkage) { 47990b57cec5SDimitry Andric case GVA_Internal: 48000b57cec5SDimitry Andric case GVA_AvailableExternally: 48010b57cec5SDimitry Andric case GVA_StrongExternal: 48020b57cec5SDimitry Andric return false; 48030b57cec5SDimitry Andric case GVA_DiscardableODR: 48040b57cec5SDimitry Andric case GVA_StrongODR: 48050b57cec5SDimitry Andric return true; 48060b57cec5SDimitry Andric } 48070b57cec5SDimitry Andric llvm_unreachable("No such linkage"); 48080b57cec5SDimitry Andric } 48090b57cec5SDimitry Andric 48100b57cec5SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 48110b57cec5SDimitry Andric llvm::GlobalObject &GO) { 48120b57cec5SDimitry Andric if (!shouldBeInCOMDAT(*this, D)) 48130b57cec5SDimitry Andric return; 48140b57cec5SDimitry Andric GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 48150b57cec5SDimitry Andric } 48160b57cec5SDimitry Andric 48170b57cec5SDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition. 48180b57cec5SDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 48190b57cec5SDimitry Andric bool IsTentative) { 48200b57cec5SDimitry Andric // OpenCL global variables of sampler type are translated to function calls, 48210b57cec5SDimitry Andric // therefore no need to be translated. 48220b57cec5SDimitry Andric QualType ASTTy = D->getType(); 48230b57cec5SDimitry Andric if (getLangOpts().OpenCL && ASTTy->isSamplerT()) 48240b57cec5SDimitry Andric return; 48250b57cec5SDimitry Andric 48260b57cec5SDimitry Andric // If this is OpenMP device, check if it is legal to emit this global 48270b57cec5SDimitry Andric // normally. 48280b57cec5SDimitry Andric if (LangOpts.OpenMPIsDevice && OpenMPRuntime && 48290b57cec5SDimitry Andric OpenMPRuntime->emitTargetGlobalVariable(D)) 48300b57cec5SDimitry Andric return; 48310b57cec5SDimitry Andric 4832fe6060f1SDimitry Andric llvm::TrackingVH<llvm::Constant> Init; 48330b57cec5SDimitry Andric bool NeedsGlobalCtor = false; 4834*bdd1243dSDimitry Andric // Whether the definition of the variable is available externally. 4835*bdd1243dSDimitry Andric // If yes, we shouldn't emit the GloablCtor and GlobalDtor for the variable 4836*bdd1243dSDimitry Andric // since this is the job for its original source. 4837*bdd1243dSDimitry Andric bool IsDefinitionAvailableExternally = 4838*bdd1243dSDimitry Andric getContext().GetGVALinkageForVariable(D) == GVA_AvailableExternally; 4839a7dea167SDimitry Andric bool NeedsGlobalDtor = 4840*bdd1243dSDimitry Andric !IsDefinitionAvailableExternally && 4841a7dea167SDimitry Andric D->needsDestruction(getContext()) == QualType::DK_cxx_destructor; 48420b57cec5SDimitry Andric 48430b57cec5SDimitry Andric const VarDecl *InitDecl; 48440b57cec5SDimitry Andric const Expr *InitExpr = D->getAnyInitializer(InitDecl); 48450b57cec5SDimitry Andric 4846*bdd1243dSDimitry Andric std::optional<ConstantEmitter> emitter; 48470b57cec5SDimitry Andric 48480b57cec5SDimitry Andric // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 48490b57cec5SDimitry Andric // as part of their declaration." Sema has already checked for 48500b57cec5SDimitry Andric // error cases, so we just need to set Init to UndefValue. 48510b57cec5SDimitry Andric bool IsCUDASharedVar = 48520b57cec5SDimitry Andric getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>(); 48530b57cec5SDimitry Andric // Shadows of initialized device-side global variables are also left 48540b57cec5SDimitry Andric // undefined. 4855fe6060f1SDimitry Andric // Managed Variables should be initialized on both host side and device side. 48560b57cec5SDimitry Andric bool IsCUDAShadowVar = 4857e8d8bef9SDimitry Andric !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 48580b57cec5SDimitry Andric (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() || 48590b57cec5SDimitry 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()); 48640b57cec5SDimitry 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)); 48690b57cec5SDimitry Andric else if (!InitExpr) { 48700b57cec5SDimitry Andric // This is a tentative definition; tentative definitions are 48710b57cec5SDimitry Andric // implicitly initialized with { 0 }. 48720b57cec5SDimitry Andric // 48730b57cec5SDimitry Andric // Note that tentative definitions are only emitted at the end of 48740b57cec5SDimitry Andric // a translation unit, so they should never have incomplete 48750b57cec5SDimitry Andric // type. In addition, EmitTentativeDefinition makes sure that we 48760b57cec5SDimitry Andric // never attempt to emit a tentative definition if a real one 48770b57cec5SDimitry Andric // exists. A use may still exists, however, so we still may need 48780b57cec5SDimitry Andric // to do a RAUW. 48790b57cec5SDimitry Andric assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 48800b57cec5SDimitry Andric Init = EmitNullConstant(D->getType()); 48810b57cec5SDimitry Andric } else { 48820b57cec5SDimitry Andric initializedGlobalDecl = GlobalDecl(D); 48830b57cec5SDimitry Andric emitter.emplace(*this); 4884fe6060f1SDimitry Andric llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl); 4885fe6060f1SDimitry Andric if (!Initializer) { 48860b57cec5SDimitry Andric QualType T = InitExpr->getType(); 48870b57cec5SDimitry Andric if (D->getType()->isReferenceType()) 48880b57cec5SDimitry Andric T = D->getType(); 48890b57cec5SDimitry Andric 48900b57cec5SDimitry Andric if (getLangOpts().CPlusPlus) { 489181ad6265SDimitry Andric if (InitDecl->hasFlexibleArrayInit(getContext())) 489281ad6265SDimitry Andric ErrorUnsupported(D, "flexible array initializer"); 48930b57cec5SDimitry Andric Init = EmitNullConstant(T); 4894*bdd1243dSDimitry Andric 4895*bdd1243dSDimitry Andric if (!IsDefinitionAvailableExternally) 48960b57cec5SDimitry Andric NeedsGlobalCtor = true; 48970b57cec5SDimitry Andric } else { 48980b57cec5SDimitry Andric ErrorUnsupported(D, "static initializer"); 48990b57cec5SDimitry Andric Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 49000b57cec5SDimitry Andric } 49010b57cec5SDimitry Andric } else { 4902fe6060f1SDimitry Andric Init = Initializer; 49030b57cec5SDimitry Andric // We don't need an initializer, so remove the entry for the delayed 49040b57cec5SDimitry Andric // initializer position (just in case this entry was delayed) if we 49050b57cec5SDimitry Andric // also don't need to register a destructor. 49060b57cec5SDimitry Andric if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 49070b57cec5SDimitry 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 49160b57cec5SDimitry Andric } 49170b57cec5SDimitry Andric } 49180b57cec5SDimitry Andric 49190b57cec5SDimitry Andric llvm::Type* InitType = Init->getType(); 49200b57cec5SDimitry Andric llvm::Constant *Entry = 49210b57cec5SDimitry Andric GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); 49220b57cec5SDimitry Andric 4923a7dea167SDimitry Andric // Strip off pointer casts if we got them. 4924a7dea167SDimitry Andric Entry = Entry->stripPointerCasts(); 49250b57cec5SDimitry Andric 49260b57cec5SDimitry Andric // Entry is now either a Function or GlobalVariable. 49270b57cec5SDimitry Andric auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 49280b57cec5SDimitry Andric 49290b57cec5SDimitry Andric // We have a definition after a declaration with the wrong type. 49300b57cec5SDimitry Andric // We must make a new GlobalVariable* and update everything that used OldGV 49310b57cec5SDimitry Andric // (a declaration or tentative definition) with the new GlobalVariable* 49320b57cec5SDimitry Andric // (which will be a definition). 49330b57cec5SDimitry Andric // 49340b57cec5SDimitry Andric // This happens if there is a prototype for a global (e.g. 49350b57cec5SDimitry Andric // "extern int x[];") and then a definition of a different type (e.g. 49360b57cec5SDimitry Andric // "int x[10];"). This also happens when an initializer has a different type 49370b57cec5SDimitry Andric // from the type of the global (this happens with unions). 49385ffd83dbSDimitry Andric if (!GV || GV->getValueType() != InitType || 49390b57cec5SDimitry Andric GV->getType()->getAddressSpace() != 49400b57cec5SDimitry Andric getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) { 49410b57cec5SDimitry Andric 49420b57cec5SDimitry Andric // Move the old entry aside so that we'll create a new one. 49430b57cec5SDimitry Andric Entry->setName(StringRef()); 49440b57cec5SDimitry Andric 49450b57cec5SDimitry Andric // Make a new global with the correct type, this is now guaranteed to work. 49460b57cec5SDimitry Andric GV = cast<llvm::GlobalVariable>( 4947a7dea167SDimitry Andric GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)) 4948a7dea167SDimitry Andric ->stripPointerCasts()); 49490b57cec5SDimitry Andric 49500b57cec5SDimitry Andric // Replace all uses of the old global with the new global 49510b57cec5SDimitry Andric llvm::Constant *NewPtrForOldDecl = 4952fe6060f1SDimitry Andric llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, 4953fe6060f1SDimitry Andric Entry->getType()); 49540b57cec5SDimitry Andric Entry->replaceAllUsesWith(NewPtrForOldDecl); 49550b57cec5SDimitry Andric 49560b57cec5SDimitry Andric // Erase the old global, since it is no longer used. 49570b57cec5SDimitry Andric cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 49580b57cec5SDimitry Andric } 49590b57cec5SDimitry Andric 49600b57cec5SDimitry Andric MaybeHandleStaticInExternC(D, GV); 49610b57cec5SDimitry Andric 49620b57cec5SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 49630b57cec5SDimitry Andric AddGlobalAnnotations(D, GV); 49640b57cec5SDimitry Andric 49650b57cec5SDimitry Andric // Set the llvm linkage type as appropriate. 49660b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 49670b57cec5SDimitry Andric getLLVMLinkageVarDefinition(D, GV->isConstant()); 49680b57cec5SDimitry Andric 49690b57cec5SDimitry Andric // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 49700b57cec5SDimitry Andric // the device. [...]" 49710b57cec5SDimitry Andric // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 49720b57cec5SDimitry Andric // __device__, declares a variable that: [...] 49730b57cec5SDimitry Andric // Is accessible from all the threads within the grid and from the host 49740b57cec5SDimitry Andric // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 49750b57cec5SDimitry Andric // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 49760b57cec5SDimitry Andric if (GV && LangOpts.CUDA) { 49770b57cec5SDimitry Andric if (LangOpts.CUDAIsDevice) { 49780b57cec5SDimitry Andric if (Linkage != llvm::GlobalValue::InternalLinkage && 4979349cc55cSDimitry Andric (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 4980349cc55cSDimitry Andric D->getType()->isCUDADeviceBuiltinSurfaceType() || 4981349cc55cSDimitry Andric D->getType()->isCUDADeviceBuiltinTextureType())) 49820b57cec5SDimitry Andric GV->setExternallyInitialized(true); 49830b57cec5SDimitry Andric } else { 4984fe6060f1SDimitry Andric getCUDARuntime().internalizeDeviceSideVar(D, Linkage); 49855ffd83dbSDimitry Andric } 4986fe6060f1SDimitry Andric getCUDARuntime().handleVarRegistration(D, *GV); 49870b57cec5SDimitry Andric } 49880b57cec5SDimitry Andric 49890b57cec5SDimitry Andric GV->setInitializer(Init); 49905ffd83dbSDimitry Andric if (emitter) 49915ffd83dbSDimitry Andric emitter->finalize(GV); 49920b57cec5SDimitry Andric 49930b57cec5SDimitry Andric // If it is safe to mark the global 'constant', do so now. 49940b57cec5SDimitry Andric GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 49950b57cec5SDimitry Andric isTypeConstant(D->getType(), true)); 49960b57cec5SDimitry Andric 49970b57cec5SDimitry Andric // If it is in a read-only section, mark it 'constant'. 49980b57cec5SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 49990b57cec5SDimitry Andric const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 50000b57cec5SDimitry Andric if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 50010b57cec5SDimitry Andric GV->setConstant(true); 50020b57cec5SDimitry Andric } 50030b57cec5SDimitry Andric 500481ad6265SDimitry Andric CharUnits AlignVal = getContext().getDeclAlign(D); 500581ad6265SDimitry Andric // Check for alignment specifed in an 'omp allocate' directive. 5006*bdd1243dSDimitry Andric if (std::optional<CharUnits> AlignValFromAllocate = 500781ad6265SDimitry Andric getOMPAllocateAlignment(D)) 500881ad6265SDimitry Andric AlignVal = *AlignValFromAllocate; 500981ad6265SDimitry Andric GV->setAlignment(AlignVal.getAsAlign()); 50100b57cec5SDimitry 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 && 50270b57cec5SDimitry Andric Context.getTargetInfo().getTriple().isOSDarwin() && 50285ffd83dbSDimitry Andric !D->hasAttr<ConstInitAttr>()) 50290b57cec5SDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 50300b57cec5SDimitry Andric 50310b57cec5SDimitry Andric GV->setLinkage(Linkage); 50320b57cec5SDimitry Andric if (D->hasAttr<DLLImportAttr>()) 50330b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 50340b57cec5SDimitry Andric else if (D->hasAttr<DLLExportAttr>()) 50350b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 50360b57cec5SDimitry Andric else 50370b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 50380b57cec5SDimitry Andric 50390b57cec5SDimitry Andric if (Linkage == llvm::GlobalVariable::CommonLinkage) { 50400b57cec5SDimitry Andric // common vars aren't constant even if declared const. 50410b57cec5SDimitry Andric GV->setConstant(false); 50420b57cec5SDimitry Andric // Tentative definition of global variables may be initialized with 50430b57cec5SDimitry Andric // non-zero null pointers. In this case they should have weak linkage 50440b57cec5SDimitry Andric // since common linkage must have zero initializer and must not have 50450b57cec5SDimitry Andric // explicit section therefore cannot have non-zero initial value. 50460b57cec5SDimitry Andric if (!GV->getInitializer()->isNullValue()) 50470b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 50480b57cec5SDimitry Andric } 50490b57cec5SDimitry Andric 50500b57cec5SDimitry Andric setNonAliasAttributes(D, GV); 50510b57cec5SDimitry Andric 50520b57cec5SDimitry Andric if (D->getTLSKind() && !GV->isThreadLocal()) { 50530b57cec5SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 50540b57cec5SDimitry Andric CXXThreadLocals.push_back(D); 50550b57cec5SDimitry Andric setTLSMode(GV, *D); 50560b57cec5SDimitry Andric } 50570b57cec5SDimitry Andric 50580b57cec5SDimitry Andric maybeSetTrivialComdat(*D, *GV); 50590b57cec5SDimitry Andric 50600b57cec5SDimitry Andric // Emit the initializer function if necessary. 50610b57cec5SDimitry Andric if (NeedsGlobalCtor || NeedsGlobalDtor) 50620b57cec5SDimitry Andric EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 50630b57cec5SDimitry Andric 506481ad6265SDimitry Andric SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor); 50650b57cec5SDimitry Andric 50660b57cec5SDimitry Andric // Emit global variable debug information. 50670b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 5068480093f4SDimitry Andric if (getCodeGenOpts().hasReducedDebugInfo()) 50690b57cec5SDimitry Andric DI->EmitGlobalVariable(GV, D); 50700b57cec5SDimitry Andric } 50710b57cec5SDimitry 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 50840b57cec5SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context, 50850b57cec5SDimitry Andric CodeGenModule &CGM, const VarDecl *D, 50860b57cec5SDimitry Andric bool NoCommon) { 50870b57cec5SDimitry Andric // Don't give variables common linkage if -fno-common was specified unless it 50880b57cec5SDimitry Andric // was overridden by a NoCommon attribute. 50890b57cec5SDimitry Andric if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 50900b57cec5SDimitry Andric return true; 50910b57cec5SDimitry Andric 50920b57cec5SDimitry Andric // C11 6.9.2/2: 50930b57cec5SDimitry Andric // A declaration of an identifier for an object that has file scope without 50940b57cec5SDimitry Andric // an initializer, and without a storage-class specifier or with the 50950b57cec5SDimitry Andric // storage-class specifier static, constitutes a tentative definition. 50960b57cec5SDimitry Andric if (D->getInit() || D->hasExternalStorage()) 50970b57cec5SDimitry Andric return true; 50980b57cec5SDimitry Andric 50990b57cec5SDimitry Andric // A variable cannot be both common and exist in a section. 51000b57cec5SDimitry Andric if (D->hasAttr<SectionAttr>()) 51010b57cec5SDimitry Andric return true; 51020b57cec5SDimitry Andric 51030b57cec5SDimitry Andric // A variable cannot be both common and exist in a section. 51040b57cec5SDimitry Andric // We don't try to determine which is the right section in the front-end. 51050b57cec5SDimitry Andric // If no specialized section name is applicable, it will resort to default. 51060b57cec5SDimitry Andric if (D->hasAttr<PragmaClangBSSSectionAttr>() || 51070b57cec5SDimitry Andric D->hasAttr<PragmaClangDataSectionAttr>() || 5108a7dea167SDimitry Andric D->hasAttr<PragmaClangRelroSectionAttr>() || 51090b57cec5SDimitry Andric D->hasAttr<PragmaClangRodataSectionAttr>()) 51100b57cec5SDimitry Andric return true; 51110b57cec5SDimitry Andric 51120b57cec5SDimitry Andric // Thread local vars aren't considered common linkage. 51130b57cec5SDimitry Andric if (D->getTLSKind()) 51140b57cec5SDimitry Andric return true; 51150b57cec5SDimitry Andric 51160b57cec5SDimitry Andric // Tentative definitions marked with WeakImportAttr are true definitions. 51170b57cec5SDimitry Andric if (D->hasAttr<WeakImportAttr>()) 51180b57cec5SDimitry Andric return true; 51190b57cec5SDimitry Andric 51200b57cec5SDimitry Andric // A variable cannot be both common and exist in a comdat. 51210b57cec5SDimitry Andric if (shouldBeInCOMDAT(CGM, *D)) 51220b57cec5SDimitry Andric return true; 51230b57cec5SDimitry Andric 51240b57cec5SDimitry Andric // Declarations with a required alignment do not have common linkage in MSVC 51250b57cec5SDimitry Andric // mode. 51260b57cec5SDimitry Andric if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 51270b57cec5SDimitry Andric if (D->hasAttr<AlignedAttr>()) 51280b57cec5SDimitry Andric return true; 51290b57cec5SDimitry Andric QualType VarType = D->getType(); 51300b57cec5SDimitry Andric if (Context.isAlignmentRequired(VarType)) 51310b57cec5SDimitry Andric return true; 51320b57cec5SDimitry Andric 51330b57cec5SDimitry Andric if (const auto *RT = VarType->getAs<RecordType>()) { 51340b57cec5SDimitry Andric const RecordDecl *RD = RT->getDecl(); 51350b57cec5SDimitry Andric for (const FieldDecl *FD : RD->fields()) { 51360b57cec5SDimitry Andric if (FD->isBitField()) 51370b57cec5SDimitry Andric continue; 51380b57cec5SDimitry Andric if (FD->hasAttr<AlignedAttr>()) 51390b57cec5SDimitry Andric return true; 51400b57cec5SDimitry Andric if (Context.isAlignmentRequired(FD->getType())) 51410b57cec5SDimitry Andric return true; 51420b57cec5SDimitry Andric } 51430b57cec5SDimitry Andric } 51440b57cec5SDimitry Andric } 51450b57cec5SDimitry Andric 51460b57cec5SDimitry Andric // Microsoft's link.exe doesn't support alignments greater than 32 bytes for 51470b57cec5SDimitry Andric // common symbols, so symbols with greater alignment requirements cannot be 51480b57cec5SDimitry Andric // common. 51490b57cec5SDimitry Andric // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two 51500b57cec5SDimitry Andric // alignments for common symbols via the aligncomm directive, so this 51510b57cec5SDimitry Andric // restriction only applies to MSVC environments. 51520b57cec5SDimitry Andric if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() && 51530b57cec5SDimitry Andric Context.getTypeAlignIfKnown(D->getType()) > 51540b57cec5SDimitry Andric Context.toBits(CharUnits::fromQuantity(32))) 51550b57cec5SDimitry Andric return true; 51560b57cec5SDimitry Andric 51570b57cec5SDimitry Andric return false; 51580b57cec5SDimitry Andric } 51590b57cec5SDimitry Andric 51600b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 51610b57cec5SDimitry Andric const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 51620b57cec5SDimitry Andric if (Linkage == GVA_Internal) 51630b57cec5SDimitry Andric return llvm::Function::InternalLinkage; 51640b57cec5SDimitry Andric 516581ad6265SDimitry Andric if (D->hasAttr<WeakAttr>()) 51660b57cec5SDimitry Andric return llvm::GlobalVariable::WeakAnyLinkage; 51670b57cec5SDimitry Andric 51680b57cec5SDimitry Andric if (const auto *FD = D->getAsFunction()) 51690b57cec5SDimitry Andric if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally) 51700b57cec5SDimitry Andric return llvm::GlobalVariable::LinkOnceAnyLinkage; 51710b57cec5SDimitry Andric 51720b57cec5SDimitry Andric // We are guaranteed to have a strong definition somewhere else, 51730b57cec5SDimitry Andric // so we can use available_externally linkage. 51740b57cec5SDimitry Andric if (Linkage == GVA_AvailableExternally) 51750b57cec5SDimitry Andric return llvm::GlobalValue::AvailableExternallyLinkage; 51760b57cec5SDimitry Andric 51770b57cec5SDimitry Andric // Note that Apple's kernel linker doesn't support symbol 51780b57cec5SDimitry Andric // coalescing, so we need to avoid linkonce and weak linkages there. 51790b57cec5SDimitry Andric // Normally, this means we just map to internal, but for explicit 51800b57cec5SDimitry Andric // instantiations we'll map to external. 51810b57cec5SDimitry Andric 51820b57cec5SDimitry Andric // In C++, the compiler has to emit a definition in every translation unit 51830b57cec5SDimitry Andric // that references the function. We should use linkonce_odr because 51840b57cec5SDimitry Andric // a) if all references in this translation unit are optimized away, we 51850b57cec5SDimitry Andric // don't need to codegen it. b) if the function persists, it needs to be 51860b57cec5SDimitry Andric // merged with other definitions. c) C++ has the ODR, so we know the 51870b57cec5SDimitry Andric // definition is dependable. 51880b57cec5SDimitry Andric if (Linkage == GVA_DiscardableODR) 51890b57cec5SDimitry Andric return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 51900b57cec5SDimitry Andric : llvm::Function::InternalLinkage; 51910b57cec5SDimitry Andric 51920b57cec5SDimitry Andric // An explicit instantiation of a template has weak linkage, since 51930b57cec5SDimitry Andric // explicit instantiations can occur in multiple translation units 51940b57cec5SDimitry Andric // and must all be equivalent. However, we are not allowed to 51950b57cec5SDimitry Andric // throw away these explicit instantiations. 51960b57cec5SDimitry Andric // 5197e8d8bef9SDimitry Andric // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU, 51980b57cec5SDimitry 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. 52020b57cec5SDimitry Andric if (Linkage == GVA_StrongODR) { 5203e8d8bef9SDimitry Andric if (getLangOpts().AppleKext) 52040b57cec5SDimitry Andric return llvm::Function::ExternalLinkage; 5205e8d8bef9SDimitry Andric if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 5206e8d8bef9SDimitry Andric !getLangOpts().GPURelocatableDeviceCode) 52070b57cec5SDimitry Andric return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage 52080b57cec5SDimitry Andric : llvm::Function::InternalLinkage; 52090b57cec5SDimitry Andric return llvm::Function::WeakODRLinkage; 52100b57cec5SDimitry Andric } 52110b57cec5SDimitry Andric 52120b57cec5SDimitry Andric // C++ doesn't have tentative definitions and thus cannot have common 52130b57cec5SDimitry Andric // linkage. 52140b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 52150b57cec5SDimitry Andric !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 52160b57cec5SDimitry Andric CodeGenOpts.NoCommon)) 52170b57cec5SDimitry Andric return llvm::GlobalVariable::CommonLinkage; 52180b57cec5SDimitry Andric 52190b57cec5SDimitry Andric // selectany symbols are externally visible, so use weak instead of 52200b57cec5SDimitry Andric // linkonce. MSVC optimizes away references to const selectany globals, so 52210b57cec5SDimitry Andric // all definitions should be the same and ODR linkage should be used. 52220b57cec5SDimitry Andric // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 52230b57cec5SDimitry Andric if (D->hasAttr<SelectAnyAttr>()) 52240b57cec5SDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 52250b57cec5SDimitry Andric 52260b57cec5SDimitry Andric // Otherwise, we have strong external linkage. 52270b57cec5SDimitry Andric assert(Linkage == GVA_StrongExternal); 52280b57cec5SDimitry Andric return llvm::GlobalVariable::ExternalLinkage; 52290b57cec5SDimitry Andric } 52300b57cec5SDimitry Andric 52310b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 52320b57cec5SDimitry Andric const VarDecl *VD, bool IsConstant) { 52330b57cec5SDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 52340b57cec5SDimitry Andric return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 52350b57cec5SDimitry Andric } 52360b57cec5SDimitry Andric 52370b57cec5SDimitry Andric /// Replace the uses of a function that was declared with a non-proto type. 52380b57cec5SDimitry Andric /// We want to silently drop extra arguments from call sites 52390b57cec5SDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 52400b57cec5SDimitry Andric llvm::Function *newFn) { 52410b57cec5SDimitry Andric // Fast path. 52420b57cec5SDimitry Andric if (old->use_empty()) return; 52430b57cec5SDimitry Andric 52440b57cec5SDimitry Andric llvm::Type *newRetTy = newFn->getReturnType(); 52450b57cec5SDimitry Andric SmallVector<llvm::Value*, 4> newArgs; 52460b57cec5SDimitry Andric 52470b57cec5SDimitry Andric for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 52480b57cec5SDimitry Andric ui != ue; ) { 52490b57cec5SDimitry Andric llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 52500b57cec5SDimitry Andric llvm::User *user = use->getUser(); 52510b57cec5SDimitry Andric 52520b57cec5SDimitry Andric // Recognize and replace uses of bitcasts. Most calls to 52530b57cec5SDimitry Andric // unprototyped functions will use bitcasts. 52540b57cec5SDimitry Andric if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 52550b57cec5SDimitry Andric if (bitcast->getOpcode() == llvm::Instruction::BitCast) 52560b57cec5SDimitry Andric replaceUsesOfNonProtoConstant(bitcast, newFn); 52570b57cec5SDimitry Andric continue; 52580b57cec5SDimitry Andric } 52590b57cec5SDimitry Andric 52600b57cec5SDimitry Andric // Recognize calls to the function. 52610b57cec5SDimitry Andric llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user); 52620b57cec5SDimitry Andric if (!callSite) continue; 52630b57cec5SDimitry Andric if (!callSite->isCallee(&*use)) 52640b57cec5SDimitry Andric continue; 52650b57cec5SDimitry Andric 52660b57cec5SDimitry Andric // If the return types don't match exactly, then we can't 52670b57cec5SDimitry Andric // transform this call unless it's dead. 52680b57cec5SDimitry Andric if (callSite->getType() != newRetTy && !callSite->use_empty()) 52690b57cec5SDimitry Andric continue; 52700b57cec5SDimitry Andric 52710b57cec5SDimitry Andric // Get the call site's attribute list. 52720b57cec5SDimitry Andric SmallVector<llvm::AttributeSet, 8> newArgAttrs; 52730b57cec5SDimitry Andric llvm::AttributeList oldAttrs = callSite->getAttributes(); 52740b57cec5SDimitry Andric 52750b57cec5SDimitry Andric // If the function was passed too few arguments, don't transform. 52760b57cec5SDimitry Andric unsigned newNumArgs = newFn->arg_size(); 52770b57cec5SDimitry Andric if (callSite->arg_size() < newNumArgs) 52780b57cec5SDimitry Andric continue; 52790b57cec5SDimitry Andric 52800b57cec5SDimitry Andric // If extra arguments were passed, we silently drop them. 52810b57cec5SDimitry Andric // If any of the types mismatch, we don't transform. 52820b57cec5SDimitry Andric unsigned argNo = 0; 52830b57cec5SDimitry Andric bool dontTransform = false; 52840b57cec5SDimitry Andric for (llvm::Argument &A : newFn->args()) { 52850b57cec5SDimitry Andric if (callSite->getArgOperand(argNo)->getType() != A.getType()) { 52860b57cec5SDimitry Andric dontTransform = true; 52870b57cec5SDimitry Andric break; 52880b57cec5SDimitry Andric } 52890b57cec5SDimitry Andric 52900b57cec5SDimitry Andric // Add any parameter attributes. 5291349cc55cSDimitry Andric newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo)); 52920b57cec5SDimitry Andric argNo++; 52930b57cec5SDimitry Andric } 52940b57cec5SDimitry Andric if (dontTransform) 52950b57cec5SDimitry Andric continue; 52960b57cec5SDimitry Andric 52970b57cec5SDimitry Andric // Okay, we can transform this. Create the new call instruction and copy 52980b57cec5SDimitry Andric // over the required information. 52990b57cec5SDimitry Andric newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo); 53000b57cec5SDimitry Andric 53010b57cec5SDimitry Andric // Copy over any operand bundles. 5302fe6060f1SDimitry Andric SmallVector<llvm::OperandBundleDef, 1> newBundles; 53030b57cec5SDimitry Andric callSite->getOperandBundlesAsDefs(newBundles); 53040b57cec5SDimitry Andric 53050b57cec5SDimitry Andric llvm::CallBase *newCall; 5306349cc55cSDimitry Andric if (isa<llvm::CallInst>(callSite)) { 53070b57cec5SDimitry Andric newCall = 53080b57cec5SDimitry Andric llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite); 53090b57cec5SDimitry Andric } else { 53100b57cec5SDimitry Andric auto *oldInvoke = cast<llvm::InvokeInst>(callSite); 53110b57cec5SDimitry Andric newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(), 53120b57cec5SDimitry Andric oldInvoke->getUnwindDest(), newArgs, 53130b57cec5SDimitry Andric newBundles, "", callSite); 53140b57cec5SDimitry Andric } 53150b57cec5SDimitry Andric newArgs.clear(); // for the next iteration 53160b57cec5SDimitry Andric 53170b57cec5SDimitry Andric if (!newCall->getType()->isVoidTy()) 53180b57cec5SDimitry Andric newCall->takeName(callSite); 5319349cc55cSDimitry Andric newCall->setAttributes( 5320349cc55cSDimitry Andric llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(), 5321349cc55cSDimitry Andric oldAttrs.getRetAttrs(), newArgAttrs)); 53220b57cec5SDimitry Andric newCall->setCallingConv(callSite->getCallingConv()); 53230b57cec5SDimitry Andric 53240b57cec5SDimitry Andric // Finally, remove the old call, replacing any uses with the new one. 53250b57cec5SDimitry Andric if (!callSite->use_empty()) 53260b57cec5SDimitry Andric callSite->replaceAllUsesWith(newCall); 53270b57cec5SDimitry Andric 53280b57cec5SDimitry Andric // Copy debug location attached to CI. 53290b57cec5SDimitry Andric if (callSite->getDebugLoc()) 53300b57cec5SDimitry Andric newCall->setDebugLoc(callSite->getDebugLoc()); 53310b57cec5SDimitry Andric 53320b57cec5SDimitry Andric callSite->eraseFromParent(); 53330b57cec5SDimitry Andric } 53340b57cec5SDimitry Andric } 53350b57cec5SDimitry Andric 53360b57cec5SDimitry Andric /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 53370b57cec5SDimitry Andric /// implement a function with no prototype, e.g. "int foo() {}". If there are 53380b57cec5SDimitry Andric /// existing call uses of the old function in the module, this adjusts them to 53390b57cec5SDimitry Andric /// call the new function directly. 53400b57cec5SDimitry Andric /// 53410b57cec5SDimitry Andric /// This is not just a cleanup: the always_inline pass requires direct calls to 53420b57cec5SDimitry Andric /// functions to be able to inline them. If there is a bitcast in the way, it 53430b57cec5SDimitry Andric /// won't inline them. Instcombine normally deletes these calls, but it isn't 53440b57cec5SDimitry Andric /// run at -O0. 53450b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 53460b57cec5SDimitry Andric llvm::Function *NewFn) { 53470b57cec5SDimitry Andric // If we're redefining a global as a function, don't transform it. 53480b57cec5SDimitry Andric if (!isa<llvm::Function>(Old)) return; 53490b57cec5SDimitry Andric 53500b57cec5SDimitry Andric replaceUsesOfNonProtoConstant(Old, NewFn); 53510b57cec5SDimitry Andric } 53520b57cec5SDimitry Andric 53530b57cec5SDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 53540b57cec5SDimitry Andric auto DK = VD->isThisDeclarationADefinition(); 53550b57cec5SDimitry Andric if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) 53560b57cec5SDimitry Andric return; 53570b57cec5SDimitry Andric 53580b57cec5SDimitry Andric TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 53590b57cec5SDimitry Andric // If we have a definition, this might be a deferred decl. If the 53600b57cec5SDimitry Andric // instantiation is explicit, make sure we emit it at the end. 53610b57cec5SDimitry Andric if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 53620b57cec5SDimitry Andric GetAddrOfGlobalVar(VD); 53630b57cec5SDimitry Andric 53640b57cec5SDimitry Andric EmitTopLevelDecl(VD); 53650b57cec5SDimitry Andric } 53660b57cec5SDimitry Andric 53670b57cec5SDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 53680b57cec5SDimitry Andric llvm::GlobalValue *GV) { 53690b57cec5SDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 53700b57cec5SDimitry Andric 53710b57cec5SDimitry Andric // Compute the function info and LLVM type. 53720b57cec5SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 53730b57cec5SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 53740b57cec5SDimitry Andric 53750b57cec5SDimitry Andric // Get or create the prototype for the function. 53765ffd83dbSDimitry Andric if (!GV || (GV->getValueType() != Ty)) 53770b57cec5SDimitry Andric GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 53780b57cec5SDimitry Andric /*DontDefer=*/true, 53790b57cec5SDimitry Andric ForDefinition)); 53800b57cec5SDimitry Andric 53810b57cec5SDimitry Andric // Already emitted. 53820b57cec5SDimitry Andric if (!GV->isDeclaration()) 53830b57cec5SDimitry Andric return; 53840b57cec5SDimitry Andric 53850b57cec5SDimitry Andric // We need to set linkage and visibility on the function before 53860b57cec5SDimitry Andric // generating code for it because various parts of IR generation 53870b57cec5SDimitry Andric // want to propagate this information down (e.g. to local static 53880b57cec5SDimitry Andric // declarations). 53890b57cec5SDimitry Andric auto *Fn = cast<llvm::Function>(GV); 53900b57cec5SDimitry Andric setFunctionLinkage(GD, Fn); 53910b57cec5SDimitry Andric 53920b57cec5SDimitry Andric // FIXME: this is redundant with part of setFunctionDefinitionAttributes 53930b57cec5SDimitry Andric setGVProperties(Fn, GD); 53940b57cec5SDimitry Andric 53950b57cec5SDimitry Andric MaybeHandleStaticInExternC(D, Fn); 53960b57cec5SDimitry Andric 53970b57cec5SDimitry Andric maybeSetTrivialComdat(*D, *Fn); 53980b57cec5SDimitry 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); 54030b57cec5SDimitry Andric 54040b57cec5SDimitry Andric setNonAliasAttributes(GD, Fn); 54050b57cec5SDimitry Andric SetLLVMFunctionAttributesForDefinition(D, Fn); 54060b57cec5SDimitry Andric 54070b57cec5SDimitry Andric if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 54080b57cec5SDimitry Andric AddGlobalCtor(Fn, CA->getPriority()); 54090b57cec5SDimitry Andric if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 5410e8d8bef9SDimitry Andric AddGlobalDtor(Fn, DA->getPriority(), true); 54110b57cec5SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 54120b57cec5SDimitry Andric AddGlobalAnnotations(D, Fn); 54130b57cec5SDimitry Andric } 54140b57cec5SDimitry Andric 54150b57cec5SDimitry Andric void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 54160b57cec5SDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 54170b57cec5SDimitry Andric const AliasAttr *AA = D->getAttr<AliasAttr>(); 54180b57cec5SDimitry Andric assert(AA && "Not an alias?"); 54190b57cec5SDimitry Andric 54200b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 54210b57cec5SDimitry Andric 54220b57cec5SDimitry Andric if (AA->getAliasee() == MangledName) { 54230b57cec5SDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 54240b57cec5SDimitry Andric return; 54250b57cec5SDimitry Andric } 54260b57cec5SDimitry Andric 54270b57cec5SDimitry Andric // If there is a definition in the module, then it wins over the alias. 54280b57cec5SDimitry Andric // This is dubious, but allow it to be safe. Just ignore the alias. 54290b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 54300b57cec5SDimitry Andric if (Entry && !Entry->isDeclaration()) 54310b57cec5SDimitry Andric return; 54320b57cec5SDimitry Andric 54330b57cec5SDimitry Andric Aliases.push_back(GD); 54340b57cec5SDimitry Andric 54350b57cec5SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 54360b57cec5SDimitry Andric 54370b57cec5SDimitry Andric // Create a reference to the named value. This ensures that it is emitted 54380b57cec5SDimitry Andric // if a deferred decl. 54390b57cec5SDimitry Andric llvm::Constant *Aliasee; 54400b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes LT; 54410b57cec5SDimitry Andric if (isa<llvm::FunctionType>(DeclTy)) { 54420b57cec5SDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 54430b57cec5SDimitry Andric /*ForVTable=*/false); 54440b57cec5SDimitry Andric LT = getFunctionLinkage(GD); 54450b57cec5SDimitry Andric } else { 5446349cc55cSDimitry Andric Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 54470b57cec5SDimitry 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); 54520b57cec5SDimitry Andric } 54530b57cec5SDimitry Andric 54540b57cec5SDimitry Andric // Create the new alias itself, but don't set a name yet. 54555ffd83dbSDimitry Andric unsigned AS = Aliasee->getType()->getPointerAddressSpace(); 54560b57cec5SDimitry Andric auto *GA = 54575ffd83dbSDimitry Andric llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule()); 54580b57cec5SDimitry Andric 54590b57cec5SDimitry Andric if (Entry) { 54600b57cec5SDimitry Andric if (GA->getAliasee() == Entry) { 54610b57cec5SDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 54620b57cec5SDimitry Andric return; 54630b57cec5SDimitry Andric } 54640b57cec5SDimitry Andric 54650b57cec5SDimitry Andric assert(Entry->isDeclaration()); 54660b57cec5SDimitry Andric 54670b57cec5SDimitry Andric // If there is a declaration in the module, then we had an extern followed 54680b57cec5SDimitry Andric // by the alias, as in: 54690b57cec5SDimitry Andric // extern int test6(); 54700b57cec5SDimitry Andric // ... 54710b57cec5SDimitry Andric // int test6() __attribute__((alias("test7"))); 54720b57cec5SDimitry Andric // 54730b57cec5SDimitry Andric // Remove it and replace uses of it with the alias. 54740b57cec5SDimitry Andric GA->takeName(Entry); 54750b57cec5SDimitry Andric 54760b57cec5SDimitry Andric Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 54770b57cec5SDimitry Andric Entry->getType())); 54780b57cec5SDimitry Andric Entry->eraseFromParent(); 54790b57cec5SDimitry Andric } else { 54800b57cec5SDimitry Andric GA->setName(MangledName); 54810b57cec5SDimitry Andric } 54820b57cec5SDimitry Andric 54830b57cec5SDimitry Andric // Set attributes which are particular to an alias; this is a 54840b57cec5SDimitry Andric // specialization of the attributes which may be set on a global 54850b57cec5SDimitry Andric // variable/function. 54860b57cec5SDimitry Andric if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 54870b57cec5SDimitry Andric D->isWeakImported()) { 54880b57cec5SDimitry Andric GA->setLinkage(llvm::Function::WeakAnyLinkage); 54890b57cec5SDimitry Andric } 54900b57cec5SDimitry Andric 54910b57cec5SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 54920b57cec5SDimitry Andric if (VD->getTLSKind()) 54930b57cec5SDimitry Andric setTLSMode(GA, *VD); 54940b57cec5SDimitry Andric 54950b57cec5SDimitry 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()) 5500*bdd1243dSDimitry Andric DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD); 55010b57cec5SDimitry Andric } 55020b57cec5SDimitry Andric 55030b57cec5SDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 55040b57cec5SDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 55050b57cec5SDimitry Andric const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 55060b57cec5SDimitry Andric assert(IFA && "Not an ifunc?"); 55070b57cec5SDimitry Andric 55080b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 55090b57cec5SDimitry Andric 55100b57cec5SDimitry Andric if (IFA->getResolver() == MangledName) { 55110b57cec5SDimitry Andric Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 55120b57cec5SDimitry Andric return; 55130b57cec5SDimitry Andric } 55140b57cec5SDimitry Andric 55150b57cec5SDimitry Andric // Report an error if some definition overrides ifunc. 55160b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 55170b57cec5SDimitry Andric if (Entry && !Entry->isDeclaration()) { 55180b57cec5SDimitry Andric GlobalDecl OtherGD; 55190b57cec5SDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 55200b57cec5SDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 55210b57cec5SDimitry Andric Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name) 55220b57cec5SDimitry Andric << MangledName; 55230b57cec5SDimitry Andric Diags.Report(OtherGD.getDecl()->getLocation(), 55240b57cec5SDimitry Andric diag::note_previous_definition); 55250b57cec5SDimitry Andric } 55260b57cec5SDimitry Andric return; 55270b57cec5SDimitry Andric } 55280b57cec5SDimitry Andric 55290b57cec5SDimitry Andric Aliases.push_back(GD); 55300b57cec5SDimitry Andric 55310b57cec5SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 5532349cc55cSDimitry Andric llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy); 55330b57cec5SDimitry Andric llvm::Constant *Resolver = 5534349cc55cSDimitry Andric GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {}, 55350b57cec5SDimitry Andric /*ForVTable=*/false); 55360b57cec5SDimitry Andric llvm::GlobalIFunc *GIF = 55370b57cec5SDimitry Andric llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 55380b57cec5SDimitry Andric "", Resolver, &getModule()); 55390b57cec5SDimitry Andric if (Entry) { 55400b57cec5SDimitry Andric if (GIF->getResolver() == Entry) { 55410b57cec5SDimitry Andric Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 55420b57cec5SDimitry Andric return; 55430b57cec5SDimitry Andric } 55440b57cec5SDimitry Andric assert(Entry->isDeclaration()); 55450b57cec5SDimitry Andric 55460b57cec5SDimitry Andric // If there is a declaration in the module, then we had an extern followed 55470b57cec5SDimitry Andric // by the ifunc, as in: 55480b57cec5SDimitry Andric // extern int test(); 55490b57cec5SDimitry Andric // ... 55500b57cec5SDimitry Andric // int test() __attribute__((ifunc("resolver"))); 55510b57cec5SDimitry Andric // 55520b57cec5SDimitry Andric // Remove it and replace uses of it with the ifunc. 55530b57cec5SDimitry Andric GIF->takeName(Entry); 55540b57cec5SDimitry Andric 55550b57cec5SDimitry Andric Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF, 55560b57cec5SDimitry Andric Entry->getType())); 55570b57cec5SDimitry Andric Entry->eraseFromParent(); 55580b57cec5SDimitry Andric } else 55590b57cec5SDimitry Andric GIF->setName(MangledName); 55600b57cec5SDimitry Andric 55610b57cec5SDimitry Andric SetCommonAttributes(GD, GIF); 55620b57cec5SDimitry Andric } 55630b57cec5SDimitry Andric 55640b57cec5SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 55650b57cec5SDimitry Andric ArrayRef<llvm::Type*> Tys) { 55660b57cec5SDimitry Andric return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 55670b57cec5SDimitry Andric Tys); 55680b57cec5SDimitry Andric } 55690b57cec5SDimitry Andric 55700b57cec5SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> & 55710b57cec5SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 55720b57cec5SDimitry Andric const StringLiteral *Literal, bool TargetIsLSB, 55730b57cec5SDimitry Andric bool &IsUTF16, unsigned &StringLength) { 55740b57cec5SDimitry Andric StringRef String = Literal->getString(); 55750b57cec5SDimitry Andric unsigned NumBytes = String.size(); 55760b57cec5SDimitry Andric 55770b57cec5SDimitry Andric // Check for simple case. 55780b57cec5SDimitry Andric if (!Literal->containsNonAsciiOrNull()) { 55790b57cec5SDimitry Andric StringLength = NumBytes; 55800b57cec5SDimitry Andric return *Map.insert(std::make_pair(String, nullptr)).first; 55810b57cec5SDimitry Andric } 55820b57cec5SDimitry Andric 55830b57cec5SDimitry Andric // Otherwise, convert the UTF8 literals into a string of shorts. 55840b57cec5SDimitry Andric IsUTF16 = true; 55850b57cec5SDimitry Andric 55860b57cec5SDimitry Andric SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 55870b57cec5SDimitry Andric const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 55880b57cec5SDimitry Andric llvm::UTF16 *ToPtr = &ToBuf[0]; 55890b57cec5SDimitry Andric 55900b57cec5SDimitry Andric (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 55910b57cec5SDimitry Andric ToPtr + NumBytes, llvm::strictConversion); 55920b57cec5SDimitry Andric 55930b57cec5SDimitry Andric // ConvertUTF8toUTF16 returns the length in ToPtr. 55940b57cec5SDimitry Andric StringLength = ToPtr - &ToBuf[0]; 55950b57cec5SDimitry Andric 55960b57cec5SDimitry Andric // Add an explicit null. 55970b57cec5SDimitry Andric *ToPtr = 0; 55980b57cec5SDimitry Andric return *Map.insert(std::make_pair( 55990b57cec5SDimitry Andric StringRef(reinterpret_cast<const char *>(ToBuf.data()), 56000b57cec5SDimitry Andric (StringLength + 1) * 2), 56010b57cec5SDimitry Andric nullptr)).first; 56020b57cec5SDimitry Andric } 56030b57cec5SDimitry Andric 56040b57cec5SDimitry Andric ConstantAddress 56050b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 56060b57cec5SDimitry Andric unsigned StringLength = 0; 56070b57cec5SDimitry Andric bool isUTF16 = false; 56080b57cec5SDimitry Andric llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 56090b57cec5SDimitry Andric GetConstantCFStringEntry(CFConstantStringMap, Literal, 56100b57cec5SDimitry Andric getDataLayout().isLittleEndian(), isUTF16, 56110b57cec5SDimitry Andric StringLength); 56120b57cec5SDimitry Andric 56130b57cec5SDimitry Andric if (auto *C = Entry.second) 56140eae32dcSDimitry Andric return ConstantAddress( 56150eae32dcSDimitry Andric C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment())); 56160b57cec5SDimitry Andric 56170b57cec5SDimitry Andric llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 56180b57cec5SDimitry Andric llvm::Constant *Zeros[] = { Zero, Zero }; 56190b57cec5SDimitry Andric 56200b57cec5SDimitry Andric const ASTContext &Context = getContext(); 56210b57cec5SDimitry Andric const llvm::Triple &Triple = getTriple(); 56220b57cec5SDimitry Andric 56230b57cec5SDimitry Andric const auto CFRuntime = getLangOpts().CFRuntime; 56240b57cec5SDimitry Andric const bool IsSwiftABI = 56250b57cec5SDimitry Andric static_cast<unsigned>(CFRuntime) >= 56260b57cec5SDimitry Andric static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift); 56270b57cec5SDimitry Andric const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1; 56280b57cec5SDimitry Andric 56290b57cec5SDimitry Andric // If we don't already have it, get __CFConstantStringClassReference. 56300b57cec5SDimitry Andric if (!CFConstantStringClassRef) { 56310b57cec5SDimitry Andric const char *CFConstantStringClassName = "__CFConstantStringClassReference"; 56320b57cec5SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 56330b57cec5SDimitry Andric Ty = llvm::ArrayType::get(Ty, 0); 56340b57cec5SDimitry Andric 56350b57cec5SDimitry Andric switch (CFRuntime) { 56360b57cec5SDimitry Andric default: break; 5637*bdd1243dSDimitry Andric case LangOptions::CoreFoundationABI::Swift: [[fallthrough]]; 56380b57cec5SDimitry Andric case LangOptions::CoreFoundationABI::Swift5_0: 56390b57cec5SDimitry Andric CFConstantStringClassName = 56400b57cec5SDimitry Andric Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN" 56410b57cec5SDimitry Andric : "$s10Foundation19_NSCFConstantStringCN"; 56420b57cec5SDimitry Andric Ty = IntPtrTy; 56430b57cec5SDimitry Andric break; 56440b57cec5SDimitry Andric case LangOptions::CoreFoundationABI::Swift4_2: 56450b57cec5SDimitry Andric CFConstantStringClassName = 56460b57cec5SDimitry Andric Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN" 56470b57cec5SDimitry Andric : "$S10Foundation19_NSCFConstantStringCN"; 56480b57cec5SDimitry Andric Ty = IntPtrTy; 56490b57cec5SDimitry Andric break; 56500b57cec5SDimitry Andric case LangOptions::CoreFoundationABI::Swift4_1: 56510b57cec5SDimitry Andric CFConstantStringClassName = 56520b57cec5SDimitry Andric Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN" 56530b57cec5SDimitry Andric : "__T010Foundation19_NSCFConstantStringCN"; 56540b57cec5SDimitry Andric Ty = IntPtrTy; 56550b57cec5SDimitry Andric break; 56560b57cec5SDimitry Andric } 56570b57cec5SDimitry Andric 56580b57cec5SDimitry Andric llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName); 56590b57cec5SDimitry Andric 56600b57cec5SDimitry Andric if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) { 56610b57cec5SDimitry Andric llvm::GlobalValue *GV = nullptr; 56620b57cec5SDimitry Andric 56630b57cec5SDimitry Andric if ((GV = dyn_cast<llvm::GlobalValue>(C))) { 56640b57cec5SDimitry Andric IdentifierInfo &II = Context.Idents.get(GV->getName()); 56650b57cec5SDimitry Andric TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl(); 56660b57cec5SDimitry Andric DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 56670b57cec5SDimitry Andric 56680b57cec5SDimitry Andric const VarDecl *VD = nullptr; 5669fe6060f1SDimitry Andric for (const auto *Result : DC->lookup(&II)) 56700b57cec5SDimitry Andric if ((VD = dyn_cast<VarDecl>(Result))) 56710b57cec5SDimitry Andric break; 56720b57cec5SDimitry Andric 56730b57cec5SDimitry Andric if (Triple.isOSBinFormatELF()) { 56740b57cec5SDimitry Andric if (!VD) 56750b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 56760b57cec5SDimitry Andric } else { 56770b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 56780b57cec5SDimitry Andric if (!VD || !VD->hasAttr<DLLExportAttr>()) 56790b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 56800b57cec5SDimitry Andric else 56810b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 56820b57cec5SDimitry Andric } 56830b57cec5SDimitry Andric 56840b57cec5SDimitry Andric setDSOLocal(GV); 56850b57cec5SDimitry Andric } 56860b57cec5SDimitry Andric } 56870b57cec5SDimitry Andric 56880b57cec5SDimitry Andric // Decay array -> ptr 56890b57cec5SDimitry Andric CFConstantStringClassRef = 56900b57cec5SDimitry Andric IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) 56910b57cec5SDimitry Andric : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros); 56920b57cec5SDimitry Andric } 56930b57cec5SDimitry Andric 56940b57cec5SDimitry Andric QualType CFTy = Context.getCFConstantStringType(); 56950b57cec5SDimitry Andric 56960b57cec5SDimitry Andric auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 56970b57cec5SDimitry Andric 56980b57cec5SDimitry Andric ConstantInitBuilder Builder(*this); 56990b57cec5SDimitry Andric auto Fields = Builder.beginStruct(STy); 57000b57cec5SDimitry Andric 57010b57cec5SDimitry Andric // Class pointer. 570281ad6265SDimitry Andric Fields.add(cast<llvm::Constant>(CFConstantStringClassRef)); 57030b57cec5SDimitry Andric 57040b57cec5SDimitry Andric // Flags. 57050b57cec5SDimitry Andric if (IsSwiftABI) { 57060b57cec5SDimitry Andric Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01); 57070b57cec5SDimitry Andric Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8); 57080b57cec5SDimitry Andric } else { 57090b57cec5SDimitry Andric Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); 57100b57cec5SDimitry Andric } 57110b57cec5SDimitry Andric 57120b57cec5SDimitry Andric // String pointer. 57130b57cec5SDimitry Andric llvm::Constant *C = nullptr; 57140b57cec5SDimitry Andric if (isUTF16) { 5715*bdd1243dSDimitry Andric auto Arr = llvm::ArrayRef( 57160b57cec5SDimitry Andric reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 57170b57cec5SDimitry Andric Entry.first().size() / 2); 57180b57cec5SDimitry Andric C = llvm::ConstantDataArray::get(VMContext, Arr); 57190b57cec5SDimitry Andric } else { 57200b57cec5SDimitry Andric C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 57210b57cec5SDimitry Andric } 57220b57cec5SDimitry Andric 57230b57cec5SDimitry Andric // Note: -fwritable-strings doesn't make the backing store strings of 57240b57cec5SDimitry Andric // CFStrings writable. (See <rdar://problem/10657500>) 57250b57cec5SDimitry Andric auto *GV = 57260b57cec5SDimitry Andric new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 57270b57cec5SDimitry Andric llvm::GlobalValue::PrivateLinkage, C, ".str"); 57280b57cec5SDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 57290b57cec5SDimitry Andric // Don't enforce the target's minimum global alignment, since the only use 57300b57cec5SDimitry Andric // of the string is via this class initializer. 57310b57cec5SDimitry Andric CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy) 57320b57cec5SDimitry Andric : Context.getTypeAlignInChars(Context.CharTy); 5733a7dea167SDimitry Andric GV->setAlignment(Align.getAsAlign()); 57340b57cec5SDimitry Andric 57350b57cec5SDimitry Andric // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 57360b57cec5SDimitry Andric // Without it LLVM can merge the string with a non unnamed_addr one during 57370b57cec5SDimitry Andric // LTO. Doing that changes the section it ends in, which surprises ld64. 57380b57cec5SDimitry Andric if (Triple.isOSBinFormatMachO()) 57390b57cec5SDimitry Andric GV->setSection(isUTF16 ? "__TEXT,__ustring" 57400b57cec5SDimitry Andric : "__TEXT,__cstring,cstring_literals"); 57410b57cec5SDimitry Andric // Make sure the literal ends up in .rodata to allow for safe ICF and for 57420b57cec5SDimitry Andric // the static linker to adjust permissions to read-only later on. 57430b57cec5SDimitry Andric else if (Triple.isOSBinFormatELF()) 57440b57cec5SDimitry Andric GV->setSection(".rodata"); 57450b57cec5SDimitry Andric 57460b57cec5SDimitry Andric // String. 57470b57cec5SDimitry Andric llvm::Constant *Str = 57480b57cec5SDimitry Andric llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 57490b57cec5SDimitry Andric 57500b57cec5SDimitry Andric if (isUTF16) 57510b57cec5SDimitry Andric // Cast the UTF16 string to the correct type. 57520b57cec5SDimitry Andric Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy); 57530b57cec5SDimitry Andric Fields.add(Str); 57540b57cec5SDimitry Andric 57550b57cec5SDimitry Andric // String length. 57560b57cec5SDimitry Andric llvm::IntegerType *LengthTy = 57570b57cec5SDimitry Andric llvm::IntegerType::get(getModule().getContext(), 57580b57cec5SDimitry Andric Context.getTargetInfo().getLongWidth()); 57590b57cec5SDimitry Andric if (IsSwiftABI) { 57600b57cec5SDimitry Andric if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 57610b57cec5SDimitry Andric CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 57620b57cec5SDimitry Andric LengthTy = Int32Ty; 57630b57cec5SDimitry Andric else 57640b57cec5SDimitry Andric LengthTy = IntPtrTy; 57650b57cec5SDimitry Andric } 57660b57cec5SDimitry Andric Fields.addInt(LengthTy, StringLength); 57670b57cec5SDimitry 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(); 57720b57cec5SDimitry Andric 57730b57cec5SDimitry Andric // The struct. 57740b57cec5SDimitry Andric GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, 57750b57cec5SDimitry Andric /*isConstant=*/false, 57760b57cec5SDimitry Andric llvm::GlobalVariable::PrivateLinkage); 57770b57cec5SDimitry Andric GV->addAttribute("objc_arc_inert"); 57780b57cec5SDimitry Andric switch (Triple.getObjectFormat()) { 57790b57cec5SDimitry Andric case llvm::Triple::UnknownObjectFormat: 57800b57cec5SDimitry Andric llvm_unreachable("unknown file format"); 578181ad6265SDimitry Andric case llvm::Triple::DXContainer: 5782e8d8bef9SDimitry Andric case llvm::Triple::GOFF: 578381ad6265SDimitry Andric case llvm::Triple::SPIRV: 57840b57cec5SDimitry Andric case llvm::Triple::XCOFF: 578581ad6265SDimitry Andric llvm_unreachable("unimplemented"); 57860b57cec5SDimitry Andric case llvm::Triple::COFF: 57870b57cec5SDimitry Andric case llvm::Triple::ELF: 57880b57cec5SDimitry Andric case llvm::Triple::Wasm: 57890b57cec5SDimitry Andric GV->setSection("cfstring"); 57900b57cec5SDimitry Andric break; 57910b57cec5SDimitry Andric case llvm::Triple::MachO: 57920b57cec5SDimitry Andric GV->setSection("__DATA,__cfstring"); 57930b57cec5SDimitry Andric break; 57940b57cec5SDimitry Andric } 57950b57cec5SDimitry Andric Entry.second = GV; 57960b57cec5SDimitry Andric 57970eae32dcSDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 57980b57cec5SDimitry Andric } 57990b57cec5SDimitry Andric 58000b57cec5SDimitry Andric bool CodeGenModule::getExpressionLocationsEnabled() const { 58010b57cec5SDimitry Andric return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo; 58020b57cec5SDimitry Andric } 58030b57cec5SDimitry Andric 58040b57cec5SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() { 58050b57cec5SDimitry Andric if (ObjCFastEnumerationStateType.isNull()) { 58060b57cec5SDimitry Andric RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 58070b57cec5SDimitry Andric D->startDefinition(); 58080b57cec5SDimitry Andric 58090b57cec5SDimitry Andric QualType FieldTypes[] = { 58100b57cec5SDimitry Andric Context.UnsignedLongTy, 58110b57cec5SDimitry Andric Context.getPointerType(Context.getObjCIdType()), 58120b57cec5SDimitry Andric Context.getPointerType(Context.UnsignedLongTy), 58130b57cec5SDimitry Andric Context.getConstantArrayType(Context.UnsignedLongTy, 5814a7dea167SDimitry Andric llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0) 58150b57cec5SDimitry Andric }; 58160b57cec5SDimitry Andric 58170b57cec5SDimitry Andric for (size_t i = 0; i < 4; ++i) { 58180b57cec5SDimitry Andric FieldDecl *Field = FieldDecl::Create(Context, 58190b57cec5SDimitry Andric D, 58200b57cec5SDimitry Andric SourceLocation(), 58210b57cec5SDimitry Andric SourceLocation(), nullptr, 58220b57cec5SDimitry Andric FieldTypes[i], /*TInfo=*/nullptr, 58230b57cec5SDimitry Andric /*BitWidth=*/nullptr, 58240b57cec5SDimitry Andric /*Mutable=*/false, 58250b57cec5SDimitry Andric ICIS_NoInit); 58260b57cec5SDimitry Andric Field->setAccess(AS_public); 58270b57cec5SDimitry Andric D->addDecl(Field); 58280b57cec5SDimitry Andric } 58290b57cec5SDimitry Andric 58300b57cec5SDimitry Andric D->completeDefinition(); 58310b57cec5SDimitry Andric ObjCFastEnumerationStateType = Context.getTagDeclType(D); 58320b57cec5SDimitry Andric } 58330b57cec5SDimitry Andric 58340b57cec5SDimitry Andric return ObjCFastEnumerationStateType; 58350b57cec5SDimitry Andric } 58360b57cec5SDimitry Andric 58370b57cec5SDimitry Andric llvm::Constant * 58380b57cec5SDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 58390b57cec5SDimitry Andric assert(!E->getType()->isPointerType() && "Strings are always arrays"); 58400b57cec5SDimitry Andric 58410b57cec5SDimitry Andric // Don't emit it as the address of the string, emit the string data itself 58420b57cec5SDimitry Andric // as an inline array. 58430b57cec5SDimitry Andric if (E->getCharByteWidth() == 1) { 58440b57cec5SDimitry Andric SmallString<64> Str(E->getString()); 58450b57cec5SDimitry Andric 58460b57cec5SDimitry Andric // Resize the string to the right size, which is indicated by its type. 58470b57cec5SDimitry Andric const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 58480b57cec5SDimitry Andric Str.resize(CAT->getSize().getZExtValue()); 58490b57cec5SDimitry Andric return llvm::ConstantDataArray::getString(VMContext, Str, false); 58500b57cec5SDimitry Andric } 58510b57cec5SDimitry Andric 58520b57cec5SDimitry Andric auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 58530b57cec5SDimitry Andric llvm::Type *ElemTy = AType->getElementType(); 58540b57cec5SDimitry Andric unsigned NumElements = AType->getNumElements(); 58550b57cec5SDimitry Andric 58560b57cec5SDimitry Andric // Wide strings have either 2-byte or 4-byte elements. 58570b57cec5SDimitry Andric if (ElemTy->getPrimitiveSizeInBits() == 16) { 58580b57cec5SDimitry Andric SmallVector<uint16_t, 32> Elements; 58590b57cec5SDimitry Andric Elements.reserve(NumElements); 58600b57cec5SDimitry Andric 58610b57cec5SDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 58620b57cec5SDimitry Andric Elements.push_back(E->getCodeUnit(i)); 58630b57cec5SDimitry Andric Elements.resize(NumElements); 58640b57cec5SDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 58650b57cec5SDimitry Andric } 58660b57cec5SDimitry Andric 58670b57cec5SDimitry Andric assert(ElemTy->getPrimitiveSizeInBits() == 32); 58680b57cec5SDimitry Andric SmallVector<uint32_t, 32> Elements; 58690b57cec5SDimitry Andric Elements.reserve(NumElements); 58700b57cec5SDimitry Andric 58710b57cec5SDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 58720b57cec5SDimitry Andric Elements.push_back(E->getCodeUnit(i)); 58730b57cec5SDimitry Andric Elements.resize(NumElements); 58740b57cec5SDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 58750b57cec5SDimitry Andric } 58760b57cec5SDimitry Andric 58770b57cec5SDimitry Andric static llvm::GlobalVariable * 58780b57cec5SDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 58790b57cec5SDimitry Andric CodeGenModule &CGM, StringRef GlobalName, 58800b57cec5SDimitry Andric CharUnits Alignment) { 58810b57cec5SDimitry Andric unsigned AddrSpace = CGM.getContext().getTargetAddressSpace( 5882fe6060f1SDimitry Andric CGM.GetGlobalConstantAddressSpace()); 58830b57cec5SDimitry Andric 58840b57cec5SDimitry Andric llvm::Module &M = CGM.getModule(); 58850b57cec5SDimitry Andric // Create a global variable for this string 58860b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 58870b57cec5SDimitry Andric M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 58880b57cec5SDimitry Andric nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 5889a7dea167SDimitry Andric GV->setAlignment(Alignment.getAsAlign()); 58900b57cec5SDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 58910b57cec5SDimitry Andric if (GV->isWeakForLinker()) { 58920b57cec5SDimitry Andric assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 58930b57cec5SDimitry Andric GV->setComdat(M.getOrInsertComdat(GV->getName())); 58940b57cec5SDimitry Andric } 58950b57cec5SDimitry Andric CGM.setDSOLocal(GV); 58960b57cec5SDimitry Andric 58970b57cec5SDimitry Andric return GV; 58980b57cec5SDimitry Andric } 58990b57cec5SDimitry Andric 59000b57cec5SDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 59010b57cec5SDimitry Andric /// constant array for the given string literal. 59020b57cec5SDimitry Andric ConstantAddress 59030b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 59040b57cec5SDimitry Andric StringRef Name) { 59050b57cec5SDimitry Andric CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 59060b57cec5SDimitry Andric 59070b57cec5SDimitry Andric llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 59080b57cec5SDimitry Andric llvm::GlobalVariable **Entry = nullptr; 59090b57cec5SDimitry Andric if (!LangOpts.WritableStrings) { 59100b57cec5SDimitry Andric Entry = &ConstantStringMap[C]; 59110b57cec5SDimitry Andric if (auto GV = *Entry) { 5912349cc55cSDimitry Andric if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 5913a7dea167SDimitry Andric GV->setAlignment(Alignment.getAsAlign()); 59140b57cec5SDimitry Andric return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 59150eae32dcSDimitry Andric GV->getValueType(), Alignment); 59160b57cec5SDimitry Andric } 59170b57cec5SDimitry Andric } 59180b57cec5SDimitry Andric 59190b57cec5SDimitry Andric SmallString<256> MangledNameBuffer; 59200b57cec5SDimitry Andric StringRef GlobalVariableName; 59210b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes LT; 59220b57cec5SDimitry Andric 59230b57cec5SDimitry Andric // Mangle the string literal if that's how the ABI merges duplicate strings. 59240b57cec5SDimitry Andric // Don't do it if they are writable, since we don't want writes in one TU to 59250b57cec5SDimitry Andric // affect strings in another. 59260b57cec5SDimitry Andric if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) && 59270b57cec5SDimitry Andric !LangOpts.WritableStrings) { 59280b57cec5SDimitry Andric llvm::raw_svector_ostream Out(MangledNameBuffer); 59290b57cec5SDimitry Andric getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 59300b57cec5SDimitry Andric LT = llvm::GlobalValue::LinkOnceODRLinkage; 59310b57cec5SDimitry Andric GlobalVariableName = MangledNameBuffer; 59320b57cec5SDimitry Andric } else { 59330b57cec5SDimitry Andric LT = llvm::GlobalValue::PrivateLinkage; 59340b57cec5SDimitry Andric GlobalVariableName = Name; 59350b57cec5SDimitry Andric } 59360b57cec5SDimitry Andric 59370b57cec5SDimitry 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 59430b57cec5SDimitry Andric if (Entry) 59440b57cec5SDimitry Andric *Entry = GV; 59450b57cec5SDimitry Andric 594681ad6265SDimitry Andric SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0), "<string literal>"); 59470b57cec5SDimitry Andric 59480b57cec5SDimitry Andric return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 59490eae32dcSDimitry Andric GV->getValueType(), Alignment); 59500b57cec5SDimitry Andric } 59510b57cec5SDimitry Andric 59520b57cec5SDimitry Andric /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 59530b57cec5SDimitry Andric /// array for the given ObjCEncodeExpr node. 59540b57cec5SDimitry Andric ConstantAddress 59550b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 59560b57cec5SDimitry Andric std::string Str; 59570b57cec5SDimitry Andric getContext().getObjCEncodingForType(E->getEncodedType(), Str); 59580b57cec5SDimitry Andric 59590b57cec5SDimitry Andric return GetAddrOfConstantCString(Str); 59600b57cec5SDimitry Andric } 59610b57cec5SDimitry Andric 59620b57cec5SDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing 59630b57cec5SDimitry Andric /// the literal and a terminating '\0' character. 59640b57cec5SDimitry Andric /// The result has pointer to array type. 59650b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString( 59660b57cec5SDimitry Andric const std::string &Str, const char *GlobalName) { 59670b57cec5SDimitry Andric StringRef StrWithNull(Str.c_str(), Str.size() + 1); 59680b57cec5SDimitry Andric CharUnits Alignment = 59690b57cec5SDimitry Andric getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 59700b57cec5SDimitry Andric 59710b57cec5SDimitry Andric llvm::Constant *C = 59720b57cec5SDimitry Andric llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 59730b57cec5SDimitry Andric 59740b57cec5SDimitry Andric // Don't share any string literals if strings aren't constant. 59750b57cec5SDimitry Andric llvm::GlobalVariable **Entry = nullptr; 59760b57cec5SDimitry Andric if (!LangOpts.WritableStrings) { 59770b57cec5SDimitry Andric Entry = &ConstantStringMap[C]; 59780b57cec5SDimitry Andric if (auto GV = *Entry) { 5979349cc55cSDimitry Andric if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 5980a7dea167SDimitry Andric GV->setAlignment(Alignment.getAsAlign()); 59810b57cec5SDimitry Andric return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 59820eae32dcSDimitry Andric GV->getValueType(), Alignment); 59830b57cec5SDimitry Andric } 59840b57cec5SDimitry Andric } 59850b57cec5SDimitry Andric 59860b57cec5SDimitry Andric // Get the default prefix if a name wasn't specified. 59870b57cec5SDimitry Andric if (!GlobalName) 59880b57cec5SDimitry Andric GlobalName = ".str"; 59890b57cec5SDimitry Andric // Create a global variable for this. 59900b57cec5SDimitry Andric auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 59910b57cec5SDimitry Andric GlobalName, Alignment); 59920b57cec5SDimitry Andric if (Entry) 59930b57cec5SDimitry Andric *Entry = GV; 59940b57cec5SDimitry Andric 59950b57cec5SDimitry Andric return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 59960eae32dcSDimitry Andric GV->getValueType(), Alignment); 59970b57cec5SDimitry Andric } 59980b57cec5SDimitry Andric 59990b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 60000b57cec5SDimitry Andric const MaterializeTemporaryExpr *E, const Expr *Init) { 60010b57cec5SDimitry Andric assert((E->getStorageDuration() == SD_Static || 60020b57cec5SDimitry Andric E->getStorageDuration() == SD_Thread) && "not a global temporary"); 60030b57cec5SDimitry Andric const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 60040b57cec5SDimitry Andric 60050b57cec5SDimitry Andric // If we're not materializing a subobject of the temporary, keep the 60060b57cec5SDimitry Andric // cv-qualifiers from the type of the MaterializeTemporaryExpr. 60070b57cec5SDimitry Andric QualType MaterializedType = Init->getType(); 6008480093f4SDimitry Andric if (Init == E->getSubExpr()) 60090b57cec5SDimitry Andric MaterializedType = E->getType(); 60100b57cec5SDimitry Andric 60110b57cec5SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 60120b57cec5SDimitry 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 } 60320b57cec5SDimitry Andric 60330b57cec5SDimitry Andric // FIXME: If an externally-visible declaration extends multiple temporaries, 60340b57cec5SDimitry Andric // we need to give each temporary the same name in every translation unit (and 60350b57cec5SDimitry Andric // we also need to make the temporaries externally-visible). 60360b57cec5SDimitry Andric SmallString<256> Name; 60370b57cec5SDimitry Andric llvm::raw_svector_ostream Out(Name); 60380b57cec5SDimitry Andric getCXXABI().getMangleContext().mangleReferenceTemporary( 60390b57cec5SDimitry Andric VD, E->getManglingNumber(), Out); 60400b57cec5SDimitry Andric 60410b57cec5SDimitry 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); 60490b57cec5SDimitry Andric } 60500b57cec5SDimitry Andric 60510b57cec5SDimitry Andric // Try evaluating it now, it might have a constant initializer. 60520b57cec5SDimitry Andric Expr::EvalResult EvalResult; 60530b57cec5SDimitry Andric if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 60540b57cec5SDimitry Andric !EvalResult.hasSideEffects()) 60550b57cec5SDimitry Andric Value = &EvalResult.Val; 60560b57cec5SDimitry Andric 60570b57cec5SDimitry Andric LangAS AddrSpace = 60580b57cec5SDimitry Andric VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace(); 60590b57cec5SDimitry Andric 6060*bdd1243dSDimitry Andric std::optional<ConstantEmitter> emitter; 60610b57cec5SDimitry Andric llvm::Constant *InitialValue = nullptr; 60620b57cec5SDimitry Andric bool Constant = false; 60630b57cec5SDimitry Andric llvm::Type *Type; 60640b57cec5SDimitry Andric if (Value) { 60650b57cec5SDimitry Andric // The temporary has a constant initializer, use it. 60660b57cec5SDimitry Andric emitter.emplace(*this); 60670b57cec5SDimitry Andric InitialValue = emitter->emitForInitializer(*Value, AddrSpace, 60680b57cec5SDimitry Andric MaterializedType); 60690b57cec5SDimitry Andric Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 60700b57cec5SDimitry Andric Type = InitialValue->getType(); 60710b57cec5SDimitry Andric } else { 60720b57cec5SDimitry Andric // No initializer, the initialization will be provided when we 60730b57cec5SDimitry Andric // initialize the declaration which performed lifetime extension. 60740b57cec5SDimitry Andric Type = getTypes().ConvertTypeForMem(MaterializedType); 60750b57cec5SDimitry Andric } 60760b57cec5SDimitry Andric 60770b57cec5SDimitry Andric // Create a global variable for this lifetime-extended temporary. 60780b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 60790b57cec5SDimitry Andric getLLVMLinkageVarDefinition(VD, Constant); 60800b57cec5SDimitry Andric if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 60810b57cec5SDimitry Andric const VarDecl *InitVD; 60820b57cec5SDimitry Andric if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 60830b57cec5SDimitry Andric isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 60840b57cec5SDimitry Andric // Temporaries defined inside a class get linkonce_odr linkage because the 60850b57cec5SDimitry Andric // class can be defined in multiple translation units. 60860b57cec5SDimitry Andric Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 60870b57cec5SDimitry Andric } else { 60880b57cec5SDimitry Andric // There is no need for this temporary to have external linkage if the 60890b57cec5SDimitry Andric // VarDecl has external linkage. 60900b57cec5SDimitry Andric Linkage = llvm::GlobalVariable::InternalLinkage; 60910b57cec5SDimitry Andric } 60920b57cec5SDimitry Andric } 60930b57cec5SDimitry Andric auto TargetAS = getContext().getTargetAddressSpace(AddrSpace); 60940b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 60950b57cec5SDimitry Andric getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 60960b57cec5SDimitry Andric /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); 60970b57cec5SDimitry Andric if (emitter) emitter->finalize(GV); 6098*bdd1243dSDimitry Andric // Don't assign dllimport or dllexport to local linkage globals. 6099*bdd1243dSDimitry Andric if (!llvm::GlobalValue::isLocalLinkage(Linkage)) { 61000b57cec5SDimitry 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); 6104*bdd1243dSDimitry Andric } 6105a7dea167SDimitry Andric GV->setAlignment(Align.getAsAlign()); 61060b57cec5SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker()) 61070b57cec5SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 61080b57cec5SDimitry Andric if (VD->getTLSKind()) 61090b57cec5SDimitry Andric setTLSMode(GV, *VD); 61100b57cec5SDimitry Andric llvm::Constant *CV = GV; 61110b57cec5SDimitry Andric if (AddrSpace != LangAS::Default) 61120b57cec5SDimitry Andric CV = getTargetCodeGenInfo().performAddrSpaceCast( 61130b57cec5SDimitry Andric *this, GV, AddrSpace, LangAS::Default, 61140b57cec5SDimitry Andric Type->getPointerTo( 61150b57cec5SDimitry 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); 61280b57cec5SDimitry Andric } 61290b57cec5SDimitry Andric 61300b57cec5SDimitry Andric /// EmitObjCPropertyImplementations - Emit information for synthesized 61310b57cec5SDimitry Andric /// properties for an implementation. 61320b57cec5SDimitry Andric void CodeGenModule::EmitObjCPropertyImplementations(const 61330b57cec5SDimitry Andric ObjCImplementationDecl *D) { 61340b57cec5SDimitry Andric for (const auto *PID : D->property_impls()) { 61350b57cec5SDimitry Andric // Dynamic is just for type-checking. 61360b57cec5SDimitry Andric if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 61370b57cec5SDimitry Andric ObjCPropertyDecl *PD = PID->getPropertyDecl(); 61380b57cec5SDimitry Andric 61390b57cec5SDimitry Andric // Determine which methods need to be implemented, some may have 61400b57cec5SDimitry Andric // been overridden. Note that ::isPropertyAccessor is not the method 61410b57cec5SDimitry Andric // we want, that just indicates if the decl came from a 61420b57cec5SDimitry Andric // property. What we want to know is if the method is defined in 61430b57cec5SDimitry Andric // this implementation. 6144480093f4SDimitry Andric auto *Getter = PID->getGetterMethodDecl(); 6145480093f4SDimitry Andric if (!Getter || Getter->isSynthesizedAccessorStub()) 61460b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCGetter( 61470b57cec5SDimitry Andric const_cast<ObjCImplementationDecl *>(D), PID); 6148480093f4SDimitry Andric auto *Setter = PID->getSetterMethodDecl(); 6149480093f4SDimitry Andric if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub())) 61500b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCSetter( 61510b57cec5SDimitry Andric const_cast<ObjCImplementationDecl *>(D), PID); 61520b57cec5SDimitry Andric } 61530b57cec5SDimitry Andric } 61540b57cec5SDimitry Andric } 61550b57cec5SDimitry Andric 61560b57cec5SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) { 61570b57cec5SDimitry Andric const ObjCInterfaceDecl *iface = impl->getClassInterface(); 61580b57cec5SDimitry Andric for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 61590b57cec5SDimitry Andric ivar; ivar = ivar->getNextIvar()) 61600b57cec5SDimitry Andric if (ivar->getType().isDestructedType()) 61610b57cec5SDimitry Andric return true; 61620b57cec5SDimitry Andric 61630b57cec5SDimitry Andric return false; 61640b57cec5SDimitry Andric } 61650b57cec5SDimitry Andric 61660b57cec5SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM, 61670b57cec5SDimitry Andric ObjCImplementationDecl *D) { 61680b57cec5SDimitry Andric CodeGenFunction CGF(CGM); 61690b57cec5SDimitry Andric for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 61700b57cec5SDimitry Andric E = D->init_end(); B != E; ++B) { 61710b57cec5SDimitry Andric CXXCtorInitializer *CtorInitExp = *B; 61720b57cec5SDimitry Andric Expr *Init = CtorInitExp->getInit(); 61730b57cec5SDimitry Andric if (!CGF.isTrivialInitializer(Init)) 61740b57cec5SDimitry Andric return false; 61750b57cec5SDimitry Andric } 61760b57cec5SDimitry Andric return true; 61770b57cec5SDimitry Andric } 61780b57cec5SDimitry Andric 61790b57cec5SDimitry Andric /// EmitObjCIvarInitializations - Emit information for ivar initialization 61800b57cec5SDimitry Andric /// for an implementation. 61810b57cec5SDimitry Andric void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 61820b57cec5SDimitry Andric // We might need a .cxx_destruct even if we don't have any ivar initializers. 61830b57cec5SDimitry Andric if (needsDestructMethod(D)) { 61840b57cec5SDimitry Andric IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 61850b57cec5SDimitry 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, 61890b57cec5SDimitry Andric /*isInstance=*/true, /*isVariadic=*/false, 6190480093f4SDimitry Andric /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 6191480093f4SDimitry Andric /*isImplicitlyDeclared=*/true, 61920b57cec5SDimitry Andric /*isDefined=*/false, ObjCMethodDecl::Required); 61930b57cec5SDimitry Andric D->addInstanceMethod(DTORMethod); 61940b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 61950b57cec5SDimitry Andric D->setHasDestructors(true); 61960b57cec5SDimitry Andric } 61970b57cec5SDimitry Andric 61980b57cec5SDimitry Andric // If the implementation doesn't have any ivar initializers, we don't need 61990b57cec5SDimitry Andric // a .cxx_construct. 62000b57cec5SDimitry Andric if (D->getNumIvarInitializers() == 0 || 62010b57cec5SDimitry Andric AllTrivialInitializers(*this, D)) 62020b57cec5SDimitry Andric return; 62030b57cec5SDimitry Andric 62040b57cec5SDimitry Andric IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 62050b57cec5SDimitry Andric Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 62060b57cec5SDimitry 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, 62100b57cec5SDimitry Andric /*isVariadic=*/false, 6211480093f4SDimitry Andric /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 62120b57cec5SDimitry Andric /*isImplicitlyDeclared=*/true, 6213480093f4SDimitry Andric /*isDefined=*/false, ObjCMethodDecl::Required); 62140b57cec5SDimitry Andric D->addInstanceMethod(CTORMethod); 62150b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 62160b57cec5SDimitry Andric D->setHasNonZeroConstructors(true); 62170b57cec5SDimitry Andric } 62180b57cec5SDimitry Andric 62190b57cec5SDimitry Andric // EmitLinkageSpec - Emit all declarations in a linkage spec. 62200b57cec5SDimitry Andric void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 62210b57cec5SDimitry Andric if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 6222480093f4SDimitry Andric LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 62230b57cec5SDimitry Andric ErrorUnsupported(LSD, "linkage spec"); 62240b57cec5SDimitry Andric return; 62250b57cec5SDimitry Andric } 62260b57cec5SDimitry Andric 62270b57cec5SDimitry Andric EmitDeclContext(LSD); 62280b57cec5SDimitry Andric } 62290b57cec5SDimitry Andric 6230*bdd1243dSDimitry Andric void CodeGenModule::EmitTopLevelStmt(const TopLevelStmtDecl *D) { 6231*bdd1243dSDimitry Andric std::unique_ptr<CodeGenFunction> &CurCGF = 6232*bdd1243dSDimitry Andric GlobalTopLevelStmtBlockInFlight.first; 6233*bdd1243dSDimitry Andric 6234*bdd1243dSDimitry Andric // We emitted a top-level stmt but after it there is initialization. 6235*bdd1243dSDimitry Andric // Stop squashing the top-level stmts into a single function. 6236*bdd1243dSDimitry Andric if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) { 6237*bdd1243dSDimitry Andric CurCGF->FinishFunction(D->getEndLoc()); 6238*bdd1243dSDimitry Andric CurCGF = nullptr; 6239*bdd1243dSDimitry Andric } 6240*bdd1243dSDimitry Andric 6241*bdd1243dSDimitry Andric if (!CurCGF) { 6242*bdd1243dSDimitry Andric // void __stmts__N(void) 6243*bdd1243dSDimitry Andric // FIXME: Ask the ABI name mangler to pick a name. 6244*bdd1243dSDimitry Andric std::string Name = "__stmts__" + llvm::utostr(CXXGlobalInits.size()); 6245*bdd1243dSDimitry Andric FunctionArgList Args; 6246*bdd1243dSDimitry Andric QualType RetTy = getContext().VoidTy; 6247*bdd1243dSDimitry Andric const CGFunctionInfo &FnInfo = 6248*bdd1243dSDimitry Andric getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args); 6249*bdd1243dSDimitry Andric llvm::FunctionType *FnTy = getTypes().GetFunctionType(FnInfo); 6250*bdd1243dSDimitry Andric llvm::Function *Fn = llvm::Function::Create( 6251*bdd1243dSDimitry Andric FnTy, llvm::GlobalValue::InternalLinkage, Name, &getModule()); 6252*bdd1243dSDimitry Andric 6253*bdd1243dSDimitry Andric CurCGF.reset(new CodeGenFunction(*this)); 6254*bdd1243dSDimitry Andric GlobalTopLevelStmtBlockInFlight.second = D; 6255*bdd1243dSDimitry Andric CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args, 6256*bdd1243dSDimitry Andric D->getBeginLoc(), D->getBeginLoc()); 6257*bdd1243dSDimitry Andric CXXGlobalInits.push_back(Fn); 6258*bdd1243dSDimitry Andric } 6259*bdd1243dSDimitry Andric 6260*bdd1243dSDimitry Andric CurCGF->EmitStmt(D->getStmt()); 6261*bdd1243dSDimitry Andric } 6262*bdd1243dSDimitry Andric 62630b57cec5SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) { 62640b57cec5SDimitry Andric for (auto *I : DC->decls()) { 62650b57cec5SDimitry Andric // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope 62660b57cec5SDimitry Andric // are themselves considered "top-level", so EmitTopLevelDecl on an 62670b57cec5SDimitry Andric // ObjCImplDecl does not recursively visit them. We need to do that in 62680b57cec5SDimitry Andric // case they're nested inside another construct (LinkageSpecDecl / 62690b57cec5SDimitry Andric // ExportDecl) that does stop them from being considered "top-level". 62700b57cec5SDimitry Andric if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 62710b57cec5SDimitry Andric for (auto *M : OID->methods()) 62720b57cec5SDimitry Andric EmitTopLevelDecl(M); 62730b57cec5SDimitry Andric } 62740b57cec5SDimitry Andric 62750b57cec5SDimitry Andric EmitTopLevelDecl(I); 62760b57cec5SDimitry Andric } 62770b57cec5SDimitry Andric } 62780b57cec5SDimitry Andric 62790b57cec5SDimitry Andric /// EmitTopLevelDecl - Emit code for a single top level declaration. 62800b57cec5SDimitry Andric void CodeGenModule::EmitTopLevelDecl(Decl *D) { 62810b57cec5SDimitry Andric // Ignore dependent declarations. 62820b57cec5SDimitry Andric if (D->isTemplated()) 62830b57cec5SDimitry Andric return; 62840b57cec5SDimitry 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 62900b57cec5SDimitry Andric switch (D->getKind()) { 62910b57cec5SDimitry Andric case Decl::CXXConversion: 62920b57cec5SDimitry Andric case Decl::CXXMethod: 62930b57cec5SDimitry Andric case Decl::Function: 62940b57cec5SDimitry Andric EmitGlobal(cast<FunctionDecl>(D)); 62950b57cec5SDimitry Andric // Always provide some coverage mapping 62960b57cec5SDimitry Andric // even for the functions that aren't emitted. 62970b57cec5SDimitry Andric AddDeferredUnusedCoverageMapping(D); 62980b57cec5SDimitry Andric break; 62990b57cec5SDimitry Andric 63000b57cec5SDimitry Andric case Decl::CXXDeductionGuide: 63010b57cec5SDimitry Andric // Function-like, but does not result in code emission. 63020b57cec5SDimitry Andric break; 63030b57cec5SDimitry Andric 63040b57cec5SDimitry Andric case Decl::Var: 63050b57cec5SDimitry Andric case Decl::Decomposition: 63060b57cec5SDimitry Andric case Decl::VarTemplateSpecialization: 63070b57cec5SDimitry Andric EmitGlobal(cast<VarDecl>(D)); 63080b57cec5SDimitry Andric if (auto *DD = dyn_cast<DecompositionDecl>(D)) 63090b57cec5SDimitry Andric for (auto *B : DD->bindings()) 63100b57cec5SDimitry Andric if (auto *HD = B->getHoldingVar()) 63110b57cec5SDimitry Andric EmitGlobal(HD); 63120b57cec5SDimitry Andric break; 63130b57cec5SDimitry Andric 63140b57cec5SDimitry Andric // Indirect fields from global anonymous structs and unions can be 63150b57cec5SDimitry Andric // ignored; only the actual variable requires IR gen support. 63160b57cec5SDimitry Andric case Decl::IndirectField: 63170b57cec5SDimitry Andric break; 63180b57cec5SDimitry Andric 63190b57cec5SDimitry Andric // C++ Decls 63200b57cec5SDimitry Andric case Decl::Namespace: 63210b57cec5SDimitry Andric EmitDeclContext(cast<NamespaceDecl>(D)); 63220b57cec5SDimitry Andric break; 63230b57cec5SDimitry Andric case Decl::ClassTemplateSpecialization: { 63240b57cec5SDimitry Andric const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 63255ffd83dbSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 63265ffd83dbSDimitry Andric if (Spec->getSpecializationKind() == 63275ffd83dbSDimitry Andric TSK_ExplicitInstantiationDefinition && 63280b57cec5SDimitry Andric Spec->hasDefinition()) 63295ffd83dbSDimitry Andric DI->completeTemplateDefinition(*Spec); 6330*bdd1243dSDimitry 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))); 63360b57cec5SDimitry Andric if (auto *ES = D->getASTContext().getExternalSource()) 63370b57cec5SDimitry Andric if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) 6338e8d8bef9SDimitry Andric DI->completeUnusedClass(*CRD); 6339e8d8bef9SDimitry Andric } 63400b57cec5SDimitry Andric // Emit any static data members, they may be definitions. 6341e8d8bef9SDimitry Andric for (auto *I : CRD->decls()) 63420b57cec5SDimitry Andric if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) 63430b57cec5SDimitry Andric EmitTopLevelDecl(I); 63440b57cec5SDimitry Andric break; 6345e8d8bef9SDimitry Andric } 63460b57cec5SDimitry Andric // No code generation needed. 63470b57cec5SDimitry Andric case Decl::UsingShadow: 63480b57cec5SDimitry Andric case Decl::ClassTemplate: 63490b57cec5SDimitry Andric case Decl::VarTemplate: 63500b57cec5SDimitry Andric case Decl::Concept: 63510b57cec5SDimitry Andric case Decl::VarTemplatePartialSpecialization: 63520b57cec5SDimitry Andric case Decl::FunctionTemplate: 63530b57cec5SDimitry Andric case Decl::TypeAliasTemplate: 63540b57cec5SDimitry Andric case Decl::Block: 63550b57cec5SDimitry Andric case Decl::Empty: 63560b57cec5SDimitry Andric case Decl::Binding: 63570b57cec5SDimitry Andric break; 63580b57cec5SDimitry Andric case Decl::Using: // using X; [C++] 63590b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 63600b57cec5SDimitry 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; 63660b57cec5SDimitry Andric case Decl::NamespaceAlias: 63670b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 63680b57cec5SDimitry Andric DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 63695ffd83dbSDimitry Andric break; 63700b57cec5SDimitry Andric case Decl::UsingDirective: // using namespace X; [C++] 63710b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 63720b57cec5SDimitry Andric DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 63735ffd83dbSDimitry Andric break; 63740b57cec5SDimitry Andric case Decl::CXXConstructor: 63750b57cec5SDimitry Andric getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 63760b57cec5SDimitry Andric break; 63770b57cec5SDimitry Andric case Decl::CXXDestructor: 63780b57cec5SDimitry Andric getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 63790b57cec5SDimitry Andric break; 63800b57cec5SDimitry Andric 63810b57cec5SDimitry Andric case Decl::StaticAssert: 63820b57cec5SDimitry Andric // Nothing to do. 63830b57cec5SDimitry Andric break; 63840b57cec5SDimitry Andric 63850b57cec5SDimitry Andric // Objective-C Decls 63860b57cec5SDimitry Andric 63870b57cec5SDimitry Andric // Forward declarations, no (immediate) code generation. 63880b57cec5SDimitry Andric case Decl::ObjCInterface: 63890b57cec5SDimitry Andric case Decl::ObjCCategory: 63900b57cec5SDimitry Andric break; 63910b57cec5SDimitry Andric 63920b57cec5SDimitry Andric case Decl::ObjCProtocol: { 63930b57cec5SDimitry Andric auto *Proto = cast<ObjCProtocolDecl>(D); 63940b57cec5SDimitry Andric if (Proto->isThisDeclarationADefinition()) 63950b57cec5SDimitry Andric ObjCRuntime->GenerateProtocol(Proto); 63960b57cec5SDimitry Andric break; 63970b57cec5SDimitry Andric } 63980b57cec5SDimitry Andric 63990b57cec5SDimitry Andric case Decl::ObjCCategoryImpl: 64000b57cec5SDimitry Andric // Categories have properties but don't support synthesize so we 64010b57cec5SDimitry Andric // can ignore them here. 64020b57cec5SDimitry Andric ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 64030b57cec5SDimitry Andric break; 64040b57cec5SDimitry Andric 64050b57cec5SDimitry Andric case Decl::ObjCImplementation: { 64060b57cec5SDimitry Andric auto *OMD = cast<ObjCImplementationDecl>(D); 64070b57cec5SDimitry Andric EmitObjCPropertyImplementations(OMD); 64080b57cec5SDimitry Andric EmitObjCIvarInitializations(OMD); 64090b57cec5SDimitry Andric ObjCRuntime->GenerateClass(OMD); 64100b57cec5SDimitry Andric // Emit global variable debug information. 64110b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6412480093f4SDimitry Andric if (getCodeGenOpts().hasReducedDebugInfo()) 64130b57cec5SDimitry Andric DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 64140b57cec5SDimitry Andric OMD->getClassInterface()), OMD->getLocation()); 64150b57cec5SDimitry Andric break; 64160b57cec5SDimitry Andric } 64170b57cec5SDimitry Andric case Decl::ObjCMethod: { 64180b57cec5SDimitry Andric auto *OMD = cast<ObjCMethodDecl>(D); 64190b57cec5SDimitry Andric // If this is not a prototype, emit the body. 64200b57cec5SDimitry Andric if (OMD->getBody()) 64210b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCMethod(OMD); 64220b57cec5SDimitry Andric break; 64230b57cec5SDimitry Andric } 64240b57cec5SDimitry Andric case Decl::ObjCCompatibleAlias: 64250b57cec5SDimitry Andric ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 64260b57cec5SDimitry Andric break; 64270b57cec5SDimitry Andric 64280b57cec5SDimitry Andric case Decl::PragmaComment: { 64290b57cec5SDimitry Andric const auto *PCD = cast<PragmaCommentDecl>(D); 64300b57cec5SDimitry Andric switch (PCD->getCommentKind()) { 64310b57cec5SDimitry Andric case PCK_Unknown: 64320b57cec5SDimitry Andric llvm_unreachable("unexpected pragma comment kind"); 64330b57cec5SDimitry Andric case PCK_Linker: 64340b57cec5SDimitry Andric AppendLinkerOptions(PCD->getArg()); 64350b57cec5SDimitry Andric break; 64360b57cec5SDimitry Andric case PCK_Lib: 64370b57cec5SDimitry Andric AddDependentLib(PCD->getArg()); 64380b57cec5SDimitry Andric break; 64390b57cec5SDimitry Andric case PCK_Compiler: 64400b57cec5SDimitry Andric case PCK_ExeStr: 64410b57cec5SDimitry Andric case PCK_User: 64420b57cec5SDimitry Andric break; // We ignore all of these. 64430b57cec5SDimitry Andric } 64440b57cec5SDimitry Andric break; 64450b57cec5SDimitry Andric } 64460b57cec5SDimitry Andric 64470b57cec5SDimitry Andric case Decl::PragmaDetectMismatch: { 64480b57cec5SDimitry Andric const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 64490b57cec5SDimitry Andric AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 64500b57cec5SDimitry Andric break; 64510b57cec5SDimitry Andric } 64520b57cec5SDimitry Andric 64530b57cec5SDimitry Andric case Decl::LinkageSpec: 64540b57cec5SDimitry Andric EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 64550b57cec5SDimitry Andric break; 64560b57cec5SDimitry Andric 64570b57cec5SDimitry Andric case Decl::FileScopeAsm: { 64580b57cec5SDimitry Andric // File-scope asm is ignored during device-side CUDA compilation. 64590b57cec5SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 64600b57cec5SDimitry Andric break; 64610b57cec5SDimitry Andric // File-scope asm is ignored during device-side OpenMP compilation. 64620b57cec5SDimitry Andric if (LangOpts.OpenMPIsDevice) 64630b57cec5SDimitry Andric break; 6464fe6060f1SDimitry Andric // File-scope asm is ignored during device-side SYCL compilation. 6465fe6060f1SDimitry Andric if (LangOpts.SYCLIsDevice) 6466fe6060f1SDimitry Andric break; 64670b57cec5SDimitry Andric auto *AD = cast<FileScopeAsmDecl>(D); 64680b57cec5SDimitry Andric getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 64690b57cec5SDimitry Andric break; 64700b57cec5SDimitry Andric } 64710b57cec5SDimitry Andric 6472*bdd1243dSDimitry Andric case Decl::TopLevelStmt: 6473*bdd1243dSDimitry Andric EmitTopLevelStmt(cast<TopLevelStmtDecl>(D)); 6474*bdd1243dSDimitry Andric break; 6475*bdd1243dSDimitry Andric 64760b57cec5SDimitry Andric case Decl::Import: { 64770b57cec5SDimitry Andric auto *Import = cast<ImportDecl>(D); 64780b57cec5SDimitry Andric 64790b57cec5SDimitry Andric // If we've already imported this module, we're done. 64800b57cec5SDimitry Andric if (!ImportedModules.insert(Import->getImportedModule())) 64810b57cec5SDimitry Andric break; 64820b57cec5SDimitry Andric 64830b57cec5SDimitry Andric // Emit debug information for direct imports. 64840b57cec5SDimitry Andric if (!Import->getImportedOwningModule()) { 64850b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 64860b57cec5SDimitry Andric DI->EmitImportDecl(*Import); 64870b57cec5SDimitry Andric } 64880b57cec5SDimitry 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 64990b57cec5SDimitry Andric // Find all of the submodules and emit the module initializers. 65000b57cec5SDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 65010b57cec5SDimitry Andric SmallVector<clang::Module *, 16> Stack; 65020b57cec5SDimitry Andric Visited.insert(Import->getImportedModule()); 65030b57cec5SDimitry Andric Stack.push_back(Import->getImportedModule()); 65040b57cec5SDimitry Andric 65050b57cec5SDimitry Andric while (!Stack.empty()) { 65060b57cec5SDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 65070b57cec5SDimitry Andric if (!EmittedModuleInitializers.insert(Mod).second) 65080b57cec5SDimitry Andric continue; 65090b57cec5SDimitry Andric 65100b57cec5SDimitry Andric for (auto *D : Context.getModuleInitializers(Mod)) 65110b57cec5SDimitry Andric EmitTopLevelDecl(D); 65120b57cec5SDimitry Andric 65130b57cec5SDimitry Andric // Visit the submodules of this module. 65140b57cec5SDimitry Andric for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 65150b57cec5SDimitry Andric SubEnd = Mod->submodule_end(); 65160b57cec5SDimitry Andric Sub != SubEnd; ++Sub) { 65170b57cec5SDimitry Andric // Skip explicit children; they need to be explicitly imported to emit 65180b57cec5SDimitry Andric // the initializers. 65190b57cec5SDimitry Andric if ((*Sub)->IsExplicit) 65200b57cec5SDimitry Andric continue; 65210b57cec5SDimitry Andric 65220b57cec5SDimitry Andric if (Visited.insert(*Sub).second) 65230b57cec5SDimitry Andric Stack.push_back(*Sub); 65240b57cec5SDimitry Andric } 65250b57cec5SDimitry Andric } 65260b57cec5SDimitry Andric break; 65270b57cec5SDimitry Andric } 65280b57cec5SDimitry Andric 65290b57cec5SDimitry Andric case Decl::Export: 65300b57cec5SDimitry Andric EmitDeclContext(cast<ExportDecl>(D)); 65310b57cec5SDimitry Andric break; 65320b57cec5SDimitry Andric 65330b57cec5SDimitry Andric case Decl::OMPThreadPrivate: 65340b57cec5SDimitry Andric EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 65350b57cec5SDimitry Andric break; 65360b57cec5SDimitry Andric 65370b57cec5SDimitry Andric case Decl::OMPAllocate: 6538fe6060f1SDimitry Andric EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D)); 65390b57cec5SDimitry Andric break; 65400b57cec5SDimitry Andric 65410b57cec5SDimitry Andric case Decl::OMPDeclareReduction: 65420b57cec5SDimitry Andric EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 65430b57cec5SDimitry Andric break; 65440b57cec5SDimitry Andric 65450b57cec5SDimitry Andric case Decl::OMPDeclareMapper: 65460b57cec5SDimitry Andric EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D)); 65470b57cec5SDimitry Andric break; 65480b57cec5SDimitry Andric 65490b57cec5SDimitry Andric case Decl::OMPRequires: 65500b57cec5SDimitry Andric EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D)); 65510b57cec5SDimitry Andric break; 65520b57cec5SDimitry 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 6572*bdd1243dSDimitry Andric case Decl::HLSLBuffer: 6573*bdd1243dSDimitry Andric getHLSLRuntime().addBuffer(cast<HLSLBufferDecl>(D)); 6574*bdd1243dSDimitry Andric break; 6575*bdd1243dSDimitry Andric 65760b57cec5SDimitry Andric default: 65770b57cec5SDimitry Andric // Make sure we handled everything we should, every other kind is a 65780b57cec5SDimitry Andric // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 65790b57cec5SDimitry Andric // function. Need to recode Decl::Kind to do that easily. 65800b57cec5SDimitry Andric assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 65810b57cec5SDimitry Andric break; 65820b57cec5SDimitry Andric } 65830b57cec5SDimitry Andric } 65840b57cec5SDimitry Andric 65850b57cec5SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 65860b57cec5SDimitry Andric // Do we need to generate coverage mapping? 65870b57cec5SDimitry Andric if (!CodeGenOpts.CoverageMapping) 65880b57cec5SDimitry Andric return; 65890b57cec5SDimitry Andric switch (D->getKind()) { 65900b57cec5SDimitry Andric case Decl::CXXConversion: 65910b57cec5SDimitry Andric case Decl::CXXMethod: 65920b57cec5SDimitry Andric case Decl::Function: 65930b57cec5SDimitry Andric case Decl::ObjCMethod: 65940b57cec5SDimitry Andric case Decl::CXXConstructor: 65950b57cec5SDimitry Andric case Decl::CXXDestructor: { 65960b57cec5SDimitry Andric if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 65975ffd83dbSDimitry Andric break; 65980b57cec5SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 65990b57cec5SDimitry Andric if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc())) 66005ffd83dbSDimitry Andric break; 66010b57cec5SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 66020b57cec5SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 66030b57cec5SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = true; 66040b57cec5SDimitry Andric break; 66050b57cec5SDimitry Andric } 66060b57cec5SDimitry Andric default: 66070b57cec5SDimitry Andric break; 66080b57cec5SDimitry Andric }; 66090b57cec5SDimitry Andric } 66100b57cec5SDimitry Andric 66110b57cec5SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 66120b57cec5SDimitry Andric // Do we need to generate coverage mapping? 66130b57cec5SDimitry Andric if (!CodeGenOpts.CoverageMapping) 66140b57cec5SDimitry Andric return; 66150b57cec5SDimitry Andric if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 66160b57cec5SDimitry Andric if (Fn->isTemplateInstantiation()) 66170b57cec5SDimitry Andric ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 66180b57cec5SDimitry Andric } 66190b57cec5SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 66200b57cec5SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 66210b57cec5SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = false; 66220b57cec5SDimitry Andric else 66230b57cec5SDimitry Andric I->second = false; 66240b57cec5SDimitry Andric } 66250b57cec5SDimitry Andric 66260b57cec5SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 66270b57cec5SDimitry Andric // We call takeVector() here to avoid use-after-free. 66280b57cec5SDimitry Andric // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because 66290b57cec5SDimitry Andric // we deserialize function bodies to emit coverage info for them, and that 66300b57cec5SDimitry Andric // deserializes more declarations. How should we handle that case? 66310b57cec5SDimitry Andric for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) { 66320b57cec5SDimitry Andric if (!Entry.second) 66330b57cec5SDimitry Andric continue; 66340b57cec5SDimitry Andric const Decl *D = Entry.first; 66350b57cec5SDimitry Andric switch (D->getKind()) { 66360b57cec5SDimitry Andric case Decl::CXXConversion: 66370b57cec5SDimitry Andric case Decl::CXXMethod: 66380b57cec5SDimitry Andric case Decl::Function: 66390b57cec5SDimitry Andric case Decl::ObjCMethod: { 66400b57cec5SDimitry Andric CodeGenPGO PGO(*this); 66410b57cec5SDimitry Andric GlobalDecl GD(cast<FunctionDecl>(D)); 66420b57cec5SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 66430b57cec5SDimitry Andric getFunctionLinkage(GD)); 66440b57cec5SDimitry Andric break; 66450b57cec5SDimitry Andric } 66460b57cec5SDimitry Andric case Decl::CXXConstructor: { 66470b57cec5SDimitry Andric CodeGenPGO PGO(*this); 66480b57cec5SDimitry Andric GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 66490b57cec5SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 66500b57cec5SDimitry Andric getFunctionLinkage(GD)); 66510b57cec5SDimitry Andric break; 66520b57cec5SDimitry Andric } 66530b57cec5SDimitry Andric case Decl::CXXDestructor: { 66540b57cec5SDimitry Andric CodeGenPGO PGO(*this); 66550b57cec5SDimitry Andric GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 66560b57cec5SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 66570b57cec5SDimitry Andric getFunctionLinkage(GD)); 66580b57cec5SDimitry Andric break; 66590b57cec5SDimitry Andric } 66600b57cec5SDimitry Andric default: 66610b57cec5SDimitry Andric break; 66620b57cec5SDimitry Andric }; 66630b57cec5SDimitry Andric } 66640b57cec5SDimitry Andric } 66650b57cec5SDimitry 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 66790b57cec5SDimitry Andric /// Turns the given pointer into a constant. 66800b57cec5SDimitry Andric static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 66810b57cec5SDimitry Andric const void *Ptr) { 66820b57cec5SDimitry Andric uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 66830b57cec5SDimitry Andric llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 66840b57cec5SDimitry Andric return llvm::ConstantInt::get(i64, PtrInt); 66850b57cec5SDimitry Andric } 66860b57cec5SDimitry Andric 66870b57cec5SDimitry Andric static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 66880b57cec5SDimitry Andric llvm::NamedMDNode *&GlobalMetadata, 66890b57cec5SDimitry Andric GlobalDecl D, 66900b57cec5SDimitry Andric llvm::GlobalValue *Addr) { 66910b57cec5SDimitry Andric if (!GlobalMetadata) 66920b57cec5SDimitry Andric GlobalMetadata = 66930b57cec5SDimitry Andric CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 66940b57cec5SDimitry Andric 66950b57cec5SDimitry Andric // TODO: should we report variant information for ctors/dtors? 66960b57cec5SDimitry Andric llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 66970b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(GetPointerConstant( 66980b57cec5SDimitry Andric CGM.getLLVMContext(), D.getDecl()))}; 66990b57cec5SDimitry Andric GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 67000b57cec5SDimitry Andric } 67010b57cec5SDimitry 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 67680b57cec5SDimitry Andric /// For each function which is declared within an extern "C" region and marked 67690b57cec5SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled 67700b57cec5SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer 67710b57cec5SDimitry Andric /// to such functions with an unmangled name from inline assembly within the 67720b57cec5SDimitry Andric /// same translation unit. 67730b57cec5SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() { 67740b57cec5SDimitry Andric if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases()) 67750b57cec5SDimitry Andric return; 67760b57cec5SDimitry Andric for (auto &I : StaticExternCValues) { 67770b57cec5SDimitry Andric IdentifierInfo *Name = I.first; 67780b57cec5SDimitry 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)); 67930b57cec5SDimitry Andric } 67940b57cec5SDimitry Andric } 67950b57cec5SDimitry Andric 67960b57cec5SDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 67970b57cec5SDimitry Andric GlobalDecl &Result) const { 67980b57cec5SDimitry Andric auto Res = Manglings.find(MangledName); 67990b57cec5SDimitry Andric if (Res == Manglings.end()) 68000b57cec5SDimitry Andric return false; 68010b57cec5SDimitry Andric Result = Res->getValue(); 68020b57cec5SDimitry Andric return true; 68030b57cec5SDimitry Andric } 68040b57cec5SDimitry Andric 68050b57cec5SDimitry Andric /// Emits metadata nodes associating all the global values in the 68060b57cec5SDimitry Andric /// current module with the Decls they came from. This is useful for 68070b57cec5SDimitry Andric /// projects using IR gen as a subroutine. 68080b57cec5SDimitry Andric /// 68090b57cec5SDimitry Andric /// Since there's currently no way to associate an MDNode directly 68100b57cec5SDimitry Andric /// with an llvm::GlobalValue, we create a global named metadata 68110b57cec5SDimitry Andric /// with the name 'clang.global.decl.ptrs'. 68120b57cec5SDimitry Andric void CodeGenModule::EmitDeclMetadata() { 68130b57cec5SDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 68140b57cec5SDimitry Andric 68150b57cec5SDimitry Andric for (auto &I : MangledDeclNames) { 68160b57cec5SDimitry Andric llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 68170b57cec5SDimitry Andric // Some mangled names don't necessarily have an associated GlobalValue 68180b57cec5SDimitry Andric // in this module, e.g. if we mangled it for DebugInfo. 68190b57cec5SDimitry Andric if (Addr) 68200b57cec5SDimitry Andric EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 68210b57cec5SDimitry Andric } 68220b57cec5SDimitry Andric } 68230b57cec5SDimitry Andric 68240b57cec5SDimitry Andric /// Emits metadata nodes for all the local variables in the current 68250b57cec5SDimitry Andric /// function. 68260b57cec5SDimitry Andric void CodeGenFunction::EmitDeclMetadata() { 68270b57cec5SDimitry Andric if (LocalDeclMap.empty()) return; 68280b57cec5SDimitry Andric 68290b57cec5SDimitry Andric llvm::LLVMContext &Context = getLLVMContext(); 68300b57cec5SDimitry Andric 68310b57cec5SDimitry Andric // Find the unique metadata ID for this name. 68320b57cec5SDimitry Andric unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 68330b57cec5SDimitry Andric 68340b57cec5SDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 68350b57cec5SDimitry Andric 68360b57cec5SDimitry Andric for (auto &I : LocalDeclMap) { 68370b57cec5SDimitry Andric const Decl *D = I.first; 68380b57cec5SDimitry Andric llvm::Value *Addr = I.second.getPointer(); 68390b57cec5SDimitry Andric if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 68400b57cec5SDimitry Andric llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 68410b57cec5SDimitry Andric Alloca->setMetadata( 68420b57cec5SDimitry Andric DeclPtrKind, llvm::MDNode::get( 68430b57cec5SDimitry Andric Context, llvm::ValueAsMetadata::getConstant(DAddr))); 68440b57cec5SDimitry Andric } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 68450b57cec5SDimitry Andric GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 68460b57cec5SDimitry Andric EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 68470b57cec5SDimitry Andric } 68480b57cec5SDimitry Andric } 68490b57cec5SDimitry Andric } 68500b57cec5SDimitry Andric 68510b57cec5SDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() { 68520b57cec5SDimitry Andric llvm::NamedMDNode *IdentMetadata = 68530b57cec5SDimitry Andric TheModule.getOrInsertNamedMetadata("llvm.ident"); 68540b57cec5SDimitry Andric std::string Version = getClangFullVersion(); 68550b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 68560b57cec5SDimitry Andric 68570b57cec5SDimitry Andric llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 68580b57cec5SDimitry Andric IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 68590b57cec5SDimitry Andric } 68600b57cec5SDimitry Andric 68610b57cec5SDimitry Andric void CodeGenModule::EmitCommandLineMetadata() { 68620b57cec5SDimitry Andric llvm::NamedMDNode *CommandLineMetadata = 68630b57cec5SDimitry Andric TheModule.getOrInsertNamedMetadata("llvm.commandline"); 68640b57cec5SDimitry Andric std::string CommandLine = getCodeGenOpts().RecordCommandLine; 68650b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 68660b57cec5SDimitry Andric 68670b57cec5SDimitry Andric llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)}; 68680b57cec5SDimitry Andric CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode)); 68690b57cec5SDimitry Andric } 68700b57cec5SDimitry Andric 68710b57cec5SDimitry Andric void CodeGenModule::EmitCoverageFile() { 68720b57cec5SDimitry Andric if (getCodeGenOpts().CoverageDataFile.empty() && 68730b57cec5SDimitry Andric getCodeGenOpts().CoverageNotesFile.empty()) 68740b57cec5SDimitry Andric return; 68750b57cec5SDimitry Andric 68760b57cec5SDimitry Andric llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); 68770b57cec5SDimitry Andric if (!CUNode) 68780b57cec5SDimitry Andric return; 68790b57cec5SDimitry Andric 68800b57cec5SDimitry Andric llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 68810b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 68820b57cec5SDimitry Andric auto *CoverageDataFile = 68830b57cec5SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); 68840b57cec5SDimitry Andric auto *CoverageNotesFile = 68850b57cec5SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); 68860b57cec5SDimitry Andric for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 68870b57cec5SDimitry Andric llvm::MDNode *CU = CUNode->getOperand(i); 68880b57cec5SDimitry Andric llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; 68890b57cec5SDimitry Andric GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 68900b57cec5SDimitry Andric } 68910b57cec5SDimitry Andric } 68920b57cec5SDimitry Andric 68930b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 68940b57cec5SDimitry Andric bool ForEH) { 68950b57cec5SDimitry Andric // Return a bogus pointer if RTTI is disabled, unless it's for EH. 68960b57cec5SDimitry Andric // FIXME: should we even be calling this method if RTTI is disabled 68970b57cec5SDimitry 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())) 69010b57cec5SDimitry Andric return llvm::Constant::getNullValue(Int8PtrTy); 69020b57cec5SDimitry Andric 69030b57cec5SDimitry Andric if (ForEH && Ty->isObjCObjectPointerType() && 69040b57cec5SDimitry Andric LangOpts.ObjCRuntime.isGNUFamily()) 69050b57cec5SDimitry Andric return ObjCRuntime->GetEHType(Ty); 69060b57cec5SDimitry Andric 69070b57cec5SDimitry Andric return getCXXABI().getAddrOfRTTIDescriptor(Ty); 69080b57cec5SDimitry Andric } 69090b57cec5SDimitry Andric 69100b57cec5SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 69110b57cec5SDimitry Andric // Do not emit threadprivates in simd-only mode. 69120b57cec5SDimitry Andric if (LangOpts.OpenMP && LangOpts.OpenMPSimd) 69130b57cec5SDimitry Andric return; 69140b57cec5SDimitry Andric for (auto RefExpr : D->varlists()) { 69150b57cec5SDimitry Andric auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 69160b57cec5SDimitry Andric bool PerformInit = 69170b57cec5SDimitry Andric VD->getAnyInitializer() && 69180b57cec5SDimitry Andric !VD->getAnyInitializer()->isConstantInitializer(getContext(), 69190b57cec5SDimitry Andric /*ForRef=*/false); 69200b57cec5SDimitry Andric 692181ad6265SDimitry Andric Address Addr(GetAddrOfGlobalVar(VD), 692281ad6265SDimitry Andric getTypes().ConvertTypeForMem(VD->getType()), 692381ad6265SDimitry Andric getContext().getDeclAlign(VD)); 69240b57cec5SDimitry Andric if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 69250b57cec5SDimitry Andric VD, Addr, RefExpr->getBeginLoc(), PerformInit)) 69260b57cec5SDimitry Andric CXXGlobalInits.push_back(InitFunction); 69270b57cec5SDimitry Andric } 69280b57cec5SDimitry Andric } 69290b57cec5SDimitry Andric 69300b57cec5SDimitry Andric llvm::Metadata * 69310b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, 69320b57cec5SDimitry 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 69380b57cec5SDimitry Andric llvm::Metadata *&InternalId = Map[T.getCanonicalType()]; 69390b57cec5SDimitry Andric if (InternalId) 69400b57cec5SDimitry Andric return InternalId; 69410b57cec5SDimitry Andric 69420b57cec5SDimitry Andric if (isExternallyVisible(T->getLinkage())) { 69430b57cec5SDimitry Andric std::string OutName; 69440b57cec5SDimitry Andric llvm::raw_string_ostream Out(OutName); 69450b57cec5SDimitry Andric getCXXABI().getMangleContext().mangleTypeName(T, Out); 69460b57cec5SDimitry Andric Out << Suffix; 69470b57cec5SDimitry Andric 69480b57cec5SDimitry Andric InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 69490b57cec5SDimitry Andric } else { 69500b57cec5SDimitry Andric InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 69510b57cec5SDimitry Andric llvm::ArrayRef<llvm::Metadata *>()); 69520b57cec5SDimitry Andric } 69530b57cec5SDimitry Andric 69540b57cec5SDimitry Andric return InternalId; 69550b57cec5SDimitry Andric } 69560b57cec5SDimitry Andric 69570b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 69580b57cec5SDimitry Andric return CreateMetadataIdentifierImpl(T, MetadataIdMap, ""); 69590b57cec5SDimitry Andric } 69600b57cec5SDimitry Andric 69610b57cec5SDimitry Andric llvm::Metadata * 69620b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) { 69630b57cec5SDimitry Andric return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual"); 69640b57cec5SDimitry Andric } 69650b57cec5SDimitry Andric 69660b57cec5SDimitry Andric // Generalize pointer types to a void pointer with the qualifiers of the 69670b57cec5SDimitry Andric // originally pointed-to type, e.g. 'const char *' and 'char * const *' 69680b57cec5SDimitry Andric // generalize to 'const void *' while 'char *' and 'const char **' generalize to 69690b57cec5SDimitry Andric // 'void *'. 69700b57cec5SDimitry Andric static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) { 69710b57cec5SDimitry Andric if (!Ty->isPointerType()) 69720b57cec5SDimitry Andric return Ty; 69730b57cec5SDimitry Andric 69740b57cec5SDimitry Andric return Ctx.getPointerType( 69750b57cec5SDimitry Andric QualType(Ctx.VoidTy).withCVRQualifiers( 69760b57cec5SDimitry Andric Ty->getPointeeType().getCVRQualifiers())); 69770b57cec5SDimitry Andric } 69780b57cec5SDimitry Andric 69790b57cec5SDimitry Andric // Apply type generalization to a FunctionType's return and argument types 69800b57cec5SDimitry Andric static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) { 69810b57cec5SDimitry Andric if (auto *FnType = Ty->getAs<FunctionProtoType>()) { 69820b57cec5SDimitry Andric SmallVector<QualType, 8> GeneralizedParams; 69830b57cec5SDimitry Andric for (auto &Param : FnType->param_types()) 69840b57cec5SDimitry Andric GeneralizedParams.push_back(GeneralizeType(Ctx, Param)); 69850b57cec5SDimitry Andric 69860b57cec5SDimitry Andric return Ctx.getFunctionType( 69870b57cec5SDimitry Andric GeneralizeType(Ctx, FnType->getReturnType()), 69880b57cec5SDimitry Andric GeneralizedParams, FnType->getExtProtoInfo()); 69890b57cec5SDimitry Andric } 69900b57cec5SDimitry Andric 69910b57cec5SDimitry Andric if (auto *FnType = Ty->getAs<FunctionNoProtoType>()) 69920b57cec5SDimitry Andric return Ctx.getFunctionNoProtoType( 69930b57cec5SDimitry Andric GeneralizeType(Ctx, FnType->getReturnType())); 69940b57cec5SDimitry Andric 69950b57cec5SDimitry Andric llvm_unreachable("Encountered unknown FunctionType"); 69960b57cec5SDimitry Andric } 69970b57cec5SDimitry Andric 69980b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) { 69990b57cec5SDimitry Andric return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T), 70000b57cec5SDimitry Andric GeneralizedMetadataIdMap, ".generalized"); 70010b57cec5SDimitry Andric } 70020b57cec5SDimitry Andric 70030b57cec5SDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier. 70040b57cec5SDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const { 70050b57cec5SDimitry Andric // Returns true if at least one of vtable-based CFI checkers is enabled and 70060b57cec5SDimitry Andric // is not in the trapping mode. 70070b57cec5SDimitry Andric return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 70080b57cec5SDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 70090b57cec5SDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 70100b57cec5SDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 70110b57cec5SDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 70120b57cec5SDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 70130b57cec5SDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 70140b57cec5SDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 70150b57cec5SDimitry Andric } 70160b57cec5SDimitry Andric 70170b57cec5SDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 70180b57cec5SDimitry Andric CharUnits Offset, 70190b57cec5SDimitry Andric const CXXRecordDecl *RD) { 70200b57cec5SDimitry Andric llvm::Metadata *MD = 70210b57cec5SDimitry Andric CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 70220b57cec5SDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), MD); 70230b57cec5SDimitry Andric 70240b57cec5SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 70250b57cec5SDimitry Andric if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 70260b57cec5SDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), 70270b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 70280b57cec5SDimitry Andric 70290b57cec5SDimitry Andric if (NeedAllVtablesTypeId()) { 70300b57cec5SDimitry Andric llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 70310b57cec5SDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), MD); 70320b57cec5SDimitry Andric } 70330b57cec5SDimitry Andric } 70340b57cec5SDimitry Andric 70350b57cec5SDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 70360b57cec5SDimitry Andric if (!SanStats) 7037a7dea167SDimitry Andric SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule()); 70380b57cec5SDimitry Andric 70390b57cec5SDimitry Andric return *SanStats; 70400b57cec5SDimitry Andric } 704123408297SDimitry Andric 70420b57cec5SDimitry Andric llvm::Value * 70430b57cec5SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, 70440b57cec5SDimitry Andric CodeGenFunction &CGF) { 70450b57cec5SDimitry 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; 70510b57cec5SDimitry 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