1*0b57cec5SDimitry Andric //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 2*0b57cec5SDimitry Andric // 3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6*0b57cec5SDimitry Andric // 7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 8*0b57cec5SDimitry Andric // 9*0b57cec5SDimitry Andric // This coordinates the per-module state used while generating code. 10*0b57cec5SDimitry Andric // 11*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 12*0b57cec5SDimitry Andric 13*0b57cec5SDimitry Andric #include "CodeGenModule.h" 14*0b57cec5SDimitry Andric #include "CGBlocks.h" 15*0b57cec5SDimitry Andric #include "CGCUDARuntime.h" 16*0b57cec5SDimitry Andric #include "CGCXXABI.h" 17*0b57cec5SDimitry Andric #include "CGCall.h" 18*0b57cec5SDimitry Andric #include "CGDebugInfo.h" 19*0b57cec5SDimitry Andric #include "CGObjCRuntime.h" 20*0b57cec5SDimitry Andric #include "CGOpenCLRuntime.h" 21*0b57cec5SDimitry Andric #include "CGOpenMPRuntime.h" 22349cc55cSDimitry Andric #include "CGOpenMPRuntimeGPU.h" 23*0b57cec5SDimitry Andric #include "CodeGenFunction.h" 24*0b57cec5SDimitry Andric #include "CodeGenPGO.h" 25*0b57cec5SDimitry Andric #include "ConstantEmitter.h" 26*0b57cec5SDimitry Andric #include "CoverageMappingGen.h" 27*0b57cec5SDimitry Andric #include "TargetInfo.h" 28*0b57cec5SDimitry Andric #include "clang/AST/ASTContext.h" 29*0b57cec5SDimitry Andric #include "clang/AST/CharUnits.h" 30*0b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h" 31*0b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h" 32*0b57cec5SDimitry Andric #include "clang/AST/DeclTemplate.h" 33*0b57cec5SDimitry Andric #include "clang/AST/Mangle.h" 34*0b57cec5SDimitry Andric #include "clang/AST/RecordLayout.h" 35*0b57cec5SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h" 36*0b57cec5SDimitry Andric #include "clang/AST/StmtVisitor.h" 37*0b57cec5SDimitry Andric #include "clang/Basic/Builtins.h" 38*0b57cec5SDimitry Andric #include "clang/Basic/CharInfo.h" 39*0b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h" 40*0b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h" 415ffd83dbSDimitry Andric #include "clang/Basic/FileManager.h" 42*0b57cec5SDimitry Andric #include "clang/Basic/Module.h" 43*0b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h" 44*0b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h" 45*0b57cec5SDimitry Andric #include "clang/Basic/Version.h" 46*0b57cec5SDimitry Andric #include "clang/CodeGen/ConstantInitBuilder.h" 47*0b57cec5SDimitry Andric #include "clang/Frontend/FrontendDiagnostic.h" 48*0b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h" 49*0b57cec5SDimitry Andric #include "llvm/ADT/Triple.h" 50*0b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h" 51480093f4SDimitry Andric #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 52*0b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h" 53*0b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h" 54*0b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h" 55*0b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h" 56*0b57cec5SDimitry Andric #include "llvm/IR/Module.h" 57*0b57cec5SDimitry Andric #include "llvm/IR/ProfileSummary.h" 58*0b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfReader.h" 59*0b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h" 60480093f4SDimitry Andric #include "llvm/Support/CommandLine.h" 61*0b57cec5SDimitry Andric #include "llvm/Support/ConvertUTF.h" 62*0b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h" 63*0b57cec5SDimitry Andric #include "llvm/Support/MD5.h" 64*0b57cec5SDimitry Andric #include "llvm/Support/TimeProfiler.h" 65349cc55cSDimitry Andric #include "llvm/Support/X86TargetParser.h" 66*0b57cec5SDimitry Andric 67*0b57cec5SDimitry Andric using namespace clang; 68*0b57cec5SDimitry Andric using namespace CodeGen; 69*0b57cec5SDimitry Andric 70*0b57cec5SDimitry Andric static llvm::cl::opt<bool> LimitedCoverage( 71*0b57cec5SDimitry Andric "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden, 72*0b57cec5SDimitry Andric llvm::cl::desc("Emit limited coverage mapping information (experimental)"), 73*0b57cec5SDimitry Andric llvm::cl::init(false)); 74*0b57cec5SDimitry Andric 75*0b57cec5SDimitry Andric static const char AnnotationSection[] = "llvm.metadata"; 76*0b57cec5SDimitry Andric 77*0b57cec5SDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) { 78fe6060f1SDimitry Andric switch (CGM.getContext().getCXXABIKind()) { 79e8d8bef9SDimitry Andric case TargetCXXABI::AppleARM64: 80480093f4SDimitry Andric case TargetCXXABI::Fuchsia: 81*0b57cec5SDimitry Andric case TargetCXXABI::GenericAArch64: 82*0b57cec5SDimitry Andric case TargetCXXABI::GenericARM: 83*0b57cec5SDimitry Andric case TargetCXXABI::iOS: 84*0b57cec5SDimitry Andric case TargetCXXABI::WatchOS: 85*0b57cec5SDimitry Andric case TargetCXXABI::GenericMIPS: 86*0b57cec5SDimitry Andric case TargetCXXABI::GenericItanium: 87*0b57cec5SDimitry Andric case TargetCXXABI::WebAssembly: 885ffd83dbSDimitry Andric case TargetCXXABI::XL: 89*0b57cec5SDimitry Andric return CreateItaniumCXXABI(CGM); 90*0b57cec5SDimitry Andric case TargetCXXABI::Microsoft: 91*0b57cec5SDimitry Andric return CreateMicrosoftCXXABI(CGM); 92*0b57cec5SDimitry Andric } 93*0b57cec5SDimitry Andric 94*0b57cec5SDimitry Andric llvm_unreachable("invalid C++ ABI kind"); 95*0b57cec5SDimitry Andric } 96*0b57cec5SDimitry Andric 97*0b57cec5SDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO, 98*0b57cec5SDimitry Andric const PreprocessorOptions &PPO, 99*0b57cec5SDimitry Andric const CodeGenOptions &CGO, llvm::Module &M, 100*0b57cec5SDimitry Andric DiagnosticsEngine &diags, 101*0b57cec5SDimitry Andric CoverageSourceInfo *CoverageInfo) 102*0b57cec5SDimitry Andric : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO), 103*0b57cec5SDimitry Andric PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags), 104*0b57cec5SDimitry Andric Target(C.getTargetInfo()), ABI(createCXXABI(*this)), 105*0b57cec5SDimitry Andric VMContext(M.getContext()), Types(*this), VTables(*this), 106*0b57cec5SDimitry Andric SanitizerMD(new SanitizerMetadata(*this)) { 107*0b57cec5SDimitry Andric 108*0b57cec5SDimitry Andric // Initialize the type cache. 109*0b57cec5SDimitry Andric llvm::LLVMContext &LLVMContext = M.getContext(); 110*0b57cec5SDimitry Andric VoidTy = llvm::Type::getVoidTy(LLVMContext); 111*0b57cec5SDimitry Andric Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 112*0b57cec5SDimitry Andric Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 113*0b57cec5SDimitry Andric Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 114*0b57cec5SDimitry Andric Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 115*0b57cec5SDimitry Andric HalfTy = llvm::Type::getHalfTy(LLVMContext); 1165ffd83dbSDimitry Andric BFloatTy = llvm::Type::getBFloatTy(LLVMContext); 117*0b57cec5SDimitry Andric FloatTy = llvm::Type::getFloatTy(LLVMContext); 118*0b57cec5SDimitry Andric DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 119*0b57cec5SDimitry Andric PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 120*0b57cec5SDimitry Andric PointerAlignInBytes = 121*0b57cec5SDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 122*0b57cec5SDimitry Andric SizeSizeInBytes = 123*0b57cec5SDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity(); 124*0b57cec5SDimitry Andric IntAlignInBytes = 125*0b57cec5SDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity(); 126e8d8bef9SDimitry Andric CharTy = 127e8d8bef9SDimitry Andric llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth()); 128*0b57cec5SDimitry Andric IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 129*0b57cec5SDimitry Andric IntPtrTy = llvm::IntegerType::get(LLVMContext, 130*0b57cec5SDimitry Andric C.getTargetInfo().getMaxPointerWidth()); 131*0b57cec5SDimitry Andric Int8PtrTy = Int8Ty->getPointerTo(0); 132*0b57cec5SDimitry Andric Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 133349cc55cSDimitry Andric const llvm::DataLayout &DL = M.getDataLayout(); 134349cc55cSDimitry Andric AllocaInt8PtrTy = Int8Ty->getPointerTo(DL.getAllocaAddrSpace()); 135349cc55cSDimitry Andric GlobalsInt8PtrTy = Int8Ty->getPointerTo(DL.getDefaultGlobalsAddressSpace()); 136*0b57cec5SDimitry Andric ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace(); 137*0b57cec5SDimitry Andric 138*0b57cec5SDimitry Andric RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 139*0b57cec5SDimitry Andric 140*0b57cec5SDimitry Andric if (LangOpts.ObjC) 141*0b57cec5SDimitry Andric createObjCRuntime(); 142*0b57cec5SDimitry Andric if (LangOpts.OpenCL) 143*0b57cec5SDimitry Andric createOpenCLRuntime(); 144*0b57cec5SDimitry Andric if (LangOpts.OpenMP) 145*0b57cec5SDimitry Andric createOpenMPRuntime(); 146*0b57cec5SDimitry Andric if (LangOpts.CUDA) 147*0b57cec5SDimitry Andric createCUDARuntime(); 148*0b57cec5SDimitry Andric 149*0b57cec5SDimitry Andric // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 150*0b57cec5SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::Thread) || 151*0b57cec5SDimitry Andric (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 152*0b57cec5SDimitry Andric TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(), 153*0b57cec5SDimitry Andric getCXXABI().getMangleContext())); 154*0b57cec5SDimitry Andric 155*0b57cec5SDimitry Andric // If debug info or coverage generation is enabled, create the CGDebugInfo 156*0b57cec5SDimitry Andric // object. 157*0b57cec5SDimitry Andric if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo || 158*0b57cec5SDimitry Andric CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) 159*0b57cec5SDimitry Andric DebugInfo.reset(new CGDebugInfo(*this)); 160*0b57cec5SDimitry Andric 161*0b57cec5SDimitry Andric Block.GlobalUniqueCount = 0; 162*0b57cec5SDimitry Andric 163*0b57cec5SDimitry Andric if (C.getLangOpts().ObjC) 164*0b57cec5SDimitry Andric ObjCData.reset(new ObjCEntrypoints()); 165*0b57cec5SDimitry Andric 166*0b57cec5SDimitry Andric if (CodeGenOpts.hasProfileClangUse()) { 167*0b57cec5SDimitry Andric auto ReaderOrErr = llvm::IndexedInstrProfReader::create( 168*0b57cec5SDimitry Andric CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile); 169*0b57cec5SDimitry Andric if (auto E = ReaderOrErr.takeError()) { 170*0b57cec5SDimitry Andric unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 171*0b57cec5SDimitry Andric "Could not read profile %0: %1"); 172*0b57cec5SDimitry Andric llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) { 173*0b57cec5SDimitry Andric getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath 174*0b57cec5SDimitry Andric << EI.message(); 175*0b57cec5SDimitry Andric }); 176*0b57cec5SDimitry Andric } else 177*0b57cec5SDimitry Andric PGOReader = std::move(ReaderOrErr.get()); 178*0b57cec5SDimitry Andric } 179*0b57cec5SDimitry Andric 180*0b57cec5SDimitry Andric // If coverage mapping generation is enabled, create the 181*0b57cec5SDimitry Andric // CoverageMappingModuleGen object. 182*0b57cec5SDimitry Andric if (CodeGenOpts.CoverageMapping) 183*0b57cec5SDimitry Andric CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); 184fe6060f1SDimitry Andric 185fe6060f1SDimitry Andric // Generate the module name hash here if needed. 186fe6060f1SDimitry Andric if (CodeGenOpts.UniqueInternalLinkageNames && 187fe6060f1SDimitry Andric !getModule().getSourceFileName().empty()) { 188fe6060f1SDimitry Andric std::string Path = getModule().getSourceFileName(); 189fe6060f1SDimitry Andric // Check if a path substitution is needed from the MacroPrefixMap. 1906e75b2fbSDimitry Andric for (const auto &Entry : LangOpts.MacroPrefixMap) 191fe6060f1SDimitry Andric if (Path.rfind(Entry.first, 0) != std::string::npos) { 192fe6060f1SDimitry Andric Path = Entry.second + Path.substr(Entry.first.size()); 193fe6060f1SDimitry Andric break; 194fe6060f1SDimitry Andric } 195fe6060f1SDimitry Andric llvm::MD5 Md5; 196fe6060f1SDimitry Andric Md5.update(Path); 197fe6060f1SDimitry Andric llvm::MD5::MD5Result R; 198fe6060f1SDimitry Andric Md5.final(R); 199fe6060f1SDimitry Andric SmallString<32> Str; 200fe6060f1SDimitry Andric llvm::MD5::stringifyResult(R, Str); 201fe6060f1SDimitry Andric // Convert MD5hash to Decimal. Demangler suffixes can either contain 202fe6060f1SDimitry Andric // numbers or characters but not both. 203fe6060f1SDimitry Andric llvm::APInt IntHash(128, Str.str(), 16); 204fe6060f1SDimitry Andric // Prepend "__uniq" before the hash for tools like profilers to understand 205fe6060f1SDimitry Andric // that this symbol is of internal linkage type. The "__uniq" is the 206fe6060f1SDimitry Andric // pre-determined prefix that is used to tell tools that this symbol was 207fe6060f1SDimitry Andric // created with -funique-internal-linakge-symbols and the tools can strip or 208fe6060f1SDimitry Andric // keep the prefix as needed. 209fe6060f1SDimitry Andric ModuleNameHash = (Twine(".__uniq.") + 210fe6060f1SDimitry Andric Twine(toString(IntHash, /* Radix = */ 10, /* Signed = */false))).str(); 211fe6060f1SDimitry Andric } 212*0b57cec5SDimitry Andric } 213*0b57cec5SDimitry Andric 214*0b57cec5SDimitry Andric CodeGenModule::~CodeGenModule() {} 215*0b57cec5SDimitry Andric 216*0b57cec5SDimitry Andric void CodeGenModule::createObjCRuntime() { 217*0b57cec5SDimitry Andric // This is just isGNUFamily(), but we want to force implementors of 218*0b57cec5SDimitry Andric // new ABIs to decide how best to do this. 219*0b57cec5SDimitry Andric switch (LangOpts.ObjCRuntime.getKind()) { 220*0b57cec5SDimitry Andric case ObjCRuntime::GNUstep: 221*0b57cec5SDimitry Andric case ObjCRuntime::GCC: 222*0b57cec5SDimitry Andric case ObjCRuntime::ObjFW: 223*0b57cec5SDimitry Andric ObjCRuntime.reset(CreateGNUObjCRuntime(*this)); 224*0b57cec5SDimitry Andric return; 225*0b57cec5SDimitry Andric 226*0b57cec5SDimitry Andric case ObjCRuntime::FragileMacOSX: 227*0b57cec5SDimitry Andric case ObjCRuntime::MacOSX: 228*0b57cec5SDimitry Andric case ObjCRuntime::iOS: 229*0b57cec5SDimitry Andric case ObjCRuntime::WatchOS: 230*0b57cec5SDimitry Andric ObjCRuntime.reset(CreateMacObjCRuntime(*this)); 231*0b57cec5SDimitry Andric return; 232*0b57cec5SDimitry Andric } 233*0b57cec5SDimitry Andric llvm_unreachable("bad runtime kind"); 234*0b57cec5SDimitry Andric } 235*0b57cec5SDimitry Andric 236*0b57cec5SDimitry Andric void CodeGenModule::createOpenCLRuntime() { 237*0b57cec5SDimitry Andric OpenCLRuntime.reset(new CGOpenCLRuntime(*this)); 238*0b57cec5SDimitry Andric } 239*0b57cec5SDimitry Andric 240*0b57cec5SDimitry Andric void CodeGenModule::createOpenMPRuntime() { 241*0b57cec5SDimitry Andric // Select a specialized code generation class based on the target, if any. 242*0b57cec5SDimitry Andric // If it does not exist use the default implementation. 243*0b57cec5SDimitry Andric switch (getTriple().getArch()) { 244*0b57cec5SDimitry Andric case llvm::Triple::nvptx: 245*0b57cec5SDimitry Andric case llvm::Triple::nvptx64: 246e8d8bef9SDimitry Andric case llvm::Triple::amdgcn: 247e8d8bef9SDimitry Andric assert(getLangOpts().OpenMPIsDevice && 248349cc55cSDimitry Andric "OpenMP AMDGPU/NVPTX is only prepared to deal with device code."); 249349cc55cSDimitry Andric OpenMPRuntime.reset(new CGOpenMPRuntimeGPU(*this)); 250e8d8bef9SDimitry Andric break; 251*0b57cec5SDimitry Andric default: 252*0b57cec5SDimitry Andric if (LangOpts.OpenMPSimd) 253*0b57cec5SDimitry Andric OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this)); 254*0b57cec5SDimitry Andric else 255*0b57cec5SDimitry Andric OpenMPRuntime.reset(new CGOpenMPRuntime(*this)); 256*0b57cec5SDimitry Andric break; 257*0b57cec5SDimitry Andric } 258*0b57cec5SDimitry Andric } 259*0b57cec5SDimitry Andric 260*0b57cec5SDimitry Andric void CodeGenModule::createCUDARuntime() { 261*0b57cec5SDimitry Andric CUDARuntime.reset(CreateNVCUDARuntime(*this)); 262*0b57cec5SDimitry Andric } 263*0b57cec5SDimitry Andric 264*0b57cec5SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { 265*0b57cec5SDimitry Andric Replacements[Name] = C; 266*0b57cec5SDimitry Andric } 267*0b57cec5SDimitry Andric 268*0b57cec5SDimitry Andric void CodeGenModule::applyReplacements() { 269*0b57cec5SDimitry Andric for (auto &I : Replacements) { 270*0b57cec5SDimitry Andric StringRef MangledName = I.first(); 271*0b57cec5SDimitry Andric llvm::Constant *Replacement = I.second; 272*0b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 273*0b57cec5SDimitry Andric if (!Entry) 274*0b57cec5SDimitry Andric continue; 275*0b57cec5SDimitry Andric auto *OldF = cast<llvm::Function>(Entry); 276*0b57cec5SDimitry Andric auto *NewF = dyn_cast<llvm::Function>(Replacement); 277*0b57cec5SDimitry Andric if (!NewF) { 278*0b57cec5SDimitry Andric if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 279*0b57cec5SDimitry Andric NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 280*0b57cec5SDimitry Andric } else { 281*0b57cec5SDimitry Andric auto *CE = cast<llvm::ConstantExpr>(Replacement); 282*0b57cec5SDimitry Andric assert(CE->getOpcode() == llvm::Instruction::BitCast || 283*0b57cec5SDimitry Andric CE->getOpcode() == llvm::Instruction::GetElementPtr); 284*0b57cec5SDimitry Andric NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 285*0b57cec5SDimitry Andric } 286*0b57cec5SDimitry Andric } 287*0b57cec5SDimitry Andric 288*0b57cec5SDimitry Andric // Replace old with new, but keep the old order. 289*0b57cec5SDimitry Andric OldF->replaceAllUsesWith(Replacement); 290*0b57cec5SDimitry Andric if (NewF) { 291*0b57cec5SDimitry Andric NewF->removeFromParent(); 292*0b57cec5SDimitry Andric OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(), 293*0b57cec5SDimitry Andric NewF); 294*0b57cec5SDimitry Andric } 295*0b57cec5SDimitry Andric OldF->eraseFromParent(); 296*0b57cec5SDimitry Andric } 297*0b57cec5SDimitry Andric } 298*0b57cec5SDimitry Andric 299*0b57cec5SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { 300*0b57cec5SDimitry Andric GlobalValReplacements.push_back(std::make_pair(GV, C)); 301*0b57cec5SDimitry Andric } 302*0b57cec5SDimitry Andric 303*0b57cec5SDimitry Andric void CodeGenModule::applyGlobalValReplacements() { 304*0b57cec5SDimitry Andric for (auto &I : GlobalValReplacements) { 305*0b57cec5SDimitry Andric llvm::GlobalValue *GV = I.first; 306*0b57cec5SDimitry Andric llvm::Constant *C = I.second; 307*0b57cec5SDimitry Andric 308*0b57cec5SDimitry Andric GV->replaceAllUsesWith(C); 309*0b57cec5SDimitry Andric GV->eraseFromParent(); 310*0b57cec5SDimitry Andric } 311*0b57cec5SDimitry Andric } 312*0b57cec5SDimitry Andric 313*0b57cec5SDimitry Andric // This is only used in aliases that we created and we know they have a 314*0b57cec5SDimitry Andric // linear structure. 315349cc55cSDimitry Andric static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) { 316349cc55cSDimitry Andric const llvm::Constant *C; 317349cc55cSDimitry Andric if (auto *GA = dyn_cast<llvm::GlobalAlias>(GV)) 318349cc55cSDimitry Andric C = GA->getAliasee(); 319349cc55cSDimitry Andric else if (auto *GI = dyn_cast<llvm::GlobalIFunc>(GV)) 320349cc55cSDimitry Andric C = GI->getResolver(); 321349cc55cSDimitry Andric else 322349cc55cSDimitry Andric return GV; 323349cc55cSDimitry Andric 324349cc55cSDimitry Andric const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(C->stripPointerCasts()); 325349cc55cSDimitry Andric if (!AliaseeGV) 326*0b57cec5SDimitry Andric return nullptr; 327349cc55cSDimitry Andric 328349cc55cSDimitry Andric const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject(); 329349cc55cSDimitry Andric if (FinalGV == GV) 330*0b57cec5SDimitry Andric return nullptr; 331349cc55cSDimitry Andric 332349cc55cSDimitry Andric return FinalGV; 333*0b57cec5SDimitry Andric } 334349cc55cSDimitry Andric 335349cc55cSDimitry Andric static bool checkAliasedGlobal(DiagnosticsEngine &Diags, 336349cc55cSDimitry Andric SourceLocation Location, bool IsIFunc, 337349cc55cSDimitry Andric const llvm::GlobalValue *Alias, 338349cc55cSDimitry Andric const llvm::GlobalValue *&GV) { 339349cc55cSDimitry Andric GV = getAliasedGlobal(Alias); 340349cc55cSDimitry Andric if (!GV) { 341349cc55cSDimitry Andric Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc; 342349cc55cSDimitry Andric return false; 343349cc55cSDimitry Andric } 344349cc55cSDimitry Andric 345349cc55cSDimitry Andric if (GV->isDeclaration()) { 346349cc55cSDimitry Andric Diags.Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc; 347349cc55cSDimitry Andric return false; 348349cc55cSDimitry Andric } 349349cc55cSDimitry Andric 350349cc55cSDimitry Andric if (IsIFunc) { 351349cc55cSDimitry Andric // Check resolver function type. 352349cc55cSDimitry Andric const auto *F = dyn_cast<llvm::Function>(GV); 353349cc55cSDimitry Andric if (!F) { 354349cc55cSDimitry Andric Diags.Report(Location, diag::err_alias_to_undefined) 355349cc55cSDimitry Andric << IsIFunc << IsIFunc; 356349cc55cSDimitry Andric return false; 357349cc55cSDimitry Andric } 358349cc55cSDimitry Andric 359349cc55cSDimitry Andric llvm::FunctionType *FTy = F->getFunctionType(); 360349cc55cSDimitry Andric if (!FTy->getReturnType()->isPointerTy()) { 361349cc55cSDimitry Andric Diags.Report(Location, diag::err_ifunc_resolver_return); 362349cc55cSDimitry Andric return false; 363349cc55cSDimitry Andric } 364349cc55cSDimitry Andric } 365349cc55cSDimitry Andric 366349cc55cSDimitry Andric return true; 367*0b57cec5SDimitry Andric } 368*0b57cec5SDimitry Andric 369*0b57cec5SDimitry Andric void CodeGenModule::checkAliases() { 370*0b57cec5SDimitry Andric // Check if the constructed aliases are well formed. It is really unfortunate 371*0b57cec5SDimitry Andric // that we have to do this in CodeGen, but we only construct mangled names 372*0b57cec5SDimitry Andric // and aliases during codegen. 373*0b57cec5SDimitry Andric bool Error = false; 374*0b57cec5SDimitry Andric DiagnosticsEngine &Diags = getDiags(); 375*0b57cec5SDimitry Andric for (const GlobalDecl &GD : Aliases) { 376*0b57cec5SDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 377*0b57cec5SDimitry Andric SourceLocation Location; 378*0b57cec5SDimitry Andric bool IsIFunc = D->hasAttr<IFuncAttr>(); 379*0b57cec5SDimitry Andric if (const Attr *A = D->getDefiningAttr()) 380*0b57cec5SDimitry Andric Location = A->getLocation(); 381*0b57cec5SDimitry Andric else 382*0b57cec5SDimitry Andric llvm_unreachable("Not an alias or ifunc?"); 383349cc55cSDimitry Andric 384*0b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 385349cc55cSDimitry Andric llvm::GlobalValue *Alias = GetGlobalValue(MangledName); 386349cc55cSDimitry Andric const llvm::GlobalValue *GV = nullptr; 387349cc55cSDimitry Andric if (!checkAliasedGlobal(Diags, Location, IsIFunc, Alias, GV)) { 388*0b57cec5SDimitry Andric Error = true; 389349cc55cSDimitry Andric continue; 390*0b57cec5SDimitry Andric } 391*0b57cec5SDimitry Andric 392349cc55cSDimitry Andric llvm::Constant *Aliasee = 393349cc55cSDimitry Andric IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver() 394349cc55cSDimitry Andric : cast<llvm::GlobalAlias>(Alias)->getAliasee(); 395349cc55cSDimitry Andric 396*0b57cec5SDimitry Andric llvm::GlobalValue *AliaseeGV; 397*0b57cec5SDimitry Andric if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 398*0b57cec5SDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 399*0b57cec5SDimitry Andric else 400*0b57cec5SDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 401*0b57cec5SDimitry Andric 402*0b57cec5SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 403*0b57cec5SDimitry Andric StringRef AliasSection = SA->getName(); 404*0b57cec5SDimitry Andric if (AliasSection != AliaseeGV->getSection()) 405*0b57cec5SDimitry Andric Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 406*0b57cec5SDimitry Andric << AliasSection << IsIFunc << IsIFunc; 407*0b57cec5SDimitry Andric } 408*0b57cec5SDimitry Andric 409*0b57cec5SDimitry Andric // We have to handle alias to weak aliases in here. LLVM itself disallows 410*0b57cec5SDimitry Andric // this since the object semantics would not match the IL one. For 411*0b57cec5SDimitry Andric // compatibility with gcc we implement it by just pointing the alias 412*0b57cec5SDimitry Andric // to its aliasee's aliasee. We also warn, since the user is probably 413*0b57cec5SDimitry Andric // expecting the link to be weak. 414349cc55cSDimitry Andric if (auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) { 415*0b57cec5SDimitry Andric if (GA->isInterposable()) { 416*0b57cec5SDimitry Andric Diags.Report(Location, diag::warn_alias_to_weak_alias) 417*0b57cec5SDimitry Andric << GV->getName() << GA->getName() << IsIFunc; 418*0b57cec5SDimitry Andric Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 419349cc55cSDimitry Andric GA->getAliasee(), Alias->getType()); 420349cc55cSDimitry Andric 421349cc55cSDimitry Andric if (IsIFunc) 422349cc55cSDimitry Andric cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee); 423349cc55cSDimitry Andric else 424349cc55cSDimitry Andric cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee); 425*0b57cec5SDimitry Andric } 426*0b57cec5SDimitry Andric } 427*0b57cec5SDimitry Andric } 428*0b57cec5SDimitry Andric if (!Error) 429*0b57cec5SDimitry Andric return; 430*0b57cec5SDimitry Andric 431*0b57cec5SDimitry Andric for (const GlobalDecl &GD : Aliases) { 432*0b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 433349cc55cSDimitry Andric llvm::GlobalValue *Alias = GetGlobalValue(MangledName); 434*0b57cec5SDimitry Andric Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 435*0b57cec5SDimitry Andric Alias->eraseFromParent(); 436*0b57cec5SDimitry Andric } 437*0b57cec5SDimitry Andric } 438*0b57cec5SDimitry Andric 439*0b57cec5SDimitry Andric void CodeGenModule::clear() { 440*0b57cec5SDimitry Andric DeferredDeclsToEmit.clear(); 441*0b57cec5SDimitry Andric if (OpenMPRuntime) 442*0b57cec5SDimitry Andric OpenMPRuntime->clear(); 443*0b57cec5SDimitry Andric } 444*0b57cec5SDimitry Andric 445*0b57cec5SDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 446*0b57cec5SDimitry Andric StringRef MainFile) { 447*0b57cec5SDimitry Andric if (!hasDiagnostics()) 448*0b57cec5SDimitry Andric return; 449*0b57cec5SDimitry Andric if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 450*0b57cec5SDimitry Andric if (MainFile.empty()) 451*0b57cec5SDimitry Andric MainFile = "<stdin>"; 452*0b57cec5SDimitry Andric Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 453*0b57cec5SDimitry Andric } else { 454*0b57cec5SDimitry Andric if (Mismatched > 0) 455*0b57cec5SDimitry Andric Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched; 456*0b57cec5SDimitry Andric 457*0b57cec5SDimitry Andric if (Missing > 0) 458*0b57cec5SDimitry Andric Diags.Report(diag::warn_profile_data_missing) << Visited << Missing; 459*0b57cec5SDimitry Andric } 460*0b57cec5SDimitry Andric } 461*0b57cec5SDimitry Andric 462e8d8bef9SDimitry Andric static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO, 463e8d8bef9SDimitry Andric llvm::Module &M) { 464e8d8bef9SDimitry Andric if (!LO.VisibilityFromDLLStorageClass) 465e8d8bef9SDimitry Andric return; 466e8d8bef9SDimitry Andric 467e8d8bef9SDimitry Andric llvm::GlobalValue::VisibilityTypes DLLExportVisibility = 468e8d8bef9SDimitry Andric CodeGenModule::GetLLVMVisibility(LO.getDLLExportVisibility()); 469e8d8bef9SDimitry Andric llvm::GlobalValue::VisibilityTypes NoDLLStorageClassVisibility = 470e8d8bef9SDimitry Andric CodeGenModule::GetLLVMVisibility(LO.getNoDLLStorageClassVisibility()); 471e8d8bef9SDimitry Andric llvm::GlobalValue::VisibilityTypes ExternDeclDLLImportVisibility = 472e8d8bef9SDimitry Andric CodeGenModule::GetLLVMVisibility(LO.getExternDeclDLLImportVisibility()); 473e8d8bef9SDimitry Andric llvm::GlobalValue::VisibilityTypes ExternDeclNoDLLStorageClassVisibility = 474e8d8bef9SDimitry Andric CodeGenModule::GetLLVMVisibility( 475e8d8bef9SDimitry Andric LO.getExternDeclNoDLLStorageClassVisibility()); 476e8d8bef9SDimitry Andric 477e8d8bef9SDimitry Andric for (llvm::GlobalValue &GV : M.global_values()) { 478e8d8bef9SDimitry Andric if (GV.hasAppendingLinkage() || GV.hasLocalLinkage()) 479e8d8bef9SDimitry Andric continue; 480e8d8bef9SDimitry Andric 481e8d8bef9SDimitry Andric // Reset DSO locality before setting the visibility. This removes 482e8d8bef9SDimitry Andric // any effects that visibility options and annotations may have 483e8d8bef9SDimitry Andric // had on the DSO locality. Setting the visibility will implicitly set 484e8d8bef9SDimitry Andric // appropriate globals to DSO Local; however, this will be pessimistic 485e8d8bef9SDimitry Andric // w.r.t. to the normal compiler IRGen. 486e8d8bef9SDimitry Andric GV.setDSOLocal(false); 487e8d8bef9SDimitry Andric 488e8d8bef9SDimitry Andric if (GV.isDeclarationForLinker()) { 489e8d8bef9SDimitry Andric GV.setVisibility(GV.getDLLStorageClass() == 490e8d8bef9SDimitry Andric llvm::GlobalValue::DLLImportStorageClass 491e8d8bef9SDimitry Andric ? ExternDeclDLLImportVisibility 492e8d8bef9SDimitry Andric : ExternDeclNoDLLStorageClassVisibility); 493e8d8bef9SDimitry Andric } else { 494e8d8bef9SDimitry Andric GV.setVisibility(GV.getDLLStorageClass() == 495e8d8bef9SDimitry Andric llvm::GlobalValue::DLLExportStorageClass 496e8d8bef9SDimitry Andric ? DLLExportVisibility 497e8d8bef9SDimitry Andric : NoDLLStorageClassVisibility); 498e8d8bef9SDimitry Andric } 499e8d8bef9SDimitry Andric 500e8d8bef9SDimitry Andric GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 501e8d8bef9SDimitry Andric } 502e8d8bef9SDimitry Andric } 503e8d8bef9SDimitry Andric 504*0b57cec5SDimitry Andric void CodeGenModule::Release() { 505*0b57cec5SDimitry Andric EmitDeferred(); 506*0b57cec5SDimitry Andric EmitVTablesOpportunistically(); 507*0b57cec5SDimitry Andric applyGlobalValReplacements(); 508*0b57cec5SDimitry Andric applyReplacements(); 509*0b57cec5SDimitry Andric checkAliases(); 510*0b57cec5SDimitry Andric emitMultiVersionFunctions(); 511*0b57cec5SDimitry Andric EmitCXXGlobalInitFunc(); 5125ffd83dbSDimitry Andric EmitCXXGlobalCleanUpFunc(); 513*0b57cec5SDimitry Andric registerGlobalDtorsWithAtExit(); 514*0b57cec5SDimitry Andric EmitCXXThreadLocalInitFunc(); 515*0b57cec5SDimitry Andric if (ObjCRuntime) 516*0b57cec5SDimitry Andric if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 517*0b57cec5SDimitry Andric AddGlobalCtor(ObjCInitFunction); 518fe6060f1SDimitry Andric if (Context.getLangOpts().CUDA && CUDARuntime) { 519fe6060f1SDimitry Andric if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule()) 520*0b57cec5SDimitry Andric AddGlobalCtor(CudaCtorFunction); 521*0b57cec5SDimitry Andric } 522*0b57cec5SDimitry Andric if (OpenMPRuntime) { 523*0b57cec5SDimitry Andric if (llvm::Function *OpenMPRequiresDirectiveRegFun = 524*0b57cec5SDimitry Andric OpenMPRuntime->emitRequiresDirectiveRegFun()) { 525*0b57cec5SDimitry Andric AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0); 526*0b57cec5SDimitry Andric } 527a7dea167SDimitry Andric OpenMPRuntime->createOffloadEntriesAndInfoMetadata(); 528*0b57cec5SDimitry Andric OpenMPRuntime->clear(); 529*0b57cec5SDimitry Andric } 530*0b57cec5SDimitry Andric if (PGOReader) { 531*0b57cec5SDimitry Andric getModule().setProfileSummary( 532*0b57cec5SDimitry Andric PGOReader->getSummary(/* UseCS */ false).getMD(VMContext), 533*0b57cec5SDimitry Andric llvm::ProfileSummary::PSK_Instr); 534*0b57cec5SDimitry Andric if (PGOStats.hasDiagnostics()) 535*0b57cec5SDimitry Andric PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 536*0b57cec5SDimitry Andric } 537*0b57cec5SDimitry Andric EmitCtorList(GlobalCtors, "llvm.global_ctors"); 538*0b57cec5SDimitry Andric EmitCtorList(GlobalDtors, "llvm.global_dtors"); 539*0b57cec5SDimitry Andric EmitGlobalAnnotations(); 540*0b57cec5SDimitry Andric EmitStaticExternCAliases(); 541*0b57cec5SDimitry Andric EmitDeferredUnusedCoverageMappings(); 542fe6060f1SDimitry Andric CodeGenPGO(*this).setValueProfilingFlag(getModule()); 543*0b57cec5SDimitry Andric if (CoverageMapping) 544*0b57cec5SDimitry Andric CoverageMapping->emit(); 545*0b57cec5SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 546*0b57cec5SDimitry Andric CodeGenFunction(*this).EmitCfiCheckFail(); 547*0b57cec5SDimitry Andric CodeGenFunction(*this).EmitCfiCheckStub(); 548*0b57cec5SDimitry Andric } 549*0b57cec5SDimitry Andric emitAtAvailableLinkGuard(); 5505ffd83dbSDimitry Andric if (Context.getTargetInfo().getTriple().isWasm() && 5515ffd83dbSDimitry Andric !Context.getTargetInfo().getTriple().isOSEmscripten()) { 5525ffd83dbSDimitry Andric EmitMainVoidAlias(); 5535ffd83dbSDimitry Andric } 554fe6060f1SDimitry Andric 555fe6060f1SDimitry Andric // Emit reference of __amdgpu_device_library_preserve_asan_functions to 556fe6060f1SDimitry Andric // preserve ASAN functions in bitcode libraries. 557fe6060f1SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::Address) && getTriple().isAMDGPU()) { 558fe6060f1SDimitry Andric auto *FT = llvm::FunctionType::get(VoidTy, {}); 559fe6060f1SDimitry Andric auto *F = llvm::Function::Create( 560fe6060f1SDimitry Andric FT, llvm::GlobalValue::ExternalLinkage, 561fe6060f1SDimitry Andric "__amdgpu_device_library_preserve_asan_functions", &getModule()); 562fe6060f1SDimitry Andric auto *Var = new llvm::GlobalVariable( 563fe6060f1SDimitry Andric getModule(), FT->getPointerTo(), 564fe6060f1SDimitry Andric /*isConstant=*/true, llvm::GlobalValue::WeakAnyLinkage, F, 565fe6060f1SDimitry Andric "__amdgpu_device_library_preserve_asan_functions_ptr", nullptr, 566fe6060f1SDimitry Andric llvm::GlobalVariable::NotThreadLocal); 567fe6060f1SDimitry Andric addCompilerUsedGlobal(Var); 56804eeddc0SDimitry Andric if (!getModule().getModuleFlag("amdgpu_hostcall")) { 569349cc55cSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "amdgpu_hostcall", 1); 570fe6060f1SDimitry Andric } 57104eeddc0SDimitry Andric } 572fe6060f1SDimitry Andric 573*0b57cec5SDimitry Andric emitLLVMUsed(); 574*0b57cec5SDimitry Andric if (SanStats) 575*0b57cec5SDimitry Andric SanStats->finish(); 576*0b57cec5SDimitry Andric 577*0b57cec5SDimitry Andric if (CodeGenOpts.Autolink && 578*0b57cec5SDimitry Andric (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 579*0b57cec5SDimitry Andric EmitModuleLinkOptions(); 580*0b57cec5SDimitry Andric } 581*0b57cec5SDimitry Andric 582*0b57cec5SDimitry Andric // On ELF we pass the dependent library specifiers directly to the linker 583*0b57cec5SDimitry Andric // without manipulating them. This is in contrast to other platforms where 584*0b57cec5SDimitry Andric // they are mapped to a specific linker option by the compiler. This 585*0b57cec5SDimitry Andric // difference is a result of the greater variety of ELF linkers and the fact 586*0b57cec5SDimitry Andric // that ELF linkers tend to handle libraries in a more complicated fashion 587*0b57cec5SDimitry Andric // than on other platforms. This forces us to defer handling the dependent 588*0b57cec5SDimitry Andric // libs to the linker. 589*0b57cec5SDimitry Andric // 590*0b57cec5SDimitry Andric // CUDA/HIP device and host libraries are different. Currently there is no 591*0b57cec5SDimitry Andric // way to differentiate dependent libraries for host or device. Existing 592*0b57cec5SDimitry Andric // usage of #pragma comment(lib, *) is intended for host libraries on 593*0b57cec5SDimitry Andric // Windows. Therefore emit llvm.dependent-libraries only for host. 594*0b57cec5SDimitry Andric if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) { 595*0b57cec5SDimitry Andric auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries"); 596*0b57cec5SDimitry Andric for (auto *MD : ELFDependentLibraries) 597*0b57cec5SDimitry Andric NMD->addOperand(MD); 598*0b57cec5SDimitry Andric } 599*0b57cec5SDimitry Andric 600*0b57cec5SDimitry Andric // Record mregparm value now so it is visible through rest of codegen. 601*0b57cec5SDimitry Andric if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) 602*0b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters", 603*0b57cec5SDimitry Andric CodeGenOpts.NumRegisterParameters); 604*0b57cec5SDimitry Andric 605*0b57cec5SDimitry Andric if (CodeGenOpts.DwarfVersion) { 606480093f4SDimitry Andric getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version", 607*0b57cec5SDimitry Andric CodeGenOpts.DwarfVersion); 608*0b57cec5SDimitry Andric } 6095ffd83dbSDimitry Andric 610fe6060f1SDimitry Andric if (CodeGenOpts.Dwarf64) 611fe6060f1SDimitry Andric getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1); 612fe6060f1SDimitry Andric 6135ffd83dbSDimitry Andric if (Context.getLangOpts().SemanticInterposition) 6145ffd83dbSDimitry Andric // Require various optimization to respect semantic interposition. 61504eeddc0SDimitry Andric getModule().setSemanticInterposition(true); 6165ffd83dbSDimitry Andric 617*0b57cec5SDimitry Andric if (CodeGenOpts.EmitCodeView) { 618*0b57cec5SDimitry Andric // Indicate that we want CodeView in the metadata. 619*0b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); 620*0b57cec5SDimitry Andric } 621*0b57cec5SDimitry Andric if (CodeGenOpts.CodeViewGHash) { 622*0b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1); 623*0b57cec5SDimitry Andric } 624*0b57cec5SDimitry Andric if (CodeGenOpts.ControlFlowGuard) { 625480093f4SDimitry Andric // Function ID tables and checks for Control Flow Guard (cfguard=2). 626480093f4SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2); 627480093f4SDimitry Andric } else if (CodeGenOpts.ControlFlowGuardNoChecks) { 628480093f4SDimitry Andric // Function ID tables for Control Flow Guard (cfguard=1). 629480093f4SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1); 630*0b57cec5SDimitry Andric } 631fe6060f1SDimitry Andric if (CodeGenOpts.EHContGuard) { 632fe6060f1SDimitry Andric // Function ID tables for EH Continuation Guard. 633fe6060f1SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1); 634fe6060f1SDimitry Andric } 635*0b57cec5SDimitry Andric if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { 636*0b57cec5SDimitry Andric // We don't support LTO with 2 with different StrictVTablePointers 637*0b57cec5SDimitry Andric // FIXME: we could support it by stripping all the information introduced 638*0b57cec5SDimitry Andric // by StrictVTablePointers. 639*0b57cec5SDimitry Andric 640*0b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); 641*0b57cec5SDimitry Andric 642*0b57cec5SDimitry Andric llvm::Metadata *Ops[2] = { 643*0b57cec5SDimitry Andric llvm::MDString::get(VMContext, "StrictVTablePointers"), 644*0b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 645*0b57cec5SDimitry Andric llvm::Type::getInt32Ty(VMContext), 1))}; 646*0b57cec5SDimitry Andric 647*0b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Require, 648*0b57cec5SDimitry Andric "StrictVTablePointersRequirement", 649*0b57cec5SDimitry Andric llvm::MDNode::get(VMContext, Ops)); 650*0b57cec5SDimitry Andric } 6515ffd83dbSDimitry Andric if (getModuleDebugInfo()) 652*0b57cec5SDimitry Andric // We support a single version in the linked module. The LLVM 653*0b57cec5SDimitry Andric // parser will drop debug info with a different version number 654*0b57cec5SDimitry Andric // (and warn about it, too). 655*0b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 656*0b57cec5SDimitry Andric llvm::DEBUG_METADATA_VERSION); 657*0b57cec5SDimitry Andric 658*0b57cec5SDimitry Andric // We need to record the widths of enums and wchar_t, so that we can generate 659*0b57cec5SDimitry Andric // the correct build attributes in the ARM backend. wchar_size is also used by 660*0b57cec5SDimitry Andric // TargetLibraryInfo. 661*0b57cec5SDimitry Andric uint64_t WCharWidth = 662*0b57cec5SDimitry Andric Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 663*0b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 664*0b57cec5SDimitry Andric 665*0b57cec5SDimitry Andric llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 666*0b57cec5SDimitry Andric if ( Arch == llvm::Triple::arm 667*0b57cec5SDimitry Andric || Arch == llvm::Triple::armeb 668*0b57cec5SDimitry Andric || Arch == llvm::Triple::thumb 669*0b57cec5SDimitry Andric || Arch == llvm::Triple::thumbeb) { 670*0b57cec5SDimitry Andric // The minimum width of an enum in bytes 671*0b57cec5SDimitry Andric uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 672*0b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 673*0b57cec5SDimitry Andric } 674*0b57cec5SDimitry Andric 67513138422SDimitry Andric if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) { 67613138422SDimitry Andric StringRef ABIStr = Target.getABI(); 67713138422SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 67813138422SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "target-abi", 67913138422SDimitry Andric llvm::MDString::get(Ctx, ABIStr)); 68013138422SDimitry Andric } 68113138422SDimitry Andric 682*0b57cec5SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 683*0b57cec5SDimitry Andric // Indicate that we want cross-DSO control flow integrity checks. 684*0b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); 685*0b57cec5SDimitry Andric } 686*0b57cec5SDimitry Andric 6875ffd83dbSDimitry Andric if (CodeGenOpts.WholeProgramVTables) { 6885ffd83dbSDimitry Andric // Indicate whether VFE was enabled for this module, so that the 6895ffd83dbSDimitry Andric // vcall_visibility metadata added under whole program vtables is handled 6905ffd83dbSDimitry Andric // appropriately in the optimizer. 6915ffd83dbSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim", 6925ffd83dbSDimitry Andric CodeGenOpts.VirtualFunctionElimination); 6935ffd83dbSDimitry Andric } 6945ffd83dbSDimitry Andric 695a7dea167SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) { 696a7dea167SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, 697a7dea167SDimitry Andric "CFI Canonical Jump Tables", 698a7dea167SDimitry Andric CodeGenOpts.SanitizeCfiCanonicalJumpTables); 699a7dea167SDimitry Andric } 700a7dea167SDimitry Andric 701*0b57cec5SDimitry Andric if (CodeGenOpts.CFProtectionReturn && 702*0b57cec5SDimitry Andric Target.checkCFProtectionReturnSupported(getDiags())) { 703*0b57cec5SDimitry Andric // Indicate that we want to instrument return control flow protection. 704*0b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return", 705*0b57cec5SDimitry Andric 1); 706*0b57cec5SDimitry Andric } 707*0b57cec5SDimitry Andric 708*0b57cec5SDimitry Andric if (CodeGenOpts.CFProtectionBranch && 709*0b57cec5SDimitry Andric Target.checkCFProtectionBranchSupported(getDiags())) { 710*0b57cec5SDimitry Andric // Indicate that we want to instrument branch control flow protection. 711*0b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch", 712*0b57cec5SDimitry Andric 1); 713*0b57cec5SDimitry Andric } 714*0b57cec5SDimitry Andric 71504eeddc0SDimitry Andric if (CodeGenOpts.IBTSeal) 71604eeddc0SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "ibt-seal", 1); 71704eeddc0SDimitry Andric 7184824e7fdSDimitry Andric // Add module metadata for return address signing (ignoring 7194824e7fdSDimitry Andric // non-leaf/all) and stack tagging. These are actually turned on by function 7204824e7fdSDimitry Andric // attributes, but we use module metadata to emit build attributes. This is 7214824e7fdSDimitry Andric // needed for LTO, where the function attributes are inside bitcode 7224824e7fdSDimitry Andric // serialised into a global variable by the time build attributes are 7234824e7fdSDimitry Andric // emitted, so we can't access them. 7244824e7fdSDimitry Andric if (Context.getTargetInfo().hasFeature("ptrauth") && 7254824e7fdSDimitry Andric LangOpts.getSignReturnAddressScope() != 7264824e7fdSDimitry Andric LangOptions::SignReturnAddressScopeKind::None) 7274824e7fdSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, 7284824e7fdSDimitry Andric "sign-return-address-buildattr", 1); 7294824e7fdSDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::MemTag)) 7304824e7fdSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, 7314824e7fdSDimitry Andric "tag-stack-memory-buildattr", 1); 7324824e7fdSDimitry Andric 7334824e7fdSDimitry Andric if (Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb || 7344824e7fdSDimitry Andric Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 || 735e8d8bef9SDimitry Andric Arch == llvm::Triple::aarch64_be) { 7364824e7fdSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "branch-target-enforcement", 737e8d8bef9SDimitry Andric LangOpts.BranchTargetEnforcement); 738e8d8bef9SDimitry Andric 739e8d8bef9SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "sign-return-address", 740e8d8bef9SDimitry Andric LangOpts.hasSignReturnAddress()); 741e8d8bef9SDimitry Andric 742e8d8bef9SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "sign-return-address-all", 743e8d8bef9SDimitry Andric LangOpts.isSignReturnAddressScopeAll()); 744e8d8bef9SDimitry Andric 7454824e7fdSDimitry Andric if (Arch != llvm::Triple::thumb && Arch != llvm::Triple::thumbeb) { 746e8d8bef9SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, 747e8d8bef9SDimitry Andric "sign-return-address-with-bkey", 748e8d8bef9SDimitry Andric !LangOpts.isSignReturnAddressWithAKey()); 749e8d8bef9SDimitry Andric } 7504824e7fdSDimitry Andric } 751e8d8bef9SDimitry Andric 752e8d8bef9SDimitry Andric if (!CodeGenOpts.MemoryProfileOutput.empty()) { 753e8d8bef9SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 754e8d8bef9SDimitry Andric getModule().addModuleFlag( 755e8d8bef9SDimitry Andric llvm::Module::Error, "MemProfProfileFilename", 756e8d8bef9SDimitry Andric llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput)); 757e8d8bef9SDimitry Andric } 758e8d8bef9SDimitry Andric 759*0b57cec5SDimitry Andric if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) { 760*0b57cec5SDimitry Andric // Indicate whether __nvvm_reflect should be configured to flush denormal 761*0b57cec5SDimitry Andric // floating point values to 0. (This corresponds to its "__CUDA_FTZ" 762*0b57cec5SDimitry Andric // property.) 763*0b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", 7645ffd83dbSDimitry Andric CodeGenOpts.FP32DenormalMode.Output != 7655ffd83dbSDimitry Andric llvm::DenormalMode::IEEE); 766*0b57cec5SDimitry Andric } 767*0b57cec5SDimitry Andric 768fe6060f1SDimitry Andric if (LangOpts.EHAsynch) 769fe6060f1SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1); 770fe6060f1SDimitry Andric 771fe6060f1SDimitry Andric // Indicate whether this Module was compiled with -fopenmp 772fe6060f1SDimitry Andric if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 773fe6060f1SDimitry Andric getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP); 774fe6060f1SDimitry Andric if (getLangOpts().OpenMPIsDevice) 775fe6060f1SDimitry Andric getModule().addModuleFlag(llvm::Module::Max, "openmp-device", 776fe6060f1SDimitry Andric LangOpts.OpenMP); 777fe6060f1SDimitry Andric 778*0b57cec5SDimitry Andric // Emit OpenCL specific module metadata: OpenCL/SPIR version. 779*0b57cec5SDimitry Andric if (LangOpts.OpenCL) { 780*0b57cec5SDimitry Andric EmitOpenCLMetadata(); 781*0b57cec5SDimitry Andric // Emit SPIR version. 782*0b57cec5SDimitry Andric if (getTriple().isSPIR()) { 783*0b57cec5SDimitry Andric // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the 784*0b57cec5SDimitry Andric // opencl.spir.version named metadata. 785349cc55cSDimitry Andric // C++ for OpenCL has a distinct mapping for version compatibility with 786349cc55cSDimitry Andric // OpenCL. 787349cc55cSDimitry Andric auto Version = LangOpts.getOpenCLCompatibleVersion(); 788*0b57cec5SDimitry Andric llvm::Metadata *SPIRVerElts[] = { 789*0b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 790*0b57cec5SDimitry Andric Int32Ty, Version / 100)), 791*0b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 792*0b57cec5SDimitry Andric Int32Ty, (Version / 100 > 1) ? 0 : 2))}; 793*0b57cec5SDimitry Andric llvm::NamedMDNode *SPIRVerMD = 794*0b57cec5SDimitry Andric TheModule.getOrInsertNamedMetadata("opencl.spir.version"); 795*0b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 796*0b57cec5SDimitry Andric SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts)); 797*0b57cec5SDimitry Andric } 798*0b57cec5SDimitry Andric } 799*0b57cec5SDimitry Andric 800*0b57cec5SDimitry Andric if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 801*0b57cec5SDimitry Andric assert(PLevel < 3 && "Invalid PIC Level"); 802*0b57cec5SDimitry Andric getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel)); 803*0b57cec5SDimitry Andric if (Context.getLangOpts().PIE) 804*0b57cec5SDimitry Andric getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel)); 805*0b57cec5SDimitry Andric } 806*0b57cec5SDimitry Andric 807*0b57cec5SDimitry Andric if (getCodeGenOpts().CodeModel.size() > 0) { 808*0b57cec5SDimitry Andric unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel) 809*0b57cec5SDimitry Andric .Case("tiny", llvm::CodeModel::Tiny) 810*0b57cec5SDimitry Andric .Case("small", llvm::CodeModel::Small) 811*0b57cec5SDimitry Andric .Case("kernel", llvm::CodeModel::Kernel) 812*0b57cec5SDimitry Andric .Case("medium", llvm::CodeModel::Medium) 813*0b57cec5SDimitry Andric .Case("large", llvm::CodeModel::Large) 814*0b57cec5SDimitry Andric .Default(~0u); 815*0b57cec5SDimitry Andric if (CM != ~0u) { 816*0b57cec5SDimitry Andric llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM); 817*0b57cec5SDimitry Andric getModule().setCodeModel(codeModel); 818*0b57cec5SDimitry Andric } 819*0b57cec5SDimitry Andric } 820*0b57cec5SDimitry Andric 821*0b57cec5SDimitry Andric if (CodeGenOpts.NoPLT) 822*0b57cec5SDimitry Andric getModule().setRtLibUseGOT(); 823fe6060f1SDimitry Andric if (CodeGenOpts.UnwindTables) 824fe6060f1SDimitry Andric getModule().setUwtable(); 825fe6060f1SDimitry Andric 826fe6060f1SDimitry Andric switch (CodeGenOpts.getFramePointer()) { 827fe6060f1SDimitry Andric case CodeGenOptions::FramePointerKind::None: 828fe6060f1SDimitry Andric // 0 ("none") is the default. 829fe6060f1SDimitry Andric break; 830fe6060f1SDimitry Andric case CodeGenOptions::FramePointerKind::NonLeaf: 831fe6060f1SDimitry Andric getModule().setFramePointer(llvm::FramePointerKind::NonLeaf); 832fe6060f1SDimitry Andric break; 833fe6060f1SDimitry Andric case CodeGenOptions::FramePointerKind::All: 834fe6060f1SDimitry Andric getModule().setFramePointer(llvm::FramePointerKind::All); 835fe6060f1SDimitry Andric break; 836fe6060f1SDimitry Andric } 837*0b57cec5SDimitry Andric 838*0b57cec5SDimitry Andric SimplifyPersonality(); 839*0b57cec5SDimitry Andric 840*0b57cec5SDimitry Andric if (getCodeGenOpts().EmitDeclMetadata) 841*0b57cec5SDimitry Andric EmitDeclMetadata(); 842*0b57cec5SDimitry Andric 843*0b57cec5SDimitry Andric if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 844*0b57cec5SDimitry Andric EmitCoverageFile(); 845*0b57cec5SDimitry Andric 8465ffd83dbSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 8475ffd83dbSDimitry Andric DI->finalize(); 848*0b57cec5SDimitry Andric 849*0b57cec5SDimitry Andric if (getCodeGenOpts().EmitVersionIdentMetadata) 850*0b57cec5SDimitry Andric EmitVersionIdentMetadata(); 851*0b57cec5SDimitry Andric 852*0b57cec5SDimitry Andric if (!getCodeGenOpts().RecordCommandLine.empty()) 853*0b57cec5SDimitry Andric EmitCommandLineMetadata(); 854*0b57cec5SDimitry Andric 855fe6060f1SDimitry Andric if (!getCodeGenOpts().StackProtectorGuard.empty()) 856fe6060f1SDimitry Andric getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard); 857fe6060f1SDimitry Andric if (!getCodeGenOpts().StackProtectorGuardReg.empty()) 858fe6060f1SDimitry Andric getModule().setStackProtectorGuardReg( 859fe6060f1SDimitry Andric getCodeGenOpts().StackProtectorGuardReg); 860fe6060f1SDimitry Andric if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX) 861fe6060f1SDimitry Andric getModule().setStackProtectorGuardOffset( 862fe6060f1SDimitry Andric getCodeGenOpts().StackProtectorGuardOffset); 863fe6060f1SDimitry Andric if (getCodeGenOpts().StackAlignment) 864fe6060f1SDimitry Andric getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment); 865349cc55cSDimitry Andric if (getCodeGenOpts().SkipRaxSetup) 866349cc55cSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "SkipRaxSetup", 1); 867fe6060f1SDimitry Andric 8685ffd83dbSDimitry Andric getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames); 8695ffd83dbSDimitry Andric 8705ffd83dbSDimitry Andric EmitBackendOptionsMetadata(getCodeGenOpts()); 871e8d8bef9SDimitry Andric 872e8d8bef9SDimitry Andric // Set visibility from DLL storage class 873e8d8bef9SDimitry Andric // We do this at the end of LLVM IR generation; after any operation 874e8d8bef9SDimitry Andric // that might affect the DLL storage class or the visibility, and 875e8d8bef9SDimitry Andric // before anything that might act on these. 876e8d8bef9SDimitry Andric setVisibilityFromDLLStorageClass(LangOpts, getModule()); 877*0b57cec5SDimitry Andric } 878*0b57cec5SDimitry Andric 879*0b57cec5SDimitry Andric void CodeGenModule::EmitOpenCLMetadata() { 880*0b57cec5SDimitry Andric // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the 881*0b57cec5SDimitry Andric // opencl.ocl.version named metadata node. 882349cc55cSDimitry Andric // C++ for OpenCL has a distinct mapping for versions compatibile with OpenCL. 883349cc55cSDimitry Andric auto Version = LangOpts.getOpenCLCompatibleVersion(); 884*0b57cec5SDimitry Andric llvm::Metadata *OCLVerElts[] = { 885*0b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 886*0b57cec5SDimitry Andric Int32Ty, Version / 100)), 887*0b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 888*0b57cec5SDimitry Andric Int32Ty, (Version % 100) / 10))}; 889*0b57cec5SDimitry Andric llvm::NamedMDNode *OCLVerMD = 890*0b57cec5SDimitry Andric TheModule.getOrInsertNamedMetadata("opencl.ocl.version"); 891*0b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 892*0b57cec5SDimitry Andric OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts)); 893*0b57cec5SDimitry Andric } 894*0b57cec5SDimitry Andric 8955ffd83dbSDimitry Andric void CodeGenModule::EmitBackendOptionsMetadata( 8965ffd83dbSDimitry Andric const CodeGenOptions CodeGenOpts) { 8975ffd83dbSDimitry Andric switch (getTriple().getArch()) { 8985ffd83dbSDimitry Andric default: 8995ffd83dbSDimitry Andric break; 9005ffd83dbSDimitry Andric case llvm::Triple::riscv32: 9015ffd83dbSDimitry Andric case llvm::Triple::riscv64: 9025ffd83dbSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "SmallDataLimit", 9035ffd83dbSDimitry Andric CodeGenOpts.SmallDataLimit); 9045ffd83dbSDimitry Andric break; 9055ffd83dbSDimitry Andric } 9065ffd83dbSDimitry Andric } 9075ffd83dbSDimitry Andric 908*0b57cec5SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 909*0b57cec5SDimitry Andric // Make sure that this type is translated. 910*0b57cec5SDimitry Andric Types.UpdateCompletedType(TD); 911*0b57cec5SDimitry Andric } 912*0b57cec5SDimitry Andric 913*0b57cec5SDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { 914*0b57cec5SDimitry Andric // Make sure that this type is translated. 915*0b57cec5SDimitry Andric Types.RefreshTypeCacheForClass(RD); 916*0b57cec5SDimitry Andric } 917*0b57cec5SDimitry Andric 918*0b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) { 919*0b57cec5SDimitry Andric if (!TBAA) 920*0b57cec5SDimitry Andric return nullptr; 921*0b57cec5SDimitry Andric return TBAA->getTypeInfo(QTy); 922*0b57cec5SDimitry Andric } 923*0b57cec5SDimitry Andric 924*0b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) { 925*0b57cec5SDimitry Andric if (!TBAA) 926*0b57cec5SDimitry Andric return TBAAAccessInfo(); 9275ffd83dbSDimitry Andric if (getLangOpts().CUDAIsDevice) { 9285ffd83dbSDimitry Andric // As CUDA builtin surface/texture types are replaced, skip generating TBAA 9295ffd83dbSDimitry Andric // access info. 9305ffd83dbSDimitry Andric if (AccessType->isCUDADeviceBuiltinSurfaceType()) { 9315ffd83dbSDimitry Andric if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() != 9325ffd83dbSDimitry Andric nullptr) 9335ffd83dbSDimitry Andric return TBAAAccessInfo(); 9345ffd83dbSDimitry Andric } else if (AccessType->isCUDADeviceBuiltinTextureType()) { 9355ffd83dbSDimitry Andric if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() != 9365ffd83dbSDimitry Andric nullptr) 9375ffd83dbSDimitry Andric return TBAAAccessInfo(); 9385ffd83dbSDimitry Andric } 9395ffd83dbSDimitry Andric } 940*0b57cec5SDimitry Andric return TBAA->getAccessInfo(AccessType); 941*0b57cec5SDimitry Andric } 942*0b57cec5SDimitry Andric 943*0b57cec5SDimitry Andric TBAAAccessInfo 944*0b57cec5SDimitry Andric CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) { 945*0b57cec5SDimitry Andric if (!TBAA) 946*0b57cec5SDimitry Andric return TBAAAccessInfo(); 947*0b57cec5SDimitry Andric return TBAA->getVTablePtrAccessInfo(VTablePtrType); 948*0b57cec5SDimitry Andric } 949*0b57cec5SDimitry Andric 950*0b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 951*0b57cec5SDimitry Andric if (!TBAA) 952*0b57cec5SDimitry Andric return nullptr; 953*0b57cec5SDimitry Andric return TBAA->getTBAAStructInfo(QTy); 954*0b57cec5SDimitry Andric } 955*0b57cec5SDimitry Andric 956*0b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) { 957*0b57cec5SDimitry Andric if (!TBAA) 958*0b57cec5SDimitry Andric return nullptr; 959*0b57cec5SDimitry Andric return TBAA->getBaseTypeInfo(QTy); 960*0b57cec5SDimitry Andric } 961*0b57cec5SDimitry Andric 962*0b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) { 963*0b57cec5SDimitry Andric if (!TBAA) 964*0b57cec5SDimitry Andric return nullptr; 965*0b57cec5SDimitry Andric return TBAA->getAccessTagInfo(Info); 966*0b57cec5SDimitry Andric } 967*0b57cec5SDimitry Andric 968*0b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, 969*0b57cec5SDimitry Andric TBAAAccessInfo TargetInfo) { 970*0b57cec5SDimitry Andric if (!TBAA) 971*0b57cec5SDimitry Andric return TBAAAccessInfo(); 972*0b57cec5SDimitry Andric return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo); 973*0b57cec5SDimitry Andric } 974*0b57cec5SDimitry Andric 975*0b57cec5SDimitry Andric TBAAAccessInfo 976*0b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, 977*0b57cec5SDimitry Andric TBAAAccessInfo InfoB) { 978*0b57cec5SDimitry Andric if (!TBAA) 979*0b57cec5SDimitry Andric return TBAAAccessInfo(); 980*0b57cec5SDimitry Andric return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB); 981*0b57cec5SDimitry Andric } 982*0b57cec5SDimitry Andric 983*0b57cec5SDimitry Andric TBAAAccessInfo 984*0b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, 985*0b57cec5SDimitry Andric TBAAAccessInfo SrcInfo) { 986*0b57cec5SDimitry Andric if (!TBAA) 987*0b57cec5SDimitry Andric return TBAAAccessInfo(); 988*0b57cec5SDimitry Andric return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo); 989*0b57cec5SDimitry Andric } 990*0b57cec5SDimitry Andric 991*0b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, 992*0b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo) { 993*0b57cec5SDimitry Andric if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo)) 994*0b57cec5SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag); 995*0b57cec5SDimitry Andric } 996*0b57cec5SDimitry Andric 997*0b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup( 998*0b57cec5SDimitry Andric llvm::Instruction *I, const CXXRecordDecl *RD) { 999*0b57cec5SDimitry Andric I->setMetadata(llvm::LLVMContext::MD_invariant_group, 1000*0b57cec5SDimitry Andric llvm::MDNode::get(getLLVMContext(), {})); 1001*0b57cec5SDimitry Andric } 1002*0b57cec5SDimitry Andric 1003*0b57cec5SDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) { 1004*0b57cec5SDimitry Andric unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 1005*0b57cec5SDimitry Andric getDiags().Report(Context.getFullLoc(loc), diagID) << message; 1006*0b57cec5SDimitry Andric } 1007*0b57cec5SDimitry Andric 1008*0b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the 1009*0b57cec5SDimitry Andric /// specified stmt yet. 1010*0b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 1011*0b57cec5SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 1012*0b57cec5SDimitry Andric "cannot compile this %0 yet"); 1013*0b57cec5SDimitry Andric std::string Msg = Type; 1014*0b57cec5SDimitry Andric getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID) 1015*0b57cec5SDimitry Andric << Msg << S->getSourceRange(); 1016*0b57cec5SDimitry Andric } 1017*0b57cec5SDimitry Andric 1018*0b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the 1019*0b57cec5SDimitry Andric /// specified decl yet. 1020*0b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 1021*0b57cec5SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 1022*0b57cec5SDimitry Andric "cannot compile this %0 yet"); 1023*0b57cec5SDimitry Andric std::string Msg = Type; 1024*0b57cec5SDimitry Andric getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 1025*0b57cec5SDimitry Andric } 1026*0b57cec5SDimitry Andric 1027*0b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 1028*0b57cec5SDimitry Andric return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 1029*0b57cec5SDimitry Andric } 1030*0b57cec5SDimitry Andric 1031*0b57cec5SDimitry Andric void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 1032*0b57cec5SDimitry Andric const NamedDecl *D) const { 1033*0b57cec5SDimitry Andric if (GV->hasDLLImportStorageClass()) 1034*0b57cec5SDimitry Andric return; 1035*0b57cec5SDimitry Andric // Internal definitions always have default visibility. 1036*0b57cec5SDimitry Andric if (GV->hasLocalLinkage()) { 1037*0b57cec5SDimitry Andric GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 1038*0b57cec5SDimitry Andric return; 1039*0b57cec5SDimitry Andric } 1040*0b57cec5SDimitry Andric if (!D) 1041*0b57cec5SDimitry Andric return; 1042*0b57cec5SDimitry Andric // Set visibility for definitions, and for declarations if requested globally 1043*0b57cec5SDimitry Andric // or set explicitly. 1044*0b57cec5SDimitry Andric LinkageInfo LV = D->getLinkageAndVisibility(); 1045*0b57cec5SDimitry Andric if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls || 1046*0b57cec5SDimitry Andric !GV->isDeclarationForLinker()) 1047*0b57cec5SDimitry Andric GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 1048*0b57cec5SDimitry Andric } 1049*0b57cec5SDimitry Andric 1050*0b57cec5SDimitry Andric static bool shouldAssumeDSOLocal(const CodeGenModule &CGM, 1051*0b57cec5SDimitry Andric llvm::GlobalValue *GV) { 1052*0b57cec5SDimitry Andric if (GV->hasLocalLinkage()) 1053*0b57cec5SDimitry Andric return true; 1054*0b57cec5SDimitry Andric 1055*0b57cec5SDimitry Andric if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()) 1056*0b57cec5SDimitry Andric return true; 1057*0b57cec5SDimitry Andric 1058*0b57cec5SDimitry Andric // DLLImport explicitly marks the GV as external. 1059*0b57cec5SDimitry Andric if (GV->hasDLLImportStorageClass()) 1060*0b57cec5SDimitry Andric return false; 1061*0b57cec5SDimitry Andric 1062*0b57cec5SDimitry Andric const llvm::Triple &TT = CGM.getTriple(); 1063*0b57cec5SDimitry Andric if (TT.isWindowsGNUEnvironment()) { 1064*0b57cec5SDimitry Andric // In MinGW, variables without DLLImport can still be automatically 1065*0b57cec5SDimitry Andric // imported from a DLL by the linker; don't mark variables that 1066*0b57cec5SDimitry Andric // potentially could come from another DLL as DSO local. 1067fe6060f1SDimitry Andric 1068fe6060f1SDimitry Andric // With EmulatedTLS, TLS variables can be autoimported from other DLLs 1069fe6060f1SDimitry Andric // (and this actually happens in the public interface of libstdc++), so 1070fe6060f1SDimitry Andric // such variables can't be marked as DSO local. (Native TLS variables 1071fe6060f1SDimitry Andric // can't be dllimported at all, though.) 1072*0b57cec5SDimitry Andric if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) && 1073fe6060f1SDimitry Andric (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS)) 1074*0b57cec5SDimitry Andric return false; 1075*0b57cec5SDimitry Andric } 1076*0b57cec5SDimitry Andric 1077*0b57cec5SDimitry Andric // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols 1078*0b57cec5SDimitry Andric // remain unresolved in the link, they can be resolved to zero, which is 1079*0b57cec5SDimitry Andric // outside the current DSO. 1080*0b57cec5SDimitry Andric if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage()) 1081*0b57cec5SDimitry Andric return false; 1082*0b57cec5SDimitry Andric 1083*0b57cec5SDimitry Andric // Every other GV is local on COFF. 1084*0b57cec5SDimitry Andric // Make an exception for windows OS in the triple: Some firmware builds use 1085*0b57cec5SDimitry Andric // *-win32-macho triples. This (accidentally?) produced windows relocations 1086*0b57cec5SDimitry Andric // without GOT tables in older clang versions; Keep this behaviour. 1087*0b57cec5SDimitry Andric // FIXME: even thread local variables? 1088*0b57cec5SDimitry Andric if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO())) 1089*0b57cec5SDimitry Andric return true; 1090*0b57cec5SDimitry Andric 1091*0b57cec5SDimitry Andric // Only handle COFF and ELF for now. 1092*0b57cec5SDimitry Andric if (!TT.isOSBinFormatELF()) 1093*0b57cec5SDimitry Andric return false; 1094*0b57cec5SDimitry Andric 1095fe6060f1SDimitry Andric // If this is not an executable, don't assume anything is local. 1096fe6060f1SDimitry Andric const auto &CGOpts = CGM.getCodeGenOpts(); 1097fe6060f1SDimitry Andric llvm::Reloc::Model RM = CGOpts.RelocationModel; 1098fe6060f1SDimitry Andric const auto &LOpts = CGM.getLangOpts(); 1099e8d8bef9SDimitry Andric if (RM != llvm::Reloc::Static && !LOpts.PIE) { 1100e8d8bef9SDimitry Andric // On ELF, if -fno-semantic-interposition is specified and the target 1101e8d8bef9SDimitry Andric // supports local aliases, there will be neither CC1 1102e8d8bef9SDimitry Andric // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set 1103fe6060f1SDimitry Andric // dso_local on the function if using a local alias is preferable (can avoid 1104fe6060f1SDimitry Andric // PLT indirection). 1105fe6060f1SDimitry Andric if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias())) 1106*0b57cec5SDimitry Andric return false; 1107e8d8bef9SDimitry Andric return !(CGM.getLangOpts().SemanticInterposition || 1108e8d8bef9SDimitry Andric CGM.getLangOpts().HalfNoSemanticInterposition); 1109e8d8bef9SDimitry Andric } 1110*0b57cec5SDimitry Andric 1111*0b57cec5SDimitry Andric // A definition cannot be preempted from an executable. 1112*0b57cec5SDimitry Andric if (!GV->isDeclarationForLinker()) 1113*0b57cec5SDimitry Andric return true; 1114*0b57cec5SDimitry Andric 1115*0b57cec5SDimitry Andric // Most PIC code sequences that assume that a symbol is local cannot produce a 1116*0b57cec5SDimitry Andric // 0 if it turns out the symbol is undefined. While this is ABI and relocation 1117*0b57cec5SDimitry Andric // depended, it seems worth it to handle it here. 1118*0b57cec5SDimitry Andric if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage()) 1119*0b57cec5SDimitry Andric return false; 1120*0b57cec5SDimitry Andric 1121e8d8bef9SDimitry Andric // PowerPC64 prefers TOC indirection to avoid copy relocations. 1122e8d8bef9SDimitry Andric if (TT.isPPC64()) 1123*0b57cec5SDimitry Andric return false; 1124*0b57cec5SDimitry Andric 1125e8d8bef9SDimitry Andric if (CGOpts.DirectAccessExternalData) { 1126e8d8bef9SDimitry Andric // If -fdirect-access-external-data (default for -fno-pic), set dso_local 1127e8d8bef9SDimitry Andric // for non-thread-local variables. If the symbol is not defined in the 1128e8d8bef9SDimitry Andric // executable, a copy relocation will be needed at link time. dso_local is 1129e8d8bef9SDimitry Andric // excluded for thread-local variables because they generally don't support 1130e8d8bef9SDimitry Andric // copy relocations. 1131*0b57cec5SDimitry Andric if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV)) 1132e8d8bef9SDimitry Andric if (!Var->isThreadLocal()) 1133*0b57cec5SDimitry Andric return true; 1134*0b57cec5SDimitry Andric 1135e8d8bef9SDimitry Andric // -fno-pic sets dso_local on a function declaration to allow direct 1136e8d8bef9SDimitry Andric // accesses when taking its address (similar to a data symbol). If the 1137e8d8bef9SDimitry Andric // function is not defined in the executable, a canonical PLT entry will be 1138e8d8bef9SDimitry Andric // needed at link time. -fno-direct-access-external-data can avoid the 1139e8d8bef9SDimitry Andric // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as 1140e8d8bef9SDimitry Andric // it could just cause trouble without providing perceptible benefits. 1141*0b57cec5SDimitry Andric if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static) 1142*0b57cec5SDimitry Andric return true; 1143e8d8bef9SDimitry Andric } 1144e8d8bef9SDimitry Andric 1145e8d8bef9SDimitry Andric // If we can use copy relocations we can assume it is local. 1146*0b57cec5SDimitry Andric 11475ffd83dbSDimitry Andric // Otherwise don't assume it is local. 1148*0b57cec5SDimitry Andric return false; 1149*0b57cec5SDimitry Andric } 1150*0b57cec5SDimitry Andric 1151*0b57cec5SDimitry Andric void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const { 1152*0b57cec5SDimitry Andric GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV)); 1153*0b57cec5SDimitry Andric } 1154*0b57cec5SDimitry Andric 1155*0b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 1156*0b57cec5SDimitry Andric GlobalDecl GD) const { 1157*0b57cec5SDimitry Andric const auto *D = dyn_cast<NamedDecl>(GD.getDecl()); 1158*0b57cec5SDimitry Andric // C++ destructors have a few C++ ABI specific special cases. 1159*0b57cec5SDimitry Andric if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) { 1160*0b57cec5SDimitry Andric getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType()); 1161*0b57cec5SDimitry Andric return; 1162*0b57cec5SDimitry Andric } 1163*0b57cec5SDimitry Andric setDLLImportDLLExport(GV, D); 1164*0b57cec5SDimitry Andric } 1165*0b57cec5SDimitry Andric 1166*0b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 1167*0b57cec5SDimitry Andric const NamedDecl *D) const { 1168*0b57cec5SDimitry Andric if (D && D->isExternallyVisible()) { 1169*0b57cec5SDimitry Andric if (D->hasAttr<DLLImportAttr>()) 1170*0b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 1171*0b57cec5SDimitry Andric else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker()) 1172*0b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 1173*0b57cec5SDimitry Andric } 1174*0b57cec5SDimitry Andric } 1175*0b57cec5SDimitry Andric 1176*0b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 1177*0b57cec5SDimitry Andric GlobalDecl GD) const { 1178*0b57cec5SDimitry Andric setDLLImportDLLExport(GV, GD); 1179*0b57cec5SDimitry Andric setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl())); 1180*0b57cec5SDimitry Andric } 1181*0b57cec5SDimitry Andric 1182*0b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 1183*0b57cec5SDimitry Andric const NamedDecl *D) const { 1184*0b57cec5SDimitry Andric setDLLImportDLLExport(GV, D); 1185*0b57cec5SDimitry Andric setGVPropertiesAux(GV, D); 1186*0b57cec5SDimitry Andric } 1187*0b57cec5SDimitry Andric 1188*0b57cec5SDimitry Andric void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV, 1189*0b57cec5SDimitry Andric const NamedDecl *D) const { 1190*0b57cec5SDimitry Andric setGlobalVisibility(GV, D); 1191*0b57cec5SDimitry Andric setDSOLocal(GV); 1192*0b57cec5SDimitry Andric GV->setPartition(CodeGenOpts.SymbolPartition); 1193*0b57cec5SDimitry Andric } 1194*0b57cec5SDimitry Andric 1195*0b57cec5SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 1196*0b57cec5SDimitry Andric return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 1197*0b57cec5SDimitry Andric .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 1198*0b57cec5SDimitry Andric .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 1199*0b57cec5SDimitry Andric .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 1200*0b57cec5SDimitry Andric .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 1201*0b57cec5SDimitry Andric } 1202*0b57cec5SDimitry Andric 12035ffd83dbSDimitry Andric llvm::GlobalVariable::ThreadLocalMode 12045ffd83dbSDimitry Andric CodeGenModule::GetDefaultLLVMTLSModel() const { 12055ffd83dbSDimitry Andric switch (CodeGenOpts.getDefaultTLSModel()) { 1206*0b57cec5SDimitry Andric case CodeGenOptions::GeneralDynamicTLSModel: 1207*0b57cec5SDimitry Andric return llvm::GlobalVariable::GeneralDynamicTLSModel; 1208*0b57cec5SDimitry Andric case CodeGenOptions::LocalDynamicTLSModel: 1209*0b57cec5SDimitry Andric return llvm::GlobalVariable::LocalDynamicTLSModel; 1210*0b57cec5SDimitry Andric case CodeGenOptions::InitialExecTLSModel: 1211*0b57cec5SDimitry Andric return llvm::GlobalVariable::InitialExecTLSModel; 1212*0b57cec5SDimitry Andric case CodeGenOptions::LocalExecTLSModel: 1213*0b57cec5SDimitry Andric return llvm::GlobalVariable::LocalExecTLSModel; 1214*0b57cec5SDimitry Andric } 1215*0b57cec5SDimitry Andric llvm_unreachable("Invalid TLS model!"); 1216*0b57cec5SDimitry Andric } 1217*0b57cec5SDimitry Andric 1218*0b57cec5SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 1219*0b57cec5SDimitry Andric assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 1220*0b57cec5SDimitry Andric 1221*0b57cec5SDimitry Andric llvm::GlobalValue::ThreadLocalMode TLM; 12225ffd83dbSDimitry Andric TLM = GetDefaultLLVMTLSModel(); 1223*0b57cec5SDimitry Andric 1224*0b57cec5SDimitry Andric // Override the TLS model if it is explicitly specified. 1225*0b57cec5SDimitry Andric if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 1226*0b57cec5SDimitry Andric TLM = GetLLVMTLSModel(Attr->getModel()); 1227*0b57cec5SDimitry Andric } 1228*0b57cec5SDimitry Andric 1229*0b57cec5SDimitry Andric GV->setThreadLocalMode(TLM); 1230*0b57cec5SDimitry Andric } 1231*0b57cec5SDimitry Andric 1232*0b57cec5SDimitry Andric static std::string getCPUSpecificMangling(const CodeGenModule &CGM, 1233*0b57cec5SDimitry Andric StringRef Name) { 1234*0b57cec5SDimitry Andric const TargetInfo &Target = CGM.getTarget(); 1235*0b57cec5SDimitry Andric return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str(); 1236*0b57cec5SDimitry Andric } 1237*0b57cec5SDimitry Andric 1238*0b57cec5SDimitry Andric static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, 1239*0b57cec5SDimitry Andric const CPUSpecificAttr *Attr, 1240*0b57cec5SDimitry Andric unsigned CPUIndex, 1241*0b57cec5SDimitry Andric raw_ostream &Out) { 1242*0b57cec5SDimitry Andric // cpu_specific gets the current name, dispatch gets the resolver if IFunc is 1243*0b57cec5SDimitry Andric // supported. 1244*0b57cec5SDimitry Andric if (Attr) 1245*0b57cec5SDimitry Andric Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName()); 1246*0b57cec5SDimitry Andric else if (CGM.getTarget().supportsIFunc()) 1247*0b57cec5SDimitry Andric Out << ".resolver"; 1248*0b57cec5SDimitry Andric } 1249*0b57cec5SDimitry Andric 1250*0b57cec5SDimitry Andric static void AppendTargetMangling(const CodeGenModule &CGM, 1251*0b57cec5SDimitry Andric const TargetAttr *Attr, raw_ostream &Out) { 1252*0b57cec5SDimitry Andric if (Attr->isDefaultVersion()) 1253*0b57cec5SDimitry Andric return; 1254*0b57cec5SDimitry Andric 1255*0b57cec5SDimitry Andric Out << '.'; 1256*0b57cec5SDimitry Andric const TargetInfo &Target = CGM.getTarget(); 1257480093f4SDimitry Andric ParsedTargetAttr Info = 1258*0b57cec5SDimitry Andric Attr->parse([&Target](StringRef LHS, StringRef RHS) { 1259*0b57cec5SDimitry Andric // Multiversioning doesn't allow "no-${feature}", so we can 1260*0b57cec5SDimitry Andric // only have "+" prefixes here. 1261*0b57cec5SDimitry Andric assert(LHS.startswith("+") && RHS.startswith("+") && 1262*0b57cec5SDimitry Andric "Features should always have a prefix."); 1263*0b57cec5SDimitry Andric return Target.multiVersionSortPriority(LHS.substr(1)) > 1264*0b57cec5SDimitry Andric Target.multiVersionSortPriority(RHS.substr(1)); 1265*0b57cec5SDimitry Andric }); 1266*0b57cec5SDimitry Andric 1267*0b57cec5SDimitry Andric bool IsFirst = true; 1268*0b57cec5SDimitry Andric 1269*0b57cec5SDimitry Andric if (!Info.Architecture.empty()) { 1270*0b57cec5SDimitry Andric IsFirst = false; 1271*0b57cec5SDimitry Andric Out << "arch_" << Info.Architecture; 1272*0b57cec5SDimitry Andric } 1273*0b57cec5SDimitry Andric 1274*0b57cec5SDimitry Andric for (StringRef Feat : Info.Features) { 1275*0b57cec5SDimitry Andric if (!IsFirst) 1276*0b57cec5SDimitry Andric Out << '_'; 1277*0b57cec5SDimitry Andric IsFirst = false; 1278*0b57cec5SDimitry Andric Out << Feat.substr(1); 1279*0b57cec5SDimitry Andric } 1280*0b57cec5SDimitry Andric } 1281*0b57cec5SDimitry Andric 1282fe6060f1SDimitry Andric // Returns true if GD is a function decl with internal linkage and 1283fe6060f1SDimitry Andric // needs a unique suffix after the mangled name. 1284fe6060f1SDimitry Andric static bool isUniqueInternalLinkageDecl(GlobalDecl GD, 1285fe6060f1SDimitry Andric CodeGenModule &CGM) { 1286fe6060f1SDimitry Andric const Decl *D = GD.getDecl(); 1287fe6060f1SDimitry Andric return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) && 1288fe6060f1SDimitry Andric (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage); 1289fe6060f1SDimitry Andric } 1290fe6060f1SDimitry Andric 12914824e7fdSDimitry Andric static void AppendTargetClonesMangling(const CodeGenModule &CGM, 12924824e7fdSDimitry Andric const TargetClonesAttr *Attr, 12934824e7fdSDimitry Andric unsigned VersionIndex, 12944824e7fdSDimitry Andric raw_ostream &Out) { 12954824e7fdSDimitry Andric Out << '.'; 12964824e7fdSDimitry Andric StringRef FeatureStr = Attr->getFeatureStr(VersionIndex); 12974824e7fdSDimitry Andric if (FeatureStr.startswith("arch=")) 12984824e7fdSDimitry Andric Out << "arch_" << FeatureStr.substr(sizeof("arch=") - 1); 12994824e7fdSDimitry Andric else 13004824e7fdSDimitry Andric Out << FeatureStr; 13014824e7fdSDimitry Andric 13024824e7fdSDimitry Andric Out << '.' << Attr->getMangledIndex(VersionIndex); 13034824e7fdSDimitry Andric } 13044824e7fdSDimitry Andric 1305fe6060f1SDimitry Andric static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD, 1306*0b57cec5SDimitry Andric const NamedDecl *ND, 1307*0b57cec5SDimitry Andric bool OmitMultiVersionMangling = false) { 1308*0b57cec5SDimitry Andric SmallString<256> Buffer; 1309*0b57cec5SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 1310*0b57cec5SDimitry Andric MangleContext &MC = CGM.getCXXABI().getMangleContext(); 1311fe6060f1SDimitry Andric if (!CGM.getModuleNameHash().empty()) 1312fe6060f1SDimitry Andric MC.needsUniqueInternalLinkageNames(); 1313fe6060f1SDimitry Andric bool ShouldMangle = MC.shouldMangleDeclName(ND); 1314fe6060f1SDimitry Andric if (ShouldMangle) 13155ffd83dbSDimitry Andric MC.mangleName(GD.getWithDecl(ND), Out); 13165ffd83dbSDimitry Andric else { 1317*0b57cec5SDimitry Andric IdentifierInfo *II = ND->getIdentifier(); 1318*0b57cec5SDimitry Andric assert(II && "Attempt to mangle unnamed decl."); 1319*0b57cec5SDimitry Andric const auto *FD = dyn_cast<FunctionDecl>(ND); 1320*0b57cec5SDimitry Andric 1321*0b57cec5SDimitry Andric if (FD && 1322*0b57cec5SDimitry Andric FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { 1323*0b57cec5SDimitry Andric Out << "__regcall3__" << II->getName(); 13245ffd83dbSDimitry Andric } else if (FD && FD->hasAttr<CUDAGlobalAttr>() && 13255ffd83dbSDimitry Andric GD.getKernelReferenceKind() == KernelReferenceKind::Stub) { 13265ffd83dbSDimitry Andric Out << "__device_stub__" << II->getName(); 1327*0b57cec5SDimitry Andric } else { 1328*0b57cec5SDimitry Andric Out << II->getName(); 1329*0b57cec5SDimitry Andric } 1330*0b57cec5SDimitry Andric } 1331*0b57cec5SDimitry Andric 1332fe6060f1SDimitry Andric // Check if the module name hash should be appended for internal linkage 1333fe6060f1SDimitry Andric // symbols. This should come before multi-version target suffixes are 1334fe6060f1SDimitry Andric // appended. This is to keep the name and module hash suffix of the 1335fe6060f1SDimitry Andric // internal linkage function together. The unique suffix should only be 1336fe6060f1SDimitry Andric // added when name mangling is done to make sure that the final name can 1337fe6060f1SDimitry Andric // be properly demangled. For example, for C functions without prototypes, 1338fe6060f1SDimitry Andric // name mangling is not done and the unique suffix should not be appeneded 1339fe6060f1SDimitry Andric // then. 1340fe6060f1SDimitry Andric if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) { 1341fe6060f1SDimitry Andric assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames && 1342fe6060f1SDimitry Andric "Hash computed when not explicitly requested"); 1343fe6060f1SDimitry Andric Out << CGM.getModuleNameHash(); 1344fe6060f1SDimitry Andric } 1345fe6060f1SDimitry Andric 1346*0b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 1347*0b57cec5SDimitry Andric if (FD->isMultiVersion() && !OmitMultiVersionMangling) { 1348*0b57cec5SDimitry Andric switch (FD->getMultiVersionKind()) { 1349*0b57cec5SDimitry Andric case MultiVersionKind::CPUDispatch: 1350*0b57cec5SDimitry Andric case MultiVersionKind::CPUSpecific: 1351*0b57cec5SDimitry Andric AppendCPUSpecificCPUDispatchMangling(CGM, 1352*0b57cec5SDimitry Andric FD->getAttr<CPUSpecificAttr>(), 1353*0b57cec5SDimitry Andric GD.getMultiVersionIndex(), Out); 1354*0b57cec5SDimitry Andric break; 1355*0b57cec5SDimitry Andric case MultiVersionKind::Target: 1356*0b57cec5SDimitry Andric AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out); 1357*0b57cec5SDimitry Andric break; 13584824e7fdSDimitry Andric case MultiVersionKind::TargetClones: 13594824e7fdSDimitry Andric AppendTargetClonesMangling(CGM, FD->getAttr<TargetClonesAttr>(), 13604824e7fdSDimitry Andric GD.getMultiVersionIndex(), Out); 13614824e7fdSDimitry Andric break; 1362*0b57cec5SDimitry Andric case MultiVersionKind::None: 1363*0b57cec5SDimitry Andric llvm_unreachable("None multiversion type isn't valid here"); 1364*0b57cec5SDimitry Andric } 1365*0b57cec5SDimitry Andric } 1366*0b57cec5SDimitry Andric 1367fe6060f1SDimitry Andric // Make unique name for device side static file-scope variable for HIP. 1368fe6060f1SDimitry Andric if (CGM.getContext().shouldExternalizeStaticVar(ND) && 1369fe6060f1SDimitry Andric CGM.getLangOpts().GPURelocatableDeviceCode && 1370fe6060f1SDimitry Andric CGM.getLangOpts().CUDAIsDevice && !CGM.getLangOpts().CUID.empty()) 1371fe6060f1SDimitry Andric CGM.printPostfixForExternalizedStaticVar(Out); 13725ffd83dbSDimitry Andric return std::string(Out.str()); 1373*0b57cec5SDimitry Andric } 1374*0b57cec5SDimitry Andric 1375*0b57cec5SDimitry Andric void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD, 137604eeddc0SDimitry Andric const FunctionDecl *FD, 137704eeddc0SDimitry Andric StringRef &CurName) { 1378*0b57cec5SDimitry Andric if (!FD->isMultiVersion()) 1379*0b57cec5SDimitry Andric return; 1380*0b57cec5SDimitry Andric 1381*0b57cec5SDimitry Andric // Get the name of what this would be without the 'target' attribute. This 1382*0b57cec5SDimitry Andric // allows us to lookup the version that was emitted when this wasn't a 1383*0b57cec5SDimitry Andric // multiversion function. 1384*0b57cec5SDimitry Andric std::string NonTargetName = 1385*0b57cec5SDimitry Andric getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 1386*0b57cec5SDimitry Andric GlobalDecl OtherGD; 1387*0b57cec5SDimitry Andric if (lookupRepresentativeDecl(NonTargetName, OtherGD)) { 1388*0b57cec5SDimitry Andric assert(OtherGD.getCanonicalDecl() 1389*0b57cec5SDimitry Andric .getDecl() 1390*0b57cec5SDimitry Andric ->getAsFunction() 1391*0b57cec5SDimitry Andric ->isMultiVersion() && 1392*0b57cec5SDimitry Andric "Other GD should now be a multiversioned function"); 1393*0b57cec5SDimitry Andric // OtherFD is the version of this function that was mangled BEFORE 1394*0b57cec5SDimitry Andric // becoming a MultiVersion function. It potentially needs to be updated. 1395*0b57cec5SDimitry Andric const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl() 1396*0b57cec5SDimitry Andric .getDecl() 1397*0b57cec5SDimitry Andric ->getAsFunction() 1398*0b57cec5SDimitry Andric ->getMostRecentDecl(); 1399*0b57cec5SDimitry Andric std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD); 1400*0b57cec5SDimitry Andric // This is so that if the initial version was already the 'default' 1401*0b57cec5SDimitry Andric // version, we don't try to update it. 1402*0b57cec5SDimitry Andric if (OtherName != NonTargetName) { 1403*0b57cec5SDimitry Andric // Remove instead of erase, since others may have stored the StringRef 1404*0b57cec5SDimitry Andric // to this. 1405*0b57cec5SDimitry Andric const auto ExistingRecord = Manglings.find(NonTargetName); 1406*0b57cec5SDimitry Andric if (ExistingRecord != std::end(Manglings)) 1407*0b57cec5SDimitry Andric Manglings.remove(&(*ExistingRecord)); 1408*0b57cec5SDimitry Andric auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD)); 140904eeddc0SDimitry Andric StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] = 141004eeddc0SDimitry Andric Result.first->first(); 141104eeddc0SDimitry Andric // If this is the current decl is being created, make sure we update the name. 141204eeddc0SDimitry Andric if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl()) 141304eeddc0SDimitry Andric CurName = OtherNameRef; 1414*0b57cec5SDimitry Andric if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName)) 1415*0b57cec5SDimitry Andric Entry->setName(OtherName); 1416*0b57cec5SDimitry Andric } 1417*0b57cec5SDimitry Andric } 1418*0b57cec5SDimitry Andric } 1419*0b57cec5SDimitry Andric 1420*0b57cec5SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 1421*0b57cec5SDimitry Andric GlobalDecl CanonicalGD = GD.getCanonicalDecl(); 1422*0b57cec5SDimitry Andric 1423*0b57cec5SDimitry Andric // Some ABIs don't have constructor variants. Make sure that base and 1424*0b57cec5SDimitry Andric // complete constructors get mangled the same. 1425*0b57cec5SDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { 1426*0b57cec5SDimitry Andric if (!getTarget().getCXXABI().hasConstructorVariants()) { 1427*0b57cec5SDimitry Andric CXXCtorType OrigCtorType = GD.getCtorType(); 1428*0b57cec5SDimitry Andric assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); 1429*0b57cec5SDimitry Andric if (OrigCtorType == Ctor_Base) 1430*0b57cec5SDimitry Andric CanonicalGD = GlobalDecl(CD, Ctor_Complete); 1431*0b57cec5SDimitry Andric } 1432*0b57cec5SDimitry Andric } 1433*0b57cec5SDimitry Andric 1434fe6060f1SDimitry Andric // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a 1435fe6060f1SDimitry Andric // static device variable depends on whether the variable is referenced by 1436fe6060f1SDimitry Andric // a host or device host function. Therefore the mangled name cannot be 1437fe6060f1SDimitry Andric // cached. 1438fe6060f1SDimitry Andric if (!LangOpts.CUDAIsDevice || 1439fe6060f1SDimitry Andric !getContext().mayExternalizeStaticVar(GD.getDecl())) { 1440*0b57cec5SDimitry Andric auto FoundName = MangledDeclNames.find(CanonicalGD); 1441*0b57cec5SDimitry Andric if (FoundName != MangledDeclNames.end()) 1442*0b57cec5SDimitry Andric return FoundName->second; 1443fe6060f1SDimitry Andric } 1444*0b57cec5SDimitry Andric 1445*0b57cec5SDimitry Andric // Keep the first result in the case of a mangling collision. 1446*0b57cec5SDimitry Andric const auto *ND = cast<NamedDecl>(GD.getDecl()); 1447*0b57cec5SDimitry Andric std::string MangledName = getMangledNameImpl(*this, GD, ND); 1448*0b57cec5SDimitry Andric 14495ffd83dbSDimitry Andric // Ensure either we have different ABIs between host and device compilations, 14505ffd83dbSDimitry Andric // says host compilation following MSVC ABI but device compilation follows 14515ffd83dbSDimitry Andric // Itanium C++ ABI or, if they follow the same ABI, kernel names after 14525ffd83dbSDimitry Andric // mangling should be the same after name stubbing. The later checking is 14535ffd83dbSDimitry Andric // very important as the device kernel name being mangled in host-compilation 14545ffd83dbSDimitry Andric // is used to resolve the device binaries to be executed. Inconsistent naming 14555ffd83dbSDimitry Andric // result in undefined behavior. Even though we cannot check that naming 14565ffd83dbSDimitry Andric // directly between host- and device-compilations, the host- and 14575ffd83dbSDimitry Andric // device-mangling in host compilation could help catching certain ones. 14585ffd83dbSDimitry Andric assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || 14595ffd83dbSDimitry Andric getLangOpts().CUDAIsDevice || 14605ffd83dbSDimitry Andric (getContext().getAuxTargetInfo() && 14615ffd83dbSDimitry Andric (getContext().getAuxTargetInfo()->getCXXABI() != 14625ffd83dbSDimitry Andric getContext().getTargetInfo().getCXXABI())) || 14635ffd83dbSDimitry Andric getCUDARuntime().getDeviceSideName(ND) == 14645ffd83dbSDimitry Andric getMangledNameImpl( 14655ffd83dbSDimitry Andric *this, 14665ffd83dbSDimitry Andric GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), 14675ffd83dbSDimitry Andric ND)); 1468*0b57cec5SDimitry Andric 1469*0b57cec5SDimitry Andric auto Result = Manglings.insert(std::make_pair(MangledName, GD)); 1470*0b57cec5SDimitry Andric return MangledDeclNames[CanonicalGD] = Result.first->first(); 1471*0b57cec5SDimitry Andric } 1472*0b57cec5SDimitry Andric 1473*0b57cec5SDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 1474*0b57cec5SDimitry Andric const BlockDecl *BD) { 1475*0b57cec5SDimitry Andric MangleContext &MangleCtx = getCXXABI().getMangleContext(); 1476*0b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 1477*0b57cec5SDimitry Andric 1478*0b57cec5SDimitry Andric SmallString<256> Buffer; 1479*0b57cec5SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 1480*0b57cec5SDimitry Andric if (!D) 1481*0b57cec5SDimitry Andric MangleCtx.mangleGlobalBlock(BD, 1482*0b57cec5SDimitry Andric dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 1483*0b57cec5SDimitry Andric else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 1484*0b57cec5SDimitry Andric MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 1485*0b57cec5SDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 1486*0b57cec5SDimitry Andric MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 1487*0b57cec5SDimitry Andric else 1488*0b57cec5SDimitry Andric MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 1489*0b57cec5SDimitry Andric 1490*0b57cec5SDimitry Andric auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 1491*0b57cec5SDimitry Andric return Result.first->first(); 1492*0b57cec5SDimitry Andric } 1493*0b57cec5SDimitry Andric 1494*0b57cec5SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 1495*0b57cec5SDimitry Andric return getModule().getNamedValue(Name); 1496*0b57cec5SDimitry Andric } 1497*0b57cec5SDimitry Andric 1498*0b57cec5SDimitry Andric /// AddGlobalCtor - Add a function to the list that will be called before 1499*0b57cec5SDimitry Andric /// main() runs. 1500*0b57cec5SDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 1501*0b57cec5SDimitry Andric llvm::Constant *AssociatedData) { 1502*0b57cec5SDimitry Andric // FIXME: Type coercion of void()* types. 1503*0b57cec5SDimitry Andric GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); 1504*0b57cec5SDimitry Andric } 1505*0b57cec5SDimitry Andric 1506*0b57cec5SDimitry Andric /// AddGlobalDtor - Add a function to the list that will be called 1507*0b57cec5SDimitry Andric /// when the module is unloaded. 1508e8d8bef9SDimitry Andric void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority, 1509e8d8bef9SDimitry Andric bool IsDtorAttrFunc) { 1510e8d8bef9SDimitry Andric if (CodeGenOpts.RegisterGlobalDtorsWithAtExit && 1511e8d8bef9SDimitry Andric (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) { 1512*0b57cec5SDimitry Andric DtorsUsingAtExit[Priority].push_back(Dtor); 1513*0b57cec5SDimitry Andric return; 1514*0b57cec5SDimitry Andric } 1515*0b57cec5SDimitry Andric 1516*0b57cec5SDimitry Andric // FIXME: Type coercion of void()* types. 1517*0b57cec5SDimitry Andric GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); 1518*0b57cec5SDimitry Andric } 1519*0b57cec5SDimitry Andric 1520*0b57cec5SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { 1521*0b57cec5SDimitry Andric if (Fns.empty()) return; 1522*0b57cec5SDimitry Andric 1523*0b57cec5SDimitry Andric // Ctor function type is void()*. 1524*0b57cec5SDimitry Andric llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 1525*0b57cec5SDimitry Andric llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy, 1526*0b57cec5SDimitry Andric TheModule.getDataLayout().getProgramAddressSpace()); 1527*0b57cec5SDimitry Andric 1528*0b57cec5SDimitry Andric // Get the type of a ctor entry, { i32, void ()*, i8* }. 1529*0b57cec5SDimitry Andric llvm::StructType *CtorStructTy = llvm::StructType::get( 1530*0b57cec5SDimitry Andric Int32Ty, CtorPFTy, VoidPtrTy); 1531*0b57cec5SDimitry Andric 1532*0b57cec5SDimitry Andric // Construct the constructor and destructor arrays. 1533*0b57cec5SDimitry Andric ConstantInitBuilder builder(*this); 1534*0b57cec5SDimitry Andric auto ctors = builder.beginArray(CtorStructTy); 1535*0b57cec5SDimitry Andric for (const auto &I : Fns) { 1536*0b57cec5SDimitry Andric auto ctor = ctors.beginStruct(CtorStructTy); 1537*0b57cec5SDimitry Andric ctor.addInt(Int32Ty, I.Priority); 1538*0b57cec5SDimitry Andric ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy)); 1539*0b57cec5SDimitry Andric if (I.AssociatedData) 1540*0b57cec5SDimitry Andric ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)); 1541*0b57cec5SDimitry Andric else 1542*0b57cec5SDimitry Andric ctor.addNullPointer(VoidPtrTy); 1543*0b57cec5SDimitry Andric ctor.finishAndAddTo(ctors); 1544*0b57cec5SDimitry Andric } 1545*0b57cec5SDimitry Andric 1546*0b57cec5SDimitry Andric auto list = 1547*0b57cec5SDimitry Andric ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(), 1548*0b57cec5SDimitry Andric /*constant*/ false, 1549*0b57cec5SDimitry Andric llvm::GlobalValue::AppendingLinkage); 1550*0b57cec5SDimitry Andric 1551*0b57cec5SDimitry Andric // The LTO linker doesn't seem to like it when we set an alignment 1552*0b57cec5SDimitry Andric // on appending variables. Take it off as a workaround. 1553a7dea167SDimitry Andric list->setAlignment(llvm::None); 1554*0b57cec5SDimitry Andric 1555*0b57cec5SDimitry Andric Fns.clear(); 1556*0b57cec5SDimitry Andric } 1557*0b57cec5SDimitry Andric 1558*0b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes 1559*0b57cec5SDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 1560*0b57cec5SDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 1561*0b57cec5SDimitry Andric 1562*0b57cec5SDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 1563*0b57cec5SDimitry Andric 1564*0b57cec5SDimitry Andric if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D)) 1565*0b57cec5SDimitry Andric return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType()); 1566*0b57cec5SDimitry Andric 1567*0b57cec5SDimitry Andric if (isa<CXXConstructorDecl>(D) && 1568*0b57cec5SDimitry Andric cast<CXXConstructorDecl>(D)->isInheritingConstructor() && 1569*0b57cec5SDimitry Andric Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1570*0b57cec5SDimitry Andric // Our approach to inheriting constructors is fundamentally different from 1571*0b57cec5SDimitry Andric // that used by the MS ABI, so keep our inheriting constructor thunks 1572*0b57cec5SDimitry Andric // internal rather than trying to pick an unambiguous mangling for them. 1573*0b57cec5SDimitry Andric return llvm::GlobalValue::InternalLinkage; 1574*0b57cec5SDimitry Andric } 1575*0b57cec5SDimitry Andric 1576*0b57cec5SDimitry Andric return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false); 1577*0b57cec5SDimitry Andric } 1578*0b57cec5SDimitry Andric 1579*0b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { 1580*0b57cec5SDimitry Andric llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 1581*0b57cec5SDimitry Andric if (!MDS) return nullptr; 1582*0b57cec5SDimitry Andric 1583*0b57cec5SDimitry Andric return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString())); 1584*0b57cec5SDimitry Andric } 1585*0b57cec5SDimitry Andric 1586*0b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD, 1587*0b57cec5SDimitry Andric const CGFunctionInfo &Info, 1588fe6060f1SDimitry Andric llvm::Function *F, bool IsThunk) { 1589*0b57cec5SDimitry Andric unsigned CallingConv; 1590*0b57cec5SDimitry Andric llvm::AttributeList PAL; 1591fe6060f1SDimitry Andric ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, 1592fe6060f1SDimitry Andric /*AttrOnCallSite=*/false, IsThunk); 1593*0b57cec5SDimitry Andric F->setAttributes(PAL); 1594*0b57cec5SDimitry Andric F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 1595*0b57cec5SDimitry Andric } 1596*0b57cec5SDimitry Andric 1597*0b57cec5SDimitry Andric static void removeImageAccessQualifier(std::string& TyName) { 1598*0b57cec5SDimitry Andric std::string ReadOnlyQual("__read_only"); 1599*0b57cec5SDimitry Andric std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual); 1600*0b57cec5SDimitry Andric if (ReadOnlyPos != std::string::npos) 1601*0b57cec5SDimitry Andric // "+ 1" for the space after access qualifier. 1602*0b57cec5SDimitry Andric TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1); 1603*0b57cec5SDimitry Andric else { 1604*0b57cec5SDimitry Andric std::string WriteOnlyQual("__write_only"); 1605*0b57cec5SDimitry Andric std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual); 1606*0b57cec5SDimitry Andric if (WriteOnlyPos != std::string::npos) 1607*0b57cec5SDimitry Andric TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1); 1608*0b57cec5SDimitry Andric else { 1609*0b57cec5SDimitry Andric std::string ReadWriteQual("__read_write"); 1610*0b57cec5SDimitry Andric std::string::size_type ReadWritePos = TyName.find(ReadWriteQual); 1611*0b57cec5SDimitry Andric if (ReadWritePos != std::string::npos) 1612*0b57cec5SDimitry Andric TyName.erase(ReadWritePos, ReadWriteQual.size() + 1); 1613*0b57cec5SDimitry Andric } 1614*0b57cec5SDimitry Andric } 1615*0b57cec5SDimitry Andric } 1616*0b57cec5SDimitry Andric 1617*0b57cec5SDimitry Andric // Returns the address space id that should be produced to the 1618*0b57cec5SDimitry Andric // kernel_arg_addr_space metadata. This is always fixed to the ids 1619*0b57cec5SDimitry Andric // as specified in the SPIR 2.0 specification in order to differentiate 1620*0b57cec5SDimitry Andric // for example in clGetKernelArgInfo() implementation between the address 1621*0b57cec5SDimitry Andric // spaces with targets without unique mapping to the OpenCL address spaces 1622*0b57cec5SDimitry Andric // (basically all single AS CPUs). 1623*0b57cec5SDimitry Andric static unsigned ArgInfoAddressSpace(LangAS AS) { 1624*0b57cec5SDimitry Andric switch (AS) { 1625e8d8bef9SDimitry Andric case LangAS::opencl_global: 1626e8d8bef9SDimitry Andric return 1; 1627e8d8bef9SDimitry Andric case LangAS::opencl_constant: 1628e8d8bef9SDimitry Andric return 2; 1629e8d8bef9SDimitry Andric case LangAS::opencl_local: 1630e8d8bef9SDimitry Andric return 3; 1631e8d8bef9SDimitry Andric case LangAS::opencl_generic: 1632e8d8bef9SDimitry Andric return 4; // Not in SPIR 2.0 specs. 1633e8d8bef9SDimitry Andric case LangAS::opencl_global_device: 1634e8d8bef9SDimitry Andric return 5; 1635e8d8bef9SDimitry Andric case LangAS::opencl_global_host: 1636e8d8bef9SDimitry Andric return 6; 1637*0b57cec5SDimitry Andric default: 1638*0b57cec5SDimitry Andric return 0; // Assume private. 1639*0b57cec5SDimitry Andric } 1640*0b57cec5SDimitry Andric } 1641*0b57cec5SDimitry Andric 1642*0b57cec5SDimitry Andric void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn, 1643*0b57cec5SDimitry Andric const FunctionDecl *FD, 1644*0b57cec5SDimitry Andric CodeGenFunction *CGF) { 1645*0b57cec5SDimitry Andric assert(((FD && CGF) || (!FD && !CGF)) && 1646*0b57cec5SDimitry Andric "Incorrect use - FD and CGF should either be both null or not!"); 1647*0b57cec5SDimitry Andric // Create MDNodes that represent the kernel arg metadata. 1648*0b57cec5SDimitry Andric // Each MDNode is a list in the form of "key", N number of values which is 1649*0b57cec5SDimitry Andric // the same number of values as their are kernel arguments. 1650*0b57cec5SDimitry Andric 1651*0b57cec5SDimitry Andric const PrintingPolicy &Policy = Context.getPrintingPolicy(); 1652*0b57cec5SDimitry Andric 1653*0b57cec5SDimitry Andric // MDNode for the kernel argument address space qualifiers. 1654*0b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> addressQuals; 1655*0b57cec5SDimitry Andric 1656*0b57cec5SDimitry Andric // MDNode for the kernel argument access qualifiers (images only). 1657*0b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> accessQuals; 1658*0b57cec5SDimitry Andric 1659*0b57cec5SDimitry Andric // MDNode for the kernel argument type names. 1660*0b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> argTypeNames; 1661*0b57cec5SDimitry Andric 1662*0b57cec5SDimitry Andric // MDNode for the kernel argument base type names. 1663*0b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> argBaseTypeNames; 1664*0b57cec5SDimitry Andric 1665*0b57cec5SDimitry Andric // MDNode for the kernel argument type qualifiers. 1666*0b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> argTypeQuals; 1667*0b57cec5SDimitry Andric 1668*0b57cec5SDimitry Andric // MDNode for the kernel argument names. 1669*0b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> argNames; 1670*0b57cec5SDimitry Andric 1671*0b57cec5SDimitry Andric if (FD && CGF) 1672*0b57cec5SDimitry Andric for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { 1673*0b57cec5SDimitry Andric const ParmVarDecl *parm = FD->getParamDecl(i); 1674*0b57cec5SDimitry Andric QualType ty = parm->getType(); 1675*0b57cec5SDimitry Andric std::string typeQuals; 1676*0b57cec5SDimitry Andric 1677fe6060f1SDimitry Andric // Get image and pipe access qualifier: 1678fe6060f1SDimitry Andric if (ty->isImageType() || ty->isPipeType()) { 1679fe6060f1SDimitry Andric const Decl *PDecl = parm; 1680fe6060f1SDimitry Andric if (auto *TD = dyn_cast<TypedefType>(ty)) 1681fe6060f1SDimitry Andric PDecl = TD->getDecl(); 1682fe6060f1SDimitry Andric const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>(); 1683fe6060f1SDimitry Andric if (A && A->isWriteOnly()) 1684fe6060f1SDimitry Andric accessQuals.push_back(llvm::MDString::get(VMContext, "write_only")); 1685fe6060f1SDimitry Andric else if (A && A->isReadWrite()) 1686fe6060f1SDimitry Andric accessQuals.push_back(llvm::MDString::get(VMContext, "read_write")); 1687fe6060f1SDimitry Andric else 1688fe6060f1SDimitry Andric accessQuals.push_back(llvm::MDString::get(VMContext, "read_only")); 1689fe6060f1SDimitry Andric } else 1690fe6060f1SDimitry Andric accessQuals.push_back(llvm::MDString::get(VMContext, "none")); 1691fe6060f1SDimitry Andric 1692fe6060f1SDimitry Andric // Get argument name. 1693fe6060f1SDimitry Andric argNames.push_back(llvm::MDString::get(VMContext, parm->getName())); 1694fe6060f1SDimitry Andric 1695fe6060f1SDimitry Andric auto getTypeSpelling = [&](QualType Ty) { 1696fe6060f1SDimitry Andric auto typeName = Ty.getUnqualifiedType().getAsString(Policy); 1697fe6060f1SDimitry Andric 1698fe6060f1SDimitry Andric if (Ty.isCanonical()) { 1699fe6060f1SDimitry Andric StringRef typeNameRef = typeName; 1700fe6060f1SDimitry Andric // Turn "unsigned type" to "utype" 1701fe6060f1SDimitry Andric if (typeNameRef.consume_front("unsigned ")) 1702fe6060f1SDimitry Andric return std::string("u") + typeNameRef.str(); 1703fe6060f1SDimitry Andric if (typeNameRef.consume_front("signed ")) 1704fe6060f1SDimitry Andric return typeNameRef.str(); 1705fe6060f1SDimitry Andric } 1706fe6060f1SDimitry Andric 1707fe6060f1SDimitry Andric return typeName; 1708fe6060f1SDimitry Andric }; 1709fe6060f1SDimitry Andric 1710*0b57cec5SDimitry Andric if (ty->isPointerType()) { 1711*0b57cec5SDimitry Andric QualType pointeeTy = ty->getPointeeType(); 1712*0b57cec5SDimitry Andric 1713*0b57cec5SDimitry Andric // Get address qualifier. 1714*0b57cec5SDimitry Andric addressQuals.push_back( 1715*0b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(CGF->Builder.getInt32( 1716*0b57cec5SDimitry Andric ArgInfoAddressSpace(pointeeTy.getAddressSpace())))); 1717*0b57cec5SDimitry Andric 1718*0b57cec5SDimitry Andric // Get argument type name. 1719fe6060f1SDimitry Andric std::string typeName = getTypeSpelling(pointeeTy) + "*"; 1720*0b57cec5SDimitry Andric std::string baseTypeName = 1721fe6060f1SDimitry Andric getTypeSpelling(pointeeTy.getCanonicalType()) + "*"; 1722fe6060f1SDimitry Andric argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 1723*0b57cec5SDimitry Andric argBaseTypeNames.push_back( 1724*0b57cec5SDimitry Andric llvm::MDString::get(VMContext, baseTypeName)); 1725*0b57cec5SDimitry Andric 1726*0b57cec5SDimitry Andric // Get argument type qualifiers: 1727*0b57cec5SDimitry Andric if (ty.isRestrictQualified()) 1728*0b57cec5SDimitry Andric typeQuals = "restrict"; 1729*0b57cec5SDimitry Andric if (pointeeTy.isConstQualified() || 1730*0b57cec5SDimitry Andric (pointeeTy.getAddressSpace() == LangAS::opencl_constant)) 1731*0b57cec5SDimitry Andric typeQuals += typeQuals.empty() ? "const" : " const"; 1732*0b57cec5SDimitry Andric if (pointeeTy.isVolatileQualified()) 1733*0b57cec5SDimitry Andric typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 1734*0b57cec5SDimitry Andric } else { 1735*0b57cec5SDimitry Andric uint32_t AddrSpc = 0; 1736*0b57cec5SDimitry Andric bool isPipe = ty->isPipeType(); 1737*0b57cec5SDimitry Andric if (ty->isImageType() || isPipe) 1738*0b57cec5SDimitry Andric AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global); 1739*0b57cec5SDimitry Andric 1740*0b57cec5SDimitry Andric addressQuals.push_back( 1741*0b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc))); 1742*0b57cec5SDimitry Andric 1743*0b57cec5SDimitry Andric // Get argument type name. 1744fe6060f1SDimitry Andric ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty; 1745fe6060f1SDimitry Andric std::string typeName = getTypeSpelling(ty); 1746fe6060f1SDimitry Andric std::string baseTypeName = getTypeSpelling(ty.getCanonicalType()); 1747*0b57cec5SDimitry Andric 1748*0b57cec5SDimitry Andric // Remove access qualifiers on images 1749*0b57cec5SDimitry Andric // (as they are inseparable from type in clang implementation, 1750*0b57cec5SDimitry Andric // but OpenCL spec provides a special query to get access qualifier 1751*0b57cec5SDimitry Andric // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER): 1752*0b57cec5SDimitry Andric if (ty->isImageType()) { 1753*0b57cec5SDimitry Andric removeImageAccessQualifier(typeName); 1754*0b57cec5SDimitry Andric removeImageAccessQualifier(baseTypeName); 1755*0b57cec5SDimitry Andric } 1756*0b57cec5SDimitry Andric 1757*0b57cec5SDimitry Andric argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 1758*0b57cec5SDimitry Andric argBaseTypeNames.push_back( 1759*0b57cec5SDimitry Andric llvm::MDString::get(VMContext, baseTypeName)); 1760*0b57cec5SDimitry Andric 1761*0b57cec5SDimitry Andric if (isPipe) 1762*0b57cec5SDimitry Andric typeQuals = "pipe"; 1763*0b57cec5SDimitry Andric } 1764*0b57cec5SDimitry Andric argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals)); 1765*0b57cec5SDimitry Andric } 1766*0b57cec5SDimitry Andric 1767*0b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_addr_space", 1768*0b57cec5SDimitry Andric llvm::MDNode::get(VMContext, addressQuals)); 1769*0b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_access_qual", 1770*0b57cec5SDimitry Andric llvm::MDNode::get(VMContext, accessQuals)); 1771*0b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_type", 1772*0b57cec5SDimitry Andric llvm::MDNode::get(VMContext, argTypeNames)); 1773*0b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_base_type", 1774*0b57cec5SDimitry Andric llvm::MDNode::get(VMContext, argBaseTypeNames)); 1775*0b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_type_qual", 1776*0b57cec5SDimitry Andric llvm::MDNode::get(VMContext, argTypeQuals)); 1777*0b57cec5SDimitry Andric if (getCodeGenOpts().EmitOpenCLArgMetadata) 1778*0b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_name", 1779*0b57cec5SDimitry Andric llvm::MDNode::get(VMContext, argNames)); 1780*0b57cec5SDimitry Andric } 1781*0b57cec5SDimitry Andric 1782*0b57cec5SDimitry Andric /// Determines whether the language options require us to model 1783*0b57cec5SDimitry Andric /// unwind exceptions. We treat -fexceptions as mandating this 1784*0b57cec5SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions 1785*0b57cec5SDimitry Andric /// enabled. This means, for example, that C with -fexceptions 1786*0b57cec5SDimitry Andric /// enables this. 1787*0b57cec5SDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) { 1788*0b57cec5SDimitry Andric // If exceptions are completely disabled, obviously this is false. 1789*0b57cec5SDimitry Andric if (!LangOpts.Exceptions) return false; 1790*0b57cec5SDimitry Andric 1791*0b57cec5SDimitry Andric // If C++ exceptions are enabled, this is true. 1792*0b57cec5SDimitry Andric if (LangOpts.CXXExceptions) return true; 1793*0b57cec5SDimitry Andric 1794*0b57cec5SDimitry Andric // If ObjC exceptions are enabled, this depends on the ABI. 1795*0b57cec5SDimitry Andric if (LangOpts.ObjCExceptions) { 1796*0b57cec5SDimitry Andric return LangOpts.ObjCRuntime.hasUnwindExceptions(); 1797*0b57cec5SDimitry Andric } 1798*0b57cec5SDimitry Andric 1799*0b57cec5SDimitry Andric return true; 1800*0b57cec5SDimitry Andric } 1801*0b57cec5SDimitry Andric 1802*0b57cec5SDimitry Andric static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, 1803*0b57cec5SDimitry Andric const CXXMethodDecl *MD) { 1804*0b57cec5SDimitry Andric // Check that the type metadata can ever actually be used by a call. 1805*0b57cec5SDimitry Andric if (!CGM.getCodeGenOpts().LTOUnit || 1806*0b57cec5SDimitry Andric !CGM.HasHiddenLTOVisibility(MD->getParent())) 1807*0b57cec5SDimitry Andric return false; 1808*0b57cec5SDimitry Andric 1809*0b57cec5SDimitry Andric // Only functions whose address can be taken with a member function pointer 1810*0b57cec5SDimitry Andric // need this sort of type metadata. 1811*0b57cec5SDimitry Andric return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) && 1812*0b57cec5SDimitry Andric !isa<CXXDestructorDecl>(MD); 1813*0b57cec5SDimitry Andric } 1814*0b57cec5SDimitry Andric 1815*0b57cec5SDimitry Andric std::vector<const CXXRecordDecl *> 1816*0b57cec5SDimitry Andric CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) { 1817*0b57cec5SDimitry Andric llvm::SetVector<const CXXRecordDecl *> MostBases; 1818*0b57cec5SDimitry Andric 1819*0b57cec5SDimitry Andric std::function<void (const CXXRecordDecl *)> CollectMostBases; 1820*0b57cec5SDimitry Andric CollectMostBases = [&](const CXXRecordDecl *RD) { 1821*0b57cec5SDimitry Andric if (RD->getNumBases() == 0) 1822*0b57cec5SDimitry Andric MostBases.insert(RD); 1823*0b57cec5SDimitry Andric for (const CXXBaseSpecifier &B : RD->bases()) 1824*0b57cec5SDimitry Andric CollectMostBases(B.getType()->getAsCXXRecordDecl()); 1825*0b57cec5SDimitry Andric }; 1826*0b57cec5SDimitry Andric CollectMostBases(RD); 1827*0b57cec5SDimitry Andric return MostBases.takeVector(); 1828*0b57cec5SDimitry Andric } 1829*0b57cec5SDimitry Andric 1830*0b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 1831*0b57cec5SDimitry Andric llvm::Function *F) { 183204eeddc0SDimitry Andric llvm::AttrBuilder B(F->getContext()); 1833*0b57cec5SDimitry Andric 1834*0b57cec5SDimitry Andric if (CodeGenOpts.UnwindTables) 1835*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::UWTable); 1836*0b57cec5SDimitry Andric 18375ffd83dbSDimitry Andric if (CodeGenOpts.StackClashProtector) 18385ffd83dbSDimitry Andric B.addAttribute("probe-stack", "inline-asm"); 18395ffd83dbSDimitry Andric 1840*0b57cec5SDimitry Andric if (!hasUnwindExceptions(LangOpts)) 1841*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoUnwind); 1842*0b57cec5SDimitry Andric 1843*0b57cec5SDimitry Andric if (!D || !D->hasAttr<NoStackProtectorAttr>()) { 1844*0b57cec5SDimitry Andric if (LangOpts.getStackProtector() == LangOptions::SSPOn) 1845*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::StackProtect); 1846*0b57cec5SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 1847*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectStrong); 1848*0b57cec5SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 1849*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectReq); 1850*0b57cec5SDimitry Andric } 1851*0b57cec5SDimitry Andric 1852*0b57cec5SDimitry Andric if (!D) { 1853*0b57cec5SDimitry Andric // If we don't have a declaration to control inlining, the function isn't 1854*0b57cec5SDimitry Andric // explicitly marked as alwaysinline for semantic reasons, and inlining is 1855*0b57cec5SDimitry Andric // disabled, mark the function as noinline. 1856*0b57cec5SDimitry Andric if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 1857*0b57cec5SDimitry Andric CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) 1858*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 1859*0b57cec5SDimitry Andric 1860349cc55cSDimitry Andric F->addFnAttrs(B); 1861*0b57cec5SDimitry Andric return; 1862*0b57cec5SDimitry Andric } 1863*0b57cec5SDimitry Andric 1864*0b57cec5SDimitry Andric // Track whether we need to add the optnone LLVM attribute, 1865*0b57cec5SDimitry Andric // starting with the default for this optimization level. 1866*0b57cec5SDimitry Andric bool ShouldAddOptNone = 1867*0b57cec5SDimitry Andric !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0; 1868*0b57cec5SDimitry Andric // We can't add optnone in the following cases, it won't pass the verifier. 1869*0b57cec5SDimitry Andric ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>(); 1870*0b57cec5SDimitry Andric ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>(); 1871*0b57cec5SDimitry Andric 1872480093f4SDimitry Andric // Add optnone, but do so only if the function isn't always_inline. 1873480093f4SDimitry Andric if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) && 1874480093f4SDimitry Andric !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 1875*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::OptimizeNone); 1876*0b57cec5SDimitry Andric 1877*0b57cec5SDimitry Andric // OptimizeNone implies noinline; we should not be inlining such functions. 1878*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 1879*0b57cec5SDimitry Andric 1880*0b57cec5SDimitry Andric // We still need to handle naked functions even though optnone subsumes 1881*0b57cec5SDimitry Andric // much of their semantics. 1882*0b57cec5SDimitry Andric if (D->hasAttr<NakedAttr>()) 1883*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::Naked); 1884*0b57cec5SDimitry Andric 1885*0b57cec5SDimitry Andric // OptimizeNone wins over OptimizeForSize and MinSize. 1886*0b57cec5SDimitry Andric F->removeFnAttr(llvm::Attribute::OptimizeForSize); 1887*0b57cec5SDimitry Andric F->removeFnAttr(llvm::Attribute::MinSize); 1888*0b57cec5SDimitry Andric } else if (D->hasAttr<NakedAttr>()) { 1889*0b57cec5SDimitry Andric // Naked implies noinline: we should not be inlining such functions. 1890*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::Naked); 1891*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 1892*0b57cec5SDimitry Andric } else if (D->hasAttr<NoDuplicateAttr>()) { 1893*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoDuplicate); 1894480093f4SDimitry Andric } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 1895480093f4SDimitry Andric // Add noinline if the function isn't always_inline. 1896*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 1897*0b57cec5SDimitry Andric } else if (D->hasAttr<AlwaysInlineAttr>() && 1898*0b57cec5SDimitry Andric !F->hasFnAttribute(llvm::Attribute::NoInline)) { 1899*0b57cec5SDimitry Andric // (noinline wins over always_inline, and we can't specify both in IR) 1900*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::AlwaysInline); 1901*0b57cec5SDimitry Andric } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { 1902*0b57cec5SDimitry Andric // If we're not inlining, then force everything that isn't always_inline to 1903*0b57cec5SDimitry Andric // carry an explicit noinline attribute. 1904*0b57cec5SDimitry Andric if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) 1905*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 1906*0b57cec5SDimitry Andric } else { 1907*0b57cec5SDimitry Andric // Otherwise, propagate the inline hint attribute and potentially use its 1908*0b57cec5SDimitry Andric // absence to mark things as noinline. 1909*0b57cec5SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) { 1910*0b57cec5SDimitry Andric // Search function and template pattern redeclarations for inline. 1911*0b57cec5SDimitry Andric auto CheckForInline = [](const FunctionDecl *FD) { 1912*0b57cec5SDimitry Andric auto CheckRedeclForInline = [](const FunctionDecl *Redecl) { 1913*0b57cec5SDimitry Andric return Redecl->isInlineSpecified(); 1914*0b57cec5SDimitry Andric }; 1915*0b57cec5SDimitry Andric if (any_of(FD->redecls(), CheckRedeclForInline)) 1916*0b57cec5SDimitry Andric return true; 1917*0b57cec5SDimitry Andric const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern(); 1918*0b57cec5SDimitry Andric if (!Pattern) 1919*0b57cec5SDimitry Andric return false; 1920*0b57cec5SDimitry Andric return any_of(Pattern->redecls(), CheckRedeclForInline); 1921*0b57cec5SDimitry Andric }; 1922*0b57cec5SDimitry Andric if (CheckForInline(FD)) { 1923*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::InlineHint); 1924*0b57cec5SDimitry Andric } else if (CodeGenOpts.getInlining() == 1925*0b57cec5SDimitry Andric CodeGenOptions::OnlyHintInlining && 1926*0b57cec5SDimitry Andric !FD->isInlined() && 1927*0b57cec5SDimitry Andric !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 1928*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 1929*0b57cec5SDimitry Andric } 1930*0b57cec5SDimitry Andric } 1931*0b57cec5SDimitry Andric } 1932*0b57cec5SDimitry Andric 1933*0b57cec5SDimitry Andric // Add other optimization related attributes if we are optimizing this 1934*0b57cec5SDimitry Andric // function. 1935*0b57cec5SDimitry Andric if (!D->hasAttr<OptimizeNoneAttr>()) { 1936*0b57cec5SDimitry Andric if (D->hasAttr<ColdAttr>()) { 1937*0b57cec5SDimitry Andric if (!ShouldAddOptNone) 1938*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::OptimizeForSize); 1939*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::Cold); 1940*0b57cec5SDimitry Andric } 1941e8d8bef9SDimitry Andric if (D->hasAttr<HotAttr>()) 1942e8d8bef9SDimitry Andric B.addAttribute(llvm::Attribute::Hot); 1943*0b57cec5SDimitry Andric if (D->hasAttr<MinSizeAttr>()) 1944*0b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::MinSize); 1945*0b57cec5SDimitry Andric } 1946*0b57cec5SDimitry Andric 1947349cc55cSDimitry Andric F->addFnAttrs(B); 1948*0b57cec5SDimitry Andric 1949*0b57cec5SDimitry Andric unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 1950*0b57cec5SDimitry Andric if (alignment) 1951a7dea167SDimitry Andric F->setAlignment(llvm::Align(alignment)); 1952*0b57cec5SDimitry Andric 1953*0b57cec5SDimitry Andric if (!D->hasAttr<AlignedAttr>()) 1954*0b57cec5SDimitry Andric if (LangOpts.FunctionAlignment) 1955a7dea167SDimitry Andric F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment)); 1956*0b57cec5SDimitry Andric 1957*0b57cec5SDimitry Andric // Some C++ ABIs require 2-byte alignment for member functions, in order to 1958*0b57cec5SDimitry Andric // reserve a bit for differentiating between virtual and non-virtual member 1959*0b57cec5SDimitry Andric // functions. If the current target's C++ ABI requires this and this is a 1960*0b57cec5SDimitry Andric // member function, set its alignment accordingly. 1961*0b57cec5SDimitry Andric if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 1962*0b57cec5SDimitry Andric if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 1963a7dea167SDimitry Andric F->setAlignment(llvm::Align(2)); 1964*0b57cec5SDimitry Andric } 1965*0b57cec5SDimitry Andric 1966a7dea167SDimitry Andric // In the cross-dso CFI mode with canonical jump tables, we want !type 1967a7dea167SDimitry Andric // attributes on definitions only. 1968a7dea167SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso && 1969a7dea167SDimitry Andric CodeGenOpts.SanitizeCfiCanonicalJumpTables) { 1970a7dea167SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) { 1971a7dea167SDimitry Andric // Skip available_externally functions. They won't be codegen'ed in the 1972a7dea167SDimitry Andric // current module anyway. 1973a7dea167SDimitry Andric if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally) 1974*0b57cec5SDimitry Andric CreateFunctionTypeMetadataForIcall(FD, F); 1975a7dea167SDimitry Andric } 1976a7dea167SDimitry Andric } 1977*0b57cec5SDimitry Andric 1978*0b57cec5SDimitry Andric // Emit type metadata on member functions for member function pointer checks. 1979*0b57cec5SDimitry Andric // These are only ever necessary on definitions; we're guaranteed that the 1980*0b57cec5SDimitry Andric // definition will be present in the LTO unit as a result of LTO visibility. 1981*0b57cec5SDimitry Andric auto *MD = dyn_cast<CXXMethodDecl>(D); 1982*0b57cec5SDimitry Andric if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) { 1983*0b57cec5SDimitry Andric for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) { 1984*0b57cec5SDimitry Andric llvm::Metadata *Id = 1985*0b57cec5SDimitry Andric CreateMetadataIdentifierForType(Context.getMemberPointerType( 1986*0b57cec5SDimitry Andric MD->getType(), Context.getRecordType(Base).getTypePtr())); 1987*0b57cec5SDimitry Andric F->addTypeMetadata(0, Id); 1988*0b57cec5SDimitry Andric } 1989*0b57cec5SDimitry Andric } 1990*0b57cec5SDimitry Andric } 1991*0b57cec5SDimitry Andric 1992e8d8bef9SDimitry Andric void CodeGenModule::setLLVMFunctionFEnvAttributes(const FunctionDecl *D, 1993e8d8bef9SDimitry Andric llvm::Function *F) { 1994e8d8bef9SDimitry Andric if (D->hasAttr<StrictFPAttr>()) { 199504eeddc0SDimitry Andric llvm::AttrBuilder FuncAttrs(F->getContext()); 1996e8d8bef9SDimitry Andric FuncAttrs.addAttribute("strictfp"); 1997349cc55cSDimitry Andric F->addFnAttrs(FuncAttrs); 1998e8d8bef9SDimitry Andric } 1999e8d8bef9SDimitry Andric } 2000e8d8bef9SDimitry Andric 2001*0b57cec5SDimitry Andric void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) { 2002*0b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 2003349cc55cSDimitry Andric if (isa_and_nonnull<NamedDecl>(D)) 2004*0b57cec5SDimitry Andric setGVProperties(GV, GD); 2005*0b57cec5SDimitry Andric else 2006*0b57cec5SDimitry Andric GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 2007*0b57cec5SDimitry Andric 2008*0b57cec5SDimitry Andric if (D && D->hasAttr<UsedAttr>()) 2009fe6060f1SDimitry Andric addUsedOrCompilerUsedGlobal(GV); 2010*0b57cec5SDimitry Andric 2011*0b57cec5SDimitry Andric if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) { 2012*0b57cec5SDimitry Andric const auto *VD = cast<VarDecl>(D); 2013*0b57cec5SDimitry Andric if (VD->getType().isConstQualified() && 2014*0b57cec5SDimitry Andric VD->getStorageDuration() == SD_Static) 2015fe6060f1SDimitry Andric addUsedOrCompilerUsedGlobal(GV); 2016*0b57cec5SDimitry Andric } 2017*0b57cec5SDimitry Andric } 2018*0b57cec5SDimitry Andric 2019*0b57cec5SDimitry Andric bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD, 2020*0b57cec5SDimitry Andric llvm::AttrBuilder &Attrs) { 2021*0b57cec5SDimitry Andric // Add target-cpu and target-features attributes to functions. If 2022*0b57cec5SDimitry Andric // we have a decl for the function and it has a target attribute then 2023*0b57cec5SDimitry Andric // parse that and add it to the feature set. 2024*0b57cec5SDimitry Andric StringRef TargetCPU = getTarget().getTargetOpts().CPU; 2025e8d8bef9SDimitry Andric StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU; 2026*0b57cec5SDimitry Andric std::vector<std::string> Features; 2027*0b57cec5SDimitry Andric const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl()); 2028*0b57cec5SDimitry Andric FD = FD ? FD->getMostRecentDecl() : FD; 2029*0b57cec5SDimitry Andric const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr; 2030*0b57cec5SDimitry Andric const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr; 20314824e7fdSDimitry Andric const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr; 2032*0b57cec5SDimitry Andric bool AddedAttr = false; 20334824e7fdSDimitry Andric if (TD || SD || TC) { 2034*0b57cec5SDimitry Andric llvm::StringMap<bool> FeatureMap; 2035480093f4SDimitry Andric getContext().getFunctionFeatureMap(FeatureMap, GD); 2036*0b57cec5SDimitry Andric 2037*0b57cec5SDimitry Andric // Produce the canonical string for this set of features. 2038*0b57cec5SDimitry Andric for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap) 2039*0b57cec5SDimitry Andric Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str()); 2040*0b57cec5SDimitry Andric 2041*0b57cec5SDimitry Andric // Now add the target-cpu and target-features to the function. 2042*0b57cec5SDimitry Andric // While we populated the feature map above, we still need to 2043*0b57cec5SDimitry Andric // get and parse the target attribute so we can get the cpu for 2044*0b57cec5SDimitry Andric // the function. 2045*0b57cec5SDimitry Andric if (TD) { 2046480093f4SDimitry Andric ParsedTargetAttr ParsedAttr = TD->parse(); 2047e8d8bef9SDimitry Andric if (!ParsedAttr.Architecture.empty() && 2048e8d8bef9SDimitry Andric getTarget().isValidCPUName(ParsedAttr.Architecture)) { 2049*0b57cec5SDimitry Andric TargetCPU = ParsedAttr.Architecture; 2050e8d8bef9SDimitry Andric TuneCPU = ""; // Clear the tune CPU. 2051e8d8bef9SDimitry Andric } 2052e8d8bef9SDimitry Andric if (!ParsedAttr.Tune.empty() && 2053e8d8bef9SDimitry Andric getTarget().isValidCPUName(ParsedAttr.Tune)) 2054e8d8bef9SDimitry Andric TuneCPU = ParsedAttr.Tune; 2055*0b57cec5SDimitry Andric } 2056*0b57cec5SDimitry Andric } else { 2057*0b57cec5SDimitry Andric // Otherwise just add the existing target cpu and target features to the 2058*0b57cec5SDimitry Andric // function. 2059*0b57cec5SDimitry Andric Features = getTarget().getTargetOpts().Features; 2060*0b57cec5SDimitry Andric } 2061*0b57cec5SDimitry Andric 2062e8d8bef9SDimitry Andric if (!TargetCPU.empty()) { 2063*0b57cec5SDimitry Andric Attrs.addAttribute("target-cpu", TargetCPU); 2064*0b57cec5SDimitry Andric AddedAttr = true; 2065*0b57cec5SDimitry Andric } 2066e8d8bef9SDimitry Andric if (!TuneCPU.empty()) { 2067e8d8bef9SDimitry Andric Attrs.addAttribute("tune-cpu", TuneCPU); 2068e8d8bef9SDimitry Andric AddedAttr = true; 2069e8d8bef9SDimitry Andric } 2070*0b57cec5SDimitry Andric if (!Features.empty()) { 2071*0b57cec5SDimitry Andric llvm::sort(Features); 2072*0b57cec5SDimitry Andric Attrs.addAttribute("target-features", llvm::join(Features, ",")); 2073*0b57cec5SDimitry Andric AddedAttr = true; 2074*0b57cec5SDimitry Andric } 2075*0b57cec5SDimitry Andric 2076*0b57cec5SDimitry Andric return AddedAttr; 2077*0b57cec5SDimitry Andric } 2078*0b57cec5SDimitry Andric 2079*0b57cec5SDimitry Andric void CodeGenModule::setNonAliasAttributes(GlobalDecl GD, 2080*0b57cec5SDimitry Andric llvm::GlobalObject *GO) { 2081*0b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 2082*0b57cec5SDimitry Andric SetCommonAttributes(GD, GO); 2083*0b57cec5SDimitry Andric 2084*0b57cec5SDimitry Andric if (D) { 2085*0b57cec5SDimitry Andric if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) { 2086fe6060f1SDimitry Andric if (D->hasAttr<RetainAttr>()) 2087fe6060f1SDimitry Andric addUsedGlobal(GV); 2088*0b57cec5SDimitry Andric if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) 2089*0b57cec5SDimitry Andric GV->addAttribute("bss-section", SA->getName()); 2090*0b57cec5SDimitry Andric if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) 2091*0b57cec5SDimitry Andric GV->addAttribute("data-section", SA->getName()); 2092*0b57cec5SDimitry Andric if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) 2093*0b57cec5SDimitry Andric GV->addAttribute("rodata-section", SA->getName()); 2094a7dea167SDimitry Andric if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>()) 2095a7dea167SDimitry Andric GV->addAttribute("relro-section", SA->getName()); 2096*0b57cec5SDimitry Andric } 2097*0b57cec5SDimitry Andric 2098*0b57cec5SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(GO)) { 2099fe6060f1SDimitry Andric if (D->hasAttr<RetainAttr>()) 2100fe6060f1SDimitry Andric addUsedGlobal(F); 2101*0b57cec5SDimitry Andric if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) 2102*0b57cec5SDimitry Andric if (!D->getAttr<SectionAttr>()) 2103*0b57cec5SDimitry Andric F->addFnAttr("implicit-section-name", SA->getName()); 2104*0b57cec5SDimitry Andric 210504eeddc0SDimitry Andric llvm::AttrBuilder Attrs(F->getContext()); 2106*0b57cec5SDimitry Andric if (GetCPUAndFeaturesAttributes(GD, Attrs)) { 2107*0b57cec5SDimitry Andric // We know that GetCPUAndFeaturesAttributes will always have the 2108*0b57cec5SDimitry Andric // newest set, since it has the newest possible FunctionDecl, so the 2109*0b57cec5SDimitry Andric // new ones should replace the old. 211004eeddc0SDimitry Andric llvm::AttributeMask RemoveAttrs; 2111e8d8bef9SDimitry Andric RemoveAttrs.addAttribute("target-cpu"); 2112e8d8bef9SDimitry Andric RemoveAttrs.addAttribute("target-features"); 2113e8d8bef9SDimitry Andric RemoveAttrs.addAttribute("tune-cpu"); 2114349cc55cSDimitry Andric F->removeFnAttrs(RemoveAttrs); 2115349cc55cSDimitry Andric F->addFnAttrs(Attrs); 2116*0b57cec5SDimitry Andric } 2117*0b57cec5SDimitry Andric } 2118*0b57cec5SDimitry Andric 2119*0b57cec5SDimitry Andric if (const auto *CSA = D->getAttr<CodeSegAttr>()) 2120*0b57cec5SDimitry Andric GO->setSection(CSA->getName()); 2121*0b57cec5SDimitry Andric else if (const auto *SA = D->getAttr<SectionAttr>()) 2122*0b57cec5SDimitry Andric GO->setSection(SA->getName()); 2123*0b57cec5SDimitry Andric } 2124*0b57cec5SDimitry Andric 2125*0b57cec5SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 2126*0b57cec5SDimitry Andric } 2127*0b57cec5SDimitry Andric 2128*0b57cec5SDimitry Andric void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD, 2129*0b57cec5SDimitry Andric llvm::Function *F, 2130*0b57cec5SDimitry Andric const CGFunctionInfo &FI) { 2131*0b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 2132fe6060f1SDimitry Andric SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false); 2133*0b57cec5SDimitry Andric SetLLVMFunctionAttributesForDefinition(D, F); 2134*0b57cec5SDimitry Andric 2135*0b57cec5SDimitry Andric F->setLinkage(llvm::Function::InternalLinkage); 2136*0b57cec5SDimitry Andric 2137*0b57cec5SDimitry Andric setNonAliasAttributes(GD, F); 2138*0b57cec5SDimitry Andric } 2139*0b57cec5SDimitry Andric 2140*0b57cec5SDimitry Andric static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) { 2141*0b57cec5SDimitry Andric // Set linkage and visibility in case we never see a definition. 2142*0b57cec5SDimitry Andric LinkageInfo LV = ND->getLinkageAndVisibility(); 2143*0b57cec5SDimitry Andric // Don't set internal linkage on declarations. 2144*0b57cec5SDimitry Andric // "extern_weak" is overloaded in LLVM; we probably should have 2145*0b57cec5SDimitry Andric // separate linkage types for this. 2146*0b57cec5SDimitry Andric if (isExternallyVisible(LV.getLinkage()) && 2147*0b57cec5SDimitry Andric (ND->hasAttr<WeakAttr>() || ND->isWeakImported())) 2148*0b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 2149*0b57cec5SDimitry Andric } 2150*0b57cec5SDimitry Andric 2151*0b57cec5SDimitry Andric void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, 2152*0b57cec5SDimitry Andric llvm::Function *F) { 2153*0b57cec5SDimitry Andric // Only if we are checking indirect calls. 2154*0b57cec5SDimitry Andric if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 2155*0b57cec5SDimitry Andric return; 2156*0b57cec5SDimitry Andric 2157*0b57cec5SDimitry Andric // Non-static class methods are handled via vtable or member function pointer 2158*0b57cec5SDimitry Andric // checks elsewhere. 2159*0b57cec5SDimitry Andric if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 2160*0b57cec5SDimitry Andric return; 2161*0b57cec5SDimitry Andric 2162*0b57cec5SDimitry Andric llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 2163*0b57cec5SDimitry Andric F->addTypeMetadata(0, MD); 2164*0b57cec5SDimitry Andric F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType())); 2165*0b57cec5SDimitry Andric 2166*0b57cec5SDimitry Andric // Emit a hash-based bit set entry for cross-DSO calls. 2167*0b57cec5SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 2168*0b57cec5SDimitry Andric if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 2169*0b57cec5SDimitry Andric F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 2170*0b57cec5SDimitry Andric } 2171*0b57cec5SDimitry Andric 2172*0b57cec5SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 2173*0b57cec5SDimitry Andric bool IsIncompleteFunction, 2174*0b57cec5SDimitry Andric bool IsThunk) { 2175*0b57cec5SDimitry Andric 2176*0b57cec5SDimitry Andric if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 2177*0b57cec5SDimitry Andric // If this is an intrinsic function, set the function's attributes 2178*0b57cec5SDimitry Andric // to the intrinsic's attributes. 2179*0b57cec5SDimitry Andric F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 2180*0b57cec5SDimitry Andric return; 2181*0b57cec5SDimitry Andric } 2182*0b57cec5SDimitry Andric 2183*0b57cec5SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 2184*0b57cec5SDimitry Andric 2185*0b57cec5SDimitry Andric if (!IsIncompleteFunction) 2186fe6060f1SDimitry Andric SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F, 2187fe6060f1SDimitry Andric IsThunk); 2188*0b57cec5SDimitry Andric 2189*0b57cec5SDimitry Andric // Add the Returned attribute for "this", except for iOS 5 and earlier 2190*0b57cec5SDimitry Andric // where substantial code, including the libstdc++ dylib, was compiled with 2191*0b57cec5SDimitry Andric // GCC and does not actually return "this". 2192*0b57cec5SDimitry Andric if (!IsThunk && getCXXABI().HasThisReturn(GD) && 2193*0b57cec5SDimitry Andric !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { 2194*0b57cec5SDimitry Andric assert(!F->arg_empty() && 2195*0b57cec5SDimitry Andric F->arg_begin()->getType() 2196*0b57cec5SDimitry Andric ->canLosslesslyBitCastTo(F->getReturnType()) && 2197*0b57cec5SDimitry Andric "unexpected this return"); 2198349cc55cSDimitry Andric F->addParamAttr(0, llvm::Attribute::Returned); 2199*0b57cec5SDimitry Andric } 2200*0b57cec5SDimitry Andric 2201*0b57cec5SDimitry Andric // Only a few attributes are set on declarations; these may later be 2202*0b57cec5SDimitry Andric // overridden by a definition. 2203*0b57cec5SDimitry Andric 2204*0b57cec5SDimitry Andric setLinkageForGV(F, FD); 2205*0b57cec5SDimitry Andric setGVProperties(F, FD); 2206*0b57cec5SDimitry Andric 2207*0b57cec5SDimitry Andric // Setup target-specific attributes. 2208*0b57cec5SDimitry Andric if (!IsIncompleteFunction && F->isDeclaration()) 2209*0b57cec5SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(FD, F, *this); 2210*0b57cec5SDimitry Andric 2211*0b57cec5SDimitry Andric if (const auto *CSA = FD->getAttr<CodeSegAttr>()) 2212*0b57cec5SDimitry Andric F->setSection(CSA->getName()); 2213*0b57cec5SDimitry Andric else if (const auto *SA = FD->getAttr<SectionAttr>()) 2214*0b57cec5SDimitry Andric F->setSection(SA->getName()); 2215*0b57cec5SDimitry Andric 2216349cc55cSDimitry Andric if (const auto *EA = FD->getAttr<ErrorAttr>()) { 2217349cc55cSDimitry Andric if (EA->isError()) 2218349cc55cSDimitry Andric F->addFnAttr("dontcall-error", EA->getUserDiagnostic()); 2219349cc55cSDimitry Andric else if (EA->isWarning()) 2220349cc55cSDimitry Andric F->addFnAttr("dontcall-warn", EA->getUserDiagnostic()); 2221349cc55cSDimitry Andric } 2222349cc55cSDimitry Andric 2223d65cd7a5SDimitry Andric // If we plan on emitting this inline builtin, we can't treat it as a builtin. 2224480093f4SDimitry Andric if (FD->isInlineBuiltinDeclaration()) { 2225d65cd7a5SDimitry Andric const FunctionDecl *FDBody; 2226d65cd7a5SDimitry Andric bool HasBody = FD->hasBody(FDBody); 2227d65cd7a5SDimitry Andric (void)HasBody; 2228d65cd7a5SDimitry Andric assert(HasBody && "Inline builtin declarations should always have an " 2229d65cd7a5SDimitry Andric "available body!"); 2230d65cd7a5SDimitry Andric if (shouldEmitFunction(FDBody)) 2231349cc55cSDimitry Andric F->addFnAttr(llvm::Attribute::NoBuiltin); 2232480093f4SDimitry Andric } 2233480093f4SDimitry Andric 2234*0b57cec5SDimitry Andric if (FD->isReplaceableGlobalAllocationFunction()) { 2235*0b57cec5SDimitry Andric // A replaceable global allocation function does not act like a builtin by 2236*0b57cec5SDimitry Andric // default, only if it is invoked by a new-expression or delete-expression. 2237349cc55cSDimitry Andric F->addFnAttr(llvm::Attribute::NoBuiltin); 2238*0b57cec5SDimitry Andric } 2239*0b57cec5SDimitry Andric 2240*0b57cec5SDimitry Andric if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 2241*0b57cec5SDimitry Andric F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2242*0b57cec5SDimitry Andric else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 2243*0b57cec5SDimitry Andric if (MD->isVirtual()) 2244*0b57cec5SDimitry Andric F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2245*0b57cec5SDimitry Andric 2246*0b57cec5SDimitry Andric // Don't emit entries for function declarations in the cross-DSO mode. This 2247a7dea167SDimitry Andric // is handled with better precision by the receiving DSO. But if jump tables 2248a7dea167SDimitry Andric // are non-canonical then we need type metadata in order to produce the local 2249a7dea167SDimitry Andric // jump table. 2250a7dea167SDimitry Andric if (!CodeGenOpts.SanitizeCfiCrossDso || 2251a7dea167SDimitry Andric !CodeGenOpts.SanitizeCfiCanonicalJumpTables) 2252*0b57cec5SDimitry Andric CreateFunctionTypeMetadataForIcall(FD, F); 2253*0b57cec5SDimitry Andric 2254*0b57cec5SDimitry Andric if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) 2255*0b57cec5SDimitry Andric getOpenMPRuntime().emitDeclareSimdFunction(FD, F); 2256*0b57cec5SDimitry Andric 2257*0b57cec5SDimitry Andric if (const auto *CB = FD->getAttr<CallbackAttr>()) { 2258*0b57cec5SDimitry Andric // Annotate the callback behavior as metadata: 2259*0b57cec5SDimitry Andric // - The callback callee (as argument number). 2260*0b57cec5SDimitry Andric // - The callback payloads (as argument numbers). 2261*0b57cec5SDimitry Andric llvm::LLVMContext &Ctx = F->getContext(); 2262*0b57cec5SDimitry Andric llvm::MDBuilder MDB(Ctx); 2263*0b57cec5SDimitry Andric 2264*0b57cec5SDimitry Andric // The payload indices are all but the first one in the encoding. The first 2265*0b57cec5SDimitry Andric // identifies the callback callee. 2266*0b57cec5SDimitry Andric int CalleeIdx = *CB->encoding_begin(); 2267*0b57cec5SDimitry Andric ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end()); 2268*0b57cec5SDimitry Andric F->addMetadata(llvm::LLVMContext::MD_callback, 2269*0b57cec5SDimitry Andric *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding( 2270*0b57cec5SDimitry Andric CalleeIdx, PayloadIndices, 2271*0b57cec5SDimitry Andric /* VarArgsArePassed */ false)})); 2272*0b57cec5SDimitry Andric } 2273*0b57cec5SDimitry Andric } 2274*0b57cec5SDimitry Andric 2275*0b57cec5SDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 2276e8d8bef9SDimitry Andric assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 2277*0b57cec5SDimitry Andric "Only globals with definition can force usage."); 2278*0b57cec5SDimitry Andric LLVMUsed.emplace_back(GV); 2279*0b57cec5SDimitry Andric } 2280*0b57cec5SDimitry Andric 2281*0b57cec5SDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 2282*0b57cec5SDimitry Andric assert(!GV->isDeclaration() && 2283*0b57cec5SDimitry Andric "Only globals with definition can force usage."); 2284*0b57cec5SDimitry Andric LLVMCompilerUsed.emplace_back(GV); 2285*0b57cec5SDimitry Andric } 2286*0b57cec5SDimitry Andric 2287fe6060f1SDimitry Andric void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) { 2288fe6060f1SDimitry Andric assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 2289fe6060f1SDimitry Andric "Only globals with definition can force usage."); 2290fe6060f1SDimitry Andric if (getTriple().isOSBinFormatELF()) 2291fe6060f1SDimitry Andric LLVMCompilerUsed.emplace_back(GV); 2292fe6060f1SDimitry Andric else 2293fe6060f1SDimitry Andric LLVMUsed.emplace_back(GV); 2294fe6060f1SDimitry Andric } 2295fe6060f1SDimitry Andric 2296*0b57cec5SDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name, 2297*0b57cec5SDimitry Andric std::vector<llvm::WeakTrackingVH> &List) { 2298*0b57cec5SDimitry Andric // Don't create llvm.used if there is no need. 2299*0b57cec5SDimitry Andric if (List.empty()) 2300*0b57cec5SDimitry Andric return; 2301*0b57cec5SDimitry Andric 2302*0b57cec5SDimitry Andric // Convert List to what ConstantArray needs. 2303*0b57cec5SDimitry Andric SmallVector<llvm::Constant*, 8> UsedArray; 2304*0b57cec5SDimitry Andric UsedArray.resize(List.size()); 2305*0b57cec5SDimitry Andric for (unsigned i = 0, e = List.size(); i != e; ++i) { 2306*0b57cec5SDimitry Andric UsedArray[i] = 2307*0b57cec5SDimitry Andric llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 2308*0b57cec5SDimitry Andric cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 2309*0b57cec5SDimitry Andric } 2310*0b57cec5SDimitry Andric 2311*0b57cec5SDimitry Andric if (UsedArray.empty()) 2312*0b57cec5SDimitry Andric return; 2313*0b57cec5SDimitry Andric llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 2314*0b57cec5SDimitry Andric 2315*0b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 2316*0b57cec5SDimitry Andric CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 2317*0b57cec5SDimitry Andric llvm::ConstantArray::get(ATy, UsedArray), Name); 2318*0b57cec5SDimitry Andric 2319*0b57cec5SDimitry Andric GV->setSection("llvm.metadata"); 2320*0b57cec5SDimitry Andric } 2321*0b57cec5SDimitry Andric 2322*0b57cec5SDimitry Andric void CodeGenModule::emitLLVMUsed() { 2323*0b57cec5SDimitry Andric emitUsed(*this, "llvm.used", LLVMUsed); 2324*0b57cec5SDimitry Andric emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 2325*0b57cec5SDimitry Andric } 2326*0b57cec5SDimitry Andric 2327*0b57cec5SDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 2328*0b57cec5SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 2329*0b57cec5SDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 2330*0b57cec5SDimitry Andric } 2331*0b57cec5SDimitry Andric 2332*0b57cec5SDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 2333*0b57cec5SDimitry Andric llvm::SmallString<32> Opt; 2334*0b57cec5SDimitry Andric getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 2335480093f4SDimitry Andric if (Opt.empty()) 2336480093f4SDimitry Andric return; 2337*0b57cec5SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 2338*0b57cec5SDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 2339*0b57cec5SDimitry Andric } 2340*0b57cec5SDimitry Andric 2341*0b57cec5SDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) { 2342*0b57cec5SDimitry Andric auto &C = getLLVMContext(); 2343*0b57cec5SDimitry Andric if (getTarget().getTriple().isOSBinFormatELF()) { 2344*0b57cec5SDimitry Andric ELFDependentLibraries.push_back( 2345*0b57cec5SDimitry Andric llvm::MDNode::get(C, llvm::MDString::get(C, Lib))); 2346*0b57cec5SDimitry Andric return; 2347*0b57cec5SDimitry Andric } 2348*0b57cec5SDimitry Andric 2349*0b57cec5SDimitry Andric llvm::SmallString<24> Opt; 2350*0b57cec5SDimitry Andric getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 2351*0b57cec5SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 2352*0b57cec5SDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts)); 2353*0b57cec5SDimitry Andric } 2354*0b57cec5SDimitry Andric 2355*0b57cec5SDimitry Andric /// Add link options implied by the given module, including modules 2356*0b57cec5SDimitry Andric /// it depends on, using a postorder walk. 2357*0b57cec5SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 2358*0b57cec5SDimitry Andric SmallVectorImpl<llvm::MDNode *> &Metadata, 2359*0b57cec5SDimitry Andric llvm::SmallPtrSet<Module *, 16> &Visited) { 2360*0b57cec5SDimitry Andric // Import this module's parent. 2361*0b57cec5SDimitry Andric if (Mod->Parent && Visited.insert(Mod->Parent).second) { 2362*0b57cec5SDimitry Andric addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 2363*0b57cec5SDimitry Andric } 2364*0b57cec5SDimitry Andric 2365*0b57cec5SDimitry Andric // Import this module's dependencies. 2366349cc55cSDimitry Andric for (Module *Import : llvm::reverse(Mod->Imports)) { 2367349cc55cSDimitry Andric if (Visited.insert(Import).second) 2368349cc55cSDimitry Andric addLinkOptionsPostorder(CGM, Import, Metadata, Visited); 2369*0b57cec5SDimitry Andric } 2370*0b57cec5SDimitry Andric 2371*0b57cec5SDimitry Andric // Add linker options to link against the libraries/frameworks 2372*0b57cec5SDimitry Andric // described by this module. 2373*0b57cec5SDimitry Andric llvm::LLVMContext &Context = CGM.getLLVMContext(); 2374*0b57cec5SDimitry Andric bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF(); 2375*0b57cec5SDimitry Andric 2376*0b57cec5SDimitry Andric // For modules that use export_as for linking, use that module 2377*0b57cec5SDimitry Andric // name instead. 2378*0b57cec5SDimitry Andric if (Mod->UseExportAsModuleLinkName) 2379*0b57cec5SDimitry Andric return; 2380*0b57cec5SDimitry Andric 2381349cc55cSDimitry Andric for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) { 2382*0b57cec5SDimitry Andric // Link against a framework. Frameworks are currently Darwin only, so we 2383*0b57cec5SDimitry Andric // don't to ask TargetCodeGenInfo for the spelling of the linker option. 2384349cc55cSDimitry Andric if (LL.IsFramework) { 2385349cc55cSDimitry Andric llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"), 2386349cc55cSDimitry Andric llvm::MDString::get(Context, LL.Library)}; 2387*0b57cec5SDimitry Andric 2388*0b57cec5SDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, Args)); 2389*0b57cec5SDimitry Andric continue; 2390*0b57cec5SDimitry Andric } 2391*0b57cec5SDimitry Andric 2392*0b57cec5SDimitry Andric // Link against a library. 2393*0b57cec5SDimitry Andric if (IsELF) { 2394*0b57cec5SDimitry Andric llvm::Metadata *Args[2] = { 2395*0b57cec5SDimitry Andric llvm::MDString::get(Context, "lib"), 2396349cc55cSDimitry Andric llvm::MDString::get(Context, LL.Library), 2397*0b57cec5SDimitry Andric }; 2398*0b57cec5SDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, Args)); 2399*0b57cec5SDimitry Andric } else { 2400*0b57cec5SDimitry Andric llvm::SmallString<24> Opt; 2401349cc55cSDimitry Andric CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt); 2402*0b57cec5SDimitry Andric auto *OptString = llvm::MDString::get(Context, Opt); 2403*0b57cec5SDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, OptString)); 2404*0b57cec5SDimitry Andric } 2405*0b57cec5SDimitry Andric } 2406*0b57cec5SDimitry Andric } 2407*0b57cec5SDimitry Andric 2408*0b57cec5SDimitry Andric void CodeGenModule::EmitModuleLinkOptions() { 2409*0b57cec5SDimitry Andric // Collect the set of all of the modules we want to visit to emit link 2410*0b57cec5SDimitry Andric // options, which is essentially the imported modules and all of their 2411*0b57cec5SDimitry Andric // non-explicit child modules. 2412*0b57cec5SDimitry Andric llvm::SetVector<clang::Module *> LinkModules; 2413*0b57cec5SDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 2414*0b57cec5SDimitry Andric SmallVector<clang::Module *, 16> Stack; 2415*0b57cec5SDimitry Andric 2416*0b57cec5SDimitry Andric // Seed the stack with imported modules. 2417*0b57cec5SDimitry Andric for (Module *M : ImportedModules) { 2418*0b57cec5SDimitry Andric // Do not add any link flags when an implementation TU of a module imports 2419*0b57cec5SDimitry Andric // a header of that same module. 2420*0b57cec5SDimitry Andric if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && 2421*0b57cec5SDimitry Andric !getLangOpts().isCompilingModule()) 2422*0b57cec5SDimitry Andric continue; 2423*0b57cec5SDimitry Andric if (Visited.insert(M).second) 2424*0b57cec5SDimitry Andric Stack.push_back(M); 2425*0b57cec5SDimitry Andric } 2426*0b57cec5SDimitry Andric 2427*0b57cec5SDimitry Andric // Find all of the modules to import, making a little effort to prune 2428*0b57cec5SDimitry Andric // non-leaf modules. 2429*0b57cec5SDimitry Andric while (!Stack.empty()) { 2430*0b57cec5SDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 2431*0b57cec5SDimitry Andric 2432*0b57cec5SDimitry Andric bool AnyChildren = false; 2433*0b57cec5SDimitry Andric 2434*0b57cec5SDimitry Andric // Visit the submodules of this module. 2435*0b57cec5SDimitry Andric for (const auto &SM : Mod->submodules()) { 2436*0b57cec5SDimitry Andric // Skip explicit children; they need to be explicitly imported to be 2437*0b57cec5SDimitry Andric // linked against. 2438*0b57cec5SDimitry Andric if (SM->IsExplicit) 2439*0b57cec5SDimitry Andric continue; 2440*0b57cec5SDimitry Andric 2441*0b57cec5SDimitry Andric if (Visited.insert(SM).second) { 2442*0b57cec5SDimitry Andric Stack.push_back(SM); 2443*0b57cec5SDimitry Andric AnyChildren = true; 2444*0b57cec5SDimitry Andric } 2445*0b57cec5SDimitry Andric } 2446*0b57cec5SDimitry Andric 2447*0b57cec5SDimitry Andric // We didn't find any children, so add this module to the list of 2448*0b57cec5SDimitry Andric // modules to link against. 2449*0b57cec5SDimitry Andric if (!AnyChildren) { 2450*0b57cec5SDimitry Andric LinkModules.insert(Mod); 2451*0b57cec5SDimitry Andric } 2452*0b57cec5SDimitry Andric } 2453*0b57cec5SDimitry Andric 2454*0b57cec5SDimitry Andric // Add link options for all of the imported modules in reverse topological 2455*0b57cec5SDimitry Andric // order. We don't do anything to try to order import link flags with respect 2456*0b57cec5SDimitry Andric // to linker options inserted by things like #pragma comment(). 2457*0b57cec5SDimitry Andric SmallVector<llvm::MDNode *, 16> MetadataArgs; 2458*0b57cec5SDimitry Andric Visited.clear(); 2459*0b57cec5SDimitry Andric for (Module *M : LinkModules) 2460*0b57cec5SDimitry Andric if (Visited.insert(M).second) 2461*0b57cec5SDimitry Andric addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 2462*0b57cec5SDimitry Andric std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 2463*0b57cec5SDimitry Andric LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 2464*0b57cec5SDimitry Andric 2465*0b57cec5SDimitry Andric // Add the linker options metadata flag. 2466*0b57cec5SDimitry Andric auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options"); 2467*0b57cec5SDimitry Andric for (auto *MD : LinkerOptionsMetadata) 2468*0b57cec5SDimitry Andric NMD->addOperand(MD); 2469*0b57cec5SDimitry Andric } 2470*0b57cec5SDimitry Andric 2471*0b57cec5SDimitry Andric void CodeGenModule::EmitDeferred() { 2472*0b57cec5SDimitry Andric // Emit deferred declare target declarations. 2473*0b57cec5SDimitry Andric if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 2474*0b57cec5SDimitry Andric getOpenMPRuntime().emitDeferredTargetDecls(); 2475*0b57cec5SDimitry Andric 2476*0b57cec5SDimitry Andric // Emit code for any potentially referenced deferred decls. Since a 2477*0b57cec5SDimitry Andric // previously unused static decl may become used during the generation of code 2478*0b57cec5SDimitry Andric // for a static function, iterate until no changes are made. 2479*0b57cec5SDimitry Andric 2480*0b57cec5SDimitry Andric if (!DeferredVTables.empty()) { 2481*0b57cec5SDimitry Andric EmitDeferredVTables(); 2482*0b57cec5SDimitry Andric 2483*0b57cec5SDimitry Andric // Emitting a vtable doesn't directly cause more vtables to 2484*0b57cec5SDimitry Andric // become deferred, although it can cause functions to be 2485*0b57cec5SDimitry Andric // emitted that then need those vtables. 2486*0b57cec5SDimitry Andric assert(DeferredVTables.empty()); 2487*0b57cec5SDimitry Andric } 2488*0b57cec5SDimitry Andric 2489e8d8bef9SDimitry Andric // Emit CUDA/HIP static device variables referenced by host code only. 2490fe6060f1SDimitry Andric // Note we should not clear CUDADeviceVarODRUsedByHost since it is still 2491fe6060f1SDimitry Andric // needed for further handling. 2492fe6060f1SDimitry Andric if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) 2493fe6060f1SDimitry Andric for (const auto *V : getContext().CUDADeviceVarODRUsedByHost) 2494e8d8bef9SDimitry Andric DeferredDeclsToEmit.push_back(V); 2495e8d8bef9SDimitry Andric 2496*0b57cec5SDimitry Andric // Stop if we're out of both deferred vtables and deferred declarations. 2497*0b57cec5SDimitry Andric if (DeferredDeclsToEmit.empty()) 2498*0b57cec5SDimitry Andric return; 2499*0b57cec5SDimitry Andric 2500*0b57cec5SDimitry Andric // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 2501*0b57cec5SDimitry Andric // work, it will not interfere with this. 2502*0b57cec5SDimitry Andric std::vector<GlobalDecl> CurDeclsToEmit; 2503*0b57cec5SDimitry Andric CurDeclsToEmit.swap(DeferredDeclsToEmit); 2504*0b57cec5SDimitry Andric 2505*0b57cec5SDimitry Andric for (GlobalDecl &D : CurDeclsToEmit) { 2506*0b57cec5SDimitry Andric // We should call GetAddrOfGlobal with IsForDefinition set to true in order 2507*0b57cec5SDimitry Andric // to get GlobalValue with exactly the type we need, not something that 2508*0b57cec5SDimitry Andric // might had been created for another decl with the same mangled name but 2509*0b57cec5SDimitry Andric // different type. 2510*0b57cec5SDimitry Andric llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 2511*0b57cec5SDimitry Andric GetAddrOfGlobal(D, ForDefinition)); 2512*0b57cec5SDimitry Andric 2513*0b57cec5SDimitry Andric // In case of different address spaces, we may still get a cast, even with 2514*0b57cec5SDimitry Andric // IsForDefinition equal to true. Query mangled names table to get 2515*0b57cec5SDimitry Andric // GlobalValue. 2516*0b57cec5SDimitry Andric if (!GV) 2517*0b57cec5SDimitry Andric GV = GetGlobalValue(getMangledName(D)); 2518*0b57cec5SDimitry Andric 2519*0b57cec5SDimitry Andric // Make sure GetGlobalValue returned non-null. 2520*0b57cec5SDimitry Andric assert(GV); 2521*0b57cec5SDimitry Andric 2522*0b57cec5SDimitry Andric // Check to see if we've already emitted this. This is necessary 2523*0b57cec5SDimitry Andric // for a couple of reasons: first, decls can end up in the 2524*0b57cec5SDimitry Andric // deferred-decls queue multiple times, and second, decls can end 2525*0b57cec5SDimitry Andric // up with definitions in unusual ways (e.g. by an extern inline 2526*0b57cec5SDimitry Andric // function acquiring a strong function redefinition). Just 2527*0b57cec5SDimitry Andric // ignore these cases. 2528*0b57cec5SDimitry Andric if (!GV->isDeclaration()) 2529*0b57cec5SDimitry Andric continue; 2530*0b57cec5SDimitry Andric 2531a7dea167SDimitry Andric // If this is OpenMP, check if it is legal to emit this global normally. 2532a7dea167SDimitry Andric if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D)) 2533a7dea167SDimitry Andric continue; 2534a7dea167SDimitry Andric 2535*0b57cec5SDimitry Andric // Otherwise, emit the definition and move on to the next one. 2536*0b57cec5SDimitry Andric EmitGlobalDefinition(D, GV); 2537*0b57cec5SDimitry Andric 2538*0b57cec5SDimitry Andric // If we found out that we need to emit more decls, do that recursively. 2539*0b57cec5SDimitry Andric // This has the advantage that the decls are emitted in a DFS and related 2540*0b57cec5SDimitry Andric // ones are close together, which is convenient for testing. 2541*0b57cec5SDimitry Andric if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 2542*0b57cec5SDimitry Andric EmitDeferred(); 2543*0b57cec5SDimitry Andric assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 2544*0b57cec5SDimitry Andric } 2545*0b57cec5SDimitry Andric } 2546*0b57cec5SDimitry Andric } 2547*0b57cec5SDimitry Andric 2548*0b57cec5SDimitry Andric void CodeGenModule::EmitVTablesOpportunistically() { 2549*0b57cec5SDimitry Andric // Try to emit external vtables as available_externally if they have emitted 2550*0b57cec5SDimitry Andric // all inlined virtual functions. It runs after EmitDeferred() and therefore 2551*0b57cec5SDimitry Andric // is not allowed to create new references to things that need to be emitted 2552*0b57cec5SDimitry Andric // lazily. Note that it also uses fact that we eagerly emitting RTTI. 2553*0b57cec5SDimitry Andric 2554*0b57cec5SDimitry Andric assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) 2555*0b57cec5SDimitry Andric && "Only emit opportunistic vtables with optimizations"); 2556*0b57cec5SDimitry Andric 2557*0b57cec5SDimitry Andric for (const CXXRecordDecl *RD : OpportunisticVTables) { 2558*0b57cec5SDimitry Andric assert(getVTables().isVTableExternal(RD) && 2559*0b57cec5SDimitry Andric "This queue should only contain external vtables"); 2560*0b57cec5SDimitry Andric if (getCXXABI().canSpeculativelyEmitVTable(RD)) 2561*0b57cec5SDimitry Andric VTables.GenerateClassData(RD); 2562*0b57cec5SDimitry Andric } 2563*0b57cec5SDimitry Andric OpportunisticVTables.clear(); 2564*0b57cec5SDimitry Andric } 2565*0b57cec5SDimitry Andric 2566*0b57cec5SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() { 2567*0b57cec5SDimitry Andric if (Annotations.empty()) 2568*0b57cec5SDimitry Andric return; 2569*0b57cec5SDimitry Andric 2570*0b57cec5SDimitry Andric // Create a new global variable for the ConstantStruct in the Module. 2571*0b57cec5SDimitry Andric llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 2572*0b57cec5SDimitry Andric Annotations[0]->getType(), Annotations.size()), Annotations); 2573*0b57cec5SDimitry Andric auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 2574*0b57cec5SDimitry Andric llvm::GlobalValue::AppendingLinkage, 2575*0b57cec5SDimitry Andric Array, "llvm.global.annotations"); 2576*0b57cec5SDimitry Andric gv->setSection(AnnotationSection); 2577*0b57cec5SDimitry Andric } 2578*0b57cec5SDimitry Andric 2579*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 2580*0b57cec5SDimitry Andric llvm::Constant *&AStr = AnnotationStrings[Str]; 2581*0b57cec5SDimitry Andric if (AStr) 2582*0b57cec5SDimitry Andric return AStr; 2583*0b57cec5SDimitry Andric 2584*0b57cec5SDimitry Andric // Not found yet, create a new global. 2585*0b57cec5SDimitry Andric llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 2586*0b57cec5SDimitry Andric auto *gv = 2587*0b57cec5SDimitry Andric new llvm::GlobalVariable(getModule(), s->getType(), true, 2588*0b57cec5SDimitry Andric llvm::GlobalValue::PrivateLinkage, s, ".str"); 2589*0b57cec5SDimitry Andric gv->setSection(AnnotationSection); 2590*0b57cec5SDimitry Andric gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2591*0b57cec5SDimitry Andric AStr = gv; 2592*0b57cec5SDimitry Andric return gv; 2593*0b57cec5SDimitry Andric } 2594*0b57cec5SDimitry Andric 2595*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 2596*0b57cec5SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 2597*0b57cec5SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(Loc); 2598*0b57cec5SDimitry Andric if (PLoc.isValid()) 2599*0b57cec5SDimitry Andric return EmitAnnotationString(PLoc.getFilename()); 2600*0b57cec5SDimitry Andric return EmitAnnotationString(SM.getBufferName(Loc)); 2601*0b57cec5SDimitry Andric } 2602*0b57cec5SDimitry Andric 2603*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 2604*0b57cec5SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 2605*0b57cec5SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(L); 2606*0b57cec5SDimitry Andric unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 2607*0b57cec5SDimitry Andric SM.getExpansionLineNumber(L); 2608*0b57cec5SDimitry Andric return llvm::ConstantInt::get(Int32Ty, LineNo); 2609*0b57cec5SDimitry Andric } 2610*0b57cec5SDimitry Andric 2611e8d8bef9SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) { 2612e8d8bef9SDimitry Andric ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()}; 2613e8d8bef9SDimitry Andric if (Exprs.empty()) 2614349cc55cSDimitry Andric return llvm::ConstantPointerNull::get(GlobalsInt8PtrTy); 2615e8d8bef9SDimitry Andric 2616e8d8bef9SDimitry Andric llvm::FoldingSetNodeID ID; 2617e8d8bef9SDimitry Andric for (Expr *E : Exprs) { 2618e8d8bef9SDimitry Andric ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult()); 2619e8d8bef9SDimitry Andric } 2620e8d8bef9SDimitry Andric llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()]; 2621e8d8bef9SDimitry Andric if (Lookup) 2622e8d8bef9SDimitry Andric return Lookup; 2623e8d8bef9SDimitry Andric 2624e8d8bef9SDimitry Andric llvm::SmallVector<llvm::Constant *, 4> LLVMArgs; 2625e8d8bef9SDimitry Andric LLVMArgs.reserve(Exprs.size()); 2626e8d8bef9SDimitry Andric ConstantEmitter ConstEmiter(*this); 2627e8d8bef9SDimitry Andric llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) { 2628e8d8bef9SDimitry Andric const auto *CE = cast<clang::ConstantExpr>(E); 2629e8d8bef9SDimitry Andric return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(), 2630e8d8bef9SDimitry Andric CE->getType()); 2631e8d8bef9SDimitry Andric }); 2632e8d8bef9SDimitry Andric auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs); 2633e8d8bef9SDimitry Andric auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true, 2634e8d8bef9SDimitry Andric llvm::GlobalValue::PrivateLinkage, Struct, 2635e8d8bef9SDimitry Andric ".args"); 2636e8d8bef9SDimitry Andric GV->setSection(AnnotationSection); 2637e8d8bef9SDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2638349cc55cSDimitry Andric auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, GlobalsInt8PtrTy); 2639e8d8bef9SDimitry Andric 2640e8d8bef9SDimitry Andric Lookup = Bitcasted; 2641e8d8bef9SDimitry Andric return Bitcasted; 2642e8d8bef9SDimitry Andric } 2643e8d8bef9SDimitry Andric 2644*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 2645*0b57cec5SDimitry Andric const AnnotateAttr *AA, 2646*0b57cec5SDimitry Andric SourceLocation L) { 2647*0b57cec5SDimitry Andric // Get the globals for file name, annotation, and the line number. 2648*0b57cec5SDimitry Andric llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 2649*0b57cec5SDimitry Andric *UnitGV = EmitAnnotationUnit(L), 2650e8d8bef9SDimitry Andric *LineNoCst = EmitAnnotationLineNo(L), 2651e8d8bef9SDimitry Andric *Args = EmitAnnotationArgs(AA); 2652*0b57cec5SDimitry Andric 2653349cc55cSDimitry Andric llvm::Constant *GVInGlobalsAS = GV; 2654349cc55cSDimitry Andric if (GV->getAddressSpace() != 2655349cc55cSDimitry Andric getDataLayout().getDefaultGlobalsAddressSpace()) { 2656349cc55cSDimitry Andric GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast( 2657349cc55cSDimitry Andric GV, GV->getValueType()->getPointerTo( 2658349cc55cSDimitry Andric getDataLayout().getDefaultGlobalsAddressSpace())); 2659480093f4SDimitry Andric } 2660480093f4SDimitry Andric 2661*0b57cec5SDimitry Andric // Create the ConstantStruct for the global annotation. 2662e8d8bef9SDimitry Andric llvm::Constant *Fields[] = { 2663349cc55cSDimitry Andric llvm::ConstantExpr::getBitCast(GVInGlobalsAS, GlobalsInt8PtrTy), 2664349cc55cSDimitry Andric llvm::ConstantExpr::getBitCast(AnnoGV, GlobalsInt8PtrTy), 2665349cc55cSDimitry Andric llvm::ConstantExpr::getBitCast(UnitGV, GlobalsInt8PtrTy), 2666e8d8bef9SDimitry Andric LineNoCst, 2667e8d8bef9SDimitry Andric Args, 2668*0b57cec5SDimitry Andric }; 2669*0b57cec5SDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 2670*0b57cec5SDimitry Andric } 2671*0b57cec5SDimitry Andric 2672*0b57cec5SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 2673*0b57cec5SDimitry Andric llvm::GlobalValue *GV) { 2674*0b57cec5SDimitry Andric assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 2675*0b57cec5SDimitry Andric // Get the struct elements for these annotations. 2676*0b57cec5SDimitry Andric for (const auto *I : D->specific_attrs<AnnotateAttr>()) 2677*0b57cec5SDimitry Andric Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 2678*0b57cec5SDimitry Andric } 2679*0b57cec5SDimitry Andric 2680fe6060f1SDimitry Andric bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, 2681*0b57cec5SDimitry Andric SourceLocation Loc) const { 2682fe6060f1SDimitry Andric const auto &NoSanitizeL = getContext().getNoSanitizeList(); 2683fe6060f1SDimitry Andric // NoSanitize by function name. 2684fe6060f1SDimitry Andric if (NoSanitizeL.containsFunction(Kind, Fn->getName())) 2685*0b57cec5SDimitry Andric return true; 2686fe6060f1SDimitry Andric // NoSanitize by location. 2687*0b57cec5SDimitry Andric if (Loc.isValid()) 2688fe6060f1SDimitry Andric return NoSanitizeL.containsLocation(Kind, Loc); 2689*0b57cec5SDimitry Andric // If location is unknown, this may be a compiler-generated function. Assume 2690*0b57cec5SDimitry Andric // it's located in the main file. 2691*0b57cec5SDimitry Andric auto &SM = Context.getSourceManager(); 2692*0b57cec5SDimitry Andric if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 2693fe6060f1SDimitry Andric return NoSanitizeL.containsFile(Kind, MainFile->getName()); 2694*0b57cec5SDimitry Andric } 2695*0b57cec5SDimitry Andric return false; 2696*0b57cec5SDimitry Andric } 2697*0b57cec5SDimitry Andric 2698fe6060f1SDimitry Andric bool CodeGenModule::isInNoSanitizeList(llvm::GlobalVariable *GV, 2699*0b57cec5SDimitry Andric SourceLocation Loc, QualType Ty, 2700*0b57cec5SDimitry Andric StringRef Category) const { 2701fe6060f1SDimitry Andric // For now globals can be ignored only in ASan and KASan. 2702*0b57cec5SDimitry Andric const SanitizerMask EnabledAsanMask = 2703*0b57cec5SDimitry Andric LangOpts.Sanitize.Mask & 2704*0b57cec5SDimitry Andric (SanitizerKind::Address | SanitizerKind::KernelAddress | 2705*0b57cec5SDimitry Andric SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress | 2706*0b57cec5SDimitry Andric SanitizerKind::MemTag); 2707*0b57cec5SDimitry Andric if (!EnabledAsanMask) 2708*0b57cec5SDimitry Andric return false; 2709fe6060f1SDimitry Andric const auto &NoSanitizeL = getContext().getNoSanitizeList(); 2710fe6060f1SDimitry Andric if (NoSanitizeL.containsGlobal(EnabledAsanMask, GV->getName(), Category)) 2711*0b57cec5SDimitry Andric return true; 2712fe6060f1SDimitry Andric if (NoSanitizeL.containsLocation(EnabledAsanMask, Loc, Category)) 2713*0b57cec5SDimitry Andric return true; 2714*0b57cec5SDimitry Andric // Check global type. 2715*0b57cec5SDimitry Andric if (!Ty.isNull()) { 2716*0b57cec5SDimitry Andric // Drill down the array types: if global variable of a fixed type is 2717fe6060f1SDimitry Andric // not sanitized, we also don't instrument arrays of them. 2718*0b57cec5SDimitry Andric while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 2719*0b57cec5SDimitry Andric Ty = AT->getElementType(); 2720*0b57cec5SDimitry Andric Ty = Ty.getCanonicalType().getUnqualifiedType(); 2721fe6060f1SDimitry Andric // Only record types (classes, structs etc.) are ignored. 2722*0b57cec5SDimitry Andric if (Ty->isRecordType()) { 2723*0b57cec5SDimitry Andric std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 2724fe6060f1SDimitry Andric if (NoSanitizeL.containsType(EnabledAsanMask, TypeStr, Category)) 2725*0b57cec5SDimitry Andric return true; 2726*0b57cec5SDimitry Andric } 2727*0b57cec5SDimitry Andric } 2728*0b57cec5SDimitry Andric return false; 2729*0b57cec5SDimitry Andric } 2730*0b57cec5SDimitry Andric 2731*0b57cec5SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 2732*0b57cec5SDimitry Andric StringRef Category) const { 2733*0b57cec5SDimitry Andric const auto &XRayFilter = getContext().getXRayFilter(); 2734*0b57cec5SDimitry Andric using ImbueAttr = XRayFunctionFilter::ImbueAttribute; 2735*0b57cec5SDimitry Andric auto Attr = ImbueAttr::NONE; 2736*0b57cec5SDimitry Andric if (Loc.isValid()) 2737*0b57cec5SDimitry Andric Attr = XRayFilter.shouldImbueLocation(Loc, Category); 2738*0b57cec5SDimitry Andric if (Attr == ImbueAttr::NONE) 2739*0b57cec5SDimitry Andric Attr = XRayFilter.shouldImbueFunction(Fn->getName()); 2740*0b57cec5SDimitry Andric switch (Attr) { 2741*0b57cec5SDimitry Andric case ImbueAttr::NONE: 2742*0b57cec5SDimitry Andric return false; 2743*0b57cec5SDimitry Andric case ImbueAttr::ALWAYS: 2744*0b57cec5SDimitry Andric Fn->addFnAttr("function-instrument", "xray-always"); 2745*0b57cec5SDimitry Andric break; 2746*0b57cec5SDimitry Andric case ImbueAttr::ALWAYS_ARG1: 2747*0b57cec5SDimitry Andric Fn->addFnAttr("function-instrument", "xray-always"); 2748*0b57cec5SDimitry Andric Fn->addFnAttr("xray-log-args", "1"); 2749*0b57cec5SDimitry Andric break; 2750*0b57cec5SDimitry Andric case ImbueAttr::NEVER: 2751*0b57cec5SDimitry Andric Fn->addFnAttr("function-instrument", "xray-never"); 2752*0b57cec5SDimitry Andric break; 2753*0b57cec5SDimitry Andric } 2754*0b57cec5SDimitry Andric return true; 2755*0b57cec5SDimitry Andric } 2756*0b57cec5SDimitry Andric 2757e8d8bef9SDimitry Andric bool CodeGenModule::isProfileInstrExcluded(llvm::Function *Fn, 2758e8d8bef9SDimitry Andric SourceLocation Loc) const { 2759e8d8bef9SDimitry Andric const auto &ProfileList = getContext().getProfileList(); 2760e8d8bef9SDimitry Andric // If the profile list is empty, then instrument everything. 2761e8d8bef9SDimitry Andric if (ProfileList.isEmpty()) 2762e8d8bef9SDimitry Andric return false; 2763e8d8bef9SDimitry Andric CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr(); 2764e8d8bef9SDimitry Andric // First, check the function name. 2765e8d8bef9SDimitry Andric Optional<bool> V = ProfileList.isFunctionExcluded(Fn->getName(), Kind); 2766e8d8bef9SDimitry Andric if (V.hasValue()) 2767e8d8bef9SDimitry Andric return *V; 2768e8d8bef9SDimitry Andric // Next, check the source location. 2769e8d8bef9SDimitry Andric if (Loc.isValid()) { 2770e8d8bef9SDimitry Andric Optional<bool> V = ProfileList.isLocationExcluded(Loc, Kind); 2771e8d8bef9SDimitry Andric if (V.hasValue()) 2772e8d8bef9SDimitry Andric return *V; 2773e8d8bef9SDimitry Andric } 2774e8d8bef9SDimitry Andric // If location is unknown, this may be a compiler-generated function. Assume 2775e8d8bef9SDimitry Andric // it's located in the main file. 2776e8d8bef9SDimitry Andric auto &SM = Context.getSourceManager(); 2777e8d8bef9SDimitry Andric if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 2778e8d8bef9SDimitry Andric Optional<bool> V = ProfileList.isFileExcluded(MainFile->getName(), Kind); 2779e8d8bef9SDimitry Andric if (V.hasValue()) 2780e8d8bef9SDimitry Andric return *V; 2781e8d8bef9SDimitry Andric } 2782e8d8bef9SDimitry Andric return ProfileList.getDefault(); 2783e8d8bef9SDimitry Andric } 2784e8d8bef9SDimitry Andric 2785*0b57cec5SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 2786*0b57cec5SDimitry Andric // Never defer when EmitAllDecls is specified. 2787*0b57cec5SDimitry Andric if (LangOpts.EmitAllDecls) 2788*0b57cec5SDimitry Andric return true; 2789*0b57cec5SDimitry Andric 2790*0b57cec5SDimitry Andric if (CodeGenOpts.KeepStaticConsts) { 2791*0b57cec5SDimitry Andric const auto *VD = dyn_cast<VarDecl>(Global); 2792*0b57cec5SDimitry Andric if (VD && VD->getType().isConstQualified() && 2793*0b57cec5SDimitry Andric VD->getStorageDuration() == SD_Static) 2794*0b57cec5SDimitry Andric return true; 2795*0b57cec5SDimitry Andric } 2796*0b57cec5SDimitry Andric 2797*0b57cec5SDimitry Andric return getContext().DeclMustBeEmitted(Global); 2798*0b57cec5SDimitry Andric } 2799*0b57cec5SDimitry Andric 2800*0b57cec5SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 2801fe6060f1SDimitry Andric // In OpenMP 5.0 variables and function may be marked as 2802fe6060f1SDimitry Andric // device_type(host/nohost) and we should not emit them eagerly unless we sure 2803fe6060f1SDimitry Andric // that they must be emitted on the host/device. To be sure we need to have 2804fe6060f1SDimitry Andric // seen a declare target with an explicit mentioning of the function, we know 2805fe6060f1SDimitry Andric // we have if the level of the declare target attribute is -1. Note that we 2806fe6060f1SDimitry Andric // check somewhere else if we should emit this at all. 2807fe6060f1SDimitry Andric if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) { 2808fe6060f1SDimitry Andric llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = 2809fe6060f1SDimitry Andric OMPDeclareTargetDeclAttr::getActiveAttr(Global); 2810fe6060f1SDimitry Andric if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1) 2811fe6060f1SDimitry Andric return false; 2812fe6060f1SDimitry Andric } 2813fe6060f1SDimitry Andric 2814a7dea167SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 2815*0b57cec5SDimitry Andric if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 2816*0b57cec5SDimitry Andric // Implicit template instantiations may change linkage if they are later 2817*0b57cec5SDimitry Andric // explicitly instantiated, so they should not be emitted eagerly. 2818*0b57cec5SDimitry Andric return false; 2819a7dea167SDimitry Andric } 2820*0b57cec5SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(Global)) 2821*0b57cec5SDimitry Andric if (Context.getInlineVariableDefinitionKind(VD) == 2822*0b57cec5SDimitry Andric ASTContext::InlineVariableDefinitionKind::WeakUnknown) 2823*0b57cec5SDimitry Andric // A definition of an inline constexpr static data member may change 2824*0b57cec5SDimitry Andric // linkage later if it's redeclared outside the class. 2825*0b57cec5SDimitry Andric return false; 2826*0b57cec5SDimitry Andric // If OpenMP is enabled and threadprivates must be generated like TLS, delay 2827*0b57cec5SDimitry Andric // codegen for global variables, because they may be marked as threadprivate. 2828*0b57cec5SDimitry Andric if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 2829*0b57cec5SDimitry Andric getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) && 2830*0b57cec5SDimitry Andric !isTypeConstant(Global->getType(), false) && 2831*0b57cec5SDimitry Andric !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global)) 2832*0b57cec5SDimitry Andric return false; 2833*0b57cec5SDimitry Andric 2834*0b57cec5SDimitry Andric return true; 2835*0b57cec5SDimitry Andric } 2836*0b57cec5SDimitry Andric 28375ffd83dbSDimitry Andric ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) { 28385ffd83dbSDimitry Andric StringRef Name = getMangledName(GD); 2839*0b57cec5SDimitry Andric 2840*0b57cec5SDimitry Andric // The UUID descriptor should be pointer aligned. 2841*0b57cec5SDimitry Andric CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 2842*0b57cec5SDimitry Andric 2843*0b57cec5SDimitry Andric // Look for an existing global. 2844*0b57cec5SDimitry Andric if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 28450eae32dcSDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 2846*0b57cec5SDimitry Andric 28475ffd83dbSDimitry Andric ConstantEmitter Emitter(*this); 28485ffd83dbSDimitry Andric llvm::Constant *Init; 28495ffd83dbSDimitry Andric 28505ffd83dbSDimitry Andric APValue &V = GD->getAsAPValue(); 28515ffd83dbSDimitry Andric if (!V.isAbsent()) { 28525ffd83dbSDimitry Andric // If possible, emit the APValue version of the initializer. In particular, 28535ffd83dbSDimitry Andric // this gets the type of the constant right. 28545ffd83dbSDimitry Andric Init = Emitter.emitForInitializer( 28555ffd83dbSDimitry Andric GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType()); 28565ffd83dbSDimitry Andric } else { 28575ffd83dbSDimitry Andric // As a fallback, directly construct the constant. 28585ffd83dbSDimitry Andric // FIXME: This may get padding wrong under esoteric struct layout rules. 28595ffd83dbSDimitry Andric // MSVC appears to create a complete type 'struct __s_GUID' that it 28605ffd83dbSDimitry Andric // presumably uses to represent these constants. 28615ffd83dbSDimitry Andric MSGuidDecl::Parts Parts = GD->getParts(); 28625ffd83dbSDimitry Andric llvm::Constant *Fields[4] = { 28635ffd83dbSDimitry Andric llvm::ConstantInt::get(Int32Ty, Parts.Part1), 28645ffd83dbSDimitry Andric llvm::ConstantInt::get(Int16Ty, Parts.Part2), 28655ffd83dbSDimitry Andric llvm::ConstantInt::get(Int16Ty, Parts.Part3), 28665ffd83dbSDimitry Andric llvm::ConstantDataArray::getRaw( 28675ffd83dbSDimitry Andric StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8, 28685ffd83dbSDimitry Andric Int8Ty)}; 28695ffd83dbSDimitry Andric Init = llvm::ConstantStruct::getAnon(Fields); 28705ffd83dbSDimitry Andric } 2871*0b57cec5SDimitry Andric 2872*0b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 2873*0b57cec5SDimitry Andric getModule(), Init->getType(), 2874*0b57cec5SDimitry Andric /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 2875*0b57cec5SDimitry Andric if (supportsCOMDAT()) 2876*0b57cec5SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 2877*0b57cec5SDimitry Andric setDSOLocal(GV); 28785ffd83dbSDimitry Andric 28795ffd83dbSDimitry Andric if (!V.isAbsent()) { 28805ffd83dbSDimitry Andric Emitter.finalize(GV); 28810eae32dcSDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 28825ffd83dbSDimitry Andric } 28830eae32dcSDimitry Andric 28840eae32dcSDimitry Andric llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType()); 28850eae32dcSDimitry Andric llvm::Constant *Addr = llvm::ConstantExpr::getBitCast( 28860eae32dcSDimitry Andric GV, Ty->getPointerTo(GV->getAddressSpace())); 28870eae32dcSDimitry Andric return ConstantAddress(Addr, Ty, Alignment); 2888*0b57cec5SDimitry Andric } 2889*0b57cec5SDimitry Andric 2890e8d8bef9SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject( 2891e8d8bef9SDimitry Andric const TemplateParamObjectDecl *TPO) { 2892e8d8bef9SDimitry Andric StringRef Name = getMangledName(TPO); 2893e8d8bef9SDimitry Andric CharUnits Alignment = getNaturalTypeAlignment(TPO->getType()); 2894e8d8bef9SDimitry Andric 2895e8d8bef9SDimitry Andric if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 28960eae32dcSDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 2897e8d8bef9SDimitry Andric 2898e8d8bef9SDimitry Andric ConstantEmitter Emitter(*this); 2899e8d8bef9SDimitry Andric llvm::Constant *Init = Emitter.emitForInitializer( 2900e8d8bef9SDimitry Andric TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType()); 2901e8d8bef9SDimitry Andric 2902e8d8bef9SDimitry Andric if (!Init) { 2903e8d8bef9SDimitry Andric ErrorUnsupported(TPO, "template parameter object"); 2904e8d8bef9SDimitry Andric return ConstantAddress::invalid(); 2905e8d8bef9SDimitry Andric } 2906e8d8bef9SDimitry Andric 2907e8d8bef9SDimitry Andric auto *GV = new llvm::GlobalVariable( 2908e8d8bef9SDimitry Andric getModule(), Init->getType(), 2909e8d8bef9SDimitry Andric /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 2910e8d8bef9SDimitry Andric if (supportsCOMDAT()) 2911e8d8bef9SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 2912e8d8bef9SDimitry Andric Emitter.finalize(GV); 2913e8d8bef9SDimitry Andric 29140eae32dcSDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 2915e8d8bef9SDimitry Andric } 2916e8d8bef9SDimitry Andric 2917*0b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 2918*0b57cec5SDimitry Andric const AliasAttr *AA = VD->getAttr<AliasAttr>(); 2919*0b57cec5SDimitry Andric assert(AA && "No alias?"); 2920*0b57cec5SDimitry Andric 2921*0b57cec5SDimitry Andric CharUnits Alignment = getContext().getDeclAlign(VD); 2922*0b57cec5SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 2923*0b57cec5SDimitry Andric 2924*0b57cec5SDimitry Andric // See if there is already something with the target's name in the module. 2925*0b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 2926*0b57cec5SDimitry Andric if (Entry) { 2927*0b57cec5SDimitry Andric unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 2928*0b57cec5SDimitry Andric auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 29290eae32dcSDimitry Andric return ConstantAddress(Ptr, DeclTy, Alignment); 2930*0b57cec5SDimitry Andric } 2931*0b57cec5SDimitry Andric 2932*0b57cec5SDimitry Andric llvm::Constant *Aliasee; 2933*0b57cec5SDimitry Andric if (isa<llvm::FunctionType>(DeclTy)) 2934*0b57cec5SDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 2935*0b57cec5SDimitry Andric GlobalDecl(cast<FunctionDecl>(VD)), 2936*0b57cec5SDimitry Andric /*ForVTable=*/false); 2937*0b57cec5SDimitry Andric else 2938349cc55cSDimitry Andric Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 2939349cc55cSDimitry Andric nullptr); 2940*0b57cec5SDimitry Andric 2941*0b57cec5SDimitry Andric auto *F = cast<llvm::GlobalValue>(Aliasee); 2942*0b57cec5SDimitry Andric F->setLinkage(llvm::Function::ExternalWeakLinkage); 2943*0b57cec5SDimitry Andric WeakRefReferences.insert(F); 2944*0b57cec5SDimitry Andric 29450eae32dcSDimitry Andric return ConstantAddress(Aliasee, DeclTy, Alignment); 2946*0b57cec5SDimitry Andric } 2947*0b57cec5SDimitry Andric 2948*0b57cec5SDimitry Andric void CodeGenModule::EmitGlobal(GlobalDecl GD) { 2949*0b57cec5SDimitry Andric const auto *Global = cast<ValueDecl>(GD.getDecl()); 2950*0b57cec5SDimitry Andric 2951*0b57cec5SDimitry Andric // Weak references don't produce any output by themselves. 2952*0b57cec5SDimitry Andric if (Global->hasAttr<WeakRefAttr>()) 2953*0b57cec5SDimitry Andric return; 2954*0b57cec5SDimitry Andric 2955*0b57cec5SDimitry Andric // If this is an alias definition (which otherwise looks like a declaration) 2956*0b57cec5SDimitry Andric // emit it now. 2957*0b57cec5SDimitry Andric if (Global->hasAttr<AliasAttr>()) 2958*0b57cec5SDimitry Andric return EmitAliasDefinition(GD); 2959*0b57cec5SDimitry Andric 2960*0b57cec5SDimitry Andric // IFunc like an alias whose value is resolved at runtime by calling resolver. 2961*0b57cec5SDimitry Andric if (Global->hasAttr<IFuncAttr>()) 2962*0b57cec5SDimitry Andric return emitIFuncDefinition(GD); 2963*0b57cec5SDimitry Andric 2964*0b57cec5SDimitry Andric // If this is a cpu_dispatch multiversion function, emit the resolver. 2965*0b57cec5SDimitry Andric if (Global->hasAttr<CPUDispatchAttr>()) 2966*0b57cec5SDimitry Andric return emitCPUDispatchDefinition(GD); 2967*0b57cec5SDimitry Andric 2968*0b57cec5SDimitry Andric // If this is CUDA, be selective about which declarations we emit. 2969*0b57cec5SDimitry Andric if (LangOpts.CUDA) { 2970*0b57cec5SDimitry Andric if (LangOpts.CUDAIsDevice) { 2971*0b57cec5SDimitry Andric if (!Global->hasAttr<CUDADeviceAttr>() && 2972*0b57cec5SDimitry Andric !Global->hasAttr<CUDAGlobalAttr>() && 2973*0b57cec5SDimitry Andric !Global->hasAttr<CUDAConstantAttr>() && 2974*0b57cec5SDimitry Andric !Global->hasAttr<CUDASharedAttr>() && 29755ffd83dbSDimitry Andric !Global->getType()->isCUDADeviceBuiltinSurfaceType() && 29765ffd83dbSDimitry Andric !Global->getType()->isCUDADeviceBuiltinTextureType()) 2977*0b57cec5SDimitry Andric return; 2978*0b57cec5SDimitry Andric } else { 2979*0b57cec5SDimitry Andric // We need to emit host-side 'shadows' for all global 2980*0b57cec5SDimitry Andric // device-side variables because the CUDA runtime needs their 2981*0b57cec5SDimitry Andric // size and host-side address in order to provide access to 2982*0b57cec5SDimitry Andric // their device-side incarnations. 2983*0b57cec5SDimitry Andric 2984*0b57cec5SDimitry Andric // So device-only functions are the only things we skip. 2985*0b57cec5SDimitry Andric if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 2986*0b57cec5SDimitry Andric Global->hasAttr<CUDADeviceAttr>()) 2987*0b57cec5SDimitry Andric return; 2988*0b57cec5SDimitry Andric 2989*0b57cec5SDimitry Andric assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 2990*0b57cec5SDimitry Andric "Expected Variable or Function"); 2991*0b57cec5SDimitry Andric } 2992*0b57cec5SDimitry Andric } 2993*0b57cec5SDimitry Andric 2994*0b57cec5SDimitry Andric if (LangOpts.OpenMP) { 2995a7dea167SDimitry Andric // If this is OpenMP, check if it is legal to emit this global normally. 2996*0b57cec5SDimitry Andric if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 2997*0b57cec5SDimitry Andric return; 2998*0b57cec5SDimitry Andric if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 2999*0b57cec5SDimitry Andric if (MustBeEmitted(Global)) 3000*0b57cec5SDimitry Andric EmitOMPDeclareReduction(DRD); 3001*0b57cec5SDimitry Andric return; 3002*0b57cec5SDimitry Andric } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) { 3003*0b57cec5SDimitry Andric if (MustBeEmitted(Global)) 3004*0b57cec5SDimitry Andric EmitOMPDeclareMapper(DMD); 3005*0b57cec5SDimitry Andric return; 3006*0b57cec5SDimitry Andric } 3007*0b57cec5SDimitry Andric } 3008*0b57cec5SDimitry Andric 3009*0b57cec5SDimitry Andric // Ignore declarations, they will be emitted on their first use. 3010*0b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 3011*0b57cec5SDimitry Andric // Forward declarations are emitted lazily on first use. 3012*0b57cec5SDimitry Andric if (!FD->doesThisDeclarationHaveABody()) { 3013*0b57cec5SDimitry Andric if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 3014*0b57cec5SDimitry Andric return; 3015*0b57cec5SDimitry Andric 3016*0b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 3017*0b57cec5SDimitry Andric 3018*0b57cec5SDimitry Andric // Compute the function info and LLVM type. 3019*0b57cec5SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 3020*0b57cec5SDimitry Andric llvm::Type *Ty = getTypes().GetFunctionType(FI); 3021*0b57cec5SDimitry Andric 3022*0b57cec5SDimitry Andric GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 3023*0b57cec5SDimitry Andric /*DontDefer=*/false); 3024*0b57cec5SDimitry Andric return; 3025*0b57cec5SDimitry Andric } 3026*0b57cec5SDimitry Andric } else { 3027*0b57cec5SDimitry Andric const auto *VD = cast<VarDecl>(Global); 3028*0b57cec5SDimitry Andric assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 3029*0b57cec5SDimitry Andric if (VD->isThisDeclarationADefinition() != VarDecl::Definition && 3030*0b57cec5SDimitry Andric !Context.isMSStaticDataMemberInlineDefinition(VD)) { 3031*0b57cec5SDimitry Andric if (LangOpts.OpenMP) { 3032*0b57cec5SDimitry Andric // Emit declaration of the must-be-emitted declare target variable. 3033*0b57cec5SDimitry Andric if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 3034*0b57cec5SDimitry Andric OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 3035*0b57cec5SDimitry Andric bool UnifiedMemoryEnabled = 3036*0b57cec5SDimitry Andric getOpenMPRuntime().hasRequiresUnifiedSharedMemory(); 3037*0b57cec5SDimitry Andric if (*Res == OMPDeclareTargetDeclAttr::MT_To && 3038*0b57cec5SDimitry Andric !UnifiedMemoryEnabled) { 3039*0b57cec5SDimitry Andric (void)GetAddrOfGlobalVar(VD); 3040*0b57cec5SDimitry Andric } else { 3041*0b57cec5SDimitry Andric assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) || 3042*0b57cec5SDimitry Andric (*Res == OMPDeclareTargetDeclAttr::MT_To && 3043*0b57cec5SDimitry Andric UnifiedMemoryEnabled)) && 3044*0b57cec5SDimitry Andric "Link clause or to clause with unified memory expected."); 3045*0b57cec5SDimitry Andric (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD); 3046*0b57cec5SDimitry Andric } 3047*0b57cec5SDimitry Andric 3048*0b57cec5SDimitry Andric return; 3049*0b57cec5SDimitry Andric } 3050*0b57cec5SDimitry Andric } 3051*0b57cec5SDimitry Andric // If this declaration may have caused an inline variable definition to 3052*0b57cec5SDimitry Andric // change linkage, make sure that it's emitted. 3053*0b57cec5SDimitry Andric if (Context.getInlineVariableDefinitionKind(VD) == 3054*0b57cec5SDimitry Andric ASTContext::InlineVariableDefinitionKind::Strong) 3055*0b57cec5SDimitry Andric GetAddrOfGlobalVar(VD); 3056*0b57cec5SDimitry Andric return; 3057*0b57cec5SDimitry Andric } 3058*0b57cec5SDimitry Andric } 3059*0b57cec5SDimitry Andric 3060*0b57cec5SDimitry Andric // Defer code generation to first use when possible, e.g. if this is an inline 3061*0b57cec5SDimitry Andric // function. If the global must always be emitted, do it eagerly if possible 3062*0b57cec5SDimitry Andric // to benefit from cache locality. 3063*0b57cec5SDimitry Andric if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 3064*0b57cec5SDimitry Andric // Emit the definition if it can't be deferred. 3065*0b57cec5SDimitry Andric EmitGlobalDefinition(GD); 3066*0b57cec5SDimitry Andric return; 3067*0b57cec5SDimitry Andric } 3068*0b57cec5SDimitry Andric 3069*0b57cec5SDimitry Andric // If we're deferring emission of a C++ variable with an 3070*0b57cec5SDimitry Andric // initializer, remember the order in which it appeared in the file. 3071*0b57cec5SDimitry Andric if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 3072*0b57cec5SDimitry Andric cast<VarDecl>(Global)->hasInit()) { 3073*0b57cec5SDimitry Andric DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 3074*0b57cec5SDimitry Andric CXXGlobalInits.push_back(nullptr); 3075*0b57cec5SDimitry Andric } 3076*0b57cec5SDimitry Andric 3077*0b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 3078*0b57cec5SDimitry Andric if (GetGlobalValue(MangledName) != nullptr) { 3079*0b57cec5SDimitry Andric // The value has already been used and should therefore be emitted. 3080*0b57cec5SDimitry Andric addDeferredDeclToEmit(GD); 3081*0b57cec5SDimitry Andric } else if (MustBeEmitted(Global)) { 3082*0b57cec5SDimitry Andric // The value must be emitted, but cannot be emitted eagerly. 3083*0b57cec5SDimitry Andric assert(!MayBeEmittedEagerly(Global)); 3084*0b57cec5SDimitry Andric addDeferredDeclToEmit(GD); 3085*0b57cec5SDimitry Andric } else { 3086*0b57cec5SDimitry Andric // Otherwise, remember that we saw a deferred decl with this name. The 3087*0b57cec5SDimitry Andric // first use of the mangled name will cause it to move into 3088*0b57cec5SDimitry Andric // DeferredDeclsToEmit. 3089*0b57cec5SDimitry Andric DeferredDecls[MangledName] = GD; 3090*0b57cec5SDimitry Andric } 3091*0b57cec5SDimitry Andric } 3092*0b57cec5SDimitry Andric 3093*0b57cec5SDimitry Andric // Check if T is a class type with a destructor that's not dllimport. 3094*0b57cec5SDimitry Andric static bool HasNonDllImportDtor(QualType T) { 3095*0b57cec5SDimitry Andric if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) 3096*0b57cec5SDimitry Andric if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 3097*0b57cec5SDimitry Andric if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) 3098*0b57cec5SDimitry Andric return true; 3099*0b57cec5SDimitry Andric 3100*0b57cec5SDimitry Andric return false; 3101*0b57cec5SDimitry Andric } 3102*0b57cec5SDimitry Andric 3103*0b57cec5SDimitry Andric namespace { 3104*0b57cec5SDimitry Andric struct FunctionIsDirectlyRecursive 3105*0b57cec5SDimitry Andric : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> { 3106*0b57cec5SDimitry Andric const StringRef Name; 3107*0b57cec5SDimitry Andric const Builtin::Context &BI; 3108*0b57cec5SDimitry Andric FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) 3109*0b57cec5SDimitry Andric : Name(N), BI(C) {} 3110*0b57cec5SDimitry Andric 3111*0b57cec5SDimitry Andric bool VisitCallExpr(const CallExpr *E) { 3112*0b57cec5SDimitry Andric const FunctionDecl *FD = E->getDirectCallee(); 3113*0b57cec5SDimitry Andric if (!FD) 3114*0b57cec5SDimitry Andric return false; 3115*0b57cec5SDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 3116*0b57cec5SDimitry Andric if (Attr && Name == Attr->getLabel()) 3117*0b57cec5SDimitry Andric return true; 3118*0b57cec5SDimitry Andric unsigned BuiltinID = FD->getBuiltinID(); 3119*0b57cec5SDimitry Andric if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 3120*0b57cec5SDimitry Andric return false; 3121*0b57cec5SDimitry Andric StringRef BuiltinName = BI.getName(BuiltinID); 3122*0b57cec5SDimitry Andric if (BuiltinName.startswith("__builtin_") && 3123*0b57cec5SDimitry Andric Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 3124*0b57cec5SDimitry Andric return true; 3125*0b57cec5SDimitry Andric } 3126*0b57cec5SDimitry Andric return false; 3127*0b57cec5SDimitry Andric } 3128*0b57cec5SDimitry Andric 3129*0b57cec5SDimitry Andric bool VisitStmt(const Stmt *S) { 3130*0b57cec5SDimitry Andric for (const Stmt *Child : S->children()) 3131*0b57cec5SDimitry Andric if (Child && this->Visit(Child)) 3132*0b57cec5SDimitry Andric return true; 3133*0b57cec5SDimitry Andric return false; 3134*0b57cec5SDimitry Andric } 3135*0b57cec5SDimitry Andric }; 3136*0b57cec5SDimitry Andric 3137*0b57cec5SDimitry Andric // Make sure we're not referencing non-imported vars or functions. 3138*0b57cec5SDimitry Andric struct DLLImportFunctionVisitor 3139*0b57cec5SDimitry Andric : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 3140*0b57cec5SDimitry Andric bool SafeToInline = true; 3141*0b57cec5SDimitry Andric 3142*0b57cec5SDimitry Andric bool shouldVisitImplicitCode() const { return true; } 3143*0b57cec5SDimitry Andric 3144*0b57cec5SDimitry Andric bool VisitVarDecl(VarDecl *VD) { 3145*0b57cec5SDimitry Andric if (VD->getTLSKind()) { 3146*0b57cec5SDimitry Andric // A thread-local variable cannot be imported. 3147*0b57cec5SDimitry Andric SafeToInline = false; 3148*0b57cec5SDimitry Andric return SafeToInline; 3149*0b57cec5SDimitry Andric } 3150*0b57cec5SDimitry Andric 3151*0b57cec5SDimitry Andric // A variable definition might imply a destructor call. 3152*0b57cec5SDimitry Andric if (VD->isThisDeclarationADefinition()) 3153*0b57cec5SDimitry Andric SafeToInline = !HasNonDllImportDtor(VD->getType()); 3154*0b57cec5SDimitry Andric 3155*0b57cec5SDimitry Andric return SafeToInline; 3156*0b57cec5SDimitry Andric } 3157*0b57cec5SDimitry Andric 3158*0b57cec5SDimitry Andric bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 3159*0b57cec5SDimitry Andric if (const auto *D = E->getTemporary()->getDestructor()) 3160*0b57cec5SDimitry Andric SafeToInline = D->hasAttr<DLLImportAttr>(); 3161*0b57cec5SDimitry Andric return SafeToInline; 3162*0b57cec5SDimitry Andric } 3163*0b57cec5SDimitry Andric 3164*0b57cec5SDimitry Andric bool VisitDeclRefExpr(DeclRefExpr *E) { 3165*0b57cec5SDimitry Andric ValueDecl *VD = E->getDecl(); 3166*0b57cec5SDimitry Andric if (isa<FunctionDecl>(VD)) 3167*0b57cec5SDimitry Andric SafeToInline = VD->hasAttr<DLLImportAttr>(); 3168*0b57cec5SDimitry Andric else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 3169*0b57cec5SDimitry Andric SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 3170*0b57cec5SDimitry Andric return SafeToInline; 3171*0b57cec5SDimitry Andric } 3172*0b57cec5SDimitry Andric 3173*0b57cec5SDimitry Andric bool VisitCXXConstructExpr(CXXConstructExpr *E) { 3174*0b57cec5SDimitry Andric SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); 3175*0b57cec5SDimitry Andric return SafeToInline; 3176*0b57cec5SDimitry Andric } 3177*0b57cec5SDimitry Andric 3178*0b57cec5SDimitry Andric bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3179*0b57cec5SDimitry Andric CXXMethodDecl *M = E->getMethodDecl(); 3180*0b57cec5SDimitry Andric if (!M) { 3181*0b57cec5SDimitry Andric // Call through a pointer to member function. This is safe to inline. 3182*0b57cec5SDimitry Andric SafeToInline = true; 3183*0b57cec5SDimitry Andric } else { 3184*0b57cec5SDimitry Andric SafeToInline = M->hasAttr<DLLImportAttr>(); 3185*0b57cec5SDimitry Andric } 3186*0b57cec5SDimitry Andric return SafeToInline; 3187*0b57cec5SDimitry Andric } 3188*0b57cec5SDimitry Andric 3189*0b57cec5SDimitry Andric bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 3190*0b57cec5SDimitry Andric SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 3191*0b57cec5SDimitry Andric return SafeToInline; 3192*0b57cec5SDimitry Andric } 3193*0b57cec5SDimitry Andric 3194*0b57cec5SDimitry Andric bool VisitCXXNewExpr(CXXNewExpr *E) { 3195*0b57cec5SDimitry Andric SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 3196*0b57cec5SDimitry Andric return SafeToInline; 3197*0b57cec5SDimitry Andric } 3198*0b57cec5SDimitry Andric }; 3199*0b57cec5SDimitry Andric } 3200*0b57cec5SDimitry Andric 3201*0b57cec5SDimitry Andric // isTriviallyRecursive - Check if this function calls another 3202*0b57cec5SDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin, 3203*0b57cec5SDimitry Andric // ends up pointing to itself. 3204*0b57cec5SDimitry Andric bool 3205*0b57cec5SDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 3206*0b57cec5SDimitry Andric StringRef Name; 3207*0b57cec5SDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 3208*0b57cec5SDimitry Andric // asm labels are a special kind of mangling we have to support. 3209*0b57cec5SDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 3210*0b57cec5SDimitry Andric if (!Attr) 3211*0b57cec5SDimitry Andric return false; 3212*0b57cec5SDimitry Andric Name = Attr->getLabel(); 3213*0b57cec5SDimitry Andric } else { 3214*0b57cec5SDimitry Andric Name = FD->getName(); 3215*0b57cec5SDimitry Andric } 3216*0b57cec5SDimitry Andric 3217*0b57cec5SDimitry Andric FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 3218*0b57cec5SDimitry Andric const Stmt *Body = FD->getBody(); 3219*0b57cec5SDimitry Andric return Body ? Walker.Visit(Body) : false; 3220*0b57cec5SDimitry Andric } 3221*0b57cec5SDimitry Andric 3222*0b57cec5SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 3223*0b57cec5SDimitry Andric if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 3224*0b57cec5SDimitry Andric return true; 3225*0b57cec5SDimitry Andric const auto *F = cast<FunctionDecl>(GD.getDecl()); 3226*0b57cec5SDimitry Andric if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 3227*0b57cec5SDimitry Andric return false; 3228*0b57cec5SDimitry Andric 3229fe6060f1SDimitry Andric if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) { 3230*0b57cec5SDimitry Andric // Check whether it would be safe to inline this dllimport function. 3231*0b57cec5SDimitry Andric DLLImportFunctionVisitor Visitor; 3232*0b57cec5SDimitry Andric Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 3233*0b57cec5SDimitry Andric if (!Visitor.SafeToInline) 3234*0b57cec5SDimitry Andric return false; 3235*0b57cec5SDimitry Andric 3236*0b57cec5SDimitry Andric if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { 3237*0b57cec5SDimitry Andric // Implicit destructor invocations aren't captured in the AST, so the 3238*0b57cec5SDimitry Andric // check above can't see them. Check for them manually here. 3239*0b57cec5SDimitry Andric for (const Decl *Member : Dtor->getParent()->decls()) 3240*0b57cec5SDimitry Andric if (isa<FieldDecl>(Member)) 3241*0b57cec5SDimitry Andric if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) 3242*0b57cec5SDimitry Andric return false; 3243*0b57cec5SDimitry Andric for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) 3244*0b57cec5SDimitry Andric if (HasNonDllImportDtor(B.getType())) 3245*0b57cec5SDimitry Andric return false; 3246*0b57cec5SDimitry Andric } 3247*0b57cec5SDimitry Andric } 3248*0b57cec5SDimitry Andric 3249349cc55cSDimitry Andric // Inline builtins declaration must be emitted. They often are fortified 3250349cc55cSDimitry Andric // functions. 3251349cc55cSDimitry Andric if (F->isInlineBuiltinDeclaration()) 3252349cc55cSDimitry Andric return true; 3253349cc55cSDimitry Andric 3254*0b57cec5SDimitry Andric // PR9614. Avoid cases where the source code is lying to us. An available 3255*0b57cec5SDimitry Andric // externally function should have an equivalent function somewhere else, 32565ffd83dbSDimitry Andric // but a function that calls itself through asm label/`__builtin_` trickery is 32575ffd83dbSDimitry Andric // clearly not equivalent to the real implementation. 3258*0b57cec5SDimitry Andric // This happens in glibc's btowc and in some configure checks. 3259*0b57cec5SDimitry Andric return !isTriviallyRecursive(F); 3260*0b57cec5SDimitry Andric } 3261*0b57cec5SDimitry Andric 3262*0b57cec5SDimitry Andric bool CodeGenModule::shouldOpportunisticallyEmitVTables() { 3263*0b57cec5SDimitry Andric return CodeGenOpts.OptimizationLevel > 0; 3264*0b57cec5SDimitry Andric } 3265*0b57cec5SDimitry Andric 3266*0b57cec5SDimitry Andric void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD, 3267*0b57cec5SDimitry Andric llvm::GlobalValue *GV) { 3268*0b57cec5SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3269*0b57cec5SDimitry Andric 3270*0b57cec5SDimitry Andric if (FD->isCPUSpecificMultiVersion()) { 3271*0b57cec5SDimitry Andric auto *Spec = FD->getAttr<CPUSpecificAttr>(); 3272*0b57cec5SDimitry Andric for (unsigned I = 0; I < Spec->cpus_size(); ++I) 3273*0b57cec5SDimitry Andric EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); 3274*0b57cec5SDimitry Andric // Requires multiple emits. 32754824e7fdSDimitry Andric } else if (FD->isTargetClonesMultiVersion()) { 32764824e7fdSDimitry Andric auto *Clone = FD->getAttr<TargetClonesAttr>(); 32774824e7fdSDimitry Andric for (unsigned I = 0; I < Clone->featuresStrs_size(); ++I) 32784824e7fdSDimitry Andric if (Clone->isFirstOfVersion(I)) 32794824e7fdSDimitry Andric EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); 32804824e7fdSDimitry Andric EmitTargetClonesResolver(GD); 3281*0b57cec5SDimitry Andric } else 3282*0b57cec5SDimitry Andric EmitGlobalFunctionDefinition(GD, GV); 3283*0b57cec5SDimitry Andric } 3284*0b57cec5SDimitry Andric 3285*0b57cec5SDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 3286*0b57cec5SDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 3287*0b57cec5SDimitry Andric 3288*0b57cec5SDimitry Andric PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 3289*0b57cec5SDimitry Andric Context.getSourceManager(), 3290*0b57cec5SDimitry Andric "Generating code for declaration"); 3291*0b57cec5SDimitry Andric 3292*0b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 3293*0b57cec5SDimitry Andric // At -O0, don't generate IR for functions with available_externally 3294*0b57cec5SDimitry Andric // linkage. 3295*0b57cec5SDimitry Andric if (!shouldEmitFunction(GD)) 3296*0b57cec5SDimitry Andric return; 3297*0b57cec5SDimitry Andric 3298*0b57cec5SDimitry Andric llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() { 3299*0b57cec5SDimitry Andric std::string Name; 3300*0b57cec5SDimitry Andric llvm::raw_string_ostream OS(Name); 3301*0b57cec5SDimitry Andric FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(), 3302*0b57cec5SDimitry Andric /*Qualified=*/true); 3303*0b57cec5SDimitry Andric return Name; 3304*0b57cec5SDimitry Andric }); 3305*0b57cec5SDimitry Andric 3306*0b57cec5SDimitry Andric if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 3307*0b57cec5SDimitry Andric // Make sure to emit the definition(s) before we emit the thunks. 3308*0b57cec5SDimitry Andric // This is necessary for the generation of certain thunks. 3309*0b57cec5SDimitry Andric if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method)) 3310*0b57cec5SDimitry Andric ABI->emitCXXStructor(GD); 3311*0b57cec5SDimitry Andric else if (FD->isMultiVersion()) 3312*0b57cec5SDimitry Andric EmitMultiVersionFunctionDefinition(GD, GV); 3313*0b57cec5SDimitry Andric else 3314*0b57cec5SDimitry Andric EmitGlobalFunctionDefinition(GD, GV); 3315*0b57cec5SDimitry Andric 3316*0b57cec5SDimitry Andric if (Method->isVirtual()) 3317*0b57cec5SDimitry Andric getVTables().EmitThunks(GD); 3318*0b57cec5SDimitry Andric 3319*0b57cec5SDimitry Andric return; 3320*0b57cec5SDimitry Andric } 3321*0b57cec5SDimitry Andric 3322*0b57cec5SDimitry Andric if (FD->isMultiVersion()) 3323*0b57cec5SDimitry Andric return EmitMultiVersionFunctionDefinition(GD, GV); 3324*0b57cec5SDimitry Andric return EmitGlobalFunctionDefinition(GD, GV); 3325*0b57cec5SDimitry Andric } 3326*0b57cec5SDimitry Andric 3327*0b57cec5SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 3328*0b57cec5SDimitry Andric return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 3329*0b57cec5SDimitry Andric 3330*0b57cec5SDimitry Andric llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 3331*0b57cec5SDimitry Andric } 3332*0b57cec5SDimitry Andric 3333*0b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 3334*0b57cec5SDimitry Andric llvm::Function *NewFn); 3335*0b57cec5SDimitry Andric 3336*0b57cec5SDimitry Andric static unsigned 3337*0b57cec5SDimitry Andric TargetMVPriority(const TargetInfo &TI, 3338*0b57cec5SDimitry Andric const CodeGenFunction::MultiVersionResolverOption &RO) { 3339*0b57cec5SDimitry Andric unsigned Priority = 0; 3340*0b57cec5SDimitry Andric for (StringRef Feat : RO.Conditions.Features) 3341*0b57cec5SDimitry Andric Priority = std::max(Priority, TI.multiVersionSortPriority(Feat)); 3342*0b57cec5SDimitry Andric 3343*0b57cec5SDimitry Andric if (!RO.Conditions.Architecture.empty()) 3344*0b57cec5SDimitry Andric Priority = std::max( 3345*0b57cec5SDimitry Andric Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture)); 3346*0b57cec5SDimitry Andric return Priority; 3347*0b57cec5SDimitry Andric } 3348*0b57cec5SDimitry Andric 3349349cc55cSDimitry Andric // Multiversion functions should be at most 'WeakODRLinkage' so that a different 3350349cc55cSDimitry Andric // TU can forward declare the function without causing problems. Particularly 3351349cc55cSDimitry Andric // in the cases of CPUDispatch, this causes issues. This also makes sure we 3352349cc55cSDimitry Andric // work with internal linkage functions, so that the same function name can be 3353349cc55cSDimitry Andric // used with internal linkage in multiple TUs. 3354349cc55cSDimitry Andric llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM, 3355349cc55cSDimitry Andric GlobalDecl GD) { 3356349cc55cSDimitry Andric const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 3357349cc55cSDimitry Andric if (FD->getFormalLinkage() == InternalLinkage) 3358349cc55cSDimitry Andric return llvm::GlobalValue::InternalLinkage; 3359349cc55cSDimitry Andric return llvm::GlobalValue::WeakODRLinkage; 3360349cc55cSDimitry Andric } 3361349cc55cSDimitry Andric 33624824e7fdSDimitry Andric void CodeGenModule::EmitTargetClonesResolver(GlobalDecl GD) { 33634824e7fdSDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 33644824e7fdSDimitry Andric assert(FD && "Not a FunctionDecl?"); 33654824e7fdSDimitry Andric const auto *TC = FD->getAttr<TargetClonesAttr>(); 33664824e7fdSDimitry Andric assert(TC && "Not a target_clones Function?"); 33674824e7fdSDimitry Andric 33684824e7fdSDimitry Andric QualType CanonTy = Context.getCanonicalType(FD->getType()); 33694824e7fdSDimitry Andric llvm::Type *DeclTy = getTypes().ConvertType(CanonTy); 33704824e7fdSDimitry Andric 33714824e7fdSDimitry Andric if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) { 33724824e7fdSDimitry Andric const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD); 33734824e7fdSDimitry Andric DeclTy = getTypes().GetFunctionType(FInfo); 33744824e7fdSDimitry Andric } 33754824e7fdSDimitry Andric 33764824e7fdSDimitry Andric llvm::Function *ResolverFunc; 33774824e7fdSDimitry Andric if (getTarget().supportsIFunc()) { 33784824e7fdSDimitry Andric auto *IFunc = cast<llvm::GlobalIFunc>( 33794824e7fdSDimitry Andric GetOrCreateMultiVersionResolver(GD, DeclTy, FD)); 33804824e7fdSDimitry Andric ResolverFunc = cast<llvm::Function>(IFunc->getResolver()); 33814824e7fdSDimitry Andric } else 33824824e7fdSDimitry Andric ResolverFunc = 33834824e7fdSDimitry Andric cast<llvm::Function>(GetOrCreateMultiVersionResolver(GD, DeclTy, FD)); 33844824e7fdSDimitry Andric 33854824e7fdSDimitry Andric SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 33864824e7fdSDimitry Andric for (unsigned VersionIndex = 0; VersionIndex < TC->featuresStrs_size(); 33874824e7fdSDimitry Andric ++VersionIndex) { 33884824e7fdSDimitry Andric if (!TC->isFirstOfVersion(VersionIndex)) 33894824e7fdSDimitry Andric continue; 33904824e7fdSDimitry Andric StringRef Version = TC->getFeatureStr(VersionIndex); 33914824e7fdSDimitry Andric StringRef MangledName = 33924824e7fdSDimitry Andric getMangledName(GD.getWithMultiVersionIndex(VersionIndex)); 33934824e7fdSDimitry Andric llvm::Constant *Func = GetGlobalValue(MangledName); 33944824e7fdSDimitry Andric assert(Func && 33954824e7fdSDimitry Andric "Should have already been created before calling resolver emit"); 33964824e7fdSDimitry Andric 33974824e7fdSDimitry Andric StringRef Architecture; 33984824e7fdSDimitry Andric llvm::SmallVector<StringRef, 1> Feature; 33994824e7fdSDimitry Andric 34004824e7fdSDimitry Andric if (Version.startswith("arch=")) 34014824e7fdSDimitry Andric Architecture = Version.drop_front(sizeof("arch=") - 1); 34024824e7fdSDimitry Andric else if (Version != "default") 34034824e7fdSDimitry Andric Feature.push_back(Version); 34044824e7fdSDimitry Andric 34054824e7fdSDimitry Andric Options.emplace_back(cast<llvm::Function>(Func), Architecture, Feature); 34064824e7fdSDimitry Andric } 34074824e7fdSDimitry Andric 34084824e7fdSDimitry Andric const TargetInfo &TI = getTarget(); 34094824e7fdSDimitry Andric std::stable_sort( 34104824e7fdSDimitry Andric Options.begin(), Options.end(), 34114824e7fdSDimitry Andric [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS, 34124824e7fdSDimitry Andric const CodeGenFunction::MultiVersionResolverOption &RHS) { 34134824e7fdSDimitry Andric return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS); 34144824e7fdSDimitry Andric }); 34154824e7fdSDimitry Andric CodeGenFunction CGF(*this); 34164824e7fdSDimitry Andric CGF.EmitMultiVersionResolver(ResolverFunc, Options); 34174824e7fdSDimitry Andric } 34184824e7fdSDimitry Andric 3419*0b57cec5SDimitry Andric void CodeGenModule::emitMultiVersionFunctions() { 3420fe6060f1SDimitry Andric std::vector<GlobalDecl> MVFuncsToEmit; 3421fe6060f1SDimitry Andric MultiVersionFuncs.swap(MVFuncsToEmit); 3422fe6060f1SDimitry Andric for (GlobalDecl GD : MVFuncsToEmit) { 3423*0b57cec5SDimitry Andric SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 3424*0b57cec5SDimitry Andric const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 3425*0b57cec5SDimitry Andric getContext().forEachMultiversionedFunctionVersion( 3426*0b57cec5SDimitry Andric FD, [this, &GD, &Options](const FunctionDecl *CurFD) { 3427*0b57cec5SDimitry Andric GlobalDecl CurGD{ 3428*0b57cec5SDimitry Andric (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)}; 3429*0b57cec5SDimitry Andric StringRef MangledName = getMangledName(CurGD); 3430*0b57cec5SDimitry Andric llvm::Constant *Func = GetGlobalValue(MangledName); 3431*0b57cec5SDimitry Andric if (!Func) { 3432*0b57cec5SDimitry Andric if (CurFD->isDefined()) { 3433*0b57cec5SDimitry Andric EmitGlobalFunctionDefinition(CurGD, nullptr); 3434*0b57cec5SDimitry Andric Func = GetGlobalValue(MangledName); 3435*0b57cec5SDimitry Andric } else { 3436*0b57cec5SDimitry Andric const CGFunctionInfo &FI = 3437*0b57cec5SDimitry Andric getTypes().arrangeGlobalDeclaration(GD); 3438*0b57cec5SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 3439*0b57cec5SDimitry Andric Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, 3440*0b57cec5SDimitry Andric /*DontDefer=*/false, ForDefinition); 3441*0b57cec5SDimitry Andric } 3442*0b57cec5SDimitry Andric assert(Func && "This should have just been created"); 3443*0b57cec5SDimitry Andric } 3444*0b57cec5SDimitry Andric 3445*0b57cec5SDimitry Andric const auto *TA = CurFD->getAttr<TargetAttr>(); 3446*0b57cec5SDimitry Andric llvm::SmallVector<StringRef, 8> Feats; 3447*0b57cec5SDimitry Andric TA->getAddedFeatures(Feats); 3448*0b57cec5SDimitry Andric 3449*0b57cec5SDimitry Andric Options.emplace_back(cast<llvm::Function>(Func), 3450*0b57cec5SDimitry Andric TA->getArchitecture(), Feats); 3451*0b57cec5SDimitry Andric }); 3452*0b57cec5SDimitry Andric 3453*0b57cec5SDimitry Andric llvm::Function *ResolverFunc; 3454*0b57cec5SDimitry Andric const TargetInfo &TI = getTarget(); 3455*0b57cec5SDimitry Andric 3456a7dea167SDimitry Andric if (TI.supportsIFunc() || FD->isTargetMultiVersion()) { 3457*0b57cec5SDimitry Andric ResolverFunc = cast<llvm::Function>( 3458*0b57cec5SDimitry Andric GetGlobalValue((getMangledName(GD) + ".resolver").str())); 3459349cc55cSDimitry Andric ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD)); 3460a7dea167SDimitry Andric } else { 3461*0b57cec5SDimitry Andric ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD))); 3462a7dea167SDimitry Andric } 3463*0b57cec5SDimitry Andric 3464*0b57cec5SDimitry Andric if (supportsCOMDAT()) 3465*0b57cec5SDimitry Andric ResolverFunc->setComdat( 3466*0b57cec5SDimitry Andric getModule().getOrInsertComdat(ResolverFunc->getName())); 3467*0b57cec5SDimitry Andric 3468*0b57cec5SDimitry Andric llvm::stable_sort( 3469*0b57cec5SDimitry Andric Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS, 3470*0b57cec5SDimitry Andric const CodeGenFunction::MultiVersionResolverOption &RHS) { 3471*0b57cec5SDimitry Andric return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS); 3472*0b57cec5SDimitry Andric }); 3473*0b57cec5SDimitry Andric CodeGenFunction CGF(*this); 3474*0b57cec5SDimitry Andric CGF.EmitMultiVersionResolver(ResolverFunc, Options); 3475*0b57cec5SDimitry Andric } 3476fe6060f1SDimitry Andric 3477fe6060f1SDimitry Andric // Ensure that any additions to the deferred decls list caused by emitting a 3478fe6060f1SDimitry Andric // variant are emitted. This can happen when the variant itself is inline and 3479fe6060f1SDimitry Andric // calls a function without linkage. 3480fe6060f1SDimitry Andric if (!MVFuncsToEmit.empty()) 3481fe6060f1SDimitry Andric EmitDeferred(); 3482fe6060f1SDimitry Andric 3483fe6060f1SDimitry Andric // Ensure that any additions to the multiversion funcs list from either the 3484fe6060f1SDimitry Andric // deferred decls or the multiversion functions themselves are emitted. 3485fe6060f1SDimitry Andric if (!MultiVersionFuncs.empty()) 3486fe6060f1SDimitry Andric emitMultiVersionFunctions(); 3487*0b57cec5SDimitry Andric } 3488*0b57cec5SDimitry Andric 3489*0b57cec5SDimitry Andric void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) { 3490*0b57cec5SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3491*0b57cec5SDimitry Andric assert(FD && "Not a FunctionDecl?"); 349204eeddc0SDimitry Andric assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?"); 3493*0b57cec5SDimitry Andric const auto *DD = FD->getAttr<CPUDispatchAttr>(); 3494*0b57cec5SDimitry Andric assert(DD && "Not a cpu_dispatch Function?"); 3495*0b57cec5SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertType(FD->getType()); 3496*0b57cec5SDimitry Andric 3497*0b57cec5SDimitry Andric if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) { 3498*0b57cec5SDimitry Andric const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD); 3499*0b57cec5SDimitry Andric DeclTy = getTypes().GetFunctionType(FInfo); 3500*0b57cec5SDimitry Andric } 3501*0b57cec5SDimitry Andric 3502*0b57cec5SDimitry Andric StringRef ResolverName = getMangledName(GD); 350304eeddc0SDimitry Andric UpdateMultiVersionNames(GD, FD, ResolverName); 3504*0b57cec5SDimitry Andric 3505*0b57cec5SDimitry Andric llvm::Type *ResolverType; 3506*0b57cec5SDimitry Andric GlobalDecl ResolverGD; 350704eeddc0SDimitry Andric if (getTarget().supportsIFunc()) { 3508*0b57cec5SDimitry Andric ResolverType = llvm::FunctionType::get( 3509*0b57cec5SDimitry Andric llvm::PointerType::get(DeclTy, 3510*0b57cec5SDimitry Andric Context.getTargetAddressSpace(FD->getType())), 3511*0b57cec5SDimitry Andric false); 351204eeddc0SDimitry Andric } 3513*0b57cec5SDimitry Andric else { 3514*0b57cec5SDimitry Andric ResolverType = DeclTy; 3515*0b57cec5SDimitry Andric ResolverGD = GD; 3516*0b57cec5SDimitry Andric } 3517*0b57cec5SDimitry Andric 3518*0b57cec5SDimitry Andric auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction( 3519*0b57cec5SDimitry Andric ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false)); 3520349cc55cSDimitry Andric ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD)); 3521a7dea167SDimitry Andric if (supportsCOMDAT()) 3522a7dea167SDimitry Andric ResolverFunc->setComdat( 3523a7dea167SDimitry Andric getModule().getOrInsertComdat(ResolverFunc->getName())); 3524*0b57cec5SDimitry Andric 3525*0b57cec5SDimitry Andric SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 3526*0b57cec5SDimitry Andric const TargetInfo &Target = getTarget(); 3527*0b57cec5SDimitry Andric unsigned Index = 0; 3528*0b57cec5SDimitry Andric for (const IdentifierInfo *II : DD->cpus()) { 3529*0b57cec5SDimitry Andric // Get the name of the target function so we can look it up/create it. 3530*0b57cec5SDimitry Andric std::string MangledName = getMangledNameImpl(*this, GD, FD, true) + 3531*0b57cec5SDimitry Andric getCPUSpecificMangling(*this, II->getName()); 3532*0b57cec5SDimitry Andric 3533*0b57cec5SDimitry Andric llvm::Constant *Func = GetGlobalValue(MangledName); 3534*0b57cec5SDimitry Andric 3535*0b57cec5SDimitry Andric if (!Func) { 3536*0b57cec5SDimitry Andric GlobalDecl ExistingDecl = Manglings.lookup(MangledName); 3537*0b57cec5SDimitry Andric if (ExistingDecl.getDecl() && 3538*0b57cec5SDimitry Andric ExistingDecl.getDecl()->getAsFunction()->isDefined()) { 3539*0b57cec5SDimitry Andric EmitGlobalFunctionDefinition(ExistingDecl, nullptr); 3540*0b57cec5SDimitry Andric Func = GetGlobalValue(MangledName); 3541*0b57cec5SDimitry Andric } else { 3542*0b57cec5SDimitry Andric if (!ExistingDecl.getDecl()) 3543*0b57cec5SDimitry Andric ExistingDecl = GD.getWithMultiVersionIndex(Index); 3544*0b57cec5SDimitry Andric 3545*0b57cec5SDimitry Andric Func = GetOrCreateLLVMFunction( 3546*0b57cec5SDimitry Andric MangledName, DeclTy, ExistingDecl, 3547*0b57cec5SDimitry Andric /*ForVTable=*/false, /*DontDefer=*/true, 3548*0b57cec5SDimitry Andric /*IsThunk=*/false, llvm::AttributeList(), ForDefinition); 3549*0b57cec5SDimitry Andric } 3550*0b57cec5SDimitry Andric } 3551*0b57cec5SDimitry Andric 3552*0b57cec5SDimitry Andric llvm::SmallVector<StringRef, 32> Features; 3553*0b57cec5SDimitry Andric Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features); 3554*0b57cec5SDimitry Andric llvm::transform(Features, Features.begin(), 3555*0b57cec5SDimitry Andric [](StringRef Str) { return Str.substr(1); }); 3556349cc55cSDimitry Andric llvm::erase_if(Features, [&Target](StringRef Feat) { 3557*0b57cec5SDimitry Andric return !Target.validateCpuSupports(Feat); 3558349cc55cSDimitry Andric }); 3559*0b57cec5SDimitry Andric Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features); 3560*0b57cec5SDimitry Andric ++Index; 3561*0b57cec5SDimitry Andric } 3562*0b57cec5SDimitry Andric 3563fe6060f1SDimitry Andric llvm::stable_sort( 3564*0b57cec5SDimitry Andric Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS, 3565*0b57cec5SDimitry Andric const CodeGenFunction::MultiVersionResolverOption &RHS) { 3566349cc55cSDimitry Andric return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) > 3567349cc55cSDimitry Andric llvm::X86::getCpuSupportsMask(RHS.Conditions.Features); 3568*0b57cec5SDimitry Andric }); 3569*0b57cec5SDimitry Andric 3570*0b57cec5SDimitry Andric // If the list contains multiple 'default' versions, such as when it contains 3571*0b57cec5SDimitry Andric // 'pentium' and 'generic', don't emit the call to the generic one (since we 3572*0b57cec5SDimitry Andric // always run on at least a 'pentium'). We do this by deleting the 'least 3573*0b57cec5SDimitry Andric // advanced' (read, lowest mangling letter). 3574*0b57cec5SDimitry Andric while (Options.size() > 1 && 3575349cc55cSDimitry Andric llvm::X86::getCpuSupportsMask( 3576*0b57cec5SDimitry Andric (Options.end() - 2)->Conditions.Features) == 0) { 3577*0b57cec5SDimitry Andric StringRef LHSName = (Options.end() - 2)->Function->getName(); 3578*0b57cec5SDimitry Andric StringRef RHSName = (Options.end() - 1)->Function->getName(); 3579*0b57cec5SDimitry Andric if (LHSName.compare(RHSName) < 0) 3580*0b57cec5SDimitry Andric Options.erase(Options.end() - 2); 3581*0b57cec5SDimitry Andric else 3582*0b57cec5SDimitry Andric Options.erase(Options.end() - 1); 3583*0b57cec5SDimitry Andric } 3584*0b57cec5SDimitry Andric 3585*0b57cec5SDimitry Andric CodeGenFunction CGF(*this); 3586*0b57cec5SDimitry Andric CGF.EmitMultiVersionResolver(ResolverFunc, Options); 3587a7dea167SDimitry Andric 3588a7dea167SDimitry Andric if (getTarget().supportsIFunc()) { 3589a7dea167SDimitry Andric std::string AliasName = getMangledNameImpl( 3590a7dea167SDimitry Andric *this, GD, FD, /*OmitMultiVersionMangling=*/true); 3591a7dea167SDimitry Andric llvm::Constant *AliasFunc = GetGlobalValue(AliasName); 3592a7dea167SDimitry Andric if (!AliasFunc) { 3593a7dea167SDimitry Andric auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction( 3594a7dea167SDimitry Andric AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true, 3595a7dea167SDimitry Andric /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition)); 3596349cc55cSDimitry Andric auto *GA = llvm::GlobalAlias::create(DeclTy, 0, 3597349cc55cSDimitry Andric getMultiversionLinkage(*this, GD), 3598349cc55cSDimitry Andric AliasName, IFunc, &getModule()); 3599a7dea167SDimitry Andric SetCommonAttributes(GD, GA); 3600a7dea167SDimitry Andric } 3601a7dea167SDimitry Andric } 3602*0b57cec5SDimitry Andric } 3603*0b57cec5SDimitry Andric 3604*0b57cec5SDimitry Andric /// If a dispatcher for the specified mangled name is not in the module, create 3605*0b57cec5SDimitry Andric /// and return an llvm Function with the specified type. 3606*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver( 3607*0b57cec5SDimitry Andric GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) { 3608*0b57cec5SDimitry Andric std::string MangledName = 3609*0b57cec5SDimitry Andric getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 3610*0b57cec5SDimitry Andric 3611*0b57cec5SDimitry Andric // Holds the name of the resolver, in ifunc mode this is the ifunc (which has 3612*0b57cec5SDimitry Andric // a separate resolver). 3613*0b57cec5SDimitry Andric std::string ResolverName = MangledName; 3614*0b57cec5SDimitry Andric if (getTarget().supportsIFunc()) 3615*0b57cec5SDimitry Andric ResolverName += ".ifunc"; 3616*0b57cec5SDimitry Andric else if (FD->isTargetMultiVersion()) 3617*0b57cec5SDimitry Andric ResolverName += ".resolver"; 3618*0b57cec5SDimitry Andric 3619*0b57cec5SDimitry Andric // If this already exists, just return that one. 3620*0b57cec5SDimitry Andric if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName)) 3621*0b57cec5SDimitry Andric return ResolverGV; 3622*0b57cec5SDimitry Andric 3623*0b57cec5SDimitry Andric // Since this is the first time we've created this IFunc, make sure 3624*0b57cec5SDimitry Andric // that we put this multiversioned function into the list to be 3625*0b57cec5SDimitry Andric // replaced later if necessary (target multiversioning only). 36264824e7fdSDimitry Andric if (FD->isTargetMultiVersion()) 3627*0b57cec5SDimitry Andric MultiVersionFuncs.push_back(GD); 36284824e7fdSDimitry Andric else if (FD->isTargetClonesMultiVersion()) { 36294824e7fdSDimitry Andric // In target_clones multiversioning, make sure we emit this if used. 36304824e7fdSDimitry Andric auto DDI = 36314824e7fdSDimitry Andric DeferredDecls.find(getMangledName(GD.getWithMultiVersionIndex(0))); 36324824e7fdSDimitry Andric if (DDI != DeferredDecls.end()) { 36334824e7fdSDimitry Andric addDeferredDeclToEmit(GD); 36344824e7fdSDimitry Andric DeferredDecls.erase(DDI); 36354824e7fdSDimitry Andric } else { 36364824e7fdSDimitry Andric // Emit the symbol of the 1st variant, so that the deferred decls know we 36374824e7fdSDimitry Andric // need it, otherwise the only global value will be the resolver/ifunc, 36384824e7fdSDimitry Andric // which end up getting broken if we search for them with GetGlobalValue'. 36394824e7fdSDimitry Andric GetOrCreateLLVMFunction( 36404824e7fdSDimitry Andric getMangledName(GD.getWithMultiVersionIndex(0)), DeclTy, FD, 36414824e7fdSDimitry Andric /*ForVTable=*/false, /*DontDefer=*/true, 36424824e7fdSDimitry Andric /*IsThunk=*/false, llvm::AttributeList(), ForDefinition); 36434824e7fdSDimitry Andric } 36444824e7fdSDimitry Andric } 3645*0b57cec5SDimitry Andric 3646*0b57cec5SDimitry Andric if (getTarget().supportsIFunc()) { 3647*0b57cec5SDimitry Andric llvm::Type *ResolverType = llvm::FunctionType::get( 3648*0b57cec5SDimitry Andric llvm::PointerType::get( 3649*0b57cec5SDimitry Andric DeclTy, getContext().getTargetAddressSpace(FD->getType())), 3650*0b57cec5SDimitry Andric false); 3651*0b57cec5SDimitry Andric llvm::Constant *Resolver = GetOrCreateLLVMFunction( 3652*0b57cec5SDimitry Andric MangledName + ".resolver", ResolverType, GlobalDecl{}, 3653*0b57cec5SDimitry Andric /*ForVTable=*/false); 3654349cc55cSDimitry Andric llvm::GlobalIFunc *GIF = 3655349cc55cSDimitry Andric llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD), 3656349cc55cSDimitry Andric "", Resolver, &getModule()); 3657*0b57cec5SDimitry Andric GIF->setName(ResolverName); 3658*0b57cec5SDimitry Andric SetCommonAttributes(FD, GIF); 3659*0b57cec5SDimitry Andric 3660*0b57cec5SDimitry Andric return GIF; 3661*0b57cec5SDimitry Andric } 3662*0b57cec5SDimitry Andric 3663*0b57cec5SDimitry Andric llvm::Constant *Resolver = GetOrCreateLLVMFunction( 3664*0b57cec5SDimitry Andric ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false); 3665*0b57cec5SDimitry Andric assert(isa<llvm::GlobalValue>(Resolver) && 3666*0b57cec5SDimitry Andric "Resolver should be created for the first time"); 3667*0b57cec5SDimitry Andric SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver)); 3668*0b57cec5SDimitry Andric return Resolver; 3669*0b57cec5SDimitry Andric } 3670*0b57cec5SDimitry Andric 3671*0b57cec5SDimitry Andric /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 3672*0b57cec5SDimitry Andric /// module, create and return an llvm Function with the specified type. If there 3673*0b57cec5SDimitry Andric /// is something in the module with the specified name, return it potentially 3674*0b57cec5SDimitry Andric /// bitcasted to the right type. 3675*0b57cec5SDimitry Andric /// 3676*0b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this. This is used 3677*0b57cec5SDimitry Andric /// to set the attributes on the function when it is first created. 3678*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( 3679*0b57cec5SDimitry Andric StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, 3680*0b57cec5SDimitry Andric bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, 3681*0b57cec5SDimitry Andric ForDefinition_t IsForDefinition) { 3682*0b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 3683*0b57cec5SDimitry Andric 3684*0b57cec5SDimitry Andric // Any attempts to use a MultiVersion function should result in retrieving 3685*0b57cec5SDimitry Andric // the iFunc instead. Name Mangling will handle the rest of the changes. 3686*0b57cec5SDimitry Andric if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) { 3687*0b57cec5SDimitry Andric // For the device mark the function as one that should be emitted. 3688*0b57cec5SDimitry Andric if (getLangOpts().OpenMPIsDevice && OpenMPRuntime && 3689*0b57cec5SDimitry Andric !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() && 3690*0b57cec5SDimitry Andric !DontDefer && !IsForDefinition) { 3691*0b57cec5SDimitry Andric if (const FunctionDecl *FDDef = FD->getDefinition()) { 3692*0b57cec5SDimitry Andric GlobalDecl GDDef; 3693*0b57cec5SDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef)) 3694*0b57cec5SDimitry Andric GDDef = GlobalDecl(CD, GD.getCtorType()); 3695*0b57cec5SDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef)) 3696*0b57cec5SDimitry Andric GDDef = GlobalDecl(DD, GD.getDtorType()); 3697*0b57cec5SDimitry Andric else 3698*0b57cec5SDimitry Andric GDDef = GlobalDecl(FDDef); 3699*0b57cec5SDimitry Andric EmitGlobal(GDDef); 3700*0b57cec5SDimitry Andric } 3701*0b57cec5SDimitry Andric } 3702*0b57cec5SDimitry Andric 3703*0b57cec5SDimitry Andric if (FD->isMultiVersion()) { 370404eeddc0SDimitry Andric UpdateMultiVersionNames(GD, FD, MangledName); 3705*0b57cec5SDimitry Andric if (!IsForDefinition) 3706*0b57cec5SDimitry Andric return GetOrCreateMultiVersionResolver(GD, Ty, FD); 3707*0b57cec5SDimitry Andric } 3708*0b57cec5SDimitry Andric } 3709*0b57cec5SDimitry Andric 3710*0b57cec5SDimitry Andric // Lookup the entry, lazily creating it if necessary. 3711*0b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3712*0b57cec5SDimitry Andric if (Entry) { 3713*0b57cec5SDimitry Andric if (WeakRefReferences.erase(Entry)) { 3714*0b57cec5SDimitry Andric const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 3715*0b57cec5SDimitry Andric if (FD && !FD->hasAttr<WeakAttr>()) 3716*0b57cec5SDimitry Andric Entry->setLinkage(llvm::Function::ExternalLinkage); 3717*0b57cec5SDimitry Andric } 3718*0b57cec5SDimitry Andric 3719*0b57cec5SDimitry Andric // Handle dropped DLL attributes. 3720*0b57cec5SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) { 3721*0b57cec5SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 3722*0b57cec5SDimitry Andric setDSOLocal(Entry); 3723*0b57cec5SDimitry Andric } 3724*0b57cec5SDimitry Andric 3725*0b57cec5SDimitry Andric // If there are two attempts to define the same mangled name, issue an 3726*0b57cec5SDimitry Andric // error. 3727*0b57cec5SDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 3728*0b57cec5SDimitry Andric GlobalDecl OtherGD; 3729*0b57cec5SDimitry Andric // Check that GD is not yet in DiagnosedConflictingDefinitions is required 3730*0b57cec5SDimitry Andric // to make sure that we issue an error only once. 3731*0b57cec5SDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 3732*0b57cec5SDimitry Andric (GD.getCanonicalDecl().getDecl() != 3733*0b57cec5SDimitry Andric OtherGD.getCanonicalDecl().getDecl()) && 3734*0b57cec5SDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 3735*0b57cec5SDimitry Andric getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 3736*0b57cec5SDimitry Andric << MangledName; 3737*0b57cec5SDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 3738*0b57cec5SDimitry Andric diag::note_previous_definition); 3739*0b57cec5SDimitry Andric } 3740*0b57cec5SDimitry Andric } 3741*0b57cec5SDimitry Andric 3742*0b57cec5SDimitry Andric if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 37435ffd83dbSDimitry Andric (Entry->getValueType() == Ty)) { 3744*0b57cec5SDimitry Andric return Entry; 3745*0b57cec5SDimitry Andric } 3746*0b57cec5SDimitry Andric 3747*0b57cec5SDimitry Andric // Make sure the result is of the correct type. 3748*0b57cec5SDimitry Andric // (If function is requested for a definition, we always need to create a new 3749*0b57cec5SDimitry Andric // function, not just return a bitcast.) 3750*0b57cec5SDimitry Andric if (!IsForDefinition) 3751*0b57cec5SDimitry Andric return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 3752*0b57cec5SDimitry Andric } 3753*0b57cec5SDimitry Andric 3754*0b57cec5SDimitry Andric // This function doesn't have a complete type (for example, the return 3755*0b57cec5SDimitry Andric // type is an incomplete struct). Use a fake type instead, and make 3756*0b57cec5SDimitry Andric // sure not to try to set attributes. 3757*0b57cec5SDimitry Andric bool IsIncompleteFunction = false; 3758*0b57cec5SDimitry Andric 3759*0b57cec5SDimitry Andric llvm::FunctionType *FTy; 3760*0b57cec5SDimitry Andric if (isa<llvm::FunctionType>(Ty)) { 3761*0b57cec5SDimitry Andric FTy = cast<llvm::FunctionType>(Ty); 3762*0b57cec5SDimitry Andric } else { 3763*0b57cec5SDimitry Andric FTy = llvm::FunctionType::get(VoidTy, false); 3764*0b57cec5SDimitry Andric IsIncompleteFunction = true; 3765*0b57cec5SDimitry Andric } 3766*0b57cec5SDimitry Andric 3767*0b57cec5SDimitry Andric llvm::Function *F = 3768*0b57cec5SDimitry Andric llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 3769*0b57cec5SDimitry Andric Entry ? StringRef() : MangledName, &getModule()); 3770*0b57cec5SDimitry Andric 3771*0b57cec5SDimitry Andric // If we already created a function with the same mangled name (but different 3772*0b57cec5SDimitry Andric // type) before, take its name and add it to the list of functions to be 3773*0b57cec5SDimitry Andric // replaced with F at the end of CodeGen. 3774*0b57cec5SDimitry Andric // 3775*0b57cec5SDimitry Andric // This happens if there is a prototype for a function (e.g. "int f()") and 3776*0b57cec5SDimitry Andric // then a definition of a different type (e.g. "int f(int x)"). 3777*0b57cec5SDimitry Andric if (Entry) { 3778*0b57cec5SDimitry Andric F->takeName(Entry); 3779*0b57cec5SDimitry Andric 3780*0b57cec5SDimitry Andric // This might be an implementation of a function without a prototype, in 3781*0b57cec5SDimitry Andric // which case, try to do special replacement of calls which match the new 3782*0b57cec5SDimitry Andric // prototype. The really key thing here is that we also potentially drop 3783*0b57cec5SDimitry Andric // arguments from the call site so as to make a direct call, which makes the 3784*0b57cec5SDimitry Andric // inliner happier and suppresses a number of optimizer warnings (!) about 3785*0b57cec5SDimitry Andric // dropping arguments. 3786*0b57cec5SDimitry Andric if (!Entry->use_empty()) { 3787*0b57cec5SDimitry Andric ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 3788*0b57cec5SDimitry Andric Entry->removeDeadConstantUsers(); 3789*0b57cec5SDimitry Andric } 3790*0b57cec5SDimitry Andric 3791*0b57cec5SDimitry Andric llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 37925ffd83dbSDimitry Andric F, Entry->getValueType()->getPointerTo()); 3793*0b57cec5SDimitry Andric addGlobalValReplacement(Entry, BC); 3794*0b57cec5SDimitry Andric } 3795*0b57cec5SDimitry Andric 3796*0b57cec5SDimitry Andric assert(F->getName() == MangledName && "name was uniqued!"); 3797*0b57cec5SDimitry Andric if (D) 3798*0b57cec5SDimitry Andric SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 3799349cc55cSDimitry Andric if (ExtraAttrs.hasFnAttrs()) { 380004eeddc0SDimitry Andric llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs()); 3801349cc55cSDimitry Andric F->addFnAttrs(B); 3802*0b57cec5SDimitry Andric } 3803*0b57cec5SDimitry Andric 3804*0b57cec5SDimitry Andric if (!DontDefer) { 3805*0b57cec5SDimitry Andric // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 3806*0b57cec5SDimitry Andric // each other bottoming out with the base dtor. Therefore we emit non-base 3807*0b57cec5SDimitry Andric // dtors on usage, even if there is no dtor definition in the TU. 3808*0b57cec5SDimitry Andric if (D && isa<CXXDestructorDecl>(D) && 3809*0b57cec5SDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 3810*0b57cec5SDimitry Andric GD.getDtorType())) 3811*0b57cec5SDimitry Andric addDeferredDeclToEmit(GD); 3812*0b57cec5SDimitry Andric 3813*0b57cec5SDimitry Andric // This is the first use or definition of a mangled name. If there is a 3814*0b57cec5SDimitry Andric // deferred decl with this name, remember that we need to emit it at the end 3815*0b57cec5SDimitry Andric // of the file. 3816*0b57cec5SDimitry Andric auto DDI = DeferredDecls.find(MangledName); 3817*0b57cec5SDimitry Andric if (DDI != DeferredDecls.end()) { 3818*0b57cec5SDimitry Andric // Move the potentially referenced deferred decl to the 3819*0b57cec5SDimitry Andric // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 3820*0b57cec5SDimitry Andric // don't need it anymore). 3821*0b57cec5SDimitry Andric addDeferredDeclToEmit(DDI->second); 3822*0b57cec5SDimitry Andric DeferredDecls.erase(DDI); 3823*0b57cec5SDimitry Andric 3824*0b57cec5SDimitry Andric // Otherwise, there are cases we have to worry about where we're 3825*0b57cec5SDimitry Andric // using a declaration for which we must emit a definition but where 3826*0b57cec5SDimitry Andric // we might not find a top-level definition: 3827*0b57cec5SDimitry Andric // - member functions defined inline in their classes 3828*0b57cec5SDimitry Andric // - friend functions defined inline in some class 3829*0b57cec5SDimitry Andric // - special member functions with implicit definitions 3830*0b57cec5SDimitry Andric // If we ever change our AST traversal to walk into class methods, 3831*0b57cec5SDimitry Andric // this will be unnecessary. 3832*0b57cec5SDimitry Andric // 3833*0b57cec5SDimitry Andric // We also don't emit a definition for a function if it's going to be an 3834*0b57cec5SDimitry Andric // entry in a vtable, unless it's already marked as used. 3835*0b57cec5SDimitry Andric } else if (getLangOpts().CPlusPlus && D) { 3836*0b57cec5SDimitry Andric // Look for a declaration that's lexically in a record. 3837*0b57cec5SDimitry Andric for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 3838*0b57cec5SDimitry Andric FD = FD->getPreviousDecl()) { 3839*0b57cec5SDimitry Andric if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 3840*0b57cec5SDimitry Andric if (FD->doesThisDeclarationHaveABody()) { 3841*0b57cec5SDimitry Andric addDeferredDeclToEmit(GD.getWithDecl(FD)); 3842*0b57cec5SDimitry Andric break; 3843*0b57cec5SDimitry Andric } 3844*0b57cec5SDimitry Andric } 3845*0b57cec5SDimitry Andric } 3846*0b57cec5SDimitry Andric } 3847*0b57cec5SDimitry Andric } 3848*0b57cec5SDimitry Andric 3849*0b57cec5SDimitry Andric // Make sure the result is of the requested type. 3850*0b57cec5SDimitry Andric if (!IsIncompleteFunction) { 38515ffd83dbSDimitry Andric assert(F->getFunctionType() == Ty); 3852*0b57cec5SDimitry Andric return F; 3853*0b57cec5SDimitry Andric } 3854*0b57cec5SDimitry Andric 3855*0b57cec5SDimitry Andric llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 3856*0b57cec5SDimitry Andric return llvm::ConstantExpr::getBitCast(F, PTy); 3857*0b57cec5SDimitry Andric } 3858*0b57cec5SDimitry Andric 3859*0b57cec5SDimitry Andric /// GetAddrOfFunction - Return the address of the given function. If Ty is 3860*0b57cec5SDimitry Andric /// non-null, then this function will use the specified type if it has to 3861*0b57cec5SDimitry Andric /// create it (this occurs when we see a definition of the function). 3862*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 3863*0b57cec5SDimitry Andric llvm::Type *Ty, 3864*0b57cec5SDimitry Andric bool ForVTable, 3865*0b57cec5SDimitry Andric bool DontDefer, 3866*0b57cec5SDimitry Andric ForDefinition_t IsForDefinition) { 38675ffd83dbSDimitry Andric assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() && 38685ffd83dbSDimitry Andric "consteval function should never be emitted"); 3869*0b57cec5SDimitry Andric // If there was no specific requested type, just convert it now. 3870*0b57cec5SDimitry Andric if (!Ty) { 3871*0b57cec5SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3872*0b57cec5SDimitry Andric Ty = getTypes().ConvertType(FD->getType()); 3873*0b57cec5SDimitry Andric } 3874*0b57cec5SDimitry Andric 3875*0b57cec5SDimitry Andric // Devirtualized destructor calls may come through here instead of via 3876*0b57cec5SDimitry Andric // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead 3877*0b57cec5SDimitry Andric // of the complete destructor when necessary. 3878*0b57cec5SDimitry Andric if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) { 3879*0b57cec5SDimitry Andric if (getTarget().getCXXABI().isMicrosoft() && 3880*0b57cec5SDimitry Andric GD.getDtorType() == Dtor_Complete && 3881*0b57cec5SDimitry Andric DD->getParent()->getNumVBases() == 0) 3882*0b57cec5SDimitry Andric GD = GlobalDecl(DD, Dtor_Base); 3883*0b57cec5SDimitry Andric } 3884*0b57cec5SDimitry Andric 3885*0b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 3886fe6060f1SDimitry Andric auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 3887*0b57cec5SDimitry Andric /*IsThunk=*/false, llvm::AttributeList(), 3888*0b57cec5SDimitry Andric IsForDefinition); 3889fe6060f1SDimitry Andric // Returns kernel handle for HIP kernel stub function. 3890fe6060f1SDimitry Andric if (LangOpts.CUDA && !LangOpts.CUDAIsDevice && 3891fe6060f1SDimitry Andric cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) { 3892fe6060f1SDimitry Andric auto *Handle = getCUDARuntime().getKernelHandle( 3893fe6060f1SDimitry Andric cast<llvm::Function>(F->stripPointerCasts()), GD); 3894fe6060f1SDimitry Andric if (IsForDefinition) 3895fe6060f1SDimitry Andric return F; 3896fe6060f1SDimitry Andric return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo()); 3897fe6060f1SDimitry Andric } 3898fe6060f1SDimitry Andric return F; 3899*0b57cec5SDimitry Andric } 3900*0b57cec5SDimitry Andric 39010eae32dcSDimitry Andric llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) { 39020eae32dcSDimitry Andric llvm::GlobalValue *F = 39030eae32dcSDimitry Andric cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts()); 39040eae32dcSDimitry Andric 39050eae32dcSDimitry Andric return llvm::ConstantExpr::getBitCast(llvm::NoCFIValue::get(F), 39060eae32dcSDimitry Andric llvm::Type::getInt8PtrTy(VMContext)); 39070eae32dcSDimitry Andric } 39080eae32dcSDimitry Andric 3909*0b57cec5SDimitry Andric static const FunctionDecl * 3910*0b57cec5SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { 3911*0b57cec5SDimitry Andric TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 3912*0b57cec5SDimitry Andric DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 3913*0b57cec5SDimitry Andric 3914*0b57cec5SDimitry Andric IdentifierInfo &CII = C.Idents.get(Name); 3915fe6060f1SDimitry Andric for (const auto *Result : DC->lookup(&CII)) 3916fe6060f1SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 3917*0b57cec5SDimitry Andric return FD; 3918*0b57cec5SDimitry Andric 3919*0b57cec5SDimitry Andric if (!C.getLangOpts().CPlusPlus) 3920*0b57cec5SDimitry Andric return nullptr; 3921*0b57cec5SDimitry Andric 3922*0b57cec5SDimitry Andric // Demangle the premangled name from getTerminateFn() 3923*0b57cec5SDimitry Andric IdentifierInfo &CXXII = 3924*0b57cec5SDimitry Andric (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ") 3925*0b57cec5SDimitry Andric ? C.Idents.get("terminate") 3926*0b57cec5SDimitry Andric : C.Idents.get(Name); 3927*0b57cec5SDimitry Andric 3928*0b57cec5SDimitry Andric for (const auto &N : {"__cxxabiv1", "std"}) { 3929*0b57cec5SDimitry Andric IdentifierInfo &NS = C.Idents.get(N); 3930fe6060f1SDimitry Andric for (const auto *Result : DC->lookup(&NS)) { 3931fe6060f1SDimitry Andric const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); 3932fe6060f1SDimitry Andric if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result)) 3933fe6060f1SDimitry Andric for (const auto *Result : LSD->lookup(&NS)) 3934*0b57cec5SDimitry Andric if ((ND = dyn_cast<NamespaceDecl>(Result))) 3935*0b57cec5SDimitry Andric break; 3936*0b57cec5SDimitry Andric 3937*0b57cec5SDimitry Andric if (ND) 3938fe6060f1SDimitry Andric for (const auto *Result : ND->lookup(&CXXII)) 3939*0b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 3940*0b57cec5SDimitry Andric return FD; 3941*0b57cec5SDimitry Andric } 3942*0b57cec5SDimitry Andric } 3943*0b57cec5SDimitry Andric 3944*0b57cec5SDimitry Andric return nullptr; 3945*0b57cec5SDimitry Andric } 3946*0b57cec5SDimitry Andric 3947*0b57cec5SDimitry Andric /// CreateRuntimeFunction - Create a new runtime function with the specified 3948*0b57cec5SDimitry Andric /// type and name. 3949*0b57cec5SDimitry Andric llvm::FunctionCallee 3950*0b57cec5SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, 3951480093f4SDimitry Andric llvm::AttributeList ExtraAttrs, bool Local, 3952480093f4SDimitry Andric bool AssumeConvergent) { 3953480093f4SDimitry Andric if (AssumeConvergent) { 3954480093f4SDimitry Andric ExtraAttrs = 3955349cc55cSDimitry Andric ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent); 3956480093f4SDimitry Andric } 3957480093f4SDimitry Andric 3958*0b57cec5SDimitry Andric llvm::Constant *C = 3959*0b57cec5SDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 3960*0b57cec5SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, 3961*0b57cec5SDimitry Andric ExtraAttrs); 3962*0b57cec5SDimitry Andric 3963*0b57cec5SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) { 3964*0b57cec5SDimitry Andric if (F->empty()) { 3965*0b57cec5SDimitry Andric F->setCallingConv(getRuntimeCC()); 3966*0b57cec5SDimitry Andric 3967*0b57cec5SDimitry Andric // In Windows Itanium environments, try to mark runtime functions 3968*0b57cec5SDimitry Andric // dllimport. For Mingw and MSVC, don't. We don't really know if the user 3969*0b57cec5SDimitry Andric // will link their standard library statically or dynamically. Marking 3970*0b57cec5SDimitry Andric // functions imported when they are not imported can cause linker errors 3971*0b57cec5SDimitry Andric // and warnings. 3972*0b57cec5SDimitry Andric if (!Local && getTriple().isWindowsItaniumEnvironment() && 3973*0b57cec5SDimitry Andric !getCodeGenOpts().LTOVisibilityPublicStd) { 3974*0b57cec5SDimitry Andric const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); 3975*0b57cec5SDimitry Andric if (!FD || FD->hasAttr<DLLImportAttr>()) { 3976*0b57cec5SDimitry Andric F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 3977*0b57cec5SDimitry Andric F->setLinkage(llvm::GlobalValue::ExternalLinkage); 3978*0b57cec5SDimitry Andric } 3979*0b57cec5SDimitry Andric } 3980*0b57cec5SDimitry Andric setDSOLocal(F); 3981*0b57cec5SDimitry Andric } 3982*0b57cec5SDimitry Andric } 3983*0b57cec5SDimitry Andric 3984*0b57cec5SDimitry Andric return {FTy, C}; 3985*0b57cec5SDimitry Andric } 3986*0b57cec5SDimitry Andric 3987*0b57cec5SDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted 3988*0b57cec5SDimitry Andric /// as a constant. 3989*0b57cec5SDimitry Andric /// 3990*0b57cec5SDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs 3991*0b57cec5SDimitry Andric /// will not be considered. The caller will need to verify that the object is 3992*0b57cec5SDimitry Andric /// not written to during its construction. 3993*0b57cec5SDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 3994*0b57cec5SDimitry Andric if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 3995*0b57cec5SDimitry Andric return false; 3996*0b57cec5SDimitry Andric 3997*0b57cec5SDimitry Andric if (Context.getLangOpts().CPlusPlus) { 3998*0b57cec5SDimitry Andric if (const CXXRecordDecl *Record 3999*0b57cec5SDimitry Andric = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 4000*0b57cec5SDimitry Andric return ExcludeCtor && !Record->hasMutableFields() && 4001*0b57cec5SDimitry Andric Record->hasTrivialDestructor(); 4002*0b57cec5SDimitry Andric } 4003*0b57cec5SDimitry Andric 4004*0b57cec5SDimitry Andric return true; 4005*0b57cec5SDimitry Andric } 4006*0b57cec5SDimitry Andric 4007*0b57cec5SDimitry Andric /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 4008fe6060f1SDimitry Andric /// create and return an llvm GlobalVariable with the specified type and address 4009fe6060f1SDimitry Andric /// space. If there is something in the module with the specified name, return 4010fe6060f1SDimitry Andric /// it potentially bitcasted to the right type. 4011*0b57cec5SDimitry Andric /// 4012*0b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this. This is used 4013*0b57cec5SDimitry Andric /// to set the attributes on the global when it is first created. 4014*0b57cec5SDimitry Andric /// 4015*0b57cec5SDimitry Andric /// If IsForDefinition is true, it is guaranteed that an actual global with 4016*0b57cec5SDimitry Andric /// type Ty will be returned, not conversion of a variable with the same 4017*0b57cec5SDimitry Andric /// mangled name but some other type. 4018*0b57cec5SDimitry Andric llvm::Constant * 4019fe6060f1SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, 4020349cc55cSDimitry Andric LangAS AddrSpace, const VarDecl *D, 4021*0b57cec5SDimitry Andric ForDefinition_t IsForDefinition) { 4022*0b57cec5SDimitry Andric // Lookup the entry, lazily creating it if necessary. 4023*0b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4024349cc55cSDimitry Andric unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace); 4025*0b57cec5SDimitry Andric if (Entry) { 4026*0b57cec5SDimitry Andric if (WeakRefReferences.erase(Entry)) { 4027*0b57cec5SDimitry Andric if (D && !D->hasAttr<WeakAttr>()) 4028*0b57cec5SDimitry Andric Entry->setLinkage(llvm::Function::ExternalLinkage); 4029*0b57cec5SDimitry Andric } 4030*0b57cec5SDimitry Andric 4031*0b57cec5SDimitry Andric // Handle dropped DLL attributes. 4032*0b57cec5SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 4033*0b57cec5SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 4034*0b57cec5SDimitry Andric 4035*0b57cec5SDimitry Andric if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D) 4036*0b57cec5SDimitry Andric getOpenMPRuntime().registerTargetGlobalVariable(D, Entry); 4037*0b57cec5SDimitry Andric 4038349cc55cSDimitry Andric if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS) 4039*0b57cec5SDimitry Andric return Entry; 4040*0b57cec5SDimitry Andric 4041*0b57cec5SDimitry Andric // If there are two attempts to define the same mangled name, issue an 4042*0b57cec5SDimitry Andric // error. 4043*0b57cec5SDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 4044*0b57cec5SDimitry Andric GlobalDecl OtherGD; 4045*0b57cec5SDimitry Andric const VarDecl *OtherD; 4046*0b57cec5SDimitry Andric 4047*0b57cec5SDimitry Andric // Check that D is not yet in DiagnosedConflictingDefinitions is required 4048*0b57cec5SDimitry Andric // to make sure that we issue an error only once. 4049*0b57cec5SDimitry Andric if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 4050*0b57cec5SDimitry Andric (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 4051*0b57cec5SDimitry Andric (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 4052*0b57cec5SDimitry Andric OtherD->hasInit() && 4053*0b57cec5SDimitry Andric DiagnosedConflictingDefinitions.insert(D).second) { 4054*0b57cec5SDimitry Andric getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 4055*0b57cec5SDimitry Andric << MangledName; 4056*0b57cec5SDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 4057*0b57cec5SDimitry Andric diag::note_previous_definition); 4058*0b57cec5SDimitry Andric } 4059*0b57cec5SDimitry Andric } 4060*0b57cec5SDimitry Andric 4061*0b57cec5SDimitry Andric // Make sure the result is of the correct type. 4062349cc55cSDimitry Andric if (Entry->getType()->getAddressSpace() != TargetAS) { 4063fe6060f1SDimitry Andric return llvm::ConstantExpr::getAddrSpaceCast(Entry, 4064349cc55cSDimitry Andric Ty->getPointerTo(TargetAS)); 4065fe6060f1SDimitry Andric } 4066*0b57cec5SDimitry Andric 4067*0b57cec5SDimitry Andric // (If global is requested for a definition, we always need to create a new 4068*0b57cec5SDimitry Andric // global, not just return a bitcast.) 4069*0b57cec5SDimitry Andric if (!IsForDefinition) 4070349cc55cSDimitry Andric return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(TargetAS)); 4071*0b57cec5SDimitry Andric } 4072*0b57cec5SDimitry Andric 4073fe6060f1SDimitry Andric auto DAddrSpace = GetGlobalVarAddressSpace(D); 4074*0b57cec5SDimitry Andric 4075*0b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 4076fe6060f1SDimitry Andric getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr, 4077fe6060f1SDimitry Andric MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal, 4078349cc55cSDimitry Andric getContext().getTargetAddressSpace(DAddrSpace)); 4079*0b57cec5SDimitry Andric 4080*0b57cec5SDimitry Andric // If we already created a global with the same mangled name (but different 4081*0b57cec5SDimitry Andric // type) before, take its name and remove it from its parent. 4082*0b57cec5SDimitry Andric if (Entry) { 4083*0b57cec5SDimitry Andric GV->takeName(Entry); 4084*0b57cec5SDimitry Andric 4085*0b57cec5SDimitry Andric if (!Entry->use_empty()) { 4086*0b57cec5SDimitry Andric llvm::Constant *NewPtrForOldDecl = 4087*0b57cec5SDimitry Andric llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 4088*0b57cec5SDimitry Andric Entry->replaceAllUsesWith(NewPtrForOldDecl); 4089*0b57cec5SDimitry Andric } 4090*0b57cec5SDimitry Andric 4091*0b57cec5SDimitry Andric Entry->eraseFromParent(); 4092*0b57cec5SDimitry Andric } 4093*0b57cec5SDimitry Andric 4094*0b57cec5SDimitry Andric // This is the first use or definition of a mangled name. If there is a 4095*0b57cec5SDimitry Andric // deferred decl with this name, remember that we need to emit it at the end 4096*0b57cec5SDimitry Andric // of the file. 4097*0b57cec5SDimitry Andric auto DDI = DeferredDecls.find(MangledName); 4098*0b57cec5SDimitry Andric if (DDI != DeferredDecls.end()) { 4099*0b57cec5SDimitry Andric // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 4100*0b57cec5SDimitry Andric // list, and remove it from DeferredDecls (since we don't need it anymore). 4101*0b57cec5SDimitry Andric addDeferredDeclToEmit(DDI->second); 4102*0b57cec5SDimitry Andric DeferredDecls.erase(DDI); 4103*0b57cec5SDimitry Andric } 4104*0b57cec5SDimitry Andric 4105*0b57cec5SDimitry Andric // Handle things which are present even on external declarations. 4106*0b57cec5SDimitry Andric if (D) { 4107*0b57cec5SDimitry Andric if (LangOpts.OpenMP && !LangOpts.OpenMPSimd) 4108*0b57cec5SDimitry Andric getOpenMPRuntime().registerTargetGlobalVariable(D, GV); 4109*0b57cec5SDimitry Andric 4110*0b57cec5SDimitry Andric // FIXME: This code is overly simple and should be merged with other global 4111*0b57cec5SDimitry Andric // handling. 4112*0b57cec5SDimitry Andric GV->setConstant(isTypeConstant(D->getType(), false)); 4113*0b57cec5SDimitry Andric 4114a7dea167SDimitry Andric GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); 4115*0b57cec5SDimitry Andric 4116*0b57cec5SDimitry Andric setLinkageForGV(GV, D); 4117*0b57cec5SDimitry Andric 4118*0b57cec5SDimitry Andric if (D->getTLSKind()) { 4119*0b57cec5SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 4120*0b57cec5SDimitry Andric CXXThreadLocals.push_back(D); 4121*0b57cec5SDimitry Andric setTLSMode(GV, *D); 4122*0b57cec5SDimitry Andric } 4123*0b57cec5SDimitry Andric 4124*0b57cec5SDimitry Andric setGVProperties(GV, D); 4125*0b57cec5SDimitry Andric 4126*0b57cec5SDimitry Andric // If required by the ABI, treat declarations of static data members with 4127*0b57cec5SDimitry Andric // inline initializers as definitions. 4128*0b57cec5SDimitry Andric if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 4129*0b57cec5SDimitry Andric EmitGlobalVarDefinition(D); 4130*0b57cec5SDimitry Andric } 4131*0b57cec5SDimitry Andric 4132*0b57cec5SDimitry Andric // Emit section information for extern variables. 4133*0b57cec5SDimitry Andric if (D->hasExternalStorage()) { 4134*0b57cec5SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 4135*0b57cec5SDimitry Andric GV->setSection(SA->getName()); 4136*0b57cec5SDimitry Andric } 4137*0b57cec5SDimitry Andric 4138*0b57cec5SDimitry Andric // Handle XCore specific ABI requirements. 4139*0b57cec5SDimitry Andric if (getTriple().getArch() == llvm::Triple::xcore && 4140*0b57cec5SDimitry Andric D->getLanguageLinkage() == CLanguageLinkage && 4141*0b57cec5SDimitry Andric D->getType().isConstant(Context) && 4142*0b57cec5SDimitry Andric isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 4143*0b57cec5SDimitry Andric GV->setSection(".cp.rodata"); 4144*0b57cec5SDimitry Andric 4145*0b57cec5SDimitry Andric // Check if we a have a const declaration with an initializer, we may be 4146*0b57cec5SDimitry Andric // able to emit it as available_externally to expose it's value to the 4147*0b57cec5SDimitry Andric // optimizer. 4148*0b57cec5SDimitry Andric if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() && 4149*0b57cec5SDimitry Andric D->getType().isConstQualified() && !GV->hasInitializer() && 4150*0b57cec5SDimitry Andric !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) { 4151*0b57cec5SDimitry Andric const auto *Record = 4152*0b57cec5SDimitry Andric Context.getBaseElementType(D->getType())->getAsCXXRecordDecl(); 4153*0b57cec5SDimitry Andric bool HasMutableFields = Record && Record->hasMutableFields(); 4154*0b57cec5SDimitry Andric if (!HasMutableFields) { 4155*0b57cec5SDimitry Andric const VarDecl *InitDecl; 4156*0b57cec5SDimitry Andric const Expr *InitExpr = D->getAnyInitializer(InitDecl); 4157*0b57cec5SDimitry Andric if (InitExpr) { 4158*0b57cec5SDimitry Andric ConstantEmitter emitter(*this); 4159*0b57cec5SDimitry Andric llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl); 4160*0b57cec5SDimitry Andric if (Init) { 4161*0b57cec5SDimitry Andric auto *InitType = Init->getType(); 41625ffd83dbSDimitry Andric if (GV->getValueType() != InitType) { 4163*0b57cec5SDimitry Andric // The type of the initializer does not match the definition. 4164*0b57cec5SDimitry Andric // This happens when an initializer has a different type from 4165*0b57cec5SDimitry Andric // the type of the global (because of padding at the end of a 4166*0b57cec5SDimitry Andric // structure for instance). 4167*0b57cec5SDimitry Andric GV->setName(StringRef()); 4168*0b57cec5SDimitry Andric // Make a new global with the correct type, this is now guaranteed 4169*0b57cec5SDimitry Andric // to work. 4170*0b57cec5SDimitry Andric auto *NewGV = cast<llvm::GlobalVariable>( 4171a7dea167SDimitry Andric GetAddrOfGlobalVar(D, InitType, IsForDefinition) 4172a7dea167SDimitry Andric ->stripPointerCasts()); 4173*0b57cec5SDimitry Andric 4174*0b57cec5SDimitry Andric // Erase the old global, since it is no longer used. 4175*0b57cec5SDimitry Andric GV->eraseFromParent(); 4176*0b57cec5SDimitry Andric GV = NewGV; 4177*0b57cec5SDimitry Andric } else { 4178*0b57cec5SDimitry Andric GV->setInitializer(Init); 4179*0b57cec5SDimitry Andric GV->setConstant(true); 4180*0b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 4181*0b57cec5SDimitry Andric } 4182*0b57cec5SDimitry Andric emitter.finalize(GV); 4183*0b57cec5SDimitry Andric } 4184*0b57cec5SDimitry Andric } 4185*0b57cec5SDimitry Andric } 4186*0b57cec5SDimitry Andric } 4187*0b57cec5SDimitry Andric } 4188*0b57cec5SDimitry Andric 4189fe6060f1SDimitry Andric if (GV->isDeclaration()) { 4190480093f4SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(D, GV, *this); 4191fe6060f1SDimitry Andric // External HIP managed variables needed to be recorded for transformation 4192fe6060f1SDimitry Andric // in both device and host compilations. 4193fe6060f1SDimitry Andric if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() && 4194fe6060f1SDimitry Andric D->hasExternalStorage()) 4195fe6060f1SDimitry Andric getCUDARuntime().handleVarRegistration(D, *GV); 4196fe6060f1SDimitry Andric } 4197480093f4SDimitry Andric 4198*0b57cec5SDimitry Andric LangAS ExpectedAS = 4199*0b57cec5SDimitry Andric D ? D->getType().getAddressSpace() 4200*0b57cec5SDimitry Andric : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default); 4201349cc55cSDimitry Andric assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS); 4202fe6060f1SDimitry Andric if (DAddrSpace != ExpectedAS) { 4203fe6060f1SDimitry Andric return getTargetCodeGenInfo().performAddrSpaceCast( 4204349cc55cSDimitry Andric *this, GV, DAddrSpace, ExpectedAS, Ty->getPointerTo(TargetAS)); 4205fe6060f1SDimitry Andric } 4206*0b57cec5SDimitry Andric 4207*0b57cec5SDimitry Andric return GV; 4208*0b57cec5SDimitry Andric } 4209*0b57cec5SDimitry Andric 4210*0b57cec5SDimitry Andric llvm::Constant * 42115ffd83dbSDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) { 4212*0b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 42135ffd83dbSDimitry Andric 4214*0b57cec5SDimitry Andric if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 4215*0b57cec5SDimitry Andric return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr, 4216*0b57cec5SDimitry Andric /*DontDefer=*/false, IsForDefinition); 42175ffd83dbSDimitry Andric 42185ffd83dbSDimitry Andric if (isa<CXXMethodDecl>(D)) { 42195ffd83dbSDimitry Andric auto FInfo = 42205ffd83dbSDimitry Andric &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D)); 4221*0b57cec5SDimitry Andric auto Ty = getTypes().GetFunctionType(*FInfo); 4222*0b57cec5SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 4223*0b57cec5SDimitry Andric IsForDefinition); 42245ffd83dbSDimitry Andric } 42255ffd83dbSDimitry Andric 42265ffd83dbSDimitry Andric if (isa<FunctionDecl>(D)) { 4227*0b57cec5SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 4228*0b57cec5SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 4229*0b57cec5SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 4230*0b57cec5SDimitry Andric IsForDefinition); 42315ffd83dbSDimitry Andric } 42325ffd83dbSDimitry Andric 42335ffd83dbSDimitry Andric return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition); 4234*0b57cec5SDimitry Andric } 4235*0b57cec5SDimitry Andric 4236*0b57cec5SDimitry Andric llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable( 4237*0b57cec5SDimitry Andric StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, 4238*0b57cec5SDimitry Andric unsigned Alignment) { 4239*0b57cec5SDimitry Andric llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 4240*0b57cec5SDimitry Andric llvm::GlobalVariable *OldGV = nullptr; 4241*0b57cec5SDimitry Andric 4242*0b57cec5SDimitry Andric if (GV) { 4243*0b57cec5SDimitry Andric // Check if the variable has the right type. 42445ffd83dbSDimitry Andric if (GV->getValueType() == Ty) 4245*0b57cec5SDimitry Andric return GV; 4246*0b57cec5SDimitry Andric 4247*0b57cec5SDimitry Andric // Because C++ name mangling, the only way we can end up with an already 4248*0b57cec5SDimitry Andric // existing global with the same name is if it has been declared extern "C". 4249*0b57cec5SDimitry Andric assert(GV->isDeclaration() && "Declaration has wrong type!"); 4250*0b57cec5SDimitry Andric OldGV = GV; 4251*0b57cec5SDimitry Andric } 4252*0b57cec5SDimitry Andric 4253*0b57cec5SDimitry Andric // Create a new variable. 4254*0b57cec5SDimitry Andric GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 4255*0b57cec5SDimitry Andric Linkage, nullptr, Name); 4256*0b57cec5SDimitry Andric 4257*0b57cec5SDimitry Andric if (OldGV) { 4258*0b57cec5SDimitry Andric // Replace occurrences of the old variable if needed. 4259*0b57cec5SDimitry Andric GV->takeName(OldGV); 4260*0b57cec5SDimitry Andric 4261*0b57cec5SDimitry Andric if (!OldGV->use_empty()) { 4262*0b57cec5SDimitry Andric llvm::Constant *NewPtrForOldDecl = 4263*0b57cec5SDimitry Andric llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 4264*0b57cec5SDimitry Andric OldGV->replaceAllUsesWith(NewPtrForOldDecl); 4265*0b57cec5SDimitry Andric } 4266*0b57cec5SDimitry Andric 4267*0b57cec5SDimitry Andric OldGV->eraseFromParent(); 4268*0b57cec5SDimitry Andric } 4269*0b57cec5SDimitry Andric 4270*0b57cec5SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker() && 4271*0b57cec5SDimitry Andric !GV->hasAvailableExternallyLinkage()) 4272*0b57cec5SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 4273*0b57cec5SDimitry Andric 4274a7dea167SDimitry Andric GV->setAlignment(llvm::MaybeAlign(Alignment)); 4275*0b57cec5SDimitry Andric 4276*0b57cec5SDimitry Andric return GV; 4277*0b57cec5SDimitry Andric } 4278*0b57cec5SDimitry Andric 4279*0b57cec5SDimitry Andric /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 4280*0b57cec5SDimitry Andric /// given global variable. If Ty is non-null and if the global doesn't exist, 4281*0b57cec5SDimitry Andric /// then it will be created with the specified type instead of whatever the 4282*0b57cec5SDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guaranteed 4283*0b57cec5SDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a 4284*0b57cec5SDimitry Andric /// variable with the same mangled name but some other type. 4285*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 4286*0b57cec5SDimitry Andric llvm::Type *Ty, 4287*0b57cec5SDimitry Andric ForDefinition_t IsForDefinition) { 4288*0b57cec5SDimitry Andric assert(D->hasGlobalStorage() && "Not a global variable"); 4289*0b57cec5SDimitry Andric QualType ASTTy = D->getType(); 4290*0b57cec5SDimitry Andric if (!Ty) 4291*0b57cec5SDimitry Andric Ty = getTypes().ConvertTypeForMem(ASTTy); 4292*0b57cec5SDimitry Andric 4293*0b57cec5SDimitry Andric StringRef MangledName = getMangledName(D); 4294349cc55cSDimitry Andric return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D, 4295fe6060f1SDimitry Andric IsForDefinition); 4296*0b57cec5SDimitry Andric } 4297*0b57cec5SDimitry Andric 4298*0b57cec5SDimitry Andric /// CreateRuntimeVariable - Create a new runtime global variable with the 4299*0b57cec5SDimitry Andric /// specified type and name. 4300*0b57cec5SDimitry Andric llvm::Constant * 4301*0b57cec5SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 4302*0b57cec5SDimitry Andric StringRef Name) { 4303349cc55cSDimitry Andric LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global 4304349cc55cSDimitry Andric : LangAS::Default; 4305fe6060f1SDimitry Andric auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr); 4306*0b57cec5SDimitry Andric setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts())); 4307*0b57cec5SDimitry Andric return Ret; 4308*0b57cec5SDimitry Andric } 4309*0b57cec5SDimitry Andric 4310*0b57cec5SDimitry Andric void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 4311*0b57cec5SDimitry Andric assert(!D->getInit() && "Cannot emit definite definitions here!"); 4312*0b57cec5SDimitry Andric 4313*0b57cec5SDimitry Andric StringRef MangledName = getMangledName(D); 4314*0b57cec5SDimitry Andric llvm::GlobalValue *GV = GetGlobalValue(MangledName); 4315*0b57cec5SDimitry Andric 4316*0b57cec5SDimitry Andric // We already have a definition, not declaration, with the same mangled name. 4317*0b57cec5SDimitry Andric // Emitting of declaration is not required (and actually overwrites emitted 4318*0b57cec5SDimitry Andric // definition). 4319*0b57cec5SDimitry Andric if (GV && !GV->isDeclaration()) 4320*0b57cec5SDimitry Andric return; 4321*0b57cec5SDimitry Andric 4322*0b57cec5SDimitry Andric // If we have not seen a reference to this variable yet, place it into the 4323*0b57cec5SDimitry Andric // deferred declarations table to be emitted if needed later. 4324*0b57cec5SDimitry Andric if (!MustBeEmitted(D) && !GV) { 4325*0b57cec5SDimitry Andric DeferredDecls[MangledName] = D; 4326*0b57cec5SDimitry Andric return; 4327*0b57cec5SDimitry Andric } 4328*0b57cec5SDimitry Andric 4329*0b57cec5SDimitry Andric // The tentative definition is the only definition. 4330*0b57cec5SDimitry Andric EmitGlobalVarDefinition(D); 4331*0b57cec5SDimitry Andric } 4332*0b57cec5SDimitry Andric 4333480093f4SDimitry Andric void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) { 4334480093f4SDimitry Andric EmitExternalVarDeclaration(D); 4335480093f4SDimitry Andric } 4336480093f4SDimitry Andric 4337*0b57cec5SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 4338*0b57cec5SDimitry Andric return Context.toCharUnitsFromBits( 4339*0b57cec5SDimitry Andric getDataLayout().getTypeStoreSizeInBits(Ty)); 4340*0b57cec5SDimitry Andric } 4341*0b57cec5SDimitry Andric 4342*0b57cec5SDimitry Andric LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { 4343*0b57cec5SDimitry Andric if (LangOpts.OpenCL) { 4344349cc55cSDimitry Andric LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global; 4345349cc55cSDimitry Andric assert(AS == LangAS::opencl_global || 4346349cc55cSDimitry Andric AS == LangAS::opencl_global_device || 4347349cc55cSDimitry Andric AS == LangAS::opencl_global_host || 4348349cc55cSDimitry Andric AS == LangAS::opencl_constant || 4349349cc55cSDimitry Andric AS == LangAS::opencl_local || 4350349cc55cSDimitry Andric AS >= LangAS::FirstTargetAddressSpace); 4351349cc55cSDimitry Andric return AS; 4352*0b57cec5SDimitry Andric } 4353*0b57cec5SDimitry Andric 4354fe6060f1SDimitry Andric if (LangOpts.SYCLIsDevice && 4355fe6060f1SDimitry Andric (!D || D->getType().getAddressSpace() == LangAS::Default)) 4356fe6060f1SDimitry Andric return LangAS::sycl_global; 4357fe6060f1SDimitry Andric 4358*0b57cec5SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { 4359*0b57cec5SDimitry Andric if (D && D->hasAttr<CUDAConstantAttr>()) 4360*0b57cec5SDimitry Andric return LangAS::cuda_constant; 4361*0b57cec5SDimitry Andric else if (D && D->hasAttr<CUDASharedAttr>()) 4362*0b57cec5SDimitry Andric return LangAS::cuda_shared; 4363*0b57cec5SDimitry Andric else if (D && D->hasAttr<CUDADeviceAttr>()) 4364*0b57cec5SDimitry Andric return LangAS::cuda_device; 4365*0b57cec5SDimitry Andric else if (D && D->getType().isConstQualified()) 4366*0b57cec5SDimitry Andric return LangAS::cuda_constant; 4367*0b57cec5SDimitry Andric else 4368*0b57cec5SDimitry Andric return LangAS::cuda_device; 4369*0b57cec5SDimitry Andric } 4370*0b57cec5SDimitry Andric 4371*0b57cec5SDimitry Andric if (LangOpts.OpenMP) { 4372*0b57cec5SDimitry Andric LangAS AS; 4373*0b57cec5SDimitry Andric if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS)) 4374*0b57cec5SDimitry Andric return AS; 4375*0b57cec5SDimitry Andric } 4376*0b57cec5SDimitry Andric return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D); 4377*0b57cec5SDimitry Andric } 4378*0b57cec5SDimitry Andric 4379fe6060f1SDimitry Andric LangAS CodeGenModule::GetGlobalConstantAddressSpace() const { 4380*0b57cec5SDimitry Andric // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 4381*0b57cec5SDimitry Andric if (LangOpts.OpenCL) 4382*0b57cec5SDimitry Andric return LangAS::opencl_constant; 4383fe6060f1SDimitry Andric if (LangOpts.SYCLIsDevice) 4384fe6060f1SDimitry Andric return LangAS::sycl_global; 4385*0b57cec5SDimitry Andric if (auto AS = getTarget().getConstantAddressSpace()) 4386*0b57cec5SDimitry Andric return AS.getValue(); 4387*0b57cec5SDimitry Andric return LangAS::Default; 4388*0b57cec5SDimitry Andric } 4389*0b57cec5SDimitry Andric 4390*0b57cec5SDimitry Andric // In address space agnostic languages, string literals are in default address 4391*0b57cec5SDimitry Andric // space in AST. However, certain targets (e.g. amdgcn) request them to be 4392*0b57cec5SDimitry Andric // emitted in constant address space in LLVM IR. To be consistent with other 4393*0b57cec5SDimitry Andric // parts of AST, string literal global variables in constant address space 4394*0b57cec5SDimitry Andric // need to be casted to default address space before being put into address 4395*0b57cec5SDimitry Andric // map and referenced by other part of CodeGen. 4396*0b57cec5SDimitry Andric // In OpenCL, string literals are in constant address space in AST, therefore 4397*0b57cec5SDimitry Andric // they should not be casted to default address space. 4398*0b57cec5SDimitry Andric static llvm::Constant * 4399*0b57cec5SDimitry Andric castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, 4400*0b57cec5SDimitry Andric llvm::GlobalVariable *GV) { 4401*0b57cec5SDimitry Andric llvm::Constant *Cast = GV; 4402*0b57cec5SDimitry Andric if (!CGM.getLangOpts().OpenCL) { 4403fe6060f1SDimitry Andric auto AS = CGM.GetGlobalConstantAddressSpace(); 4404*0b57cec5SDimitry Andric if (AS != LangAS::Default) 4405*0b57cec5SDimitry Andric Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast( 4406fe6060f1SDimitry Andric CGM, GV, AS, LangAS::Default, 4407*0b57cec5SDimitry Andric GV->getValueType()->getPointerTo( 4408*0b57cec5SDimitry Andric CGM.getContext().getTargetAddressSpace(LangAS::Default))); 4409*0b57cec5SDimitry Andric } 4410*0b57cec5SDimitry Andric return Cast; 4411*0b57cec5SDimitry Andric } 4412*0b57cec5SDimitry Andric 4413*0b57cec5SDimitry Andric template<typename SomeDecl> 4414*0b57cec5SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 4415*0b57cec5SDimitry Andric llvm::GlobalValue *GV) { 4416*0b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus) 4417*0b57cec5SDimitry Andric return; 4418*0b57cec5SDimitry Andric 4419*0b57cec5SDimitry Andric // Must have 'used' attribute, or else inline assembly can't rely on 4420*0b57cec5SDimitry Andric // the name existing. 4421*0b57cec5SDimitry Andric if (!D->template hasAttr<UsedAttr>()) 4422*0b57cec5SDimitry Andric return; 4423*0b57cec5SDimitry Andric 4424*0b57cec5SDimitry Andric // Must have internal linkage and an ordinary name. 4425*0b57cec5SDimitry Andric if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 4426*0b57cec5SDimitry Andric return; 4427*0b57cec5SDimitry Andric 4428*0b57cec5SDimitry Andric // Must be in an extern "C" context. Entities declared directly within 4429*0b57cec5SDimitry Andric // a record are not extern "C" even if the record is in such a context. 4430*0b57cec5SDimitry Andric const SomeDecl *First = D->getFirstDecl(); 4431*0b57cec5SDimitry Andric if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 4432*0b57cec5SDimitry Andric return; 4433*0b57cec5SDimitry Andric 4434*0b57cec5SDimitry Andric // OK, this is an internal linkage entity inside an extern "C" linkage 4435*0b57cec5SDimitry Andric // specification. Make a note of that so we can give it the "expected" 4436*0b57cec5SDimitry Andric // mangled name if nothing else is using that name. 4437*0b57cec5SDimitry Andric std::pair<StaticExternCMap::iterator, bool> R = 4438*0b57cec5SDimitry Andric StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 4439*0b57cec5SDimitry Andric 4440*0b57cec5SDimitry Andric // If we have multiple internal linkage entities with the same name 4441*0b57cec5SDimitry Andric // in extern "C" regions, none of them gets that name. 4442*0b57cec5SDimitry Andric if (!R.second) 4443*0b57cec5SDimitry Andric R.first->second = nullptr; 4444*0b57cec5SDimitry Andric } 4445*0b57cec5SDimitry Andric 4446*0b57cec5SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 4447*0b57cec5SDimitry Andric if (!CGM.supportsCOMDAT()) 4448*0b57cec5SDimitry Andric return false; 4449*0b57cec5SDimitry Andric 4450*0b57cec5SDimitry Andric if (D.hasAttr<SelectAnyAttr>()) 4451*0b57cec5SDimitry Andric return true; 4452*0b57cec5SDimitry Andric 4453*0b57cec5SDimitry Andric GVALinkage Linkage; 4454*0b57cec5SDimitry Andric if (auto *VD = dyn_cast<VarDecl>(&D)) 4455*0b57cec5SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 4456*0b57cec5SDimitry Andric else 4457*0b57cec5SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 4458*0b57cec5SDimitry Andric 4459*0b57cec5SDimitry Andric switch (Linkage) { 4460*0b57cec5SDimitry Andric case GVA_Internal: 4461*0b57cec5SDimitry Andric case GVA_AvailableExternally: 4462*0b57cec5SDimitry Andric case GVA_StrongExternal: 4463*0b57cec5SDimitry Andric return false; 4464*0b57cec5SDimitry Andric case GVA_DiscardableODR: 4465*0b57cec5SDimitry Andric case GVA_StrongODR: 4466*0b57cec5SDimitry Andric return true; 4467*0b57cec5SDimitry Andric } 4468*0b57cec5SDimitry Andric llvm_unreachable("No such linkage"); 4469*0b57cec5SDimitry Andric } 4470*0b57cec5SDimitry Andric 4471*0b57cec5SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 4472*0b57cec5SDimitry Andric llvm::GlobalObject &GO) { 4473*0b57cec5SDimitry Andric if (!shouldBeInCOMDAT(*this, D)) 4474*0b57cec5SDimitry Andric return; 4475*0b57cec5SDimitry Andric GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 4476*0b57cec5SDimitry Andric } 4477*0b57cec5SDimitry Andric 4478*0b57cec5SDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition. 4479*0b57cec5SDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 4480*0b57cec5SDimitry Andric bool IsTentative) { 4481*0b57cec5SDimitry Andric // OpenCL global variables of sampler type are translated to function calls, 4482*0b57cec5SDimitry Andric // therefore no need to be translated. 4483*0b57cec5SDimitry Andric QualType ASTTy = D->getType(); 4484*0b57cec5SDimitry Andric if (getLangOpts().OpenCL && ASTTy->isSamplerT()) 4485*0b57cec5SDimitry Andric return; 4486*0b57cec5SDimitry Andric 4487*0b57cec5SDimitry Andric // If this is OpenMP device, check if it is legal to emit this global 4488*0b57cec5SDimitry Andric // normally. 4489*0b57cec5SDimitry Andric if (LangOpts.OpenMPIsDevice && OpenMPRuntime && 4490*0b57cec5SDimitry Andric OpenMPRuntime->emitTargetGlobalVariable(D)) 4491*0b57cec5SDimitry Andric return; 4492*0b57cec5SDimitry Andric 4493fe6060f1SDimitry Andric llvm::TrackingVH<llvm::Constant> Init; 4494*0b57cec5SDimitry Andric bool NeedsGlobalCtor = false; 4495a7dea167SDimitry Andric bool NeedsGlobalDtor = 4496a7dea167SDimitry Andric D->needsDestruction(getContext()) == QualType::DK_cxx_destructor; 4497*0b57cec5SDimitry Andric 4498*0b57cec5SDimitry Andric const VarDecl *InitDecl; 4499*0b57cec5SDimitry Andric const Expr *InitExpr = D->getAnyInitializer(InitDecl); 4500*0b57cec5SDimitry Andric 4501*0b57cec5SDimitry Andric Optional<ConstantEmitter> emitter; 4502*0b57cec5SDimitry Andric 4503*0b57cec5SDimitry Andric // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 4504*0b57cec5SDimitry Andric // as part of their declaration." Sema has already checked for 4505*0b57cec5SDimitry Andric // error cases, so we just need to set Init to UndefValue. 4506*0b57cec5SDimitry Andric bool IsCUDASharedVar = 4507*0b57cec5SDimitry Andric getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>(); 4508*0b57cec5SDimitry Andric // Shadows of initialized device-side global variables are also left 4509*0b57cec5SDimitry Andric // undefined. 4510fe6060f1SDimitry Andric // Managed Variables should be initialized on both host side and device side. 4511*0b57cec5SDimitry Andric bool IsCUDAShadowVar = 4512e8d8bef9SDimitry Andric !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 4513*0b57cec5SDimitry Andric (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() || 4514*0b57cec5SDimitry Andric D->hasAttr<CUDASharedAttr>()); 45155ffd83dbSDimitry Andric bool IsCUDADeviceShadowVar = 4516fe6060f1SDimitry Andric getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 45175ffd83dbSDimitry Andric (D->getType()->isCUDADeviceBuiltinSurfaceType() || 4518fe6060f1SDimitry Andric D->getType()->isCUDADeviceBuiltinTextureType()); 4519*0b57cec5SDimitry Andric if (getLangOpts().CUDA && 45205ffd83dbSDimitry Andric (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) 4521fe6060f1SDimitry Andric Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 45225ffd83dbSDimitry Andric else if (D->hasAttr<LoaderUninitializedAttr>()) 4523fe6060f1SDimitry Andric Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 4524*0b57cec5SDimitry Andric else if (!InitExpr) { 4525*0b57cec5SDimitry Andric // This is a tentative definition; tentative definitions are 4526*0b57cec5SDimitry Andric // implicitly initialized with { 0 }. 4527*0b57cec5SDimitry Andric // 4528*0b57cec5SDimitry Andric // Note that tentative definitions are only emitted at the end of 4529*0b57cec5SDimitry Andric // a translation unit, so they should never have incomplete 4530*0b57cec5SDimitry Andric // type. In addition, EmitTentativeDefinition makes sure that we 4531*0b57cec5SDimitry Andric // never attempt to emit a tentative definition if a real one 4532*0b57cec5SDimitry Andric // exists. A use may still exists, however, so we still may need 4533*0b57cec5SDimitry Andric // to do a RAUW. 4534*0b57cec5SDimitry Andric assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 4535*0b57cec5SDimitry Andric Init = EmitNullConstant(D->getType()); 4536*0b57cec5SDimitry Andric } else { 4537*0b57cec5SDimitry Andric initializedGlobalDecl = GlobalDecl(D); 4538*0b57cec5SDimitry Andric emitter.emplace(*this); 4539fe6060f1SDimitry Andric llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl); 4540fe6060f1SDimitry Andric if (!Initializer) { 4541*0b57cec5SDimitry Andric QualType T = InitExpr->getType(); 4542*0b57cec5SDimitry Andric if (D->getType()->isReferenceType()) 4543*0b57cec5SDimitry Andric T = D->getType(); 4544*0b57cec5SDimitry Andric 4545*0b57cec5SDimitry Andric if (getLangOpts().CPlusPlus) { 4546*0b57cec5SDimitry Andric Init = EmitNullConstant(T); 4547*0b57cec5SDimitry Andric NeedsGlobalCtor = true; 4548*0b57cec5SDimitry Andric } else { 4549*0b57cec5SDimitry Andric ErrorUnsupported(D, "static initializer"); 4550*0b57cec5SDimitry Andric Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 4551*0b57cec5SDimitry Andric } 4552*0b57cec5SDimitry Andric } else { 4553fe6060f1SDimitry Andric Init = Initializer; 4554*0b57cec5SDimitry Andric // We don't need an initializer, so remove the entry for the delayed 4555*0b57cec5SDimitry Andric // initializer position (just in case this entry was delayed) if we 4556*0b57cec5SDimitry Andric // also don't need to register a destructor. 4557*0b57cec5SDimitry Andric if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 4558*0b57cec5SDimitry Andric DelayedCXXInitPosition.erase(D); 4559*0b57cec5SDimitry Andric } 4560*0b57cec5SDimitry Andric } 4561*0b57cec5SDimitry Andric 4562*0b57cec5SDimitry Andric llvm::Type* InitType = Init->getType(); 4563*0b57cec5SDimitry Andric llvm::Constant *Entry = 4564*0b57cec5SDimitry Andric GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); 4565*0b57cec5SDimitry Andric 4566a7dea167SDimitry Andric // Strip off pointer casts if we got them. 4567a7dea167SDimitry Andric Entry = Entry->stripPointerCasts(); 4568*0b57cec5SDimitry Andric 4569*0b57cec5SDimitry Andric // Entry is now either a Function or GlobalVariable. 4570*0b57cec5SDimitry Andric auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 4571*0b57cec5SDimitry Andric 4572*0b57cec5SDimitry Andric // We have a definition after a declaration with the wrong type. 4573*0b57cec5SDimitry Andric // We must make a new GlobalVariable* and update everything that used OldGV 4574*0b57cec5SDimitry Andric // (a declaration or tentative definition) with the new GlobalVariable* 4575*0b57cec5SDimitry Andric // (which will be a definition). 4576*0b57cec5SDimitry Andric // 4577*0b57cec5SDimitry Andric // This happens if there is a prototype for a global (e.g. 4578*0b57cec5SDimitry Andric // "extern int x[];") and then a definition of a different type (e.g. 4579*0b57cec5SDimitry Andric // "int x[10];"). This also happens when an initializer has a different type 4580*0b57cec5SDimitry Andric // from the type of the global (this happens with unions). 45815ffd83dbSDimitry Andric if (!GV || GV->getValueType() != InitType || 4582*0b57cec5SDimitry Andric GV->getType()->getAddressSpace() != 4583*0b57cec5SDimitry Andric getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) { 4584*0b57cec5SDimitry Andric 4585*0b57cec5SDimitry Andric // Move the old entry aside so that we'll create a new one. 4586*0b57cec5SDimitry Andric Entry->setName(StringRef()); 4587*0b57cec5SDimitry Andric 4588*0b57cec5SDimitry Andric // Make a new global with the correct type, this is now guaranteed to work. 4589*0b57cec5SDimitry Andric GV = cast<llvm::GlobalVariable>( 4590a7dea167SDimitry Andric GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)) 4591a7dea167SDimitry Andric ->stripPointerCasts()); 4592*0b57cec5SDimitry Andric 4593*0b57cec5SDimitry Andric // Replace all uses of the old global with the new global 4594*0b57cec5SDimitry Andric llvm::Constant *NewPtrForOldDecl = 4595fe6060f1SDimitry Andric llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, 4596fe6060f1SDimitry Andric Entry->getType()); 4597*0b57cec5SDimitry Andric Entry->replaceAllUsesWith(NewPtrForOldDecl); 4598*0b57cec5SDimitry Andric 4599*0b57cec5SDimitry Andric // Erase the old global, since it is no longer used. 4600*0b57cec5SDimitry Andric cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 4601*0b57cec5SDimitry Andric } 4602*0b57cec5SDimitry Andric 4603*0b57cec5SDimitry Andric MaybeHandleStaticInExternC(D, GV); 4604*0b57cec5SDimitry Andric 4605*0b57cec5SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 4606*0b57cec5SDimitry Andric AddGlobalAnnotations(D, GV); 4607*0b57cec5SDimitry Andric 4608*0b57cec5SDimitry Andric // Set the llvm linkage type as appropriate. 4609*0b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 4610*0b57cec5SDimitry Andric getLLVMLinkageVarDefinition(D, GV->isConstant()); 4611*0b57cec5SDimitry Andric 4612*0b57cec5SDimitry Andric // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 4613*0b57cec5SDimitry Andric // the device. [...]" 4614*0b57cec5SDimitry Andric // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 4615*0b57cec5SDimitry Andric // __device__, declares a variable that: [...] 4616*0b57cec5SDimitry Andric // Is accessible from all the threads within the grid and from the host 4617*0b57cec5SDimitry Andric // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 4618*0b57cec5SDimitry Andric // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 4619*0b57cec5SDimitry Andric if (GV && LangOpts.CUDA) { 4620*0b57cec5SDimitry Andric if (LangOpts.CUDAIsDevice) { 4621*0b57cec5SDimitry Andric if (Linkage != llvm::GlobalValue::InternalLinkage && 4622349cc55cSDimitry Andric (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 4623349cc55cSDimitry Andric D->getType()->isCUDADeviceBuiltinSurfaceType() || 4624349cc55cSDimitry Andric D->getType()->isCUDADeviceBuiltinTextureType())) 4625*0b57cec5SDimitry Andric GV->setExternallyInitialized(true); 4626*0b57cec5SDimitry Andric } else { 4627fe6060f1SDimitry Andric getCUDARuntime().internalizeDeviceSideVar(D, Linkage); 46285ffd83dbSDimitry Andric } 4629fe6060f1SDimitry Andric getCUDARuntime().handleVarRegistration(D, *GV); 4630*0b57cec5SDimitry Andric } 4631*0b57cec5SDimitry Andric 4632*0b57cec5SDimitry Andric GV->setInitializer(Init); 46335ffd83dbSDimitry Andric if (emitter) 46345ffd83dbSDimitry Andric emitter->finalize(GV); 4635*0b57cec5SDimitry Andric 4636*0b57cec5SDimitry Andric // If it is safe to mark the global 'constant', do so now. 4637*0b57cec5SDimitry Andric GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 4638*0b57cec5SDimitry Andric isTypeConstant(D->getType(), true)); 4639*0b57cec5SDimitry Andric 4640*0b57cec5SDimitry Andric // If it is in a read-only section, mark it 'constant'. 4641*0b57cec5SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 4642*0b57cec5SDimitry Andric const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 4643*0b57cec5SDimitry Andric if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 4644*0b57cec5SDimitry Andric GV->setConstant(true); 4645*0b57cec5SDimitry Andric } 4646*0b57cec5SDimitry Andric 4647a7dea167SDimitry Andric GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); 4648*0b57cec5SDimitry Andric 46495ffd83dbSDimitry Andric // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper 46505ffd83dbSDimitry Andric // function is only defined alongside the variable, not also alongside 46515ffd83dbSDimitry Andric // callers. Normally, all accesses to a thread_local go through the 46525ffd83dbSDimitry Andric // thread-wrapper in order to ensure initialization has occurred, underlying 46535ffd83dbSDimitry Andric // variable will never be used other than the thread-wrapper, so it can be 46545ffd83dbSDimitry Andric // converted to internal linkage. 46555ffd83dbSDimitry Andric // 46565ffd83dbSDimitry Andric // However, if the variable has the 'constinit' attribute, it _can_ be 46575ffd83dbSDimitry Andric // referenced directly, without calling the thread-wrapper, so the linkage 46585ffd83dbSDimitry Andric // must not be changed. 46595ffd83dbSDimitry Andric // 46605ffd83dbSDimitry Andric // Additionally, if the variable isn't plain external linkage, e.g. if it's 46615ffd83dbSDimitry Andric // weak or linkonce, the de-duplication semantics are important to preserve, 46625ffd83dbSDimitry Andric // so we don't change the linkage. 46635ffd83dbSDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic && 46645ffd83dbSDimitry Andric Linkage == llvm::GlobalValue::ExternalLinkage && 4665*0b57cec5SDimitry Andric Context.getTargetInfo().getTriple().isOSDarwin() && 46665ffd83dbSDimitry Andric !D->hasAttr<ConstInitAttr>()) 4667*0b57cec5SDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 4668*0b57cec5SDimitry Andric 4669*0b57cec5SDimitry Andric GV->setLinkage(Linkage); 4670*0b57cec5SDimitry Andric if (D->hasAttr<DLLImportAttr>()) 4671*0b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 4672*0b57cec5SDimitry Andric else if (D->hasAttr<DLLExportAttr>()) 4673*0b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 4674*0b57cec5SDimitry Andric else 4675*0b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 4676*0b57cec5SDimitry Andric 4677*0b57cec5SDimitry Andric if (Linkage == llvm::GlobalVariable::CommonLinkage) { 4678*0b57cec5SDimitry Andric // common vars aren't constant even if declared const. 4679*0b57cec5SDimitry Andric GV->setConstant(false); 4680*0b57cec5SDimitry Andric // Tentative definition of global variables may be initialized with 4681*0b57cec5SDimitry Andric // non-zero null pointers. In this case they should have weak linkage 4682*0b57cec5SDimitry Andric // since common linkage must have zero initializer and must not have 4683*0b57cec5SDimitry Andric // explicit section therefore cannot have non-zero initial value. 4684*0b57cec5SDimitry Andric if (!GV->getInitializer()->isNullValue()) 4685*0b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 4686*0b57cec5SDimitry Andric } 4687*0b57cec5SDimitry Andric 4688*0b57cec5SDimitry Andric setNonAliasAttributes(D, GV); 4689*0b57cec5SDimitry Andric 4690*0b57cec5SDimitry Andric if (D->getTLSKind() && !GV->isThreadLocal()) { 4691*0b57cec5SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 4692*0b57cec5SDimitry Andric CXXThreadLocals.push_back(D); 4693*0b57cec5SDimitry Andric setTLSMode(GV, *D); 4694*0b57cec5SDimitry Andric } 4695*0b57cec5SDimitry Andric 4696*0b57cec5SDimitry Andric maybeSetTrivialComdat(*D, *GV); 4697*0b57cec5SDimitry Andric 4698*0b57cec5SDimitry Andric // Emit the initializer function if necessary. 4699*0b57cec5SDimitry Andric if (NeedsGlobalCtor || NeedsGlobalDtor) 4700*0b57cec5SDimitry Andric EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 4701*0b57cec5SDimitry Andric 4702*0b57cec5SDimitry Andric SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); 4703*0b57cec5SDimitry Andric 4704*0b57cec5SDimitry Andric // Emit global variable debug information. 4705*0b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 4706480093f4SDimitry Andric if (getCodeGenOpts().hasReducedDebugInfo()) 4707*0b57cec5SDimitry Andric DI->EmitGlobalVariable(GV, D); 4708*0b57cec5SDimitry Andric } 4709*0b57cec5SDimitry Andric 4710480093f4SDimitry Andric void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) { 4711480093f4SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 4712480093f4SDimitry Andric if (getCodeGenOpts().hasReducedDebugInfo()) { 4713480093f4SDimitry Andric QualType ASTTy = D->getType(); 4714480093f4SDimitry Andric llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType()); 4715349cc55cSDimitry Andric llvm::Constant *GV = 4716349cc55cSDimitry Andric GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D); 4717480093f4SDimitry Andric DI->EmitExternalVariable( 4718480093f4SDimitry Andric cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D); 4719480093f4SDimitry Andric } 4720480093f4SDimitry Andric } 4721480093f4SDimitry Andric 4722*0b57cec5SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context, 4723*0b57cec5SDimitry Andric CodeGenModule &CGM, const VarDecl *D, 4724*0b57cec5SDimitry Andric bool NoCommon) { 4725*0b57cec5SDimitry Andric // Don't give variables common linkage if -fno-common was specified unless it 4726*0b57cec5SDimitry Andric // was overridden by a NoCommon attribute. 4727*0b57cec5SDimitry Andric if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 4728*0b57cec5SDimitry Andric return true; 4729*0b57cec5SDimitry Andric 4730*0b57cec5SDimitry Andric // C11 6.9.2/2: 4731*0b57cec5SDimitry Andric // A declaration of an identifier for an object that has file scope without 4732*0b57cec5SDimitry Andric // an initializer, and without a storage-class specifier or with the 4733*0b57cec5SDimitry Andric // storage-class specifier static, constitutes a tentative definition. 4734*0b57cec5SDimitry Andric if (D->getInit() || D->hasExternalStorage()) 4735*0b57cec5SDimitry Andric return true; 4736*0b57cec5SDimitry Andric 4737*0b57cec5SDimitry Andric // A variable cannot be both common and exist in a section. 4738*0b57cec5SDimitry Andric if (D->hasAttr<SectionAttr>()) 4739*0b57cec5SDimitry Andric return true; 4740*0b57cec5SDimitry Andric 4741*0b57cec5SDimitry Andric // A variable cannot be both common and exist in a section. 4742*0b57cec5SDimitry Andric // We don't try to determine which is the right section in the front-end. 4743*0b57cec5SDimitry Andric // If no specialized section name is applicable, it will resort to default. 4744*0b57cec5SDimitry Andric if (D->hasAttr<PragmaClangBSSSectionAttr>() || 4745*0b57cec5SDimitry Andric D->hasAttr<PragmaClangDataSectionAttr>() || 4746a7dea167SDimitry Andric D->hasAttr<PragmaClangRelroSectionAttr>() || 4747*0b57cec5SDimitry Andric D->hasAttr<PragmaClangRodataSectionAttr>()) 4748*0b57cec5SDimitry Andric return true; 4749*0b57cec5SDimitry Andric 4750*0b57cec5SDimitry Andric // Thread local vars aren't considered common linkage. 4751*0b57cec5SDimitry Andric if (D->getTLSKind()) 4752*0b57cec5SDimitry Andric return true; 4753*0b57cec5SDimitry Andric 4754*0b57cec5SDimitry Andric // Tentative definitions marked with WeakImportAttr are true definitions. 4755*0b57cec5SDimitry Andric if (D->hasAttr<WeakImportAttr>()) 4756*0b57cec5SDimitry Andric return true; 4757*0b57cec5SDimitry Andric 4758*0b57cec5SDimitry Andric // A variable cannot be both common and exist in a comdat. 4759*0b57cec5SDimitry Andric if (shouldBeInCOMDAT(CGM, *D)) 4760*0b57cec5SDimitry Andric return true; 4761*0b57cec5SDimitry Andric 4762*0b57cec5SDimitry Andric // Declarations with a required alignment do not have common linkage in MSVC 4763*0b57cec5SDimitry Andric // mode. 4764*0b57cec5SDimitry Andric if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 4765*0b57cec5SDimitry Andric if (D->hasAttr<AlignedAttr>()) 4766*0b57cec5SDimitry Andric return true; 4767*0b57cec5SDimitry Andric QualType VarType = D->getType(); 4768*0b57cec5SDimitry Andric if (Context.isAlignmentRequired(VarType)) 4769*0b57cec5SDimitry Andric return true; 4770*0b57cec5SDimitry Andric 4771*0b57cec5SDimitry Andric if (const auto *RT = VarType->getAs<RecordType>()) { 4772*0b57cec5SDimitry Andric const RecordDecl *RD = RT->getDecl(); 4773*0b57cec5SDimitry Andric for (const FieldDecl *FD : RD->fields()) { 4774*0b57cec5SDimitry Andric if (FD->isBitField()) 4775*0b57cec5SDimitry Andric continue; 4776*0b57cec5SDimitry Andric if (FD->hasAttr<AlignedAttr>()) 4777*0b57cec5SDimitry Andric return true; 4778*0b57cec5SDimitry Andric if (Context.isAlignmentRequired(FD->getType())) 4779*0b57cec5SDimitry Andric return true; 4780*0b57cec5SDimitry Andric } 4781*0b57cec5SDimitry Andric } 4782*0b57cec5SDimitry Andric } 4783*0b57cec5SDimitry Andric 4784*0b57cec5SDimitry Andric // Microsoft's link.exe doesn't support alignments greater than 32 bytes for 4785*0b57cec5SDimitry Andric // common symbols, so symbols with greater alignment requirements cannot be 4786*0b57cec5SDimitry Andric // common. 4787*0b57cec5SDimitry Andric // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two 4788*0b57cec5SDimitry Andric // alignments for common symbols via the aligncomm directive, so this 4789*0b57cec5SDimitry Andric // restriction only applies to MSVC environments. 4790*0b57cec5SDimitry Andric if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() && 4791*0b57cec5SDimitry Andric Context.getTypeAlignIfKnown(D->getType()) > 4792*0b57cec5SDimitry Andric Context.toBits(CharUnits::fromQuantity(32))) 4793*0b57cec5SDimitry Andric return true; 4794*0b57cec5SDimitry Andric 4795*0b57cec5SDimitry Andric return false; 4796*0b57cec5SDimitry Andric } 4797*0b57cec5SDimitry Andric 4798*0b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 4799*0b57cec5SDimitry Andric const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 4800*0b57cec5SDimitry Andric if (Linkage == GVA_Internal) 4801*0b57cec5SDimitry Andric return llvm::Function::InternalLinkage; 4802*0b57cec5SDimitry Andric 4803*0b57cec5SDimitry Andric if (D->hasAttr<WeakAttr>()) { 4804*0b57cec5SDimitry Andric if (IsConstantVariable) 4805*0b57cec5SDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 4806*0b57cec5SDimitry Andric else 4807*0b57cec5SDimitry Andric return llvm::GlobalVariable::WeakAnyLinkage; 4808*0b57cec5SDimitry Andric } 4809*0b57cec5SDimitry Andric 4810*0b57cec5SDimitry Andric if (const auto *FD = D->getAsFunction()) 4811*0b57cec5SDimitry Andric if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally) 4812*0b57cec5SDimitry Andric return llvm::GlobalVariable::LinkOnceAnyLinkage; 4813*0b57cec5SDimitry Andric 4814*0b57cec5SDimitry Andric // We are guaranteed to have a strong definition somewhere else, 4815*0b57cec5SDimitry Andric // so we can use available_externally linkage. 4816*0b57cec5SDimitry Andric if (Linkage == GVA_AvailableExternally) 4817*0b57cec5SDimitry Andric return llvm::GlobalValue::AvailableExternallyLinkage; 4818*0b57cec5SDimitry Andric 4819*0b57cec5SDimitry Andric // Note that Apple's kernel linker doesn't support symbol 4820*0b57cec5SDimitry Andric // coalescing, so we need to avoid linkonce and weak linkages there. 4821*0b57cec5SDimitry Andric // Normally, this means we just map to internal, but for explicit 4822*0b57cec5SDimitry Andric // instantiations we'll map to external. 4823*0b57cec5SDimitry Andric 4824*0b57cec5SDimitry Andric // In C++, the compiler has to emit a definition in every translation unit 4825*0b57cec5SDimitry Andric // that references the function. We should use linkonce_odr because 4826*0b57cec5SDimitry Andric // a) if all references in this translation unit are optimized away, we 4827*0b57cec5SDimitry Andric // don't need to codegen it. b) if the function persists, it needs to be 4828*0b57cec5SDimitry Andric // merged with other definitions. c) C++ has the ODR, so we know the 4829*0b57cec5SDimitry Andric // definition is dependable. 4830*0b57cec5SDimitry Andric if (Linkage == GVA_DiscardableODR) 4831*0b57cec5SDimitry Andric return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 4832*0b57cec5SDimitry Andric : llvm::Function::InternalLinkage; 4833*0b57cec5SDimitry Andric 4834*0b57cec5SDimitry Andric // An explicit instantiation of a template has weak linkage, since 4835*0b57cec5SDimitry Andric // explicit instantiations can occur in multiple translation units 4836*0b57cec5SDimitry Andric // and must all be equivalent. However, we are not allowed to 4837*0b57cec5SDimitry Andric // throw away these explicit instantiations. 4838*0b57cec5SDimitry Andric // 4839e8d8bef9SDimitry Andric // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU, 4840*0b57cec5SDimitry Andric // so say that CUDA templates are either external (for kernels) or internal. 4841e8d8bef9SDimitry Andric // This lets llvm perform aggressive inter-procedural optimizations. For 4842e8d8bef9SDimitry Andric // -fgpu-rdc case, device function calls across multiple TU's are allowed, 4843e8d8bef9SDimitry Andric // therefore we need to follow the normal linkage paradigm. 4844*0b57cec5SDimitry Andric if (Linkage == GVA_StrongODR) { 4845e8d8bef9SDimitry Andric if (getLangOpts().AppleKext) 4846*0b57cec5SDimitry Andric return llvm::Function::ExternalLinkage; 4847e8d8bef9SDimitry Andric if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 4848e8d8bef9SDimitry Andric !getLangOpts().GPURelocatableDeviceCode) 4849*0b57cec5SDimitry Andric return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage 4850*0b57cec5SDimitry Andric : llvm::Function::InternalLinkage; 4851*0b57cec5SDimitry Andric return llvm::Function::WeakODRLinkage; 4852*0b57cec5SDimitry Andric } 4853*0b57cec5SDimitry Andric 4854*0b57cec5SDimitry Andric // C++ doesn't have tentative definitions and thus cannot have common 4855*0b57cec5SDimitry Andric // linkage. 4856*0b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 4857*0b57cec5SDimitry Andric !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 4858*0b57cec5SDimitry Andric CodeGenOpts.NoCommon)) 4859*0b57cec5SDimitry Andric return llvm::GlobalVariable::CommonLinkage; 4860*0b57cec5SDimitry Andric 4861*0b57cec5SDimitry Andric // selectany symbols are externally visible, so use weak instead of 4862*0b57cec5SDimitry Andric // linkonce. MSVC optimizes away references to const selectany globals, so 4863*0b57cec5SDimitry Andric // all definitions should be the same and ODR linkage should be used. 4864*0b57cec5SDimitry Andric // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 4865*0b57cec5SDimitry Andric if (D->hasAttr<SelectAnyAttr>()) 4866*0b57cec5SDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 4867*0b57cec5SDimitry Andric 4868*0b57cec5SDimitry Andric // Otherwise, we have strong external linkage. 4869*0b57cec5SDimitry Andric assert(Linkage == GVA_StrongExternal); 4870*0b57cec5SDimitry Andric return llvm::GlobalVariable::ExternalLinkage; 4871*0b57cec5SDimitry Andric } 4872*0b57cec5SDimitry Andric 4873*0b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 4874*0b57cec5SDimitry Andric const VarDecl *VD, bool IsConstant) { 4875*0b57cec5SDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 4876*0b57cec5SDimitry Andric return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 4877*0b57cec5SDimitry Andric } 4878*0b57cec5SDimitry Andric 4879*0b57cec5SDimitry Andric /// Replace the uses of a function that was declared with a non-proto type. 4880*0b57cec5SDimitry Andric /// We want to silently drop extra arguments from call sites 4881*0b57cec5SDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 4882*0b57cec5SDimitry Andric llvm::Function *newFn) { 4883*0b57cec5SDimitry Andric // Fast path. 4884*0b57cec5SDimitry Andric if (old->use_empty()) return; 4885*0b57cec5SDimitry Andric 4886*0b57cec5SDimitry Andric llvm::Type *newRetTy = newFn->getReturnType(); 4887*0b57cec5SDimitry Andric SmallVector<llvm::Value*, 4> newArgs; 4888*0b57cec5SDimitry Andric 4889*0b57cec5SDimitry Andric for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 4890*0b57cec5SDimitry Andric ui != ue; ) { 4891*0b57cec5SDimitry Andric llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 4892*0b57cec5SDimitry Andric llvm::User *user = use->getUser(); 4893*0b57cec5SDimitry Andric 4894*0b57cec5SDimitry Andric // Recognize and replace uses of bitcasts. Most calls to 4895*0b57cec5SDimitry Andric // unprototyped functions will use bitcasts. 4896*0b57cec5SDimitry Andric if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 4897*0b57cec5SDimitry Andric if (bitcast->getOpcode() == llvm::Instruction::BitCast) 4898*0b57cec5SDimitry Andric replaceUsesOfNonProtoConstant(bitcast, newFn); 4899*0b57cec5SDimitry Andric continue; 4900*0b57cec5SDimitry Andric } 4901*0b57cec5SDimitry Andric 4902*0b57cec5SDimitry Andric // Recognize calls to the function. 4903*0b57cec5SDimitry Andric llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user); 4904*0b57cec5SDimitry Andric if (!callSite) continue; 4905*0b57cec5SDimitry Andric if (!callSite->isCallee(&*use)) 4906*0b57cec5SDimitry Andric continue; 4907*0b57cec5SDimitry Andric 4908*0b57cec5SDimitry Andric // If the return types don't match exactly, then we can't 4909*0b57cec5SDimitry Andric // transform this call unless it's dead. 4910*0b57cec5SDimitry Andric if (callSite->getType() != newRetTy && !callSite->use_empty()) 4911*0b57cec5SDimitry Andric continue; 4912*0b57cec5SDimitry Andric 4913*0b57cec5SDimitry Andric // Get the call site's attribute list. 4914*0b57cec5SDimitry Andric SmallVector<llvm::AttributeSet, 8> newArgAttrs; 4915*0b57cec5SDimitry Andric llvm::AttributeList oldAttrs = callSite->getAttributes(); 4916*0b57cec5SDimitry Andric 4917*0b57cec5SDimitry Andric // If the function was passed too few arguments, don't transform. 4918*0b57cec5SDimitry Andric unsigned newNumArgs = newFn->arg_size(); 4919*0b57cec5SDimitry Andric if (callSite->arg_size() < newNumArgs) 4920*0b57cec5SDimitry Andric continue; 4921*0b57cec5SDimitry Andric 4922*0b57cec5SDimitry Andric // If extra arguments were passed, we silently drop them. 4923*0b57cec5SDimitry Andric // If any of the types mismatch, we don't transform. 4924*0b57cec5SDimitry Andric unsigned argNo = 0; 4925*0b57cec5SDimitry Andric bool dontTransform = false; 4926*0b57cec5SDimitry Andric for (llvm::Argument &A : newFn->args()) { 4927*0b57cec5SDimitry Andric if (callSite->getArgOperand(argNo)->getType() != A.getType()) { 4928*0b57cec5SDimitry Andric dontTransform = true; 4929*0b57cec5SDimitry Andric break; 4930*0b57cec5SDimitry Andric } 4931*0b57cec5SDimitry Andric 4932*0b57cec5SDimitry Andric // Add any parameter attributes. 4933349cc55cSDimitry Andric newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo)); 4934*0b57cec5SDimitry Andric argNo++; 4935*0b57cec5SDimitry Andric } 4936*0b57cec5SDimitry Andric if (dontTransform) 4937*0b57cec5SDimitry Andric continue; 4938*0b57cec5SDimitry Andric 4939*0b57cec5SDimitry Andric // Okay, we can transform this. Create the new call instruction and copy 4940*0b57cec5SDimitry Andric // over the required information. 4941*0b57cec5SDimitry Andric newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo); 4942*0b57cec5SDimitry Andric 4943*0b57cec5SDimitry Andric // Copy over any operand bundles. 4944fe6060f1SDimitry Andric SmallVector<llvm::OperandBundleDef, 1> newBundles; 4945*0b57cec5SDimitry Andric callSite->getOperandBundlesAsDefs(newBundles); 4946*0b57cec5SDimitry Andric 4947*0b57cec5SDimitry Andric llvm::CallBase *newCall; 4948349cc55cSDimitry Andric if (isa<llvm::CallInst>(callSite)) { 4949*0b57cec5SDimitry Andric newCall = 4950*0b57cec5SDimitry Andric llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite); 4951*0b57cec5SDimitry Andric } else { 4952*0b57cec5SDimitry Andric auto *oldInvoke = cast<llvm::InvokeInst>(callSite); 4953*0b57cec5SDimitry Andric newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(), 4954*0b57cec5SDimitry Andric oldInvoke->getUnwindDest(), newArgs, 4955*0b57cec5SDimitry Andric newBundles, "", callSite); 4956*0b57cec5SDimitry Andric } 4957*0b57cec5SDimitry Andric newArgs.clear(); // for the next iteration 4958*0b57cec5SDimitry Andric 4959*0b57cec5SDimitry Andric if (!newCall->getType()->isVoidTy()) 4960*0b57cec5SDimitry Andric newCall->takeName(callSite); 4961349cc55cSDimitry Andric newCall->setAttributes( 4962349cc55cSDimitry Andric llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(), 4963349cc55cSDimitry Andric oldAttrs.getRetAttrs(), newArgAttrs)); 4964*0b57cec5SDimitry Andric newCall->setCallingConv(callSite->getCallingConv()); 4965*0b57cec5SDimitry Andric 4966*0b57cec5SDimitry Andric // Finally, remove the old call, replacing any uses with the new one. 4967*0b57cec5SDimitry Andric if (!callSite->use_empty()) 4968*0b57cec5SDimitry Andric callSite->replaceAllUsesWith(newCall); 4969*0b57cec5SDimitry Andric 4970*0b57cec5SDimitry Andric // Copy debug location attached to CI. 4971*0b57cec5SDimitry Andric if (callSite->getDebugLoc()) 4972*0b57cec5SDimitry Andric newCall->setDebugLoc(callSite->getDebugLoc()); 4973*0b57cec5SDimitry Andric 4974*0b57cec5SDimitry Andric callSite->eraseFromParent(); 4975*0b57cec5SDimitry Andric } 4976*0b57cec5SDimitry Andric } 4977*0b57cec5SDimitry Andric 4978*0b57cec5SDimitry Andric /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 4979*0b57cec5SDimitry Andric /// implement a function with no prototype, e.g. "int foo() {}". If there are 4980*0b57cec5SDimitry Andric /// existing call uses of the old function in the module, this adjusts them to 4981*0b57cec5SDimitry Andric /// call the new function directly. 4982*0b57cec5SDimitry Andric /// 4983*0b57cec5SDimitry Andric /// This is not just a cleanup: the always_inline pass requires direct calls to 4984*0b57cec5SDimitry Andric /// functions to be able to inline them. If there is a bitcast in the way, it 4985*0b57cec5SDimitry Andric /// won't inline them. Instcombine normally deletes these calls, but it isn't 4986*0b57cec5SDimitry Andric /// run at -O0. 4987*0b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 4988*0b57cec5SDimitry Andric llvm::Function *NewFn) { 4989*0b57cec5SDimitry Andric // If we're redefining a global as a function, don't transform it. 4990*0b57cec5SDimitry Andric if (!isa<llvm::Function>(Old)) return; 4991*0b57cec5SDimitry Andric 4992*0b57cec5SDimitry Andric replaceUsesOfNonProtoConstant(Old, NewFn); 4993*0b57cec5SDimitry Andric } 4994*0b57cec5SDimitry Andric 4995*0b57cec5SDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 4996*0b57cec5SDimitry Andric auto DK = VD->isThisDeclarationADefinition(); 4997*0b57cec5SDimitry Andric if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) 4998*0b57cec5SDimitry Andric return; 4999*0b57cec5SDimitry Andric 5000*0b57cec5SDimitry Andric TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 5001*0b57cec5SDimitry Andric // If we have a definition, this might be a deferred decl. If the 5002*0b57cec5SDimitry Andric // instantiation is explicit, make sure we emit it at the end. 5003*0b57cec5SDimitry Andric if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 5004*0b57cec5SDimitry Andric GetAddrOfGlobalVar(VD); 5005*0b57cec5SDimitry Andric 5006*0b57cec5SDimitry Andric EmitTopLevelDecl(VD); 5007*0b57cec5SDimitry Andric } 5008*0b57cec5SDimitry Andric 5009*0b57cec5SDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 5010*0b57cec5SDimitry Andric llvm::GlobalValue *GV) { 5011*0b57cec5SDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 5012*0b57cec5SDimitry Andric 5013*0b57cec5SDimitry Andric // Compute the function info and LLVM type. 5014*0b57cec5SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 5015*0b57cec5SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 5016*0b57cec5SDimitry Andric 5017*0b57cec5SDimitry Andric // Get or create the prototype for the function. 50185ffd83dbSDimitry Andric if (!GV || (GV->getValueType() != Ty)) 5019*0b57cec5SDimitry Andric GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 5020*0b57cec5SDimitry Andric /*DontDefer=*/true, 5021*0b57cec5SDimitry Andric ForDefinition)); 5022*0b57cec5SDimitry Andric 5023*0b57cec5SDimitry Andric // Already emitted. 5024*0b57cec5SDimitry Andric if (!GV->isDeclaration()) 5025*0b57cec5SDimitry Andric return; 5026*0b57cec5SDimitry Andric 5027*0b57cec5SDimitry Andric // We need to set linkage and visibility on the function before 5028*0b57cec5SDimitry Andric // generating code for it because various parts of IR generation 5029*0b57cec5SDimitry Andric // want to propagate this information down (e.g. to local static 5030*0b57cec5SDimitry Andric // declarations). 5031*0b57cec5SDimitry Andric auto *Fn = cast<llvm::Function>(GV); 5032*0b57cec5SDimitry Andric setFunctionLinkage(GD, Fn); 5033*0b57cec5SDimitry Andric 5034*0b57cec5SDimitry Andric // FIXME: this is redundant with part of setFunctionDefinitionAttributes 5035*0b57cec5SDimitry Andric setGVProperties(Fn, GD); 5036*0b57cec5SDimitry Andric 5037*0b57cec5SDimitry Andric MaybeHandleStaticInExternC(D, Fn); 5038*0b57cec5SDimitry Andric 5039*0b57cec5SDimitry Andric maybeSetTrivialComdat(*D, *Fn); 5040*0b57cec5SDimitry Andric 5041e8d8bef9SDimitry Andric // Set CodeGen attributes that represent floating point environment. 5042e8d8bef9SDimitry Andric setLLVMFunctionFEnvAttributes(D, Fn); 5043e8d8bef9SDimitry Andric 50445ffd83dbSDimitry Andric CodeGenFunction(*this).GenerateCode(GD, Fn, FI); 5045*0b57cec5SDimitry Andric 5046*0b57cec5SDimitry Andric setNonAliasAttributes(GD, Fn); 5047*0b57cec5SDimitry Andric SetLLVMFunctionAttributesForDefinition(D, Fn); 5048*0b57cec5SDimitry Andric 5049*0b57cec5SDimitry Andric if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 5050*0b57cec5SDimitry Andric AddGlobalCtor(Fn, CA->getPriority()); 5051*0b57cec5SDimitry Andric if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 5052e8d8bef9SDimitry Andric AddGlobalDtor(Fn, DA->getPriority(), true); 5053*0b57cec5SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 5054*0b57cec5SDimitry Andric AddGlobalAnnotations(D, Fn); 5055*0b57cec5SDimitry Andric } 5056*0b57cec5SDimitry Andric 5057*0b57cec5SDimitry Andric void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 5058*0b57cec5SDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 5059*0b57cec5SDimitry Andric const AliasAttr *AA = D->getAttr<AliasAttr>(); 5060*0b57cec5SDimitry Andric assert(AA && "Not an alias?"); 5061*0b57cec5SDimitry Andric 5062*0b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 5063*0b57cec5SDimitry Andric 5064*0b57cec5SDimitry Andric if (AA->getAliasee() == MangledName) { 5065*0b57cec5SDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 5066*0b57cec5SDimitry Andric return; 5067*0b57cec5SDimitry Andric } 5068*0b57cec5SDimitry Andric 5069*0b57cec5SDimitry Andric // If there is a definition in the module, then it wins over the alias. 5070*0b57cec5SDimitry Andric // This is dubious, but allow it to be safe. Just ignore the alias. 5071*0b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 5072*0b57cec5SDimitry Andric if (Entry && !Entry->isDeclaration()) 5073*0b57cec5SDimitry Andric return; 5074*0b57cec5SDimitry Andric 5075*0b57cec5SDimitry Andric Aliases.push_back(GD); 5076*0b57cec5SDimitry Andric 5077*0b57cec5SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 5078*0b57cec5SDimitry Andric 5079*0b57cec5SDimitry Andric // Create a reference to the named value. This ensures that it is emitted 5080*0b57cec5SDimitry Andric // if a deferred decl. 5081*0b57cec5SDimitry Andric llvm::Constant *Aliasee; 5082*0b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes LT; 5083*0b57cec5SDimitry Andric if (isa<llvm::FunctionType>(DeclTy)) { 5084*0b57cec5SDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 5085*0b57cec5SDimitry Andric /*ForVTable=*/false); 5086*0b57cec5SDimitry Andric LT = getFunctionLinkage(GD); 5087*0b57cec5SDimitry Andric } else { 5088349cc55cSDimitry Andric Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 5089*0b57cec5SDimitry Andric /*D=*/nullptr); 5090e8d8bef9SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl())) 5091e8d8bef9SDimitry Andric LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified()); 5092e8d8bef9SDimitry Andric else 5093e8d8bef9SDimitry Andric LT = getFunctionLinkage(GD); 5094*0b57cec5SDimitry Andric } 5095*0b57cec5SDimitry Andric 5096*0b57cec5SDimitry Andric // Create the new alias itself, but don't set a name yet. 50975ffd83dbSDimitry Andric unsigned AS = Aliasee->getType()->getPointerAddressSpace(); 5098*0b57cec5SDimitry Andric auto *GA = 50995ffd83dbSDimitry Andric llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule()); 5100*0b57cec5SDimitry Andric 5101*0b57cec5SDimitry Andric if (Entry) { 5102*0b57cec5SDimitry Andric if (GA->getAliasee() == Entry) { 5103*0b57cec5SDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 5104*0b57cec5SDimitry Andric return; 5105*0b57cec5SDimitry Andric } 5106*0b57cec5SDimitry Andric 5107*0b57cec5SDimitry Andric assert(Entry->isDeclaration()); 5108*0b57cec5SDimitry Andric 5109*0b57cec5SDimitry Andric // If there is a declaration in the module, then we had an extern followed 5110*0b57cec5SDimitry Andric // by the alias, as in: 5111*0b57cec5SDimitry Andric // extern int test6(); 5112*0b57cec5SDimitry Andric // ... 5113*0b57cec5SDimitry Andric // int test6() __attribute__((alias("test7"))); 5114*0b57cec5SDimitry Andric // 5115*0b57cec5SDimitry Andric // Remove it and replace uses of it with the alias. 5116*0b57cec5SDimitry Andric GA->takeName(Entry); 5117*0b57cec5SDimitry Andric 5118*0b57cec5SDimitry Andric Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 5119*0b57cec5SDimitry Andric Entry->getType())); 5120*0b57cec5SDimitry Andric Entry->eraseFromParent(); 5121*0b57cec5SDimitry Andric } else { 5122*0b57cec5SDimitry Andric GA->setName(MangledName); 5123*0b57cec5SDimitry Andric } 5124*0b57cec5SDimitry Andric 5125*0b57cec5SDimitry Andric // Set attributes which are particular to an alias; this is a 5126*0b57cec5SDimitry Andric // specialization of the attributes which may be set on a global 5127*0b57cec5SDimitry Andric // variable/function. 5128*0b57cec5SDimitry Andric if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 5129*0b57cec5SDimitry Andric D->isWeakImported()) { 5130*0b57cec5SDimitry Andric GA->setLinkage(llvm::Function::WeakAnyLinkage); 5131*0b57cec5SDimitry Andric } 5132*0b57cec5SDimitry Andric 5133*0b57cec5SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 5134*0b57cec5SDimitry Andric if (VD->getTLSKind()) 5135*0b57cec5SDimitry Andric setTLSMode(GA, *VD); 5136*0b57cec5SDimitry Andric 5137*0b57cec5SDimitry Andric SetCommonAttributes(GD, GA); 5138*0b57cec5SDimitry Andric } 5139*0b57cec5SDimitry Andric 5140*0b57cec5SDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 5141*0b57cec5SDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 5142*0b57cec5SDimitry Andric const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 5143*0b57cec5SDimitry Andric assert(IFA && "Not an ifunc?"); 5144*0b57cec5SDimitry Andric 5145*0b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 5146*0b57cec5SDimitry Andric 5147*0b57cec5SDimitry Andric if (IFA->getResolver() == MangledName) { 5148*0b57cec5SDimitry Andric Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 5149*0b57cec5SDimitry Andric return; 5150*0b57cec5SDimitry Andric } 5151*0b57cec5SDimitry Andric 5152*0b57cec5SDimitry Andric // Report an error if some definition overrides ifunc. 5153*0b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 5154*0b57cec5SDimitry Andric if (Entry && !Entry->isDeclaration()) { 5155*0b57cec5SDimitry Andric GlobalDecl OtherGD; 5156*0b57cec5SDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 5157*0b57cec5SDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 5158*0b57cec5SDimitry Andric Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name) 5159*0b57cec5SDimitry Andric << MangledName; 5160*0b57cec5SDimitry Andric Diags.Report(OtherGD.getDecl()->getLocation(), 5161*0b57cec5SDimitry Andric diag::note_previous_definition); 5162*0b57cec5SDimitry Andric } 5163*0b57cec5SDimitry Andric return; 5164*0b57cec5SDimitry Andric } 5165*0b57cec5SDimitry Andric 5166*0b57cec5SDimitry Andric Aliases.push_back(GD); 5167*0b57cec5SDimitry Andric 5168*0b57cec5SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 5169349cc55cSDimitry Andric llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy); 5170*0b57cec5SDimitry Andric llvm::Constant *Resolver = 5171349cc55cSDimitry Andric GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {}, 5172*0b57cec5SDimitry Andric /*ForVTable=*/false); 5173*0b57cec5SDimitry Andric llvm::GlobalIFunc *GIF = 5174*0b57cec5SDimitry Andric llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 5175*0b57cec5SDimitry Andric "", Resolver, &getModule()); 5176*0b57cec5SDimitry Andric if (Entry) { 5177*0b57cec5SDimitry Andric if (GIF->getResolver() == Entry) { 5178*0b57cec5SDimitry Andric Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 5179*0b57cec5SDimitry Andric return; 5180*0b57cec5SDimitry Andric } 5181*0b57cec5SDimitry Andric assert(Entry->isDeclaration()); 5182*0b57cec5SDimitry Andric 5183*0b57cec5SDimitry Andric // If there is a declaration in the module, then we had an extern followed 5184*0b57cec5SDimitry Andric // by the ifunc, as in: 5185*0b57cec5SDimitry Andric // extern int test(); 5186*0b57cec5SDimitry Andric // ... 5187*0b57cec5SDimitry Andric // int test() __attribute__((ifunc("resolver"))); 5188*0b57cec5SDimitry Andric // 5189*0b57cec5SDimitry Andric // Remove it and replace uses of it with the ifunc. 5190*0b57cec5SDimitry Andric GIF->takeName(Entry); 5191*0b57cec5SDimitry Andric 5192*0b57cec5SDimitry Andric Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF, 5193*0b57cec5SDimitry Andric Entry->getType())); 5194*0b57cec5SDimitry Andric Entry->eraseFromParent(); 5195*0b57cec5SDimitry Andric } else 5196*0b57cec5SDimitry Andric GIF->setName(MangledName); 5197*0b57cec5SDimitry Andric 5198*0b57cec5SDimitry Andric SetCommonAttributes(GD, GIF); 5199*0b57cec5SDimitry Andric } 5200*0b57cec5SDimitry Andric 5201*0b57cec5SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 5202*0b57cec5SDimitry Andric ArrayRef<llvm::Type*> Tys) { 5203*0b57cec5SDimitry Andric return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 5204*0b57cec5SDimitry Andric Tys); 5205*0b57cec5SDimitry Andric } 5206*0b57cec5SDimitry Andric 5207*0b57cec5SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> & 5208*0b57cec5SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 5209*0b57cec5SDimitry Andric const StringLiteral *Literal, bool TargetIsLSB, 5210*0b57cec5SDimitry Andric bool &IsUTF16, unsigned &StringLength) { 5211*0b57cec5SDimitry Andric StringRef String = Literal->getString(); 5212*0b57cec5SDimitry Andric unsigned NumBytes = String.size(); 5213*0b57cec5SDimitry Andric 5214*0b57cec5SDimitry Andric // Check for simple case. 5215*0b57cec5SDimitry Andric if (!Literal->containsNonAsciiOrNull()) { 5216*0b57cec5SDimitry Andric StringLength = NumBytes; 5217*0b57cec5SDimitry Andric return *Map.insert(std::make_pair(String, nullptr)).first; 5218*0b57cec5SDimitry Andric } 5219*0b57cec5SDimitry Andric 5220*0b57cec5SDimitry Andric // Otherwise, convert the UTF8 literals into a string of shorts. 5221*0b57cec5SDimitry Andric IsUTF16 = true; 5222*0b57cec5SDimitry Andric 5223*0b57cec5SDimitry Andric SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 5224*0b57cec5SDimitry Andric const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5225*0b57cec5SDimitry Andric llvm::UTF16 *ToPtr = &ToBuf[0]; 5226*0b57cec5SDimitry Andric 5227*0b57cec5SDimitry Andric (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5228*0b57cec5SDimitry Andric ToPtr + NumBytes, llvm::strictConversion); 5229*0b57cec5SDimitry Andric 5230*0b57cec5SDimitry Andric // ConvertUTF8toUTF16 returns the length in ToPtr. 5231*0b57cec5SDimitry Andric StringLength = ToPtr - &ToBuf[0]; 5232*0b57cec5SDimitry Andric 5233*0b57cec5SDimitry Andric // Add an explicit null. 5234*0b57cec5SDimitry Andric *ToPtr = 0; 5235*0b57cec5SDimitry Andric return *Map.insert(std::make_pair( 5236*0b57cec5SDimitry Andric StringRef(reinterpret_cast<const char *>(ToBuf.data()), 5237*0b57cec5SDimitry Andric (StringLength + 1) * 2), 5238*0b57cec5SDimitry Andric nullptr)).first; 5239*0b57cec5SDimitry Andric } 5240*0b57cec5SDimitry Andric 5241*0b57cec5SDimitry Andric ConstantAddress 5242*0b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 5243*0b57cec5SDimitry Andric unsigned StringLength = 0; 5244*0b57cec5SDimitry Andric bool isUTF16 = false; 5245*0b57cec5SDimitry Andric llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 5246*0b57cec5SDimitry Andric GetConstantCFStringEntry(CFConstantStringMap, Literal, 5247*0b57cec5SDimitry Andric getDataLayout().isLittleEndian(), isUTF16, 5248*0b57cec5SDimitry Andric StringLength); 5249*0b57cec5SDimitry Andric 5250*0b57cec5SDimitry Andric if (auto *C = Entry.second) 52510eae32dcSDimitry Andric return ConstantAddress( 52520eae32dcSDimitry Andric C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment())); 5253*0b57cec5SDimitry Andric 5254*0b57cec5SDimitry Andric llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 5255*0b57cec5SDimitry Andric llvm::Constant *Zeros[] = { Zero, Zero }; 5256*0b57cec5SDimitry Andric 5257*0b57cec5SDimitry Andric const ASTContext &Context = getContext(); 5258*0b57cec5SDimitry Andric const llvm::Triple &Triple = getTriple(); 5259*0b57cec5SDimitry Andric 5260*0b57cec5SDimitry Andric const auto CFRuntime = getLangOpts().CFRuntime; 5261*0b57cec5SDimitry Andric const bool IsSwiftABI = 5262*0b57cec5SDimitry Andric static_cast<unsigned>(CFRuntime) >= 5263*0b57cec5SDimitry Andric static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift); 5264*0b57cec5SDimitry Andric const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1; 5265*0b57cec5SDimitry Andric 5266*0b57cec5SDimitry Andric // If we don't already have it, get __CFConstantStringClassReference. 5267*0b57cec5SDimitry Andric if (!CFConstantStringClassRef) { 5268*0b57cec5SDimitry Andric const char *CFConstantStringClassName = "__CFConstantStringClassReference"; 5269*0b57cec5SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 5270*0b57cec5SDimitry Andric Ty = llvm::ArrayType::get(Ty, 0); 5271*0b57cec5SDimitry Andric 5272*0b57cec5SDimitry Andric switch (CFRuntime) { 5273*0b57cec5SDimitry Andric default: break; 5274*0b57cec5SDimitry Andric case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH; 5275*0b57cec5SDimitry Andric case LangOptions::CoreFoundationABI::Swift5_0: 5276*0b57cec5SDimitry Andric CFConstantStringClassName = 5277*0b57cec5SDimitry Andric Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN" 5278*0b57cec5SDimitry Andric : "$s10Foundation19_NSCFConstantStringCN"; 5279*0b57cec5SDimitry Andric Ty = IntPtrTy; 5280*0b57cec5SDimitry Andric break; 5281*0b57cec5SDimitry Andric case LangOptions::CoreFoundationABI::Swift4_2: 5282*0b57cec5SDimitry Andric CFConstantStringClassName = 5283*0b57cec5SDimitry Andric Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN" 5284*0b57cec5SDimitry Andric : "$S10Foundation19_NSCFConstantStringCN"; 5285*0b57cec5SDimitry Andric Ty = IntPtrTy; 5286*0b57cec5SDimitry Andric break; 5287*0b57cec5SDimitry Andric case LangOptions::CoreFoundationABI::Swift4_1: 5288*0b57cec5SDimitry Andric CFConstantStringClassName = 5289*0b57cec5SDimitry Andric Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN" 5290*0b57cec5SDimitry Andric : "__T010Foundation19_NSCFConstantStringCN"; 5291*0b57cec5SDimitry Andric Ty = IntPtrTy; 5292*0b57cec5SDimitry Andric break; 5293*0b57cec5SDimitry Andric } 5294*0b57cec5SDimitry Andric 5295*0b57cec5SDimitry Andric llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName); 5296*0b57cec5SDimitry Andric 5297*0b57cec5SDimitry Andric if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) { 5298*0b57cec5SDimitry Andric llvm::GlobalValue *GV = nullptr; 5299*0b57cec5SDimitry Andric 5300*0b57cec5SDimitry Andric if ((GV = dyn_cast<llvm::GlobalValue>(C))) { 5301*0b57cec5SDimitry Andric IdentifierInfo &II = Context.Idents.get(GV->getName()); 5302*0b57cec5SDimitry Andric TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl(); 5303*0b57cec5SDimitry Andric DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 5304*0b57cec5SDimitry Andric 5305*0b57cec5SDimitry Andric const VarDecl *VD = nullptr; 5306fe6060f1SDimitry Andric for (const auto *Result : DC->lookup(&II)) 5307*0b57cec5SDimitry Andric if ((VD = dyn_cast<VarDecl>(Result))) 5308*0b57cec5SDimitry Andric break; 5309*0b57cec5SDimitry Andric 5310*0b57cec5SDimitry Andric if (Triple.isOSBinFormatELF()) { 5311*0b57cec5SDimitry Andric if (!VD) 5312*0b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 5313*0b57cec5SDimitry Andric } else { 5314*0b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 5315*0b57cec5SDimitry Andric if (!VD || !VD->hasAttr<DLLExportAttr>()) 5316*0b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 5317*0b57cec5SDimitry Andric else 5318*0b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 5319*0b57cec5SDimitry Andric } 5320*0b57cec5SDimitry Andric 5321*0b57cec5SDimitry Andric setDSOLocal(GV); 5322*0b57cec5SDimitry Andric } 5323*0b57cec5SDimitry Andric } 5324*0b57cec5SDimitry Andric 5325*0b57cec5SDimitry Andric // Decay array -> ptr 5326*0b57cec5SDimitry Andric CFConstantStringClassRef = 5327*0b57cec5SDimitry Andric IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) 5328*0b57cec5SDimitry Andric : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros); 5329*0b57cec5SDimitry Andric } 5330*0b57cec5SDimitry Andric 5331*0b57cec5SDimitry Andric QualType CFTy = Context.getCFConstantStringType(); 5332*0b57cec5SDimitry Andric 5333*0b57cec5SDimitry Andric auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 5334*0b57cec5SDimitry Andric 5335*0b57cec5SDimitry Andric ConstantInitBuilder Builder(*this); 5336*0b57cec5SDimitry Andric auto Fields = Builder.beginStruct(STy); 5337*0b57cec5SDimitry Andric 5338*0b57cec5SDimitry Andric // Class pointer. 5339*0b57cec5SDimitry Andric Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef)); 5340*0b57cec5SDimitry Andric 5341*0b57cec5SDimitry Andric // Flags. 5342*0b57cec5SDimitry Andric if (IsSwiftABI) { 5343*0b57cec5SDimitry Andric Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01); 5344*0b57cec5SDimitry Andric Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8); 5345*0b57cec5SDimitry Andric } else { 5346*0b57cec5SDimitry Andric Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); 5347*0b57cec5SDimitry Andric } 5348*0b57cec5SDimitry Andric 5349*0b57cec5SDimitry Andric // String pointer. 5350*0b57cec5SDimitry Andric llvm::Constant *C = nullptr; 5351*0b57cec5SDimitry Andric if (isUTF16) { 5352*0b57cec5SDimitry Andric auto Arr = llvm::makeArrayRef( 5353*0b57cec5SDimitry Andric reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 5354*0b57cec5SDimitry Andric Entry.first().size() / 2); 5355*0b57cec5SDimitry Andric C = llvm::ConstantDataArray::get(VMContext, Arr); 5356*0b57cec5SDimitry Andric } else { 5357*0b57cec5SDimitry Andric C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 5358*0b57cec5SDimitry Andric } 5359*0b57cec5SDimitry Andric 5360*0b57cec5SDimitry Andric // Note: -fwritable-strings doesn't make the backing store strings of 5361*0b57cec5SDimitry Andric // CFStrings writable. (See <rdar://problem/10657500>) 5362*0b57cec5SDimitry Andric auto *GV = 5363*0b57cec5SDimitry Andric new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 5364*0b57cec5SDimitry Andric llvm::GlobalValue::PrivateLinkage, C, ".str"); 5365*0b57cec5SDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 5366*0b57cec5SDimitry Andric // Don't enforce the target's minimum global alignment, since the only use 5367*0b57cec5SDimitry Andric // of the string is via this class initializer. 5368*0b57cec5SDimitry Andric CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy) 5369*0b57cec5SDimitry Andric : Context.getTypeAlignInChars(Context.CharTy); 5370a7dea167SDimitry Andric GV->setAlignment(Align.getAsAlign()); 5371*0b57cec5SDimitry Andric 5372*0b57cec5SDimitry Andric // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 5373*0b57cec5SDimitry Andric // Without it LLVM can merge the string with a non unnamed_addr one during 5374*0b57cec5SDimitry Andric // LTO. Doing that changes the section it ends in, which surprises ld64. 5375*0b57cec5SDimitry Andric if (Triple.isOSBinFormatMachO()) 5376*0b57cec5SDimitry Andric GV->setSection(isUTF16 ? "__TEXT,__ustring" 5377*0b57cec5SDimitry Andric : "__TEXT,__cstring,cstring_literals"); 5378*0b57cec5SDimitry Andric // Make sure the literal ends up in .rodata to allow for safe ICF and for 5379*0b57cec5SDimitry Andric // the static linker to adjust permissions to read-only later on. 5380*0b57cec5SDimitry Andric else if (Triple.isOSBinFormatELF()) 5381*0b57cec5SDimitry Andric GV->setSection(".rodata"); 5382*0b57cec5SDimitry Andric 5383*0b57cec5SDimitry Andric // String. 5384*0b57cec5SDimitry Andric llvm::Constant *Str = 5385*0b57cec5SDimitry Andric llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 5386*0b57cec5SDimitry Andric 5387*0b57cec5SDimitry Andric if (isUTF16) 5388*0b57cec5SDimitry Andric // Cast the UTF16 string to the correct type. 5389*0b57cec5SDimitry Andric Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy); 5390*0b57cec5SDimitry Andric Fields.add(Str); 5391*0b57cec5SDimitry Andric 5392*0b57cec5SDimitry Andric // String length. 5393*0b57cec5SDimitry Andric llvm::IntegerType *LengthTy = 5394*0b57cec5SDimitry Andric llvm::IntegerType::get(getModule().getContext(), 5395*0b57cec5SDimitry Andric Context.getTargetInfo().getLongWidth()); 5396*0b57cec5SDimitry Andric if (IsSwiftABI) { 5397*0b57cec5SDimitry Andric if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 5398*0b57cec5SDimitry Andric CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 5399*0b57cec5SDimitry Andric LengthTy = Int32Ty; 5400*0b57cec5SDimitry Andric else 5401*0b57cec5SDimitry Andric LengthTy = IntPtrTy; 5402*0b57cec5SDimitry Andric } 5403*0b57cec5SDimitry Andric Fields.addInt(LengthTy, StringLength); 5404*0b57cec5SDimitry Andric 5405a7dea167SDimitry Andric // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is 5406a7dea167SDimitry Andric // properly aligned on 32-bit platforms. 5407a7dea167SDimitry Andric CharUnits Alignment = 5408a7dea167SDimitry Andric IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign(); 5409*0b57cec5SDimitry Andric 5410*0b57cec5SDimitry Andric // The struct. 5411*0b57cec5SDimitry Andric GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, 5412*0b57cec5SDimitry Andric /*isConstant=*/false, 5413*0b57cec5SDimitry Andric llvm::GlobalVariable::PrivateLinkage); 5414*0b57cec5SDimitry Andric GV->addAttribute("objc_arc_inert"); 5415*0b57cec5SDimitry Andric switch (Triple.getObjectFormat()) { 5416*0b57cec5SDimitry Andric case llvm::Triple::UnknownObjectFormat: 5417*0b57cec5SDimitry Andric llvm_unreachable("unknown file format"); 5418e8d8bef9SDimitry Andric case llvm::Triple::GOFF: 5419e8d8bef9SDimitry Andric llvm_unreachable("GOFF is not yet implemented"); 5420*0b57cec5SDimitry Andric case llvm::Triple::XCOFF: 5421*0b57cec5SDimitry Andric llvm_unreachable("XCOFF is not yet implemented"); 5422*0b57cec5SDimitry Andric case llvm::Triple::COFF: 5423*0b57cec5SDimitry Andric case llvm::Triple::ELF: 5424*0b57cec5SDimitry Andric case llvm::Triple::Wasm: 5425*0b57cec5SDimitry Andric GV->setSection("cfstring"); 5426*0b57cec5SDimitry Andric break; 5427*0b57cec5SDimitry Andric case llvm::Triple::MachO: 5428*0b57cec5SDimitry Andric GV->setSection("__DATA,__cfstring"); 5429*0b57cec5SDimitry Andric break; 5430*0b57cec5SDimitry Andric } 5431*0b57cec5SDimitry Andric Entry.second = GV; 5432*0b57cec5SDimitry Andric 54330eae32dcSDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 5434*0b57cec5SDimitry Andric } 5435*0b57cec5SDimitry Andric 5436*0b57cec5SDimitry Andric bool CodeGenModule::getExpressionLocationsEnabled() const { 5437*0b57cec5SDimitry Andric return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo; 5438*0b57cec5SDimitry Andric } 5439*0b57cec5SDimitry Andric 5440*0b57cec5SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() { 5441*0b57cec5SDimitry Andric if (ObjCFastEnumerationStateType.isNull()) { 5442*0b57cec5SDimitry Andric RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 5443*0b57cec5SDimitry Andric D->startDefinition(); 5444*0b57cec5SDimitry Andric 5445*0b57cec5SDimitry Andric QualType FieldTypes[] = { 5446*0b57cec5SDimitry Andric Context.UnsignedLongTy, 5447*0b57cec5SDimitry Andric Context.getPointerType(Context.getObjCIdType()), 5448*0b57cec5SDimitry Andric Context.getPointerType(Context.UnsignedLongTy), 5449*0b57cec5SDimitry Andric Context.getConstantArrayType(Context.UnsignedLongTy, 5450a7dea167SDimitry Andric llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0) 5451*0b57cec5SDimitry Andric }; 5452*0b57cec5SDimitry Andric 5453*0b57cec5SDimitry Andric for (size_t i = 0; i < 4; ++i) { 5454*0b57cec5SDimitry Andric FieldDecl *Field = FieldDecl::Create(Context, 5455*0b57cec5SDimitry Andric D, 5456*0b57cec5SDimitry Andric SourceLocation(), 5457*0b57cec5SDimitry Andric SourceLocation(), nullptr, 5458*0b57cec5SDimitry Andric FieldTypes[i], /*TInfo=*/nullptr, 5459*0b57cec5SDimitry Andric /*BitWidth=*/nullptr, 5460*0b57cec5SDimitry Andric /*Mutable=*/false, 5461*0b57cec5SDimitry Andric ICIS_NoInit); 5462*0b57cec5SDimitry Andric Field->setAccess(AS_public); 5463*0b57cec5SDimitry Andric D->addDecl(Field); 5464*0b57cec5SDimitry Andric } 5465*0b57cec5SDimitry Andric 5466*0b57cec5SDimitry Andric D->completeDefinition(); 5467*0b57cec5SDimitry Andric ObjCFastEnumerationStateType = Context.getTagDeclType(D); 5468*0b57cec5SDimitry Andric } 5469*0b57cec5SDimitry Andric 5470*0b57cec5SDimitry Andric return ObjCFastEnumerationStateType; 5471*0b57cec5SDimitry Andric } 5472*0b57cec5SDimitry Andric 5473*0b57cec5SDimitry Andric llvm::Constant * 5474*0b57cec5SDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 5475*0b57cec5SDimitry Andric assert(!E->getType()->isPointerType() && "Strings are always arrays"); 5476*0b57cec5SDimitry Andric 5477*0b57cec5SDimitry Andric // Don't emit it as the address of the string, emit the string data itself 5478*0b57cec5SDimitry Andric // as an inline array. 5479*0b57cec5SDimitry Andric if (E->getCharByteWidth() == 1) { 5480*0b57cec5SDimitry Andric SmallString<64> Str(E->getString()); 5481*0b57cec5SDimitry Andric 5482*0b57cec5SDimitry Andric // Resize the string to the right size, which is indicated by its type. 5483*0b57cec5SDimitry Andric const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 5484*0b57cec5SDimitry Andric Str.resize(CAT->getSize().getZExtValue()); 5485*0b57cec5SDimitry Andric return llvm::ConstantDataArray::getString(VMContext, Str, false); 5486*0b57cec5SDimitry Andric } 5487*0b57cec5SDimitry Andric 5488*0b57cec5SDimitry Andric auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 5489*0b57cec5SDimitry Andric llvm::Type *ElemTy = AType->getElementType(); 5490*0b57cec5SDimitry Andric unsigned NumElements = AType->getNumElements(); 5491*0b57cec5SDimitry Andric 5492*0b57cec5SDimitry Andric // Wide strings have either 2-byte or 4-byte elements. 5493*0b57cec5SDimitry Andric if (ElemTy->getPrimitiveSizeInBits() == 16) { 5494*0b57cec5SDimitry Andric SmallVector<uint16_t, 32> Elements; 5495*0b57cec5SDimitry Andric Elements.reserve(NumElements); 5496*0b57cec5SDimitry Andric 5497*0b57cec5SDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 5498*0b57cec5SDimitry Andric Elements.push_back(E->getCodeUnit(i)); 5499*0b57cec5SDimitry Andric Elements.resize(NumElements); 5500*0b57cec5SDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 5501*0b57cec5SDimitry Andric } 5502*0b57cec5SDimitry Andric 5503*0b57cec5SDimitry Andric assert(ElemTy->getPrimitiveSizeInBits() == 32); 5504*0b57cec5SDimitry Andric SmallVector<uint32_t, 32> Elements; 5505*0b57cec5SDimitry Andric Elements.reserve(NumElements); 5506*0b57cec5SDimitry Andric 5507*0b57cec5SDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 5508*0b57cec5SDimitry Andric Elements.push_back(E->getCodeUnit(i)); 5509*0b57cec5SDimitry Andric Elements.resize(NumElements); 5510*0b57cec5SDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 5511*0b57cec5SDimitry Andric } 5512*0b57cec5SDimitry Andric 5513*0b57cec5SDimitry Andric static llvm::GlobalVariable * 5514*0b57cec5SDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 5515*0b57cec5SDimitry Andric CodeGenModule &CGM, StringRef GlobalName, 5516*0b57cec5SDimitry Andric CharUnits Alignment) { 5517*0b57cec5SDimitry Andric unsigned AddrSpace = CGM.getContext().getTargetAddressSpace( 5518fe6060f1SDimitry Andric CGM.GetGlobalConstantAddressSpace()); 5519*0b57cec5SDimitry Andric 5520*0b57cec5SDimitry Andric llvm::Module &M = CGM.getModule(); 5521*0b57cec5SDimitry Andric // Create a global variable for this string 5522*0b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 5523*0b57cec5SDimitry Andric M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 5524*0b57cec5SDimitry Andric nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 5525a7dea167SDimitry Andric GV->setAlignment(Alignment.getAsAlign()); 5526*0b57cec5SDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 5527*0b57cec5SDimitry Andric if (GV->isWeakForLinker()) { 5528*0b57cec5SDimitry Andric assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 5529*0b57cec5SDimitry Andric GV->setComdat(M.getOrInsertComdat(GV->getName())); 5530*0b57cec5SDimitry Andric } 5531*0b57cec5SDimitry Andric CGM.setDSOLocal(GV); 5532*0b57cec5SDimitry Andric 5533*0b57cec5SDimitry Andric return GV; 5534*0b57cec5SDimitry Andric } 5535*0b57cec5SDimitry Andric 5536*0b57cec5SDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 5537*0b57cec5SDimitry Andric /// constant array for the given string literal. 5538*0b57cec5SDimitry Andric ConstantAddress 5539*0b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 5540*0b57cec5SDimitry Andric StringRef Name) { 5541*0b57cec5SDimitry Andric CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 5542*0b57cec5SDimitry Andric 5543*0b57cec5SDimitry Andric llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 5544*0b57cec5SDimitry Andric llvm::GlobalVariable **Entry = nullptr; 5545*0b57cec5SDimitry Andric if (!LangOpts.WritableStrings) { 5546*0b57cec5SDimitry Andric Entry = &ConstantStringMap[C]; 5547*0b57cec5SDimitry Andric if (auto GV = *Entry) { 5548349cc55cSDimitry Andric if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 5549a7dea167SDimitry Andric GV->setAlignment(Alignment.getAsAlign()); 5550*0b57cec5SDimitry Andric return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 55510eae32dcSDimitry Andric GV->getValueType(), Alignment); 5552*0b57cec5SDimitry Andric } 5553*0b57cec5SDimitry Andric } 5554*0b57cec5SDimitry Andric 5555*0b57cec5SDimitry Andric SmallString<256> MangledNameBuffer; 5556*0b57cec5SDimitry Andric StringRef GlobalVariableName; 5557*0b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes LT; 5558*0b57cec5SDimitry Andric 5559*0b57cec5SDimitry Andric // Mangle the string literal if that's how the ABI merges duplicate strings. 5560*0b57cec5SDimitry Andric // Don't do it if they are writable, since we don't want writes in one TU to 5561*0b57cec5SDimitry Andric // affect strings in another. 5562*0b57cec5SDimitry Andric if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) && 5563*0b57cec5SDimitry Andric !LangOpts.WritableStrings) { 5564*0b57cec5SDimitry Andric llvm::raw_svector_ostream Out(MangledNameBuffer); 5565*0b57cec5SDimitry Andric getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 5566*0b57cec5SDimitry Andric LT = llvm::GlobalValue::LinkOnceODRLinkage; 5567*0b57cec5SDimitry Andric GlobalVariableName = MangledNameBuffer; 5568*0b57cec5SDimitry Andric } else { 5569*0b57cec5SDimitry Andric LT = llvm::GlobalValue::PrivateLinkage; 5570*0b57cec5SDimitry Andric GlobalVariableName = Name; 5571*0b57cec5SDimitry Andric } 5572*0b57cec5SDimitry Andric 5573*0b57cec5SDimitry Andric auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 5574*0b57cec5SDimitry Andric if (Entry) 5575*0b57cec5SDimitry Andric *Entry = GV; 5576*0b57cec5SDimitry Andric 5577*0b57cec5SDimitry Andric SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>", 5578*0b57cec5SDimitry Andric QualType()); 5579*0b57cec5SDimitry Andric 5580*0b57cec5SDimitry Andric return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 55810eae32dcSDimitry Andric GV->getValueType(), Alignment); 5582*0b57cec5SDimitry Andric } 5583*0b57cec5SDimitry Andric 5584*0b57cec5SDimitry Andric /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 5585*0b57cec5SDimitry Andric /// array for the given ObjCEncodeExpr node. 5586*0b57cec5SDimitry Andric ConstantAddress 5587*0b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 5588*0b57cec5SDimitry Andric std::string Str; 5589*0b57cec5SDimitry Andric getContext().getObjCEncodingForType(E->getEncodedType(), Str); 5590*0b57cec5SDimitry Andric 5591*0b57cec5SDimitry Andric return GetAddrOfConstantCString(Str); 5592*0b57cec5SDimitry Andric } 5593*0b57cec5SDimitry Andric 5594*0b57cec5SDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing 5595*0b57cec5SDimitry Andric /// the literal and a terminating '\0' character. 5596*0b57cec5SDimitry Andric /// The result has pointer to array type. 5597*0b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString( 5598*0b57cec5SDimitry Andric const std::string &Str, const char *GlobalName) { 5599*0b57cec5SDimitry Andric StringRef StrWithNull(Str.c_str(), Str.size() + 1); 5600*0b57cec5SDimitry Andric CharUnits Alignment = 5601*0b57cec5SDimitry Andric getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 5602*0b57cec5SDimitry Andric 5603*0b57cec5SDimitry Andric llvm::Constant *C = 5604*0b57cec5SDimitry Andric llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 5605*0b57cec5SDimitry Andric 5606*0b57cec5SDimitry Andric // Don't share any string literals if strings aren't constant. 5607*0b57cec5SDimitry Andric llvm::GlobalVariable **Entry = nullptr; 5608*0b57cec5SDimitry Andric if (!LangOpts.WritableStrings) { 5609*0b57cec5SDimitry Andric Entry = &ConstantStringMap[C]; 5610*0b57cec5SDimitry Andric if (auto GV = *Entry) { 5611349cc55cSDimitry Andric if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 5612a7dea167SDimitry Andric GV->setAlignment(Alignment.getAsAlign()); 5613*0b57cec5SDimitry Andric return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 56140eae32dcSDimitry Andric GV->getValueType(), Alignment); 5615*0b57cec5SDimitry Andric } 5616*0b57cec5SDimitry Andric } 5617*0b57cec5SDimitry Andric 5618*0b57cec5SDimitry Andric // Get the default prefix if a name wasn't specified. 5619*0b57cec5SDimitry Andric if (!GlobalName) 5620*0b57cec5SDimitry Andric GlobalName = ".str"; 5621*0b57cec5SDimitry Andric // Create a global variable for this. 5622*0b57cec5SDimitry Andric auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 5623*0b57cec5SDimitry Andric GlobalName, Alignment); 5624*0b57cec5SDimitry Andric if (Entry) 5625*0b57cec5SDimitry Andric *Entry = GV; 5626*0b57cec5SDimitry Andric 5627*0b57cec5SDimitry Andric return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 56280eae32dcSDimitry Andric GV->getValueType(), Alignment); 5629*0b57cec5SDimitry Andric } 5630*0b57cec5SDimitry Andric 5631*0b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 5632*0b57cec5SDimitry Andric const MaterializeTemporaryExpr *E, const Expr *Init) { 5633*0b57cec5SDimitry Andric assert((E->getStorageDuration() == SD_Static || 5634*0b57cec5SDimitry Andric E->getStorageDuration() == SD_Thread) && "not a global temporary"); 5635*0b57cec5SDimitry Andric const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 5636*0b57cec5SDimitry Andric 5637*0b57cec5SDimitry Andric // If we're not materializing a subobject of the temporary, keep the 5638*0b57cec5SDimitry Andric // cv-qualifiers from the type of the MaterializeTemporaryExpr. 5639*0b57cec5SDimitry Andric QualType MaterializedType = Init->getType(); 5640480093f4SDimitry Andric if (Init == E->getSubExpr()) 5641*0b57cec5SDimitry Andric MaterializedType = E->getType(); 5642*0b57cec5SDimitry Andric 5643*0b57cec5SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 5644*0b57cec5SDimitry Andric 5645fe6060f1SDimitry Andric auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr}); 5646fe6060f1SDimitry Andric if (!InsertResult.second) { 5647fe6060f1SDimitry Andric // We've seen this before: either we already created it or we're in the 5648fe6060f1SDimitry Andric // process of doing so. 5649fe6060f1SDimitry Andric if (!InsertResult.first->second) { 5650fe6060f1SDimitry Andric // We recursively re-entered this function, probably during emission of 5651fe6060f1SDimitry Andric // the initializer. Create a placeholder. We'll clean this up in the 5652fe6060f1SDimitry Andric // outer call, at the end of this function. 5653fe6060f1SDimitry Andric llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType); 5654fe6060f1SDimitry Andric InsertResult.first->second = new llvm::GlobalVariable( 5655fe6060f1SDimitry Andric getModule(), Type, false, llvm::GlobalVariable::InternalLinkage, 5656fe6060f1SDimitry Andric nullptr); 5657fe6060f1SDimitry Andric } 56580eae32dcSDimitry Andric return ConstantAddress( 56590eae32dcSDimitry Andric InsertResult.first->second, 56600eae32dcSDimitry Andric InsertResult.first->second->getType()->getPointerElementType(), Align); 5661fe6060f1SDimitry Andric } 5662*0b57cec5SDimitry Andric 5663*0b57cec5SDimitry Andric // FIXME: If an externally-visible declaration extends multiple temporaries, 5664*0b57cec5SDimitry Andric // we need to give each temporary the same name in every translation unit (and 5665*0b57cec5SDimitry Andric // we also need to make the temporaries externally-visible). 5666*0b57cec5SDimitry Andric SmallString<256> Name; 5667*0b57cec5SDimitry Andric llvm::raw_svector_ostream Out(Name); 5668*0b57cec5SDimitry Andric getCXXABI().getMangleContext().mangleReferenceTemporary( 5669*0b57cec5SDimitry Andric VD, E->getManglingNumber(), Out); 5670*0b57cec5SDimitry Andric 5671*0b57cec5SDimitry Andric APValue *Value = nullptr; 5672a7dea167SDimitry Andric if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) { 5673a7dea167SDimitry Andric // If the initializer of the extending declaration is a constant 5674a7dea167SDimitry Andric // initializer, we should have a cached constant initializer for this 5675a7dea167SDimitry Andric // temporary. Note that this might have a different value from the value 5676a7dea167SDimitry Andric // computed by evaluating the initializer if the surrounding constant 5677a7dea167SDimitry Andric // expression modifies the temporary. 5678480093f4SDimitry Andric Value = E->getOrCreateValue(false); 5679*0b57cec5SDimitry Andric } 5680*0b57cec5SDimitry Andric 5681*0b57cec5SDimitry Andric // Try evaluating it now, it might have a constant initializer. 5682*0b57cec5SDimitry Andric Expr::EvalResult EvalResult; 5683*0b57cec5SDimitry Andric if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 5684*0b57cec5SDimitry Andric !EvalResult.hasSideEffects()) 5685*0b57cec5SDimitry Andric Value = &EvalResult.Val; 5686*0b57cec5SDimitry Andric 5687*0b57cec5SDimitry Andric LangAS AddrSpace = 5688*0b57cec5SDimitry Andric VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace(); 5689*0b57cec5SDimitry Andric 5690*0b57cec5SDimitry Andric Optional<ConstantEmitter> emitter; 5691*0b57cec5SDimitry Andric llvm::Constant *InitialValue = nullptr; 5692*0b57cec5SDimitry Andric bool Constant = false; 5693*0b57cec5SDimitry Andric llvm::Type *Type; 5694*0b57cec5SDimitry Andric if (Value) { 5695*0b57cec5SDimitry Andric // The temporary has a constant initializer, use it. 5696*0b57cec5SDimitry Andric emitter.emplace(*this); 5697*0b57cec5SDimitry Andric InitialValue = emitter->emitForInitializer(*Value, AddrSpace, 5698*0b57cec5SDimitry Andric MaterializedType); 5699*0b57cec5SDimitry Andric Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 5700*0b57cec5SDimitry Andric Type = InitialValue->getType(); 5701*0b57cec5SDimitry Andric } else { 5702*0b57cec5SDimitry Andric // No initializer, the initialization will be provided when we 5703*0b57cec5SDimitry Andric // initialize the declaration which performed lifetime extension. 5704*0b57cec5SDimitry Andric Type = getTypes().ConvertTypeForMem(MaterializedType); 5705*0b57cec5SDimitry Andric } 5706*0b57cec5SDimitry Andric 5707*0b57cec5SDimitry Andric // Create a global variable for this lifetime-extended temporary. 5708*0b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 5709*0b57cec5SDimitry Andric getLLVMLinkageVarDefinition(VD, Constant); 5710*0b57cec5SDimitry Andric if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 5711*0b57cec5SDimitry Andric const VarDecl *InitVD; 5712*0b57cec5SDimitry Andric if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 5713*0b57cec5SDimitry Andric isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 5714*0b57cec5SDimitry Andric // Temporaries defined inside a class get linkonce_odr linkage because the 5715*0b57cec5SDimitry Andric // class can be defined in multiple translation units. 5716*0b57cec5SDimitry Andric Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 5717*0b57cec5SDimitry Andric } else { 5718*0b57cec5SDimitry Andric // There is no need for this temporary to have external linkage if the 5719*0b57cec5SDimitry Andric // VarDecl has external linkage. 5720*0b57cec5SDimitry Andric Linkage = llvm::GlobalVariable::InternalLinkage; 5721*0b57cec5SDimitry Andric } 5722*0b57cec5SDimitry Andric } 5723*0b57cec5SDimitry Andric auto TargetAS = getContext().getTargetAddressSpace(AddrSpace); 5724*0b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 5725*0b57cec5SDimitry Andric getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 5726*0b57cec5SDimitry Andric /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); 5727*0b57cec5SDimitry Andric if (emitter) emitter->finalize(GV); 5728*0b57cec5SDimitry Andric setGVProperties(GV, VD); 5729a7dea167SDimitry Andric GV->setAlignment(Align.getAsAlign()); 5730*0b57cec5SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker()) 5731*0b57cec5SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 5732*0b57cec5SDimitry Andric if (VD->getTLSKind()) 5733*0b57cec5SDimitry Andric setTLSMode(GV, *VD); 5734*0b57cec5SDimitry Andric llvm::Constant *CV = GV; 5735*0b57cec5SDimitry Andric if (AddrSpace != LangAS::Default) 5736*0b57cec5SDimitry Andric CV = getTargetCodeGenInfo().performAddrSpaceCast( 5737*0b57cec5SDimitry Andric *this, GV, AddrSpace, LangAS::Default, 5738*0b57cec5SDimitry Andric Type->getPointerTo( 5739*0b57cec5SDimitry Andric getContext().getTargetAddressSpace(LangAS::Default))); 5740fe6060f1SDimitry Andric 5741fe6060f1SDimitry Andric // Update the map with the new temporary. If we created a placeholder above, 5742fe6060f1SDimitry Andric // replace it with the new global now. 5743fe6060f1SDimitry Andric llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E]; 5744fe6060f1SDimitry Andric if (Entry) { 5745fe6060f1SDimitry Andric Entry->replaceAllUsesWith( 5746fe6060f1SDimitry Andric llvm::ConstantExpr::getBitCast(CV, Entry->getType())); 5747fe6060f1SDimitry Andric llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent(); 5748fe6060f1SDimitry Andric } 5749fe6060f1SDimitry Andric Entry = CV; 5750fe6060f1SDimitry Andric 57510eae32dcSDimitry Andric return ConstantAddress(CV, Type, Align); 5752*0b57cec5SDimitry Andric } 5753*0b57cec5SDimitry Andric 5754*0b57cec5SDimitry Andric /// EmitObjCPropertyImplementations - Emit information for synthesized 5755*0b57cec5SDimitry Andric /// properties for an implementation. 5756*0b57cec5SDimitry Andric void CodeGenModule::EmitObjCPropertyImplementations(const 5757*0b57cec5SDimitry Andric ObjCImplementationDecl *D) { 5758*0b57cec5SDimitry Andric for (const auto *PID : D->property_impls()) { 5759*0b57cec5SDimitry Andric // Dynamic is just for type-checking. 5760*0b57cec5SDimitry Andric if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 5761*0b57cec5SDimitry Andric ObjCPropertyDecl *PD = PID->getPropertyDecl(); 5762*0b57cec5SDimitry Andric 5763*0b57cec5SDimitry Andric // Determine which methods need to be implemented, some may have 5764*0b57cec5SDimitry Andric // been overridden. Note that ::isPropertyAccessor is not the method 5765*0b57cec5SDimitry Andric // we want, that just indicates if the decl came from a 5766*0b57cec5SDimitry Andric // property. What we want to know is if the method is defined in 5767*0b57cec5SDimitry Andric // this implementation. 5768480093f4SDimitry Andric auto *Getter = PID->getGetterMethodDecl(); 5769480093f4SDimitry Andric if (!Getter || Getter->isSynthesizedAccessorStub()) 5770*0b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCGetter( 5771*0b57cec5SDimitry Andric const_cast<ObjCImplementationDecl *>(D), PID); 5772480093f4SDimitry Andric auto *Setter = PID->getSetterMethodDecl(); 5773480093f4SDimitry Andric if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub())) 5774*0b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCSetter( 5775*0b57cec5SDimitry Andric const_cast<ObjCImplementationDecl *>(D), PID); 5776*0b57cec5SDimitry Andric } 5777*0b57cec5SDimitry Andric } 5778*0b57cec5SDimitry Andric } 5779*0b57cec5SDimitry Andric 5780*0b57cec5SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) { 5781*0b57cec5SDimitry Andric const ObjCInterfaceDecl *iface = impl->getClassInterface(); 5782*0b57cec5SDimitry Andric for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 5783*0b57cec5SDimitry Andric ivar; ivar = ivar->getNextIvar()) 5784*0b57cec5SDimitry Andric if (ivar->getType().isDestructedType()) 5785*0b57cec5SDimitry Andric return true; 5786*0b57cec5SDimitry Andric 5787*0b57cec5SDimitry Andric return false; 5788*0b57cec5SDimitry Andric } 5789*0b57cec5SDimitry Andric 5790*0b57cec5SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM, 5791*0b57cec5SDimitry Andric ObjCImplementationDecl *D) { 5792*0b57cec5SDimitry Andric CodeGenFunction CGF(CGM); 5793*0b57cec5SDimitry Andric for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 5794*0b57cec5SDimitry Andric E = D->init_end(); B != E; ++B) { 5795*0b57cec5SDimitry Andric CXXCtorInitializer *CtorInitExp = *B; 5796*0b57cec5SDimitry Andric Expr *Init = CtorInitExp->getInit(); 5797*0b57cec5SDimitry Andric if (!CGF.isTrivialInitializer(Init)) 5798*0b57cec5SDimitry Andric return false; 5799*0b57cec5SDimitry Andric } 5800*0b57cec5SDimitry Andric return true; 5801*0b57cec5SDimitry Andric } 5802*0b57cec5SDimitry Andric 5803*0b57cec5SDimitry Andric /// EmitObjCIvarInitializations - Emit information for ivar initialization 5804*0b57cec5SDimitry Andric /// for an implementation. 5805*0b57cec5SDimitry Andric void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 5806*0b57cec5SDimitry Andric // We might need a .cxx_destruct even if we don't have any ivar initializers. 5807*0b57cec5SDimitry Andric if (needsDestructMethod(D)) { 5808*0b57cec5SDimitry Andric IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 5809*0b57cec5SDimitry Andric Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 5810480093f4SDimitry Andric ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create( 5811480093f4SDimitry Andric getContext(), D->getLocation(), D->getLocation(), cxxSelector, 5812480093f4SDimitry Andric getContext().VoidTy, nullptr, D, 5813*0b57cec5SDimitry Andric /*isInstance=*/true, /*isVariadic=*/false, 5814480093f4SDimitry Andric /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 5815480093f4SDimitry Andric /*isImplicitlyDeclared=*/true, 5816*0b57cec5SDimitry Andric /*isDefined=*/false, ObjCMethodDecl::Required); 5817*0b57cec5SDimitry Andric D->addInstanceMethod(DTORMethod); 5818*0b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 5819*0b57cec5SDimitry Andric D->setHasDestructors(true); 5820*0b57cec5SDimitry Andric } 5821*0b57cec5SDimitry Andric 5822*0b57cec5SDimitry Andric // If the implementation doesn't have any ivar initializers, we don't need 5823*0b57cec5SDimitry Andric // a .cxx_construct. 5824*0b57cec5SDimitry Andric if (D->getNumIvarInitializers() == 0 || 5825*0b57cec5SDimitry Andric AllTrivialInitializers(*this, D)) 5826*0b57cec5SDimitry Andric return; 5827*0b57cec5SDimitry Andric 5828*0b57cec5SDimitry Andric IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 5829*0b57cec5SDimitry Andric Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 5830*0b57cec5SDimitry Andric // The constructor returns 'self'. 5831480093f4SDimitry Andric ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create( 5832480093f4SDimitry Andric getContext(), D->getLocation(), D->getLocation(), cxxSelector, 5833480093f4SDimitry Andric getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true, 5834*0b57cec5SDimitry Andric /*isVariadic=*/false, 5835480093f4SDimitry Andric /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 5836*0b57cec5SDimitry Andric /*isImplicitlyDeclared=*/true, 5837480093f4SDimitry Andric /*isDefined=*/false, ObjCMethodDecl::Required); 5838*0b57cec5SDimitry Andric D->addInstanceMethod(CTORMethod); 5839*0b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 5840*0b57cec5SDimitry Andric D->setHasNonZeroConstructors(true); 5841*0b57cec5SDimitry Andric } 5842*0b57cec5SDimitry Andric 5843*0b57cec5SDimitry Andric // EmitLinkageSpec - Emit all declarations in a linkage spec. 5844*0b57cec5SDimitry Andric void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 5845*0b57cec5SDimitry Andric if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 5846480093f4SDimitry Andric LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 5847*0b57cec5SDimitry Andric ErrorUnsupported(LSD, "linkage spec"); 5848*0b57cec5SDimitry Andric return; 5849*0b57cec5SDimitry Andric } 5850*0b57cec5SDimitry Andric 5851*0b57cec5SDimitry Andric EmitDeclContext(LSD); 5852*0b57cec5SDimitry Andric } 5853*0b57cec5SDimitry Andric 5854*0b57cec5SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) { 5855*0b57cec5SDimitry Andric for (auto *I : DC->decls()) { 5856*0b57cec5SDimitry Andric // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope 5857*0b57cec5SDimitry Andric // are themselves considered "top-level", so EmitTopLevelDecl on an 5858*0b57cec5SDimitry Andric // ObjCImplDecl does not recursively visit them. We need to do that in 5859*0b57cec5SDimitry Andric // case they're nested inside another construct (LinkageSpecDecl / 5860*0b57cec5SDimitry Andric // ExportDecl) that does stop them from being considered "top-level". 5861*0b57cec5SDimitry Andric if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 5862*0b57cec5SDimitry Andric for (auto *M : OID->methods()) 5863*0b57cec5SDimitry Andric EmitTopLevelDecl(M); 5864*0b57cec5SDimitry Andric } 5865*0b57cec5SDimitry Andric 5866*0b57cec5SDimitry Andric EmitTopLevelDecl(I); 5867*0b57cec5SDimitry Andric } 5868*0b57cec5SDimitry Andric } 5869*0b57cec5SDimitry Andric 5870*0b57cec5SDimitry Andric /// EmitTopLevelDecl - Emit code for a single top level declaration. 5871*0b57cec5SDimitry Andric void CodeGenModule::EmitTopLevelDecl(Decl *D) { 5872*0b57cec5SDimitry Andric // Ignore dependent declarations. 5873*0b57cec5SDimitry Andric if (D->isTemplated()) 5874*0b57cec5SDimitry Andric return; 5875*0b57cec5SDimitry Andric 58765ffd83dbSDimitry Andric // Consteval function shouldn't be emitted. 58775ffd83dbSDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) 58785ffd83dbSDimitry Andric if (FD->isConsteval()) 58795ffd83dbSDimitry Andric return; 58805ffd83dbSDimitry Andric 5881*0b57cec5SDimitry Andric switch (D->getKind()) { 5882*0b57cec5SDimitry Andric case Decl::CXXConversion: 5883*0b57cec5SDimitry Andric case Decl::CXXMethod: 5884*0b57cec5SDimitry Andric case Decl::Function: 5885*0b57cec5SDimitry Andric EmitGlobal(cast<FunctionDecl>(D)); 5886*0b57cec5SDimitry Andric // Always provide some coverage mapping 5887*0b57cec5SDimitry Andric // even for the functions that aren't emitted. 5888*0b57cec5SDimitry Andric AddDeferredUnusedCoverageMapping(D); 5889*0b57cec5SDimitry Andric break; 5890*0b57cec5SDimitry Andric 5891*0b57cec5SDimitry Andric case Decl::CXXDeductionGuide: 5892*0b57cec5SDimitry Andric // Function-like, but does not result in code emission. 5893*0b57cec5SDimitry Andric break; 5894*0b57cec5SDimitry Andric 5895*0b57cec5SDimitry Andric case Decl::Var: 5896*0b57cec5SDimitry Andric case Decl::Decomposition: 5897*0b57cec5SDimitry Andric case Decl::VarTemplateSpecialization: 5898*0b57cec5SDimitry Andric EmitGlobal(cast<VarDecl>(D)); 5899*0b57cec5SDimitry Andric if (auto *DD = dyn_cast<DecompositionDecl>(D)) 5900*0b57cec5SDimitry Andric for (auto *B : DD->bindings()) 5901*0b57cec5SDimitry Andric if (auto *HD = B->getHoldingVar()) 5902*0b57cec5SDimitry Andric EmitGlobal(HD); 5903*0b57cec5SDimitry Andric break; 5904*0b57cec5SDimitry Andric 5905*0b57cec5SDimitry Andric // Indirect fields from global anonymous structs and unions can be 5906*0b57cec5SDimitry Andric // ignored; only the actual variable requires IR gen support. 5907*0b57cec5SDimitry Andric case Decl::IndirectField: 5908*0b57cec5SDimitry Andric break; 5909*0b57cec5SDimitry Andric 5910*0b57cec5SDimitry Andric // C++ Decls 5911*0b57cec5SDimitry Andric case Decl::Namespace: 5912*0b57cec5SDimitry Andric EmitDeclContext(cast<NamespaceDecl>(D)); 5913*0b57cec5SDimitry Andric break; 5914*0b57cec5SDimitry Andric case Decl::ClassTemplateSpecialization: { 5915*0b57cec5SDimitry Andric const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 59165ffd83dbSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 59175ffd83dbSDimitry Andric if (Spec->getSpecializationKind() == 59185ffd83dbSDimitry Andric TSK_ExplicitInstantiationDefinition && 5919*0b57cec5SDimitry Andric Spec->hasDefinition()) 59205ffd83dbSDimitry Andric DI->completeTemplateDefinition(*Spec); 5921*0b57cec5SDimitry Andric } LLVM_FALLTHROUGH; 5922e8d8bef9SDimitry Andric case Decl::CXXRecord: { 5923e8d8bef9SDimitry Andric CXXRecordDecl *CRD = cast<CXXRecordDecl>(D); 5924e8d8bef9SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) { 5925e8d8bef9SDimitry Andric if (CRD->hasDefinition()) 5926e8d8bef9SDimitry Andric DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 5927*0b57cec5SDimitry Andric if (auto *ES = D->getASTContext().getExternalSource()) 5928*0b57cec5SDimitry Andric if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) 5929e8d8bef9SDimitry Andric DI->completeUnusedClass(*CRD); 5930e8d8bef9SDimitry Andric } 5931*0b57cec5SDimitry Andric // Emit any static data members, they may be definitions. 5932e8d8bef9SDimitry Andric for (auto *I : CRD->decls()) 5933*0b57cec5SDimitry Andric if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) 5934*0b57cec5SDimitry Andric EmitTopLevelDecl(I); 5935*0b57cec5SDimitry Andric break; 5936e8d8bef9SDimitry Andric } 5937*0b57cec5SDimitry Andric // No code generation needed. 5938*0b57cec5SDimitry Andric case Decl::UsingShadow: 5939*0b57cec5SDimitry Andric case Decl::ClassTemplate: 5940*0b57cec5SDimitry Andric case Decl::VarTemplate: 5941*0b57cec5SDimitry Andric case Decl::Concept: 5942*0b57cec5SDimitry Andric case Decl::VarTemplatePartialSpecialization: 5943*0b57cec5SDimitry Andric case Decl::FunctionTemplate: 5944*0b57cec5SDimitry Andric case Decl::TypeAliasTemplate: 5945*0b57cec5SDimitry Andric case Decl::Block: 5946*0b57cec5SDimitry Andric case Decl::Empty: 5947*0b57cec5SDimitry Andric case Decl::Binding: 5948*0b57cec5SDimitry Andric break; 5949*0b57cec5SDimitry Andric case Decl::Using: // using X; [C++] 5950*0b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 5951*0b57cec5SDimitry Andric DI->EmitUsingDecl(cast<UsingDecl>(*D)); 59525ffd83dbSDimitry Andric break; 5953fe6060f1SDimitry Andric case Decl::UsingEnum: // using enum X; [C++] 5954fe6060f1SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 5955fe6060f1SDimitry Andric DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D)); 5956fe6060f1SDimitry Andric break; 5957*0b57cec5SDimitry Andric case Decl::NamespaceAlias: 5958*0b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 5959*0b57cec5SDimitry Andric DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 59605ffd83dbSDimitry Andric break; 5961*0b57cec5SDimitry Andric case Decl::UsingDirective: // using namespace X; [C++] 5962*0b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 5963*0b57cec5SDimitry Andric DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 59645ffd83dbSDimitry Andric break; 5965*0b57cec5SDimitry Andric case Decl::CXXConstructor: 5966*0b57cec5SDimitry Andric getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 5967*0b57cec5SDimitry Andric break; 5968*0b57cec5SDimitry Andric case Decl::CXXDestructor: 5969*0b57cec5SDimitry Andric getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 5970*0b57cec5SDimitry Andric break; 5971*0b57cec5SDimitry Andric 5972*0b57cec5SDimitry Andric case Decl::StaticAssert: 5973*0b57cec5SDimitry Andric // Nothing to do. 5974*0b57cec5SDimitry Andric break; 5975*0b57cec5SDimitry Andric 5976*0b57cec5SDimitry Andric // Objective-C Decls 5977*0b57cec5SDimitry Andric 5978*0b57cec5SDimitry Andric // Forward declarations, no (immediate) code generation. 5979*0b57cec5SDimitry Andric case Decl::ObjCInterface: 5980*0b57cec5SDimitry Andric case Decl::ObjCCategory: 5981*0b57cec5SDimitry Andric break; 5982*0b57cec5SDimitry Andric 5983*0b57cec5SDimitry Andric case Decl::ObjCProtocol: { 5984*0b57cec5SDimitry Andric auto *Proto = cast<ObjCProtocolDecl>(D); 5985*0b57cec5SDimitry Andric if (Proto->isThisDeclarationADefinition()) 5986*0b57cec5SDimitry Andric ObjCRuntime->GenerateProtocol(Proto); 5987*0b57cec5SDimitry Andric break; 5988*0b57cec5SDimitry Andric } 5989*0b57cec5SDimitry Andric 5990*0b57cec5SDimitry Andric case Decl::ObjCCategoryImpl: 5991*0b57cec5SDimitry Andric // Categories have properties but don't support synthesize so we 5992*0b57cec5SDimitry Andric // can ignore them here. 5993*0b57cec5SDimitry Andric ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 5994*0b57cec5SDimitry Andric break; 5995*0b57cec5SDimitry Andric 5996*0b57cec5SDimitry Andric case Decl::ObjCImplementation: { 5997*0b57cec5SDimitry Andric auto *OMD = cast<ObjCImplementationDecl>(D); 5998*0b57cec5SDimitry Andric EmitObjCPropertyImplementations(OMD); 5999*0b57cec5SDimitry Andric EmitObjCIvarInitializations(OMD); 6000*0b57cec5SDimitry Andric ObjCRuntime->GenerateClass(OMD); 6001*0b57cec5SDimitry Andric // Emit global variable debug information. 6002*0b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6003480093f4SDimitry Andric if (getCodeGenOpts().hasReducedDebugInfo()) 6004*0b57cec5SDimitry Andric DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 6005*0b57cec5SDimitry Andric OMD->getClassInterface()), OMD->getLocation()); 6006*0b57cec5SDimitry Andric break; 6007*0b57cec5SDimitry Andric } 6008*0b57cec5SDimitry Andric case Decl::ObjCMethod: { 6009*0b57cec5SDimitry Andric auto *OMD = cast<ObjCMethodDecl>(D); 6010*0b57cec5SDimitry Andric // If this is not a prototype, emit the body. 6011*0b57cec5SDimitry Andric if (OMD->getBody()) 6012*0b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCMethod(OMD); 6013*0b57cec5SDimitry Andric break; 6014*0b57cec5SDimitry Andric } 6015*0b57cec5SDimitry Andric case Decl::ObjCCompatibleAlias: 6016*0b57cec5SDimitry Andric ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 6017*0b57cec5SDimitry Andric break; 6018*0b57cec5SDimitry Andric 6019*0b57cec5SDimitry Andric case Decl::PragmaComment: { 6020*0b57cec5SDimitry Andric const auto *PCD = cast<PragmaCommentDecl>(D); 6021*0b57cec5SDimitry Andric switch (PCD->getCommentKind()) { 6022*0b57cec5SDimitry Andric case PCK_Unknown: 6023*0b57cec5SDimitry Andric llvm_unreachable("unexpected pragma comment kind"); 6024*0b57cec5SDimitry Andric case PCK_Linker: 6025*0b57cec5SDimitry Andric AppendLinkerOptions(PCD->getArg()); 6026*0b57cec5SDimitry Andric break; 6027*0b57cec5SDimitry Andric case PCK_Lib: 6028*0b57cec5SDimitry Andric AddDependentLib(PCD->getArg()); 6029*0b57cec5SDimitry Andric break; 6030*0b57cec5SDimitry Andric case PCK_Compiler: 6031*0b57cec5SDimitry Andric case PCK_ExeStr: 6032*0b57cec5SDimitry Andric case PCK_User: 6033*0b57cec5SDimitry Andric break; // We ignore all of these. 6034*0b57cec5SDimitry Andric } 6035*0b57cec5SDimitry Andric break; 6036*0b57cec5SDimitry Andric } 6037*0b57cec5SDimitry Andric 6038*0b57cec5SDimitry Andric case Decl::PragmaDetectMismatch: { 6039*0b57cec5SDimitry Andric const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 6040*0b57cec5SDimitry Andric AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 6041*0b57cec5SDimitry Andric break; 6042*0b57cec5SDimitry Andric } 6043*0b57cec5SDimitry Andric 6044*0b57cec5SDimitry Andric case Decl::LinkageSpec: 6045*0b57cec5SDimitry Andric EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 6046*0b57cec5SDimitry Andric break; 6047*0b57cec5SDimitry Andric 6048*0b57cec5SDimitry Andric case Decl::FileScopeAsm: { 6049*0b57cec5SDimitry Andric // File-scope asm is ignored during device-side CUDA compilation. 6050*0b57cec5SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 6051*0b57cec5SDimitry Andric break; 6052*0b57cec5SDimitry Andric // File-scope asm is ignored during device-side OpenMP compilation. 6053*0b57cec5SDimitry Andric if (LangOpts.OpenMPIsDevice) 6054*0b57cec5SDimitry Andric break; 6055fe6060f1SDimitry Andric // File-scope asm is ignored during device-side SYCL compilation. 6056fe6060f1SDimitry Andric if (LangOpts.SYCLIsDevice) 6057fe6060f1SDimitry Andric break; 6058*0b57cec5SDimitry Andric auto *AD = cast<FileScopeAsmDecl>(D); 6059*0b57cec5SDimitry Andric getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 6060*0b57cec5SDimitry Andric break; 6061*0b57cec5SDimitry Andric } 6062*0b57cec5SDimitry Andric 6063*0b57cec5SDimitry Andric case Decl::Import: { 6064*0b57cec5SDimitry Andric auto *Import = cast<ImportDecl>(D); 6065*0b57cec5SDimitry Andric 6066*0b57cec5SDimitry Andric // If we've already imported this module, we're done. 6067*0b57cec5SDimitry Andric if (!ImportedModules.insert(Import->getImportedModule())) 6068*0b57cec5SDimitry Andric break; 6069*0b57cec5SDimitry Andric 6070*0b57cec5SDimitry Andric // Emit debug information for direct imports. 6071*0b57cec5SDimitry Andric if (!Import->getImportedOwningModule()) { 6072*0b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6073*0b57cec5SDimitry Andric DI->EmitImportDecl(*Import); 6074*0b57cec5SDimitry Andric } 6075*0b57cec5SDimitry Andric 6076*0b57cec5SDimitry Andric // Find all of the submodules and emit the module initializers. 6077*0b57cec5SDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 6078*0b57cec5SDimitry Andric SmallVector<clang::Module *, 16> Stack; 6079*0b57cec5SDimitry Andric Visited.insert(Import->getImportedModule()); 6080*0b57cec5SDimitry Andric Stack.push_back(Import->getImportedModule()); 6081*0b57cec5SDimitry Andric 6082*0b57cec5SDimitry Andric while (!Stack.empty()) { 6083*0b57cec5SDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 6084*0b57cec5SDimitry Andric if (!EmittedModuleInitializers.insert(Mod).second) 6085*0b57cec5SDimitry Andric continue; 6086*0b57cec5SDimitry Andric 6087*0b57cec5SDimitry Andric for (auto *D : Context.getModuleInitializers(Mod)) 6088*0b57cec5SDimitry Andric EmitTopLevelDecl(D); 6089*0b57cec5SDimitry Andric 6090*0b57cec5SDimitry Andric // Visit the submodules of this module. 6091*0b57cec5SDimitry Andric for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 6092*0b57cec5SDimitry Andric SubEnd = Mod->submodule_end(); 6093*0b57cec5SDimitry Andric Sub != SubEnd; ++Sub) { 6094*0b57cec5SDimitry Andric // Skip explicit children; they need to be explicitly imported to emit 6095*0b57cec5SDimitry Andric // the initializers. 6096*0b57cec5SDimitry Andric if ((*Sub)->IsExplicit) 6097*0b57cec5SDimitry Andric continue; 6098*0b57cec5SDimitry Andric 6099*0b57cec5SDimitry Andric if (Visited.insert(*Sub).second) 6100*0b57cec5SDimitry Andric Stack.push_back(*Sub); 6101*0b57cec5SDimitry Andric } 6102*0b57cec5SDimitry Andric } 6103*0b57cec5SDimitry Andric break; 6104*0b57cec5SDimitry Andric } 6105*0b57cec5SDimitry Andric 6106*0b57cec5SDimitry Andric case Decl::Export: 6107*0b57cec5SDimitry Andric EmitDeclContext(cast<ExportDecl>(D)); 6108*0b57cec5SDimitry Andric break; 6109*0b57cec5SDimitry Andric 6110*0b57cec5SDimitry Andric case Decl::OMPThreadPrivate: 6111*0b57cec5SDimitry Andric EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 6112*0b57cec5SDimitry Andric break; 6113*0b57cec5SDimitry Andric 6114*0b57cec5SDimitry Andric case Decl::OMPAllocate: 6115fe6060f1SDimitry Andric EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D)); 6116*0b57cec5SDimitry Andric break; 6117*0b57cec5SDimitry Andric 6118*0b57cec5SDimitry Andric case Decl::OMPDeclareReduction: 6119*0b57cec5SDimitry Andric EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 6120*0b57cec5SDimitry Andric break; 6121*0b57cec5SDimitry Andric 6122*0b57cec5SDimitry Andric case Decl::OMPDeclareMapper: 6123*0b57cec5SDimitry Andric EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D)); 6124*0b57cec5SDimitry Andric break; 6125*0b57cec5SDimitry Andric 6126*0b57cec5SDimitry Andric case Decl::OMPRequires: 6127*0b57cec5SDimitry Andric EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D)); 6128*0b57cec5SDimitry Andric break; 6129*0b57cec5SDimitry Andric 6130e8d8bef9SDimitry Andric case Decl::Typedef: 6131e8d8bef9SDimitry Andric case Decl::TypeAlias: // using foo = bar; [C++11] 6132e8d8bef9SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6133e8d8bef9SDimitry Andric DI->EmitAndRetainType( 6134e8d8bef9SDimitry Andric getContext().getTypedefType(cast<TypedefNameDecl>(D))); 6135e8d8bef9SDimitry Andric break; 6136e8d8bef9SDimitry Andric 6137e8d8bef9SDimitry Andric case Decl::Record: 6138e8d8bef9SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6139e8d8bef9SDimitry Andric if (cast<RecordDecl>(D)->getDefinition()) 6140e8d8bef9SDimitry Andric DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 6141e8d8bef9SDimitry Andric break; 6142e8d8bef9SDimitry Andric 6143e8d8bef9SDimitry Andric case Decl::Enum: 6144e8d8bef9SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6145e8d8bef9SDimitry Andric if (cast<EnumDecl>(D)->getDefinition()) 6146e8d8bef9SDimitry Andric DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D))); 6147e8d8bef9SDimitry Andric break; 6148e8d8bef9SDimitry Andric 6149*0b57cec5SDimitry Andric default: 6150*0b57cec5SDimitry Andric // Make sure we handled everything we should, every other kind is a 6151*0b57cec5SDimitry Andric // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 6152*0b57cec5SDimitry Andric // function. Need to recode Decl::Kind to do that easily. 6153*0b57cec5SDimitry Andric assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 6154*0b57cec5SDimitry Andric break; 6155*0b57cec5SDimitry Andric } 6156*0b57cec5SDimitry Andric } 6157*0b57cec5SDimitry Andric 6158*0b57cec5SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 6159*0b57cec5SDimitry Andric // Do we need to generate coverage mapping? 6160*0b57cec5SDimitry Andric if (!CodeGenOpts.CoverageMapping) 6161*0b57cec5SDimitry Andric return; 6162*0b57cec5SDimitry Andric switch (D->getKind()) { 6163*0b57cec5SDimitry Andric case Decl::CXXConversion: 6164*0b57cec5SDimitry Andric case Decl::CXXMethod: 6165*0b57cec5SDimitry Andric case Decl::Function: 6166*0b57cec5SDimitry Andric case Decl::ObjCMethod: 6167*0b57cec5SDimitry Andric case Decl::CXXConstructor: 6168*0b57cec5SDimitry Andric case Decl::CXXDestructor: { 6169*0b57cec5SDimitry Andric if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 61705ffd83dbSDimitry Andric break; 6171*0b57cec5SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 6172*0b57cec5SDimitry Andric if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc())) 61735ffd83dbSDimitry Andric break; 6174*0b57cec5SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 6175*0b57cec5SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 6176*0b57cec5SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = true; 6177*0b57cec5SDimitry Andric break; 6178*0b57cec5SDimitry Andric } 6179*0b57cec5SDimitry Andric default: 6180*0b57cec5SDimitry Andric break; 6181*0b57cec5SDimitry Andric }; 6182*0b57cec5SDimitry Andric } 6183*0b57cec5SDimitry Andric 6184*0b57cec5SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 6185*0b57cec5SDimitry Andric // Do we need to generate coverage mapping? 6186*0b57cec5SDimitry Andric if (!CodeGenOpts.CoverageMapping) 6187*0b57cec5SDimitry Andric return; 6188*0b57cec5SDimitry Andric if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 6189*0b57cec5SDimitry Andric if (Fn->isTemplateInstantiation()) 6190*0b57cec5SDimitry Andric ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 6191*0b57cec5SDimitry Andric } 6192*0b57cec5SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 6193*0b57cec5SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 6194*0b57cec5SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = false; 6195*0b57cec5SDimitry Andric else 6196*0b57cec5SDimitry Andric I->second = false; 6197*0b57cec5SDimitry Andric } 6198*0b57cec5SDimitry Andric 6199*0b57cec5SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 6200*0b57cec5SDimitry Andric // We call takeVector() here to avoid use-after-free. 6201*0b57cec5SDimitry Andric // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because 6202*0b57cec5SDimitry Andric // we deserialize function bodies to emit coverage info for them, and that 6203*0b57cec5SDimitry Andric // deserializes more declarations. How should we handle that case? 6204*0b57cec5SDimitry Andric for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) { 6205*0b57cec5SDimitry Andric if (!Entry.second) 6206*0b57cec5SDimitry Andric continue; 6207*0b57cec5SDimitry Andric const Decl *D = Entry.first; 6208*0b57cec5SDimitry Andric switch (D->getKind()) { 6209*0b57cec5SDimitry Andric case Decl::CXXConversion: 6210*0b57cec5SDimitry Andric case Decl::CXXMethod: 6211*0b57cec5SDimitry Andric case Decl::Function: 6212*0b57cec5SDimitry Andric case Decl::ObjCMethod: { 6213*0b57cec5SDimitry Andric CodeGenPGO PGO(*this); 6214*0b57cec5SDimitry Andric GlobalDecl GD(cast<FunctionDecl>(D)); 6215*0b57cec5SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6216*0b57cec5SDimitry Andric getFunctionLinkage(GD)); 6217*0b57cec5SDimitry Andric break; 6218*0b57cec5SDimitry Andric } 6219*0b57cec5SDimitry Andric case Decl::CXXConstructor: { 6220*0b57cec5SDimitry Andric CodeGenPGO PGO(*this); 6221*0b57cec5SDimitry Andric GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 6222*0b57cec5SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6223*0b57cec5SDimitry Andric getFunctionLinkage(GD)); 6224*0b57cec5SDimitry Andric break; 6225*0b57cec5SDimitry Andric } 6226*0b57cec5SDimitry Andric case Decl::CXXDestructor: { 6227*0b57cec5SDimitry Andric CodeGenPGO PGO(*this); 6228*0b57cec5SDimitry Andric GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 6229*0b57cec5SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6230*0b57cec5SDimitry Andric getFunctionLinkage(GD)); 6231*0b57cec5SDimitry Andric break; 6232*0b57cec5SDimitry Andric } 6233*0b57cec5SDimitry Andric default: 6234*0b57cec5SDimitry Andric break; 6235*0b57cec5SDimitry Andric }; 6236*0b57cec5SDimitry Andric } 6237*0b57cec5SDimitry Andric } 6238*0b57cec5SDimitry Andric 62395ffd83dbSDimitry Andric void CodeGenModule::EmitMainVoidAlias() { 62405ffd83dbSDimitry Andric // In order to transition away from "__original_main" gracefully, emit an 62415ffd83dbSDimitry Andric // alias for "main" in the no-argument case so that libc can detect when 62425ffd83dbSDimitry Andric // new-style no-argument main is in used. 62435ffd83dbSDimitry Andric if (llvm::Function *F = getModule().getFunction("main")) { 62445ffd83dbSDimitry Andric if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() && 62455ffd83dbSDimitry Andric F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) 62465ffd83dbSDimitry Andric addUsedGlobal(llvm::GlobalAlias::create("__main_void", F)); 62475ffd83dbSDimitry Andric } 62485ffd83dbSDimitry Andric } 62495ffd83dbSDimitry Andric 6250*0b57cec5SDimitry Andric /// Turns the given pointer into a constant. 6251*0b57cec5SDimitry Andric static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 6252*0b57cec5SDimitry Andric const void *Ptr) { 6253*0b57cec5SDimitry Andric uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 6254*0b57cec5SDimitry Andric llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 6255*0b57cec5SDimitry Andric return llvm::ConstantInt::get(i64, PtrInt); 6256*0b57cec5SDimitry Andric } 6257*0b57cec5SDimitry Andric 6258*0b57cec5SDimitry Andric static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 6259*0b57cec5SDimitry Andric llvm::NamedMDNode *&GlobalMetadata, 6260*0b57cec5SDimitry Andric GlobalDecl D, 6261*0b57cec5SDimitry Andric llvm::GlobalValue *Addr) { 6262*0b57cec5SDimitry Andric if (!GlobalMetadata) 6263*0b57cec5SDimitry Andric GlobalMetadata = 6264*0b57cec5SDimitry Andric CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 6265*0b57cec5SDimitry Andric 6266*0b57cec5SDimitry Andric // TODO: should we report variant information for ctors/dtors? 6267*0b57cec5SDimitry Andric llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 6268*0b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(GetPointerConstant( 6269*0b57cec5SDimitry Andric CGM.getLLVMContext(), D.getDecl()))}; 6270*0b57cec5SDimitry Andric GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 6271*0b57cec5SDimitry Andric } 6272*0b57cec5SDimitry Andric 6273*0b57cec5SDimitry Andric /// For each function which is declared within an extern "C" region and marked 6274*0b57cec5SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled 6275*0b57cec5SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer 6276*0b57cec5SDimitry Andric /// to such functions with an unmangled name from inline assembly within the 6277*0b57cec5SDimitry Andric /// same translation unit. 6278*0b57cec5SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() { 6279*0b57cec5SDimitry Andric if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases()) 6280*0b57cec5SDimitry Andric return; 6281*0b57cec5SDimitry Andric for (auto &I : StaticExternCValues) { 6282*0b57cec5SDimitry Andric IdentifierInfo *Name = I.first; 6283*0b57cec5SDimitry Andric llvm::GlobalValue *Val = I.second; 6284*0b57cec5SDimitry Andric if (Val && !getModule().getNamedValue(Name->getName())) 6285fe6060f1SDimitry Andric addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 6286*0b57cec5SDimitry Andric } 6287*0b57cec5SDimitry Andric } 6288*0b57cec5SDimitry Andric 6289*0b57cec5SDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 6290*0b57cec5SDimitry Andric GlobalDecl &Result) const { 6291*0b57cec5SDimitry Andric auto Res = Manglings.find(MangledName); 6292*0b57cec5SDimitry Andric if (Res == Manglings.end()) 6293*0b57cec5SDimitry Andric return false; 6294*0b57cec5SDimitry Andric Result = Res->getValue(); 6295*0b57cec5SDimitry Andric return true; 6296*0b57cec5SDimitry Andric } 6297*0b57cec5SDimitry Andric 6298*0b57cec5SDimitry Andric /// Emits metadata nodes associating all the global values in the 6299*0b57cec5SDimitry Andric /// current module with the Decls they came from. This is useful for 6300*0b57cec5SDimitry Andric /// projects using IR gen as a subroutine. 6301*0b57cec5SDimitry Andric /// 6302*0b57cec5SDimitry Andric /// Since there's currently no way to associate an MDNode directly 6303*0b57cec5SDimitry Andric /// with an llvm::GlobalValue, we create a global named metadata 6304*0b57cec5SDimitry Andric /// with the name 'clang.global.decl.ptrs'. 6305*0b57cec5SDimitry Andric void CodeGenModule::EmitDeclMetadata() { 6306*0b57cec5SDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 6307*0b57cec5SDimitry Andric 6308*0b57cec5SDimitry Andric for (auto &I : MangledDeclNames) { 6309*0b57cec5SDimitry Andric llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 6310*0b57cec5SDimitry Andric // Some mangled names don't necessarily have an associated GlobalValue 6311*0b57cec5SDimitry Andric // in this module, e.g. if we mangled it for DebugInfo. 6312*0b57cec5SDimitry Andric if (Addr) 6313*0b57cec5SDimitry Andric EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 6314*0b57cec5SDimitry Andric } 6315*0b57cec5SDimitry Andric } 6316*0b57cec5SDimitry Andric 6317*0b57cec5SDimitry Andric /// Emits metadata nodes for all the local variables in the current 6318*0b57cec5SDimitry Andric /// function. 6319*0b57cec5SDimitry Andric void CodeGenFunction::EmitDeclMetadata() { 6320*0b57cec5SDimitry Andric if (LocalDeclMap.empty()) return; 6321*0b57cec5SDimitry Andric 6322*0b57cec5SDimitry Andric llvm::LLVMContext &Context = getLLVMContext(); 6323*0b57cec5SDimitry Andric 6324*0b57cec5SDimitry Andric // Find the unique metadata ID for this name. 6325*0b57cec5SDimitry Andric unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 6326*0b57cec5SDimitry Andric 6327*0b57cec5SDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 6328*0b57cec5SDimitry Andric 6329*0b57cec5SDimitry Andric for (auto &I : LocalDeclMap) { 6330*0b57cec5SDimitry Andric const Decl *D = I.first; 6331*0b57cec5SDimitry Andric llvm::Value *Addr = I.second.getPointer(); 6332*0b57cec5SDimitry Andric if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 6333*0b57cec5SDimitry Andric llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 6334*0b57cec5SDimitry Andric Alloca->setMetadata( 6335*0b57cec5SDimitry Andric DeclPtrKind, llvm::MDNode::get( 6336*0b57cec5SDimitry Andric Context, llvm::ValueAsMetadata::getConstant(DAddr))); 6337*0b57cec5SDimitry Andric } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 6338*0b57cec5SDimitry Andric GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 6339*0b57cec5SDimitry Andric EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 6340*0b57cec5SDimitry Andric } 6341*0b57cec5SDimitry Andric } 6342*0b57cec5SDimitry Andric } 6343*0b57cec5SDimitry Andric 6344*0b57cec5SDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() { 6345*0b57cec5SDimitry Andric llvm::NamedMDNode *IdentMetadata = 6346*0b57cec5SDimitry Andric TheModule.getOrInsertNamedMetadata("llvm.ident"); 6347*0b57cec5SDimitry Andric std::string Version = getClangFullVersion(); 6348*0b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 6349*0b57cec5SDimitry Andric 6350*0b57cec5SDimitry Andric llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 6351*0b57cec5SDimitry Andric IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 6352*0b57cec5SDimitry Andric } 6353*0b57cec5SDimitry Andric 6354*0b57cec5SDimitry Andric void CodeGenModule::EmitCommandLineMetadata() { 6355*0b57cec5SDimitry Andric llvm::NamedMDNode *CommandLineMetadata = 6356*0b57cec5SDimitry Andric TheModule.getOrInsertNamedMetadata("llvm.commandline"); 6357*0b57cec5SDimitry Andric std::string CommandLine = getCodeGenOpts().RecordCommandLine; 6358*0b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 6359*0b57cec5SDimitry Andric 6360*0b57cec5SDimitry Andric llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)}; 6361*0b57cec5SDimitry Andric CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode)); 6362*0b57cec5SDimitry Andric } 6363*0b57cec5SDimitry Andric 6364*0b57cec5SDimitry Andric void CodeGenModule::EmitCoverageFile() { 6365*0b57cec5SDimitry Andric if (getCodeGenOpts().CoverageDataFile.empty() && 6366*0b57cec5SDimitry Andric getCodeGenOpts().CoverageNotesFile.empty()) 6367*0b57cec5SDimitry Andric return; 6368*0b57cec5SDimitry Andric 6369*0b57cec5SDimitry Andric llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); 6370*0b57cec5SDimitry Andric if (!CUNode) 6371*0b57cec5SDimitry Andric return; 6372*0b57cec5SDimitry Andric 6373*0b57cec5SDimitry Andric llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 6374*0b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 6375*0b57cec5SDimitry Andric auto *CoverageDataFile = 6376*0b57cec5SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); 6377*0b57cec5SDimitry Andric auto *CoverageNotesFile = 6378*0b57cec5SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); 6379*0b57cec5SDimitry Andric for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 6380*0b57cec5SDimitry Andric llvm::MDNode *CU = CUNode->getOperand(i); 6381*0b57cec5SDimitry Andric llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; 6382*0b57cec5SDimitry Andric GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 6383*0b57cec5SDimitry Andric } 6384*0b57cec5SDimitry Andric } 6385*0b57cec5SDimitry Andric 6386*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 6387*0b57cec5SDimitry Andric bool ForEH) { 6388*0b57cec5SDimitry Andric // Return a bogus pointer if RTTI is disabled, unless it's for EH. 6389*0b57cec5SDimitry Andric // FIXME: should we even be calling this method if RTTI is disabled 6390*0b57cec5SDimitry Andric // and it's not for EH? 63915ffd83dbSDimitry Andric if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice || 63925ffd83dbSDimitry Andric (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 63935ffd83dbSDimitry Andric getTriple().isNVPTX())) 6394*0b57cec5SDimitry Andric return llvm::Constant::getNullValue(Int8PtrTy); 6395*0b57cec5SDimitry Andric 6396*0b57cec5SDimitry Andric if (ForEH && Ty->isObjCObjectPointerType() && 6397*0b57cec5SDimitry Andric LangOpts.ObjCRuntime.isGNUFamily()) 6398*0b57cec5SDimitry Andric return ObjCRuntime->GetEHType(Ty); 6399*0b57cec5SDimitry Andric 6400*0b57cec5SDimitry Andric return getCXXABI().getAddrOfRTTIDescriptor(Ty); 6401*0b57cec5SDimitry Andric } 6402*0b57cec5SDimitry Andric 6403*0b57cec5SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 6404*0b57cec5SDimitry Andric // Do not emit threadprivates in simd-only mode. 6405*0b57cec5SDimitry Andric if (LangOpts.OpenMP && LangOpts.OpenMPSimd) 6406*0b57cec5SDimitry Andric return; 6407*0b57cec5SDimitry Andric for (auto RefExpr : D->varlists()) { 6408*0b57cec5SDimitry Andric auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 6409*0b57cec5SDimitry Andric bool PerformInit = 6410*0b57cec5SDimitry Andric VD->getAnyInitializer() && 6411*0b57cec5SDimitry Andric !VD->getAnyInitializer()->isConstantInitializer(getContext(), 6412*0b57cec5SDimitry Andric /*ForRef=*/false); 6413*0b57cec5SDimitry Andric 6414*0b57cec5SDimitry Andric Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD)); 6415*0b57cec5SDimitry Andric if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 6416*0b57cec5SDimitry Andric VD, Addr, RefExpr->getBeginLoc(), PerformInit)) 6417*0b57cec5SDimitry Andric CXXGlobalInits.push_back(InitFunction); 6418*0b57cec5SDimitry Andric } 6419*0b57cec5SDimitry Andric } 6420*0b57cec5SDimitry Andric 6421*0b57cec5SDimitry Andric llvm::Metadata * 6422*0b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, 6423*0b57cec5SDimitry Andric StringRef Suffix) { 64240eae32dcSDimitry Andric if (auto *FnType = T->getAs<FunctionProtoType>()) 64250eae32dcSDimitry Andric T = getContext().getFunctionType( 64260eae32dcSDimitry Andric FnType->getReturnType(), FnType->getParamTypes(), 64270eae32dcSDimitry Andric FnType->getExtProtoInfo().withExceptionSpec(EST_None)); 64280eae32dcSDimitry Andric 6429*0b57cec5SDimitry Andric llvm::Metadata *&InternalId = Map[T.getCanonicalType()]; 6430*0b57cec5SDimitry Andric if (InternalId) 6431*0b57cec5SDimitry Andric return InternalId; 6432*0b57cec5SDimitry Andric 6433*0b57cec5SDimitry Andric if (isExternallyVisible(T->getLinkage())) { 6434*0b57cec5SDimitry Andric std::string OutName; 6435*0b57cec5SDimitry Andric llvm::raw_string_ostream Out(OutName); 6436*0b57cec5SDimitry Andric getCXXABI().getMangleContext().mangleTypeName(T, Out); 6437*0b57cec5SDimitry Andric Out << Suffix; 6438*0b57cec5SDimitry Andric 6439*0b57cec5SDimitry Andric InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 6440*0b57cec5SDimitry Andric } else { 6441*0b57cec5SDimitry Andric InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 6442*0b57cec5SDimitry Andric llvm::ArrayRef<llvm::Metadata *>()); 6443*0b57cec5SDimitry Andric } 6444*0b57cec5SDimitry Andric 6445*0b57cec5SDimitry Andric return InternalId; 6446*0b57cec5SDimitry Andric } 6447*0b57cec5SDimitry Andric 6448*0b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 6449*0b57cec5SDimitry Andric return CreateMetadataIdentifierImpl(T, MetadataIdMap, ""); 6450*0b57cec5SDimitry Andric } 6451*0b57cec5SDimitry Andric 6452*0b57cec5SDimitry Andric llvm::Metadata * 6453*0b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) { 6454*0b57cec5SDimitry Andric return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual"); 6455*0b57cec5SDimitry Andric } 6456*0b57cec5SDimitry Andric 6457*0b57cec5SDimitry Andric // Generalize pointer types to a void pointer with the qualifiers of the 6458*0b57cec5SDimitry Andric // originally pointed-to type, e.g. 'const char *' and 'char * const *' 6459*0b57cec5SDimitry Andric // generalize to 'const void *' while 'char *' and 'const char **' generalize to 6460*0b57cec5SDimitry Andric // 'void *'. 6461*0b57cec5SDimitry Andric static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) { 6462*0b57cec5SDimitry Andric if (!Ty->isPointerType()) 6463*0b57cec5SDimitry Andric return Ty; 6464*0b57cec5SDimitry Andric 6465*0b57cec5SDimitry Andric return Ctx.getPointerType( 6466*0b57cec5SDimitry Andric QualType(Ctx.VoidTy).withCVRQualifiers( 6467*0b57cec5SDimitry Andric Ty->getPointeeType().getCVRQualifiers())); 6468*0b57cec5SDimitry Andric } 6469*0b57cec5SDimitry Andric 6470*0b57cec5SDimitry Andric // Apply type generalization to a FunctionType's return and argument types 6471*0b57cec5SDimitry Andric static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) { 6472*0b57cec5SDimitry Andric if (auto *FnType = Ty->getAs<FunctionProtoType>()) { 6473*0b57cec5SDimitry Andric SmallVector<QualType, 8> GeneralizedParams; 6474*0b57cec5SDimitry Andric for (auto &Param : FnType->param_types()) 6475*0b57cec5SDimitry Andric GeneralizedParams.push_back(GeneralizeType(Ctx, Param)); 6476*0b57cec5SDimitry Andric 6477*0b57cec5SDimitry Andric return Ctx.getFunctionType( 6478*0b57cec5SDimitry Andric GeneralizeType(Ctx, FnType->getReturnType()), 6479*0b57cec5SDimitry Andric GeneralizedParams, FnType->getExtProtoInfo()); 6480*0b57cec5SDimitry Andric } 6481*0b57cec5SDimitry Andric 6482*0b57cec5SDimitry Andric if (auto *FnType = Ty->getAs<FunctionNoProtoType>()) 6483*0b57cec5SDimitry Andric return Ctx.getFunctionNoProtoType( 6484*0b57cec5SDimitry Andric GeneralizeType(Ctx, FnType->getReturnType())); 6485*0b57cec5SDimitry Andric 6486*0b57cec5SDimitry Andric llvm_unreachable("Encountered unknown FunctionType"); 6487*0b57cec5SDimitry Andric } 6488*0b57cec5SDimitry Andric 6489*0b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) { 6490*0b57cec5SDimitry Andric return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T), 6491*0b57cec5SDimitry Andric GeneralizedMetadataIdMap, ".generalized"); 6492*0b57cec5SDimitry Andric } 6493*0b57cec5SDimitry Andric 6494*0b57cec5SDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier. 6495*0b57cec5SDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const { 6496*0b57cec5SDimitry Andric // Returns true if at least one of vtable-based CFI checkers is enabled and 6497*0b57cec5SDimitry Andric // is not in the trapping mode. 6498*0b57cec5SDimitry Andric return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 6499*0b57cec5SDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 6500*0b57cec5SDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 6501*0b57cec5SDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 6502*0b57cec5SDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 6503*0b57cec5SDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 6504*0b57cec5SDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 6505*0b57cec5SDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 6506*0b57cec5SDimitry Andric } 6507*0b57cec5SDimitry Andric 6508*0b57cec5SDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 6509*0b57cec5SDimitry Andric CharUnits Offset, 6510*0b57cec5SDimitry Andric const CXXRecordDecl *RD) { 6511*0b57cec5SDimitry Andric llvm::Metadata *MD = 6512*0b57cec5SDimitry Andric CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 6513*0b57cec5SDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), MD); 6514*0b57cec5SDimitry Andric 6515*0b57cec5SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 6516*0b57cec5SDimitry Andric if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 6517*0b57cec5SDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), 6518*0b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 6519*0b57cec5SDimitry Andric 6520*0b57cec5SDimitry Andric if (NeedAllVtablesTypeId()) { 6521*0b57cec5SDimitry Andric llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 6522*0b57cec5SDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), MD); 6523*0b57cec5SDimitry Andric } 6524*0b57cec5SDimitry Andric } 6525*0b57cec5SDimitry Andric 6526*0b57cec5SDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 6527*0b57cec5SDimitry Andric if (!SanStats) 6528a7dea167SDimitry Andric SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule()); 6529*0b57cec5SDimitry Andric 6530*0b57cec5SDimitry Andric return *SanStats; 6531*0b57cec5SDimitry Andric } 653223408297SDimitry Andric 6533*0b57cec5SDimitry Andric llvm::Value * 6534*0b57cec5SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, 6535*0b57cec5SDimitry Andric CodeGenFunction &CGF) { 6536*0b57cec5SDimitry Andric llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType()); 653723408297SDimitry Andric auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr()); 653823408297SDimitry Andric auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); 6539fe6060f1SDimitry Andric auto *Call = CGF.EmitRuntimeCall( 654023408297SDimitry Andric CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C}); 654123408297SDimitry Andric return Call; 6542*0b57cec5SDimitry Andric } 65435ffd83dbSDimitry Andric 65445ffd83dbSDimitry Andric CharUnits CodeGenModule::getNaturalPointeeTypeAlignment( 65455ffd83dbSDimitry Andric QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) { 65465ffd83dbSDimitry Andric return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo, 65475ffd83dbSDimitry Andric /* forPointeeType= */ true); 65485ffd83dbSDimitry Andric } 65495ffd83dbSDimitry Andric 65505ffd83dbSDimitry Andric CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T, 65515ffd83dbSDimitry Andric LValueBaseInfo *BaseInfo, 65525ffd83dbSDimitry Andric TBAAAccessInfo *TBAAInfo, 65535ffd83dbSDimitry Andric bool forPointeeType) { 65545ffd83dbSDimitry Andric if (TBAAInfo) 65555ffd83dbSDimitry Andric *TBAAInfo = getTBAAAccessInfo(T); 65565ffd83dbSDimitry Andric 65575ffd83dbSDimitry Andric // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But 65585ffd83dbSDimitry Andric // that doesn't return the information we need to compute BaseInfo. 65595ffd83dbSDimitry Andric 65605ffd83dbSDimitry Andric // Honor alignment typedef attributes even on incomplete types. 65615ffd83dbSDimitry Andric // We also honor them straight for C++ class types, even as pointees; 65625ffd83dbSDimitry Andric // there's an expressivity gap here. 65635ffd83dbSDimitry Andric if (auto TT = T->getAs<TypedefType>()) { 65645ffd83dbSDimitry Andric if (auto Align = TT->getDecl()->getMaxAlignment()) { 65655ffd83dbSDimitry Andric if (BaseInfo) 65665ffd83dbSDimitry Andric *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType); 65675ffd83dbSDimitry Andric return getContext().toCharUnitsFromBits(Align); 65685ffd83dbSDimitry Andric } 65695ffd83dbSDimitry Andric } 65705ffd83dbSDimitry Andric 65715ffd83dbSDimitry Andric bool AlignForArray = T->isArrayType(); 65725ffd83dbSDimitry Andric 65735ffd83dbSDimitry Andric // Analyze the base element type, so we don't get confused by incomplete 65745ffd83dbSDimitry Andric // array types. 65755ffd83dbSDimitry Andric T = getContext().getBaseElementType(T); 65765ffd83dbSDimitry Andric 65775ffd83dbSDimitry Andric if (T->isIncompleteType()) { 65785ffd83dbSDimitry Andric // We could try to replicate the logic from 65795ffd83dbSDimitry Andric // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the 65805ffd83dbSDimitry Andric // type is incomplete, so it's impossible to test. We could try to reuse 65815ffd83dbSDimitry Andric // getTypeAlignIfKnown, but that doesn't return the information we need 65825ffd83dbSDimitry Andric // to set BaseInfo. So just ignore the possibility that the alignment is 65835ffd83dbSDimitry Andric // greater than one. 65845ffd83dbSDimitry Andric if (BaseInfo) 65855ffd83dbSDimitry Andric *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 65865ffd83dbSDimitry Andric return CharUnits::One(); 65875ffd83dbSDimitry Andric } 65885ffd83dbSDimitry Andric 65895ffd83dbSDimitry Andric if (BaseInfo) 65905ffd83dbSDimitry Andric *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 65915ffd83dbSDimitry Andric 65925ffd83dbSDimitry Andric CharUnits Alignment; 6593e8d8bef9SDimitry Andric const CXXRecordDecl *RD; 6594e8d8bef9SDimitry Andric if (T.getQualifiers().hasUnaligned()) { 6595e8d8bef9SDimitry Andric Alignment = CharUnits::One(); 6596e8d8bef9SDimitry Andric } else if (forPointeeType && !AlignForArray && 6597e8d8bef9SDimitry Andric (RD = T->getAsCXXRecordDecl())) { 65985ffd83dbSDimitry Andric // For C++ class pointees, we don't know whether we're pointing at a 65995ffd83dbSDimitry Andric // base or a complete object, so we generally need to use the 66005ffd83dbSDimitry Andric // non-virtual alignment. 66015ffd83dbSDimitry Andric Alignment = getClassPointerAlignment(RD); 66025ffd83dbSDimitry Andric } else { 66035ffd83dbSDimitry Andric Alignment = getContext().getTypeAlignInChars(T); 66045ffd83dbSDimitry Andric } 66055ffd83dbSDimitry Andric 66065ffd83dbSDimitry Andric // Cap to the global maximum type alignment unless the alignment 66075ffd83dbSDimitry Andric // was somehow explicit on the type. 66085ffd83dbSDimitry Andric if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { 66095ffd83dbSDimitry Andric if (Alignment.getQuantity() > MaxAlign && 66105ffd83dbSDimitry Andric !getContext().isAlignmentRequired(T)) 66115ffd83dbSDimitry Andric Alignment = CharUnits::fromQuantity(MaxAlign); 66125ffd83dbSDimitry Andric } 66135ffd83dbSDimitry Andric return Alignment; 66145ffd83dbSDimitry Andric } 66155ffd83dbSDimitry Andric 66165ffd83dbSDimitry Andric bool CodeGenModule::stopAutoInit() { 66175ffd83dbSDimitry Andric unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter; 66185ffd83dbSDimitry Andric if (StopAfter) { 66195ffd83dbSDimitry Andric // This number is positive only when -ftrivial-auto-var-init-stop-after=* is 66205ffd83dbSDimitry Andric // used 66215ffd83dbSDimitry Andric if (NumAutoVarInit >= StopAfter) { 66225ffd83dbSDimitry Andric return true; 66235ffd83dbSDimitry Andric } 66245ffd83dbSDimitry Andric if (!NumAutoVarInit) { 66255ffd83dbSDimitry Andric unsigned DiagID = getDiags().getCustomDiagID( 66265ffd83dbSDimitry Andric DiagnosticsEngine::Warning, 66275ffd83dbSDimitry Andric "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the " 66285ffd83dbSDimitry Andric "number of times ftrivial-auto-var-init=%1 gets applied."); 66295ffd83dbSDimitry Andric getDiags().Report(DiagID) 66305ffd83dbSDimitry Andric << StopAfter 66315ffd83dbSDimitry Andric << (getContext().getLangOpts().getTrivialAutoVarInit() == 66325ffd83dbSDimitry Andric LangOptions::TrivialAutoVarInitKind::Zero 66335ffd83dbSDimitry Andric ? "zero" 66345ffd83dbSDimitry Andric : "pattern"); 66355ffd83dbSDimitry Andric } 66365ffd83dbSDimitry Andric ++NumAutoVarInit; 66375ffd83dbSDimitry Andric } 66385ffd83dbSDimitry Andric return false; 66395ffd83dbSDimitry Andric } 6640fe6060f1SDimitry Andric 6641fe6060f1SDimitry Andric void CodeGenModule::printPostfixForExternalizedStaticVar( 6642fe6060f1SDimitry Andric llvm::raw_ostream &OS) const { 6643349cc55cSDimitry Andric OS << "__static__" << getContext().getCUIDHash(); 6644fe6060f1SDimitry Andric } 6645