1f22ef01cSRoman Divacky //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 2f22ef01cSRoman Divacky // 3f22ef01cSRoman Divacky // The LLVM Compiler Infrastructure 4f22ef01cSRoman Divacky // 5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source 6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details. 7f22ef01cSRoman Divacky // 8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 9f22ef01cSRoman Divacky // 10f22ef01cSRoman Divacky // This coordinates the per-module state used while generating code. 11f22ef01cSRoman Divacky // 12f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 13f22ef01cSRoman Divacky 14f22ef01cSRoman Divacky #include "CodeGenModule.h" 150623d748SDimitry Andric #include "CGBlocks.h" 166122f3e6SDimitry Andric #include "CGCUDARuntime.h" 17e580952dSDimitry Andric #include "CGCXXABI.h" 18139f7f9bSDimitry Andric #include "CGCall.h" 19139f7f9bSDimitry Andric #include "CGDebugInfo.h" 20f22ef01cSRoman Divacky #include "CGObjCRuntime.h" 216122f3e6SDimitry Andric #include "CGOpenCLRuntime.h" 2259d1ed5bSDimitry Andric #include "CGOpenMPRuntime.h" 23e7145dcbSDimitry Andric #include "CGOpenMPRuntimeNVPTX.h" 24139f7f9bSDimitry Andric #include "CodeGenFunction.h" 2559d1ed5bSDimitry Andric #include "CodeGenPGO.h" 26139f7f9bSDimitry Andric #include "CodeGenTBAA.h" 2739d628a0SDimitry Andric #include "CoverageMappingGen.h" 28f22ef01cSRoman Divacky #include "TargetInfo.h" 29f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h" 30f22ef01cSRoman Divacky #include "clang/AST/CharUnits.h" 31f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h" 32139f7f9bSDimitry Andric #include "clang/AST/DeclObjC.h" 33ffd1746dSEd Schouten #include "clang/AST/DeclTemplate.h" 342754fe60SDimitry Andric #include "clang/AST/Mangle.h" 35f22ef01cSRoman Divacky #include "clang/AST/RecordLayout.h" 36f8254f43SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h" 37dff0c46cSDimitry Andric #include "clang/Basic/Builtins.h" 38139f7f9bSDimitry Andric #include "clang/Basic/CharInfo.h" 39f22ef01cSRoman Divacky #include "clang/Basic/Diagnostic.h" 40139f7f9bSDimitry Andric #include "clang/Basic/Module.h" 41f22ef01cSRoman Divacky #include "clang/Basic/SourceManager.h" 42f22ef01cSRoman Divacky #include "clang/Basic/TargetInfo.h" 43f785676fSDimitry Andric #include "clang/Basic/Version.h" 4420e90f04SDimitry Andric #include "clang/CodeGen/ConstantInitBuilder.h" 45139f7f9bSDimitry Andric #include "clang/Frontend/CodeGenOptions.h" 46f785676fSDimitry Andric #include "clang/Sema/SemaDiagnostic.h" 47f22ef01cSRoman Divacky #include "llvm/ADT/Triple.h" 48d8866befSDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h" 4959d1ed5bSDimitry Andric #include "llvm/IR/CallSite.h" 50139f7f9bSDimitry Andric #include "llvm/IR/CallingConv.h" 51139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h" 52139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h" 53139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h" 54139f7f9bSDimitry Andric #include "llvm/IR/Module.h" 5559d1ed5bSDimitry Andric #include "llvm/ProfileData/InstrProfReader.h" 56139f7f9bSDimitry Andric #include "llvm/Support/ConvertUTF.h" 57f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h" 580623d748SDimitry Andric #include "llvm/Support/MD5.h" 59139f7f9bSDimitry Andric 60f22ef01cSRoman Divacky using namespace clang; 61f22ef01cSRoman Divacky using namespace CodeGen; 62f22ef01cSRoman Divacky 636122f3e6SDimitry Andric static const char AnnotationSection[] = "llvm.metadata"; 646122f3e6SDimitry Andric 6559d1ed5bSDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) { 66284c1978SDimitry Andric switch (CGM.getTarget().getCXXABI().getKind()) { 67139f7f9bSDimitry Andric case TargetCXXABI::GenericAArch64: 68139f7f9bSDimitry Andric case TargetCXXABI::GenericARM: 69139f7f9bSDimitry Andric case TargetCXXABI::iOS: 7059d1ed5bSDimitry Andric case TargetCXXABI::iOS64: 710623d748SDimitry Andric case TargetCXXABI::WatchOS: 72ef6fa9e2SDimitry Andric case TargetCXXABI::GenericMIPS: 73139f7f9bSDimitry Andric case TargetCXXABI::GenericItanium: 740623d748SDimitry Andric case TargetCXXABI::WebAssembly: 7559d1ed5bSDimitry Andric return CreateItaniumCXXABI(CGM); 76139f7f9bSDimitry Andric case TargetCXXABI::Microsoft: 7759d1ed5bSDimitry Andric return CreateMicrosoftCXXABI(CGM); 78e580952dSDimitry Andric } 79e580952dSDimitry Andric 80e580952dSDimitry Andric llvm_unreachable("invalid C++ ABI kind"); 81e580952dSDimitry Andric } 82e580952dSDimitry Andric 833dac3a9bSDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO, 843dac3a9bSDimitry Andric const PreprocessorOptions &PPO, 853dac3a9bSDimitry Andric const CodeGenOptions &CGO, llvm::Module &M, 8639d628a0SDimitry Andric DiagnosticsEngine &diags, 8739d628a0SDimitry Andric CoverageSourceInfo *CoverageInfo) 883dac3a9bSDimitry Andric : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO), 893dac3a9bSDimitry Andric PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags), 900623d748SDimitry Andric Target(C.getTargetInfo()), ABI(createCXXABI(*this)), 91e7145dcbSDimitry Andric VMContext(M.getContext()), Types(*this), VTables(*this), 92e7145dcbSDimitry Andric SanitizerMD(new SanitizerMetadata(*this)) { 93dff0c46cSDimitry Andric 94dff0c46cSDimitry Andric // Initialize the type cache. 95dff0c46cSDimitry Andric llvm::LLVMContext &LLVMContext = M.getContext(); 96dff0c46cSDimitry Andric VoidTy = llvm::Type::getVoidTy(LLVMContext); 97dff0c46cSDimitry Andric Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 98dff0c46cSDimitry Andric Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 99dff0c46cSDimitry Andric Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 100dff0c46cSDimitry Andric Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 101edd7eaddSDimitry Andric HalfTy = llvm::Type::getHalfTy(LLVMContext); 102dff0c46cSDimitry Andric FloatTy = llvm::Type::getFloatTy(LLVMContext); 103dff0c46cSDimitry Andric DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 104dff0c46cSDimitry Andric PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 105dff0c46cSDimitry Andric PointerAlignInBytes = 106dff0c46cSDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 10744290647SDimitry Andric SizeSizeInBytes = 10844290647SDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity(); 1090623d748SDimitry Andric IntAlignInBytes = 1100623d748SDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity(); 111dff0c46cSDimitry Andric IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 11244290647SDimitry Andric IntPtrTy = llvm::IntegerType::get(LLVMContext, 11344290647SDimitry Andric C.getTargetInfo().getMaxPointerWidth()); 114dff0c46cSDimitry Andric Int8PtrTy = Int8Ty->getPointerTo(0); 115dff0c46cSDimitry Andric Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 1166bc11b14SDimitry Andric AllocaInt8PtrTy = Int8Ty->getPointerTo( 1176bc11b14SDimitry Andric M.getDataLayout().getAllocaAddrSpace()); 118d8866befSDimitry Andric ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace(); 119dff0c46cSDimitry Andric 120139f7f9bSDimitry Andric RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 12139d628a0SDimitry Andric BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC(); 122139f7f9bSDimitry Andric 123dff0c46cSDimitry Andric if (LangOpts.ObjC1) 1243b0f4066SDimitry Andric createObjCRuntime(); 125dff0c46cSDimitry Andric if (LangOpts.OpenCL) 1266122f3e6SDimitry Andric createOpenCLRuntime(); 12759d1ed5bSDimitry Andric if (LangOpts.OpenMP) 12859d1ed5bSDimitry Andric createOpenMPRuntime(); 129dff0c46cSDimitry Andric if (LangOpts.CUDA) 1306122f3e6SDimitry Andric createCUDARuntime(); 131f22ef01cSRoman Divacky 1327ae0e2c9SDimitry Andric // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 13339d628a0SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::Thread) || 1347ae0e2c9SDimitry Andric (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 135e7145dcbSDimitry Andric TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(), 136e7145dcbSDimitry Andric getCXXABI().getMangleContext())); 1372754fe60SDimitry Andric 1383b0f4066SDimitry Andric // If debug info or coverage generation is enabled, create the CGDebugInfo 1393b0f4066SDimitry Andric // object. 140e7145dcbSDimitry Andric if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo || 141e7145dcbSDimitry Andric CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) 142e7145dcbSDimitry Andric DebugInfo.reset(new CGDebugInfo(*this)); 1432754fe60SDimitry Andric 1442754fe60SDimitry Andric Block.GlobalUniqueCount = 0; 1452754fe60SDimitry Andric 1460623d748SDimitry Andric if (C.getLangOpts().ObjC1) 147e7145dcbSDimitry Andric ObjCData.reset(new ObjCEntrypoints()); 14859d1ed5bSDimitry Andric 149e7145dcbSDimitry Andric if (CodeGenOpts.hasProfileClangUse()) { 150e7145dcbSDimitry Andric auto ReaderOrErr = llvm::IndexedInstrProfReader::create( 151e7145dcbSDimitry Andric CodeGenOpts.ProfileInstrumentUsePath); 152e7145dcbSDimitry Andric if (auto E = ReaderOrErr.takeError()) { 15359d1ed5bSDimitry Andric unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 1543dac3a9bSDimitry Andric "Could not read profile %0: %1"); 155e7145dcbSDimitry Andric llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) { 156e7145dcbSDimitry Andric getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath 157e7145dcbSDimitry Andric << EI.message(); 158e7145dcbSDimitry Andric }); 15933956c43SDimitry Andric } else 16033956c43SDimitry Andric PGOReader = std::move(ReaderOrErr.get()); 16159d1ed5bSDimitry Andric } 16239d628a0SDimitry Andric 16339d628a0SDimitry Andric // If coverage mapping generation is enabled, create the 16439d628a0SDimitry Andric // CoverageMappingModuleGen object. 16539d628a0SDimitry Andric if (CodeGenOpts.CoverageMapping) 16639d628a0SDimitry Andric CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); 167f22ef01cSRoman Divacky } 168f22ef01cSRoman Divacky 169e7145dcbSDimitry Andric CodeGenModule::~CodeGenModule() {} 170f22ef01cSRoman Divacky 171f22ef01cSRoman Divacky void CodeGenModule::createObjCRuntime() { 1727ae0e2c9SDimitry Andric // This is just isGNUFamily(), but we want to force implementors of 1737ae0e2c9SDimitry Andric // new ABIs to decide how best to do this. 1747ae0e2c9SDimitry Andric switch (LangOpts.ObjCRuntime.getKind()) { 1757ae0e2c9SDimitry Andric case ObjCRuntime::GNUstep: 1767ae0e2c9SDimitry Andric case ObjCRuntime::GCC: 1777ae0e2c9SDimitry Andric case ObjCRuntime::ObjFW: 178e7145dcbSDimitry Andric ObjCRuntime.reset(CreateGNUObjCRuntime(*this)); 1797ae0e2c9SDimitry Andric return; 1807ae0e2c9SDimitry Andric 1817ae0e2c9SDimitry Andric case ObjCRuntime::FragileMacOSX: 1827ae0e2c9SDimitry Andric case ObjCRuntime::MacOSX: 1837ae0e2c9SDimitry Andric case ObjCRuntime::iOS: 1840623d748SDimitry Andric case ObjCRuntime::WatchOS: 185e7145dcbSDimitry Andric ObjCRuntime.reset(CreateMacObjCRuntime(*this)); 1867ae0e2c9SDimitry Andric return; 1877ae0e2c9SDimitry Andric } 1887ae0e2c9SDimitry Andric llvm_unreachable("bad runtime kind"); 1896122f3e6SDimitry Andric } 1906122f3e6SDimitry Andric 1916122f3e6SDimitry Andric void CodeGenModule::createOpenCLRuntime() { 192e7145dcbSDimitry Andric OpenCLRuntime.reset(new CGOpenCLRuntime(*this)); 1936122f3e6SDimitry Andric } 1946122f3e6SDimitry Andric 19559d1ed5bSDimitry Andric void CodeGenModule::createOpenMPRuntime() { 196e7145dcbSDimitry Andric // Select a specialized code generation class based on the target, if any. 197e7145dcbSDimitry Andric // If it does not exist use the default implementation. 19844290647SDimitry Andric switch (getTriple().getArch()) { 199e7145dcbSDimitry Andric case llvm::Triple::nvptx: 200e7145dcbSDimitry Andric case llvm::Triple::nvptx64: 201e7145dcbSDimitry Andric assert(getLangOpts().OpenMPIsDevice && 202e7145dcbSDimitry Andric "OpenMP NVPTX is only prepared to deal with device code."); 203e7145dcbSDimitry Andric OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this)); 204e7145dcbSDimitry Andric break; 205e7145dcbSDimitry Andric default: 206e7145dcbSDimitry Andric OpenMPRuntime.reset(new CGOpenMPRuntime(*this)); 207e7145dcbSDimitry Andric break; 208e7145dcbSDimitry Andric } 20959d1ed5bSDimitry Andric } 21059d1ed5bSDimitry Andric 2116122f3e6SDimitry Andric void CodeGenModule::createCUDARuntime() { 212e7145dcbSDimitry Andric CUDARuntime.reset(CreateNVCUDARuntime(*this)); 213f22ef01cSRoman Divacky } 214f22ef01cSRoman Divacky 21539d628a0SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { 21639d628a0SDimitry Andric Replacements[Name] = C; 21739d628a0SDimitry Andric } 21839d628a0SDimitry Andric 219f785676fSDimitry Andric void CodeGenModule::applyReplacements() { 2208f0fd8f6SDimitry Andric for (auto &I : Replacements) { 2218f0fd8f6SDimitry Andric StringRef MangledName = I.first(); 2228f0fd8f6SDimitry Andric llvm::Constant *Replacement = I.second; 223f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 224f785676fSDimitry Andric if (!Entry) 225f785676fSDimitry Andric continue; 22659d1ed5bSDimitry Andric auto *OldF = cast<llvm::Function>(Entry); 22759d1ed5bSDimitry Andric auto *NewF = dyn_cast<llvm::Function>(Replacement); 228f785676fSDimitry Andric if (!NewF) { 22959d1ed5bSDimitry Andric if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 23059d1ed5bSDimitry Andric NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 23159d1ed5bSDimitry Andric } else { 23259d1ed5bSDimitry Andric auto *CE = cast<llvm::ConstantExpr>(Replacement); 233f785676fSDimitry Andric assert(CE->getOpcode() == llvm::Instruction::BitCast || 234f785676fSDimitry Andric CE->getOpcode() == llvm::Instruction::GetElementPtr); 235f785676fSDimitry Andric NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 236f785676fSDimitry Andric } 23759d1ed5bSDimitry Andric } 238f785676fSDimitry Andric 239f785676fSDimitry Andric // Replace old with new, but keep the old order. 240f785676fSDimitry Andric OldF->replaceAllUsesWith(Replacement); 241f785676fSDimitry Andric if (NewF) { 242f785676fSDimitry Andric NewF->removeFromParent(); 2430623d748SDimitry Andric OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(), 2440623d748SDimitry Andric NewF); 245f785676fSDimitry Andric } 246f785676fSDimitry Andric OldF->eraseFromParent(); 247f785676fSDimitry Andric } 248f785676fSDimitry Andric } 249f785676fSDimitry Andric 2500623d748SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { 2510623d748SDimitry Andric GlobalValReplacements.push_back(std::make_pair(GV, C)); 2520623d748SDimitry Andric } 2530623d748SDimitry Andric 2540623d748SDimitry Andric void CodeGenModule::applyGlobalValReplacements() { 2550623d748SDimitry Andric for (auto &I : GlobalValReplacements) { 2560623d748SDimitry Andric llvm::GlobalValue *GV = I.first; 2570623d748SDimitry Andric llvm::Constant *C = I.second; 2580623d748SDimitry Andric 2590623d748SDimitry Andric GV->replaceAllUsesWith(C); 2600623d748SDimitry Andric GV->eraseFromParent(); 2610623d748SDimitry Andric } 2620623d748SDimitry Andric } 2630623d748SDimitry Andric 26459d1ed5bSDimitry Andric // This is only used in aliases that we created and we know they have a 26559d1ed5bSDimitry Andric // linear structure. 266e7145dcbSDimitry Andric static const llvm::GlobalObject *getAliasedGlobal( 267e7145dcbSDimitry Andric const llvm::GlobalIndirectSymbol &GIS) { 268e7145dcbSDimitry Andric llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited; 269e7145dcbSDimitry Andric const llvm::Constant *C = &GIS; 27059d1ed5bSDimitry Andric for (;;) { 27159d1ed5bSDimitry Andric C = C->stripPointerCasts(); 27259d1ed5bSDimitry Andric if (auto *GO = dyn_cast<llvm::GlobalObject>(C)) 27359d1ed5bSDimitry Andric return GO; 27459d1ed5bSDimitry Andric // stripPointerCasts will not walk over weak aliases. 275e7145dcbSDimitry Andric auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C); 276e7145dcbSDimitry Andric if (!GIS2) 27759d1ed5bSDimitry Andric return nullptr; 278e7145dcbSDimitry Andric if (!Visited.insert(GIS2).second) 27959d1ed5bSDimitry Andric return nullptr; 280e7145dcbSDimitry Andric C = GIS2->getIndirectSymbol(); 28159d1ed5bSDimitry Andric } 28259d1ed5bSDimitry Andric } 28359d1ed5bSDimitry Andric 284f785676fSDimitry Andric void CodeGenModule::checkAliases() { 28559d1ed5bSDimitry Andric // Check if the constructed aliases are well formed. It is really unfortunate 28659d1ed5bSDimitry Andric // that we have to do this in CodeGen, but we only construct mangled names 28759d1ed5bSDimitry Andric // and aliases during codegen. 288f785676fSDimitry Andric bool Error = false; 28959d1ed5bSDimitry Andric DiagnosticsEngine &Diags = getDiags(); 2908f0fd8f6SDimitry Andric for (const GlobalDecl &GD : Aliases) { 29159d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 292e7145dcbSDimitry Andric SourceLocation Location; 293e7145dcbSDimitry Andric bool IsIFunc = D->hasAttr<IFuncAttr>(); 294e7145dcbSDimitry Andric if (const Attr *A = D->getDefiningAttr()) 295e7145dcbSDimitry Andric Location = A->getLocation(); 296e7145dcbSDimitry Andric else 297e7145dcbSDimitry Andric llvm_unreachable("Not an alias or ifunc?"); 298f785676fSDimitry Andric StringRef MangledName = getMangledName(GD); 299f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 300e7145dcbSDimitry Andric auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry); 30159d1ed5bSDimitry Andric const llvm::GlobalValue *GV = getAliasedGlobal(*Alias); 30259d1ed5bSDimitry Andric if (!GV) { 303f785676fSDimitry Andric Error = true; 304e7145dcbSDimitry Andric Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc; 30559d1ed5bSDimitry Andric } else if (GV->isDeclaration()) { 306f785676fSDimitry Andric Error = true; 307e7145dcbSDimitry Andric Diags.Report(Location, diag::err_alias_to_undefined) 308e7145dcbSDimitry Andric << IsIFunc << IsIFunc; 309e7145dcbSDimitry Andric } else if (IsIFunc) { 310e7145dcbSDimitry Andric // Check resolver function type. 311e7145dcbSDimitry Andric llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>( 312e7145dcbSDimitry Andric GV->getType()->getPointerElementType()); 313e7145dcbSDimitry Andric assert(FTy); 314e7145dcbSDimitry Andric if (!FTy->getReturnType()->isPointerTy()) 315e7145dcbSDimitry Andric Diags.Report(Location, diag::err_ifunc_resolver_return); 316e7145dcbSDimitry Andric if (FTy->getNumParams()) 317e7145dcbSDimitry Andric Diags.Report(Location, diag::err_ifunc_resolver_params); 31859d1ed5bSDimitry Andric } 31959d1ed5bSDimitry Andric 320e7145dcbSDimitry Andric llvm::Constant *Aliasee = Alias->getIndirectSymbol(); 32159d1ed5bSDimitry Andric llvm::GlobalValue *AliaseeGV; 32259d1ed5bSDimitry Andric if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 32359d1ed5bSDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 32459d1ed5bSDimitry Andric else 32559d1ed5bSDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 32659d1ed5bSDimitry Andric 32759d1ed5bSDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 32859d1ed5bSDimitry Andric StringRef AliasSection = SA->getName(); 32959d1ed5bSDimitry Andric if (AliasSection != AliaseeGV->getSection()) 33059d1ed5bSDimitry Andric Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 331e7145dcbSDimitry Andric << AliasSection << IsIFunc << IsIFunc; 33259d1ed5bSDimitry Andric } 33359d1ed5bSDimitry Andric 33459d1ed5bSDimitry Andric // We have to handle alias to weak aliases in here. LLVM itself disallows 33559d1ed5bSDimitry Andric // this since the object semantics would not match the IL one. For 33659d1ed5bSDimitry Andric // compatibility with gcc we implement it by just pointing the alias 33759d1ed5bSDimitry Andric // to its aliasee's aliasee. We also warn, since the user is probably 33859d1ed5bSDimitry Andric // expecting the link to be weak. 339e7145dcbSDimitry Andric if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) { 340e7145dcbSDimitry Andric if (GA->isInterposable()) { 341e7145dcbSDimitry Andric Diags.Report(Location, diag::warn_alias_to_weak_alias) 342e7145dcbSDimitry Andric << GV->getName() << GA->getName() << IsIFunc; 34359d1ed5bSDimitry Andric Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 344e7145dcbSDimitry Andric GA->getIndirectSymbol(), Alias->getType()); 345e7145dcbSDimitry Andric Alias->setIndirectSymbol(Aliasee); 34659d1ed5bSDimitry Andric } 347f785676fSDimitry Andric } 348f785676fSDimitry Andric } 349f785676fSDimitry Andric if (!Error) 350f785676fSDimitry Andric return; 351f785676fSDimitry Andric 3528f0fd8f6SDimitry Andric for (const GlobalDecl &GD : Aliases) { 353f785676fSDimitry Andric StringRef MangledName = getMangledName(GD); 354f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 355e7145dcbSDimitry Andric auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry); 356f785676fSDimitry Andric Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 357f785676fSDimitry Andric Alias->eraseFromParent(); 358f785676fSDimitry Andric } 359f785676fSDimitry Andric } 360f785676fSDimitry Andric 36159d1ed5bSDimitry Andric void CodeGenModule::clear() { 36259d1ed5bSDimitry Andric DeferredDeclsToEmit.clear(); 36333956c43SDimitry Andric if (OpenMPRuntime) 36433956c43SDimitry Andric OpenMPRuntime->clear(); 36559d1ed5bSDimitry Andric } 36659d1ed5bSDimitry Andric 36759d1ed5bSDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 36859d1ed5bSDimitry Andric StringRef MainFile) { 36959d1ed5bSDimitry Andric if (!hasDiagnostics()) 37059d1ed5bSDimitry Andric return; 37159d1ed5bSDimitry Andric if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 37259d1ed5bSDimitry Andric if (MainFile.empty()) 37359d1ed5bSDimitry Andric MainFile = "<stdin>"; 37459d1ed5bSDimitry Andric Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 375f37b6182SDimitry Andric } else { 376f37b6182SDimitry Andric if (Mismatched > 0) 377f37b6182SDimitry Andric Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched; 378f37b6182SDimitry Andric 379f37b6182SDimitry Andric if (Missing > 0) 380f37b6182SDimitry Andric Diags.Report(diag::warn_profile_data_missing) << Visited << Missing; 381f37b6182SDimitry Andric } 38259d1ed5bSDimitry Andric } 38359d1ed5bSDimitry Andric 384f22ef01cSRoman Divacky void CodeGenModule::Release() { 385f22ef01cSRoman Divacky EmitDeferred(); 386f9448bf3SDimitry Andric EmitVTablesOpportunistically(); 3870623d748SDimitry Andric applyGlobalValReplacements(); 388f785676fSDimitry Andric applyReplacements(); 389f785676fSDimitry Andric checkAliases(); 390f22ef01cSRoman Divacky EmitCXXGlobalInitFunc(); 391f22ef01cSRoman Divacky EmitCXXGlobalDtorFunc(); 392284c1978SDimitry Andric EmitCXXThreadLocalInitFunc(); 3936122f3e6SDimitry Andric if (ObjCRuntime) 3946122f3e6SDimitry Andric if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 395f22ef01cSRoman Divacky AddGlobalCtor(ObjCInitFunction); 39633956c43SDimitry Andric if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice && 39733956c43SDimitry Andric CUDARuntime) { 39833956c43SDimitry Andric if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction()) 39933956c43SDimitry Andric AddGlobalCtor(CudaCtorFunction); 40033956c43SDimitry Andric if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction()) 40133956c43SDimitry Andric AddGlobalDtor(CudaDtorFunction); 40233956c43SDimitry Andric } 403ea942507SDimitry Andric if (OpenMPRuntime) 404ea942507SDimitry Andric if (llvm::Function *OpenMPRegistrationFunction = 405302affcbSDimitry Andric OpenMPRuntime->emitRegistrationFunction()) { 406302affcbSDimitry Andric auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ? 407302affcbSDimitry Andric OpenMPRegistrationFunction : nullptr; 408302affcbSDimitry Andric AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey); 409302affcbSDimitry Andric } 4100623d748SDimitry Andric if (PGOReader) { 411e7145dcbSDimitry Andric getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext)); 4120623d748SDimitry Andric if (PGOStats.hasDiagnostics()) 41359d1ed5bSDimitry Andric PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 4140623d748SDimitry Andric } 415f22ef01cSRoman Divacky EmitCtorList(GlobalCtors, "llvm.global_ctors"); 416f22ef01cSRoman Divacky EmitCtorList(GlobalDtors, "llvm.global_dtors"); 4176122f3e6SDimitry Andric EmitGlobalAnnotations(); 418284c1978SDimitry Andric EmitStaticExternCAliases(); 41939d628a0SDimitry Andric EmitDeferredUnusedCoverageMappings(); 42039d628a0SDimitry Andric if (CoverageMapping) 42139d628a0SDimitry Andric CoverageMapping->emit(); 42220e90f04SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 423e7145dcbSDimitry Andric CodeGenFunction(*this).EmitCfiCheckFail(); 42420e90f04SDimitry Andric CodeGenFunction(*this).EmitCfiCheckStub(); 42520e90f04SDimitry Andric } 42620e90f04SDimitry Andric emitAtAvailableLinkGuard(); 42759d1ed5bSDimitry Andric emitLLVMUsed(); 428e7145dcbSDimitry Andric if (SanStats) 429e7145dcbSDimitry Andric SanStats->finish(); 430ffd1746dSEd Schouten 431f785676fSDimitry Andric if (CodeGenOpts.Autolink && 432f785676fSDimitry Andric (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 433139f7f9bSDimitry Andric EmitModuleLinkOptions(); 434139f7f9bSDimitry Andric } 43520e90f04SDimitry Andric 43620e90f04SDimitry Andric // Record mregparm value now so it is visible through rest of codegen. 43720e90f04SDimitry Andric if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) 43820e90f04SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters", 43920e90f04SDimitry Andric CodeGenOpts.NumRegisterParameters); 44020e90f04SDimitry Andric 4410623d748SDimitry Andric if (CodeGenOpts.DwarfVersion) { 442f785676fSDimitry Andric // We actually want the latest version when there are conflicts. 443f785676fSDimitry Andric // We can change from Warning to Latest if such mode is supported. 444f785676fSDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version", 445f785676fSDimitry Andric CodeGenOpts.DwarfVersion); 4460623d748SDimitry Andric } 4470623d748SDimitry Andric if (CodeGenOpts.EmitCodeView) { 4480623d748SDimitry Andric // Indicate that we want CodeView in the metadata. 4490623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); 4500623d748SDimitry Andric } 4510623d748SDimitry Andric if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { 4520623d748SDimitry Andric // We don't support LTO with 2 with different StrictVTablePointers 4530623d748SDimitry Andric // FIXME: we could support it by stripping all the information introduced 4540623d748SDimitry Andric // by StrictVTablePointers. 4550623d748SDimitry Andric 4560623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); 4570623d748SDimitry Andric 4580623d748SDimitry Andric llvm::Metadata *Ops[2] = { 4590623d748SDimitry Andric llvm::MDString::get(VMContext, "StrictVTablePointers"), 4600623d748SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 4610623d748SDimitry Andric llvm::Type::getInt32Ty(VMContext), 1))}; 4620623d748SDimitry Andric 4630623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Require, 4640623d748SDimitry Andric "StrictVTablePointersRequirement", 4650623d748SDimitry Andric llvm::MDNode::get(VMContext, Ops)); 4660623d748SDimitry Andric } 467f785676fSDimitry Andric if (DebugInfo) 46859d1ed5bSDimitry Andric // We support a single version in the linked module. The LLVM 46959d1ed5bSDimitry Andric // parser will drop debug info with a different version number 47059d1ed5bSDimitry Andric // (and warn about it, too). 47159d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 472f785676fSDimitry Andric llvm::DEBUG_METADATA_VERSION); 473139f7f9bSDimitry Andric 474d8866befSDimitry Andric // Width of wchar_t in bytes 475d8866befSDimitry Andric uint64_t WCharWidth = 476d8866befSDimitry Andric Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 477f9448bf3SDimitry Andric assert((LangOpts.ShortWChar || 478d8866befSDimitry Andric llvm::TargetLibraryInfoImpl::getTargetWCharSize(Target.getTriple()) == 479f9448bf3SDimitry Andric Target.getWCharWidth() / 8) && 480d8866befSDimitry Andric "LLVM wchar_t size out of sync"); 481d8866befSDimitry Andric 48259d1ed5bSDimitry Andric // We need to record the widths of enums and wchar_t, so that we can generate 483d8866befSDimitry Andric // the correct build attributes in the ARM backend. wchar_size is also used by 484d8866befSDimitry Andric // TargetLibraryInfo. 485d8866befSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 486d8866befSDimitry Andric 48759d1ed5bSDimitry Andric llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 48859d1ed5bSDimitry Andric if ( Arch == llvm::Triple::arm 48959d1ed5bSDimitry Andric || Arch == llvm::Triple::armeb 49059d1ed5bSDimitry Andric || Arch == llvm::Triple::thumb 49159d1ed5bSDimitry Andric || Arch == llvm::Triple::thumbeb) { 49259d1ed5bSDimitry Andric // The minimum width of an enum in bytes 49359d1ed5bSDimitry Andric uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 49459d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 49559d1ed5bSDimitry Andric } 49659d1ed5bSDimitry Andric 4970623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 4980623d748SDimitry Andric // Indicate that we want cross-DSO control flow integrity checks. 4990623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); 5000623d748SDimitry Andric } 5010623d748SDimitry Andric 50244290647SDimitry Andric if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) { 503e7145dcbSDimitry Andric // Indicate whether __nvvm_reflect should be configured to flush denormal 504e7145dcbSDimitry Andric // floating point values to 0. (This corresponds to its "__CUDA_FTZ" 505e7145dcbSDimitry Andric // property.) 506e7145dcbSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", 507e7145dcbSDimitry Andric LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0); 50839d628a0SDimitry Andric } 50939d628a0SDimitry Andric 510edd7eaddSDimitry Andric // Emit OpenCL specific module metadata: OpenCL/SPIR version. 511edd7eaddSDimitry Andric if (LangOpts.OpenCL) { 512edd7eaddSDimitry Andric EmitOpenCLMetadata(); 513edd7eaddSDimitry Andric // Emit SPIR version. 514edd7eaddSDimitry Andric if (getTriple().getArch() == llvm::Triple::spir || 515edd7eaddSDimitry Andric getTriple().getArch() == llvm::Triple::spir64) { 516edd7eaddSDimitry Andric // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the 517edd7eaddSDimitry Andric // opencl.spir.version named metadata. 518edd7eaddSDimitry Andric llvm::Metadata *SPIRVerElts[] = { 519edd7eaddSDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 520edd7eaddSDimitry Andric Int32Ty, LangOpts.OpenCLVersion / 100)), 521edd7eaddSDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 522edd7eaddSDimitry Andric Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))}; 523edd7eaddSDimitry Andric llvm::NamedMDNode *SPIRVerMD = 524edd7eaddSDimitry Andric TheModule.getOrInsertNamedMetadata("opencl.spir.version"); 525edd7eaddSDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 526edd7eaddSDimitry Andric SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts)); 527edd7eaddSDimitry Andric } 528edd7eaddSDimitry Andric } 529edd7eaddSDimitry Andric 530e7145dcbSDimitry Andric if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 531e7145dcbSDimitry Andric assert(PLevel < 3 && "Invalid PIC Level"); 532e7145dcbSDimitry Andric getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel)); 533e7145dcbSDimitry Andric if (Context.getLangOpts().PIE) 534e7145dcbSDimitry Andric getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel)); 53539d628a0SDimitry Andric } 53639d628a0SDimitry Andric 5372754fe60SDimitry Andric SimplifyPersonality(); 5382754fe60SDimitry Andric 539ffd1746dSEd Schouten if (getCodeGenOpts().EmitDeclMetadata) 540ffd1746dSEd Schouten EmitDeclMetadata(); 541bd5abe19SDimitry Andric 542bd5abe19SDimitry Andric if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 543bd5abe19SDimitry Andric EmitCoverageFile(); 5446122f3e6SDimitry Andric 5456122f3e6SDimitry Andric if (DebugInfo) 5466122f3e6SDimitry Andric DebugInfo->finalize(); 547f785676fSDimitry Andric 548f785676fSDimitry Andric EmitVersionIdentMetadata(); 54959d1ed5bSDimitry Andric 55059d1ed5bSDimitry Andric EmitTargetMetadata(); 551f22ef01cSRoman Divacky } 552f22ef01cSRoman Divacky 553edd7eaddSDimitry Andric void CodeGenModule::EmitOpenCLMetadata() { 554edd7eaddSDimitry Andric // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the 555edd7eaddSDimitry Andric // opencl.ocl.version named metadata node. 556edd7eaddSDimitry Andric llvm::Metadata *OCLVerElts[] = { 557edd7eaddSDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 558edd7eaddSDimitry Andric Int32Ty, LangOpts.OpenCLVersion / 100)), 559edd7eaddSDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 560edd7eaddSDimitry Andric Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))}; 561edd7eaddSDimitry Andric llvm::NamedMDNode *OCLVerMD = 562edd7eaddSDimitry Andric TheModule.getOrInsertNamedMetadata("opencl.ocl.version"); 563edd7eaddSDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 564edd7eaddSDimitry Andric OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts)); 565edd7eaddSDimitry Andric } 566edd7eaddSDimitry Andric 5673b0f4066SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 5683b0f4066SDimitry Andric // Make sure that this type is translated. 5693b0f4066SDimitry Andric Types.UpdateCompletedType(TD); 5703b0f4066SDimitry Andric } 5713b0f4066SDimitry Andric 572e7145dcbSDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { 573e7145dcbSDimitry Andric // Make sure that this type is translated. 574e7145dcbSDimitry Andric Types.RefreshTypeCacheForClass(RD); 575e7145dcbSDimitry Andric } 576e7145dcbSDimitry Andric 5772754fe60SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 5782754fe60SDimitry Andric if (!TBAA) 57959d1ed5bSDimitry Andric return nullptr; 5802754fe60SDimitry Andric return TBAA->getTBAAInfo(QTy); 5812754fe60SDimitry Andric } 5822754fe60SDimitry Andric 583dff0c46cSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() { 584dff0c46cSDimitry Andric if (!TBAA) 58559d1ed5bSDimitry Andric return nullptr; 586dff0c46cSDimitry Andric return TBAA->getTBAAInfoForVTablePtr(); 587dff0c46cSDimitry Andric } 588dff0c46cSDimitry Andric 5893861d79fSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 5903861d79fSDimitry Andric if (!TBAA) 59159d1ed5bSDimitry Andric return nullptr; 5923861d79fSDimitry Andric return TBAA->getTBAAStructInfo(QTy); 5933861d79fSDimitry Andric } 5943861d79fSDimitry Andric 595139f7f9bSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy, 596139f7f9bSDimitry Andric llvm::MDNode *AccessN, 597139f7f9bSDimitry Andric uint64_t O) { 598139f7f9bSDimitry Andric if (!TBAA) 59959d1ed5bSDimitry Andric return nullptr; 600139f7f9bSDimitry Andric return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O); 601139f7f9bSDimitry Andric } 602139f7f9bSDimitry Andric 603f785676fSDimitry Andric /// Decorate the instruction with a TBAA tag. For both scalar TBAA 604f785676fSDimitry Andric /// and struct-path aware TBAA, the tag has the same format: 605f785676fSDimitry Andric /// base type, access type and offset. 606284c1978SDimitry Andric /// When ConvertTypeToTag is true, we create a tag based on the scalar type. 6070623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, 608284c1978SDimitry Andric llvm::MDNode *TBAAInfo, 609284c1978SDimitry Andric bool ConvertTypeToTag) { 610f785676fSDimitry Andric if (ConvertTypeToTag && TBAA) 611284c1978SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, 612284c1978SDimitry Andric TBAA->getTBAAScalarTagInfo(TBAAInfo)); 613284c1978SDimitry Andric else 6142754fe60SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 6152754fe60SDimitry Andric } 6162754fe60SDimitry Andric 6170623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup( 6180623d748SDimitry Andric llvm::Instruction *I, const CXXRecordDecl *RD) { 61951690af2SDimitry Andric I->setMetadata(llvm::LLVMContext::MD_invariant_group, 62051690af2SDimitry Andric llvm::MDNode::get(getLLVMContext(), {})); 6210623d748SDimitry Andric } 6220623d748SDimitry Andric 62359d1ed5bSDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) { 62459d1ed5bSDimitry Andric unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 62559d1ed5bSDimitry Andric getDiags().Report(Context.getFullLoc(loc), diagID) << message; 626f22ef01cSRoman Divacky } 627f22ef01cSRoman Divacky 628f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 629f22ef01cSRoman Divacky /// specified stmt yet. 630f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 6316122f3e6SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 632f22ef01cSRoman Divacky "cannot compile this %0 yet"); 633f22ef01cSRoman Divacky std::string Msg = Type; 634f22ef01cSRoman Divacky getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 635f22ef01cSRoman Divacky << Msg << S->getSourceRange(); 636f22ef01cSRoman Divacky } 637f22ef01cSRoman Divacky 638f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 639f22ef01cSRoman Divacky /// specified decl yet. 640f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 6416122f3e6SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 642f22ef01cSRoman Divacky "cannot compile this %0 yet"); 643f22ef01cSRoman Divacky std::string Msg = Type; 644f22ef01cSRoman Divacky getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 645f22ef01cSRoman Divacky } 646f22ef01cSRoman Divacky 64717a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 64817a519f9SDimitry Andric return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 64917a519f9SDimitry Andric } 65017a519f9SDimitry Andric 651f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 6522754fe60SDimitry Andric const NamedDecl *D) const { 653f22ef01cSRoman Divacky // Internal definitions always have default visibility. 654f22ef01cSRoman Divacky if (GV->hasLocalLinkage()) { 655f22ef01cSRoman Divacky GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 656f22ef01cSRoman Divacky return; 657f22ef01cSRoman Divacky } 658f22ef01cSRoman Divacky 6592754fe60SDimitry Andric // Set visibility for definitions. 660139f7f9bSDimitry Andric LinkageInfo LV = D->getLinkageAndVisibility(); 661139f7f9bSDimitry Andric if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 662139f7f9bSDimitry Andric GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 663f22ef01cSRoman Divacky } 664f22ef01cSRoman Divacky 6657ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 6667ae0e2c9SDimitry Andric return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 6677ae0e2c9SDimitry Andric .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 6687ae0e2c9SDimitry Andric .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 6697ae0e2c9SDimitry Andric .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 6707ae0e2c9SDimitry Andric .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 6717ae0e2c9SDimitry Andric } 6727ae0e2c9SDimitry Andric 6737ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel( 6747ae0e2c9SDimitry Andric CodeGenOptions::TLSModel M) { 6757ae0e2c9SDimitry Andric switch (M) { 6767ae0e2c9SDimitry Andric case CodeGenOptions::GeneralDynamicTLSModel: 6777ae0e2c9SDimitry Andric return llvm::GlobalVariable::GeneralDynamicTLSModel; 6787ae0e2c9SDimitry Andric case CodeGenOptions::LocalDynamicTLSModel: 6797ae0e2c9SDimitry Andric return llvm::GlobalVariable::LocalDynamicTLSModel; 6807ae0e2c9SDimitry Andric case CodeGenOptions::InitialExecTLSModel: 6817ae0e2c9SDimitry Andric return llvm::GlobalVariable::InitialExecTLSModel; 6827ae0e2c9SDimitry Andric case CodeGenOptions::LocalExecTLSModel: 6837ae0e2c9SDimitry Andric return llvm::GlobalVariable::LocalExecTLSModel; 6847ae0e2c9SDimitry Andric } 6857ae0e2c9SDimitry Andric llvm_unreachable("Invalid TLS model!"); 6867ae0e2c9SDimitry Andric } 6877ae0e2c9SDimitry Andric 68839d628a0SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 689284c1978SDimitry Andric assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 6907ae0e2c9SDimitry Andric 69139d628a0SDimitry Andric llvm::GlobalValue::ThreadLocalMode TLM; 6923861d79fSDimitry Andric TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel()); 6937ae0e2c9SDimitry Andric 6947ae0e2c9SDimitry Andric // Override the TLS model if it is explicitly specified. 69559d1ed5bSDimitry Andric if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 6967ae0e2c9SDimitry Andric TLM = GetLLVMTLSModel(Attr->getModel()); 6977ae0e2c9SDimitry Andric } 6987ae0e2c9SDimitry Andric 6997ae0e2c9SDimitry Andric GV->setThreadLocalMode(TLM); 7007ae0e2c9SDimitry Andric } 7017ae0e2c9SDimitry Andric 7026122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 703444ed5c5SDimitry Andric GlobalDecl CanonicalGD = GD.getCanonicalDecl(); 704444ed5c5SDimitry Andric 705444ed5c5SDimitry Andric // Some ABIs don't have constructor variants. Make sure that base and 706444ed5c5SDimitry Andric // complete constructors get mangled the same. 707444ed5c5SDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { 708444ed5c5SDimitry Andric if (!getTarget().getCXXABI().hasConstructorVariants()) { 709444ed5c5SDimitry Andric CXXCtorType OrigCtorType = GD.getCtorType(); 710444ed5c5SDimitry Andric assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); 711444ed5c5SDimitry Andric if (OrigCtorType == Ctor_Base) 712444ed5c5SDimitry Andric CanonicalGD = GlobalDecl(CD, Ctor_Complete); 713444ed5c5SDimitry Andric } 714444ed5c5SDimitry Andric } 715444ed5c5SDimitry Andric 716444ed5c5SDimitry Andric StringRef &FoundStr = MangledDeclNames[CanonicalGD]; 71759d1ed5bSDimitry Andric if (!FoundStr.empty()) 71859d1ed5bSDimitry Andric return FoundStr; 719f22ef01cSRoman Divacky 72059d1ed5bSDimitry Andric const auto *ND = cast<NamedDecl>(GD.getDecl()); 721dff0c46cSDimitry Andric SmallString<256> Buffer; 72259d1ed5bSDimitry Andric StringRef Str; 72359d1ed5bSDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 7242754fe60SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 72559d1ed5bSDimitry Andric if (const auto *D = dyn_cast<CXXConstructorDecl>(ND)) 7262754fe60SDimitry Andric getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 72759d1ed5bSDimitry Andric else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND)) 7282754fe60SDimitry Andric getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 729ffd1746dSEd Schouten else 7302754fe60SDimitry Andric getCXXABI().getMangleContext().mangleName(ND, Out); 73159d1ed5bSDimitry Andric Str = Out.str(); 73259d1ed5bSDimitry Andric } else { 73359d1ed5bSDimitry Andric IdentifierInfo *II = ND->getIdentifier(); 73459d1ed5bSDimitry Andric assert(II && "Attempt to mangle unnamed decl."); 73544290647SDimitry Andric const auto *FD = dyn_cast<FunctionDecl>(ND); 73644290647SDimitry Andric 73744290647SDimitry Andric if (FD && 73844290647SDimitry Andric FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { 73944290647SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 74044290647SDimitry Andric Out << "__regcall3__" << II->getName(); 74144290647SDimitry Andric Str = Out.str(); 74244290647SDimitry Andric } else { 74359d1ed5bSDimitry Andric Str = II->getName(); 744ffd1746dSEd Schouten } 74544290647SDimitry Andric } 746ffd1746dSEd Schouten 74739d628a0SDimitry Andric // Keep the first result in the case of a mangling collision. 74839d628a0SDimitry Andric auto Result = Manglings.insert(std::make_pair(Str, GD)); 74939d628a0SDimitry Andric return FoundStr = Result.first->first(); 75059d1ed5bSDimitry Andric } 75159d1ed5bSDimitry Andric 75259d1ed5bSDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 753ffd1746dSEd Schouten const BlockDecl *BD) { 7542754fe60SDimitry Andric MangleContext &MangleCtx = getCXXABI().getMangleContext(); 7552754fe60SDimitry Andric const Decl *D = GD.getDecl(); 75659d1ed5bSDimitry Andric 75759d1ed5bSDimitry Andric SmallString<256> Buffer; 75859d1ed5bSDimitry Andric llvm::raw_svector_ostream Out(Buffer); 75959d1ed5bSDimitry Andric if (!D) 7607ae0e2c9SDimitry Andric MangleCtx.mangleGlobalBlock(BD, 7617ae0e2c9SDimitry Andric dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 76259d1ed5bSDimitry Andric else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 7632754fe60SDimitry Andric MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 76459d1ed5bSDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 7652754fe60SDimitry Andric MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 7662754fe60SDimitry Andric else 7672754fe60SDimitry Andric MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 76859d1ed5bSDimitry Andric 76939d628a0SDimitry Andric auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 77039d628a0SDimitry Andric return Result.first->first(); 771f22ef01cSRoman Divacky } 772f22ef01cSRoman Divacky 7736122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 774f22ef01cSRoman Divacky return getModule().getNamedValue(Name); 775f22ef01cSRoman Divacky } 776f22ef01cSRoman Divacky 777f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before 778f22ef01cSRoman Divacky /// main() runs. 77959d1ed5bSDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 78059d1ed5bSDimitry Andric llvm::Constant *AssociatedData) { 781f22ef01cSRoman Divacky // FIXME: Type coercion of void()* types. 78259d1ed5bSDimitry Andric GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); 783f22ef01cSRoman Divacky } 784f22ef01cSRoman Divacky 785f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called 786f22ef01cSRoman Divacky /// when the module is unloaded. 787f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) { 788f22ef01cSRoman Divacky // FIXME: Type coercion of void()* types. 78959d1ed5bSDimitry Andric GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); 790f22ef01cSRoman Divacky } 791f22ef01cSRoman Divacky 79244290647SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { 79344290647SDimitry Andric if (Fns.empty()) return; 79444290647SDimitry Andric 795f22ef01cSRoman Divacky // Ctor function type is void()*. 796bd5abe19SDimitry Andric llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 797f22ef01cSRoman Divacky llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 798f22ef01cSRoman Divacky 79959d1ed5bSDimitry Andric // Get the type of a ctor entry, { i32, void ()*, i8* }. 80059d1ed5bSDimitry Andric llvm::StructType *CtorStructTy = llvm::StructType::get( 8015517e702SDimitry Andric Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy); 802f22ef01cSRoman Divacky 803f22ef01cSRoman Divacky // Construct the constructor and destructor arrays. 80444290647SDimitry Andric ConstantInitBuilder builder(*this); 80544290647SDimitry Andric auto ctors = builder.beginArray(CtorStructTy); 8068f0fd8f6SDimitry Andric for (const auto &I : Fns) { 80744290647SDimitry Andric auto ctor = ctors.beginStruct(CtorStructTy); 80844290647SDimitry Andric ctor.addInt(Int32Ty, I.Priority); 80944290647SDimitry Andric ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy)); 81044290647SDimitry Andric if (I.AssociatedData) 81144290647SDimitry Andric ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)); 81244290647SDimitry Andric else 81344290647SDimitry Andric ctor.addNullPointer(VoidPtrTy); 81444290647SDimitry Andric ctor.finishAndAddTo(ctors); 815f22ef01cSRoman Divacky } 816f22ef01cSRoman Divacky 81744290647SDimitry Andric auto list = 81844290647SDimitry Andric ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(), 81944290647SDimitry Andric /*constant*/ false, 82044290647SDimitry Andric llvm::GlobalValue::AppendingLinkage); 82144290647SDimitry Andric 82244290647SDimitry Andric // The LTO linker doesn't seem to like it when we set an alignment 82344290647SDimitry Andric // on appending variables. Take it off as a workaround. 82444290647SDimitry Andric list->setAlignment(0); 82544290647SDimitry Andric 82644290647SDimitry Andric Fns.clear(); 827f22ef01cSRoman Divacky } 828f22ef01cSRoman Divacky 829f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes 830f785676fSDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 83159d1ed5bSDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 832f785676fSDimitry Andric 833e580952dSDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 834f22ef01cSRoman Divacky 83559d1ed5bSDimitry Andric if (isa<CXXDestructorDecl>(D) && 83659d1ed5bSDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 83759d1ed5bSDimitry Andric GD.getDtorType())) { 83859d1ed5bSDimitry Andric // Destructor variants in the Microsoft C++ ABI are always internal or 83959d1ed5bSDimitry Andric // linkonce_odr thunks emitted on an as-needed basis. 84059d1ed5bSDimitry Andric return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage 84159d1ed5bSDimitry Andric : llvm::GlobalValue::LinkOnceODRLinkage; 842f22ef01cSRoman Divacky } 843f22ef01cSRoman Divacky 844e7145dcbSDimitry Andric if (isa<CXXConstructorDecl>(D) && 845e7145dcbSDimitry Andric cast<CXXConstructorDecl>(D)->isInheritingConstructor() && 846e7145dcbSDimitry Andric Context.getTargetInfo().getCXXABI().isMicrosoft()) { 847e7145dcbSDimitry Andric // Our approach to inheriting constructors is fundamentally different from 848e7145dcbSDimitry Andric // that used by the MS ABI, so keep our inheriting constructor thunks 849e7145dcbSDimitry Andric // internal rather than trying to pick an unambiguous mangling for them. 850e7145dcbSDimitry Andric return llvm::GlobalValue::InternalLinkage; 851e7145dcbSDimitry Andric } 852e7145dcbSDimitry Andric 85359d1ed5bSDimitry Andric return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false); 85459d1ed5bSDimitry Andric } 855f22ef01cSRoman Divacky 85697bc6c73SDimitry Andric void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) { 85797bc6c73SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 85897bc6c73SDimitry Andric 85997bc6c73SDimitry Andric if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) { 86097bc6c73SDimitry Andric if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) { 86197bc6c73SDimitry Andric // Don't dllexport/import destructor thunks. 86297bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 86397bc6c73SDimitry Andric return; 86497bc6c73SDimitry Andric } 86597bc6c73SDimitry Andric } 86697bc6c73SDimitry Andric 86797bc6c73SDimitry Andric if (FD->hasAttr<DLLImportAttr>()) 86897bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 86997bc6c73SDimitry Andric else if (FD->hasAttr<DLLExportAttr>()) 87097bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 87197bc6c73SDimitry Andric else 87297bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 87397bc6c73SDimitry Andric } 87497bc6c73SDimitry Andric 875e7145dcbSDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { 8760623d748SDimitry Andric llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 8770623d748SDimitry Andric if (!MDS) return nullptr; 8780623d748SDimitry Andric 87944290647SDimitry Andric return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString())); 8800623d748SDimitry Andric } 8810623d748SDimitry Andric 88259d1ed5bSDimitry Andric void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D, 88359d1ed5bSDimitry Andric llvm::Function *F) { 88459d1ed5bSDimitry Andric setNonAliasAttributes(D, F); 885f22ef01cSRoman Divacky } 886f22ef01cSRoman Divacky 887f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 888f22ef01cSRoman Divacky const CGFunctionInfo &Info, 889f22ef01cSRoman Divacky llvm::Function *F) { 890f22ef01cSRoman Divacky unsigned CallingConv; 8916bc11b14SDimitry Andric llvm::AttributeList PAL; 8926bc11b14SDimitry Andric ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false); 8936bc11b14SDimitry Andric F->setAttributes(PAL); 894f22ef01cSRoman Divacky F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 895f22ef01cSRoman Divacky } 896f22ef01cSRoman Divacky 8976122f3e6SDimitry Andric /// Determines whether the language options require us to model 8986122f3e6SDimitry Andric /// unwind exceptions. We treat -fexceptions as mandating this 8996122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions 9006122f3e6SDimitry Andric /// enabled. This means, for example, that C with -fexceptions 9016122f3e6SDimitry Andric /// enables this. 902dff0c46cSDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) { 9036122f3e6SDimitry Andric // If exceptions are completely disabled, obviously this is false. 904dff0c46cSDimitry Andric if (!LangOpts.Exceptions) return false; 9056122f3e6SDimitry Andric 9066122f3e6SDimitry Andric // If C++ exceptions are enabled, this is true. 907dff0c46cSDimitry Andric if (LangOpts.CXXExceptions) return true; 9086122f3e6SDimitry Andric 9096122f3e6SDimitry Andric // If ObjC exceptions are enabled, this depends on the ABI. 910dff0c46cSDimitry Andric if (LangOpts.ObjCExceptions) { 9117ae0e2c9SDimitry Andric return LangOpts.ObjCRuntime.hasUnwindExceptions(); 9126122f3e6SDimitry Andric } 9136122f3e6SDimitry Andric 9146122f3e6SDimitry Andric return true; 9156122f3e6SDimitry Andric } 9166122f3e6SDimitry Andric 917f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 918f22ef01cSRoman Divacky llvm::Function *F) { 919f785676fSDimitry Andric llvm::AttrBuilder B; 920f785676fSDimitry Andric 921bd5abe19SDimitry Andric if (CodeGenOpts.UnwindTables) 922f785676fSDimitry Andric B.addAttribute(llvm::Attribute::UWTable); 923bd5abe19SDimitry Andric 924dff0c46cSDimitry Andric if (!hasUnwindExceptions(LangOpts)) 925f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoUnwind); 926f22ef01cSRoman Divacky 9270623d748SDimitry Andric if (LangOpts.getStackProtector() == LangOptions::SSPOn) 9280623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtect); 9290623d748SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 9300623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectStrong); 9310623d748SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 9320623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectReq); 9330623d748SDimitry Andric 9340623d748SDimitry Andric if (!D) { 93544290647SDimitry Andric // If we don't have a declaration to control inlining, the function isn't 93644290647SDimitry Andric // explicitly marked as alwaysinline for semantic reasons, and inlining is 93744290647SDimitry Andric // disabled, mark the function as noinline. 93844290647SDimitry Andric if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 93944290647SDimitry Andric CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) 94044290647SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 94144290647SDimitry Andric 942f37b6182SDimitry Andric F->addAttributes(llvm::AttributeList::FunctionIndex, B); 9430623d748SDimitry Andric return; 9440623d748SDimitry Andric } 9450623d748SDimitry Andric 946302affcbSDimitry Andric // Track whether we need to add the optnone LLVM attribute, 947302affcbSDimitry Andric // starting with the default for this optimization level. 948302affcbSDimitry Andric bool ShouldAddOptNone = 949302affcbSDimitry Andric !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0; 950302affcbSDimitry Andric // We can't add optnone in the following cases, it won't pass the verifier. 951302affcbSDimitry Andric ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>(); 952302affcbSDimitry Andric ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline); 953302affcbSDimitry Andric ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>(); 954302affcbSDimitry Andric 955302affcbSDimitry Andric if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) { 95644290647SDimitry Andric B.addAttribute(llvm::Attribute::OptimizeNone); 95744290647SDimitry Andric 95844290647SDimitry Andric // OptimizeNone implies noinline; we should not be inlining such functions. 95944290647SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 96044290647SDimitry Andric assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 96144290647SDimitry Andric "OptimizeNone and AlwaysInline on same function!"); 96244290647SDimitry Andric 96344290647SDimitry Andric // We still need to handle naked functions even though optnone subsumes 96444290647SDimitry Andric // much of their semantics. 96544290647SDimitry Andric if (D->hasAttr<NakedAttr>()) 96644290647SDimitry Andric B.addAttribute(llvm::Attribute::Naked); 96744290647SDimitry Andric 96844290647SDimitry Andric // OptimizeNone wins over OptimizeForSize and MinSize. 96944290647SDimitry Andric F->removeFnAttr(llvm::Attribute::OptimizeForSize); 97044290647SDimitry Andric F->removeFnAttr(llvm::Attribute::MinSize); 97144290647SDimitry Andric } else if (D->hasAttr<NakedAttr>()) { 9726122f3e6SDimitry Andric // Naked implies noinline: we should not be inlining such functions. 973f785676fSDimitry Andric B.addAttribute(llvm::Attribute::Naked); 974f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 97559d1ed5bSDimitry Andric } else if (D->hasAttr<NoDuplicateAttr>()) { 97659d1ed5bSDimitry Andric B.addAttribute(llvm::Attribute::NoDuplicate); 977f785676fSDimitry Andric } else if (D->hasAttr<NoInlineAttr>()) { 978f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 97959d1ed5bSDimitry Andric } else if (D->hasAttr<AlwaysInlineAttr>() && 98044290647SDimitry Andric !F->hasFnAttribute(llvm::Attribute::NoInline)) { 981f785676fSDimitry Andric // (noinline wins over always_inline, and we can't specify both in IR) 982f785676fSDimitry Andric B.addAttribute(llvm::Attribute::AlwaysInline); 98344290647SDimitry Andric } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { 98444290647SDimitry Andric // If we're not inlining, then force everything that isn't always_inline to 98544290647SDimitry Andric // carry an explicit noinline attribute. 98644290647SDimitry Andric if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) 98744290647SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 98844290647SDimitry Andric } else { 98944290647SDimitry Andric // Otherwise, propagate the inline hint attribute and potentially use its 99044290647SDimitry Andric // absence to mark things as noinline. 99144290647SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) { 99244290647SDimitry Andric if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) { 99344290647SDimitry Andric return Redecl->isInlineSpecified(); 99444290647SDimitry Andric })) { 99544290647SDimitry Andric B.addAttribute(llvm::Attribute::InlineHint); 99644290647SDimitry Andric } else if (CodeGenOpts.getInlining() == 99744290647SDimitry Andric CodeGenOptions::OnlyHintInlining && 99844290647SDimitry Andric !FD->isInlined() && 99944290647SDimitry Andric !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 100044290647SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 100144290647SDimitry Andric } 100244290647SDimitry Andric } 10036122f3e6SDimitry Andric } 10042754fe60SDimitry Andric 100544290647SDimitry Andric // Add other optimization related attributes if we are optimizing this 100644290647SDimitry Andric // function. 100744290647SDimitry Andric if (!D->hasAttr<OptimizeNoneAttr>()) { 1008f785676fSDimitry Andric if (D->hasAttr<ColdAttr>()) { 1009302affcbSDimitry Andric if (!ShouldAddOptNone) 1010f785676fSDimitry Andric B.addAttribute(llvm::Attribute::OptimizeForSize); 1011f785676fSDimitry Andric B.addAttribute(llvm::Attribute::Cold); 1012f785676fSDimitry Andric } 10133861d79fSDimitry Andric 10143861d79fSDimitry Andric if (D->hasAttr<MinSizeAttr>()) 1015f785676fSDimitry Andric B.addAttribute(llvm::Attribute::MinSize); 101644290647SDimitry Andric } 1017f22ef01cSRoman Divacky 1018f37b6182SDimitry Andric F->addAttributes(llvm::AttributeList::FunctionIndex, B); 1019f785676fSDimitry Andric 1020e580952dSDimitry Andric unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 1021e580952dSDimitry Andric if (alignment) 1022e580952dSDimitry Andric F->setAlignment(alignment); 1023e580952dSDimitry Andric 10240623d748SDimitry Andric // Some C++ ABIs require 2-byte alignment for member functions, in order to 10250623d748SDimitry Andric // reserve a bit for differentiating between virtual and non-virtual member 10260623d748SDimitry Andric // functions. If the current target's C++ ABI requires this and this is a 10270623d748SDimitry Andric // member function, set its alignment accordingly. 10280623d748SDimitry Andric if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 1029f22ef01cSRoman Divacky if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 1030f22ef01cSRoman Divacky F->setAlignment(2); 1031f22ef01cSRoman Divacky } 103244290647SDimitry Andric 103344290647SDimitry Andric // In the cross-dso CFI mode, we want !type attributes on definitions only. 103444290647SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 103544290647SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) 103644290647SDimitry Andric CreateFunctionTypeMetadata(FD, F); 10370623d748SDimitry Andric } 1038f22ef01cSRoman Divacky 1039f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D, 1040f22ef01cSRoman Divacky llvm::GlobalValue *GV) { 10410623d748SDimitry Andric if (const auto *ND = dyn_cast_or_null<NamedDecl>(D)) 10422754fe60SDimitry Andric setGlobalVisibility(GV, ND); 10432754fe60SDimitry Andric else 10442754fe60SDimitry Andric GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 1045f22ef01cSRoman Divacky 10460623d748SDimitry Andric if (D && D->hasAttr<UsedAttr>()) 104759d1ed5bSDimitry Andric addUsedGlobal(GV); 104859d1ed5bSDimitry Andric } 104959d1ed5bSDimitry Andric 105039d628a0SDimitry Andric void CodeGenModule::setAliasAttributes(const Decl *D, 105139d628a0SDimitry Andric llvm::GlobalValue *GV) { 105239d628a0SDimitry Andric SetCommonAttributes(D, GV); 105339d628a0SDimitry Andric 105439d628a0SDimitry Andric // Process the dllexport attribute based on whether the original definition 105539d628a0SDimitry Andric // (not necessarily the aliasee) was exported. 105639d628a0SDimitry Andric if (D->hasAttr<DLLExportAttr>()) 105739d628a0SDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 105839d628a0SDimitry Andric } 105939d628a0SDimitry Andric 106059d1ed5bSDimitry Andric void CodeGenModule::setNonAliasAttributes(const Decl *D, 106159d1ed5bSDimitry Andric llvm::GlobalObject *GO) { 106259d1ed5bSDimitry Andric SetCommonAttributes(D, GO); 1063f22ef01cSRoman Divacky 1064db17bf38SDimitry Andric if (D) { 1065db17bf38SDimitry Andric if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) { 1066db17bf38SDimitry Andric if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) 1067db17bf38SDimitry Andric GV->addAttribute("bss-section", SA->getName()); 1068db17bf38SDimitry Andric if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) 1069db17bf38SDimitry Andric GV->addAttribute("data-section", SA->getName()); 1070db17bf38SDimitry Andric if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) 1071db17bf38SDimitry Andric GV->addAttribute("rodata-section", SA->getName()); 1072db17bf38SDimitry Andric } 1073db17bf38SDimitry Andric 1074db17bf38SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(GO)) { 1075db17bf38SDimitry Andric if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) 1076db17bf38SDimitry Andric if (!D->getAttr<SectionAttr>()) 1077db17bf38SDimitry Andric F->addFnAttr("implicit-section-name", SA->getName()); 1078db17bf38SDimitry Andric } 1079db17bf38SDimitry Andric 1080f22ef01cSRoman Divacky if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 108159d1ed5bSDimitry Andric GO->setSection(SA->getName()); 1082db17bf38SDimitry Andric } 1083f22ef01cSRoman Divacky 108497bc6c73SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 1085f22ef01cSRoman Divacky } 1086f22ef01cSRoman Divacky 1087f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 1088f22ef01cSRoman Divacky llvm::Function *F, 1089f22ef01cSRoman Divacky const CGFunctionInfo &FI) { 1090f22ef01cSRoman Divacky SetLLVMFunctionAttributes(D, FI, F); 1091f22ef01cSRoman Divacky SetLLVMFunctionAttributesForDefinition(D, F); 1092f22ef01cSRoman Divacky 1093f22ef01cSRoman Divacky F->setLinkage(llvm::Function::InternalLinkage); 1094f22ef01cSRoman Divacky 109559d1ed5bSDimitry Andric setNonAliasAttributes(D, F); 109659d1ed5bSDimitry Andric } 109759d1ed5bSDimitry Andric 109859d1ed5bSDimitry Andric static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV, 109959d1ed5bSDimitry Andric const NamedDecl *ND) { 110059d1ed5bSDimitry Andric // Set linkage and visibility in case we never see a definition. 110159d1ed5bSDimitry Andric LinkageInfo LV = ND->getLinkageAndVisibility(); 110259d1ed5bSDimitry Andric if (LV.getLinkage() != ExternalLinkage) { 110359d1ed5bSDimitry Andric // Don't set internal linkage on declarations. 110459d1ed5bSDimitry Andric } else { 110559d1ed5bSDimitry Andric if (ND->hasAttr<DLLImportAttr>()) { 110659d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 110759d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 110859d1ed5bSDimitry Andric } else if (ND->hasAttr<DLLExportAttr>()) { 110959d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 111059d1ed5bSDimitry Andric } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) { 111159d1ed5bSDimitry Andric // "extern_weak" is overloaded in LLVM; we probably should have 111259d1ed5bSDimitry Andric // separate linkage types for this. 111359d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 111459d1ed5bSDimitry Andric } 111559d1ed5bSDimitry Andric 111659d1ed5bSDimitry Andric // Set visibility on a declaration only if it's explicit. 111759d1ed5bSDimitry Andric if (LV.isVisibilityExplicit()) 111859d1ed5bSDimitry Andric GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility())); 111959d1ed5bSDimitry Andric } 1120f22ef01cSRoman Divacky } 1121f22ef01cSRoman Divacky 1122e7145dcbSDimitry Andric void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD, 11230623d748SDimitry Andric llvm::Function *F) { 11240623d748SDimitry Andric // Only if we are checking indirect calls. 11250623d748SDimitry Andric if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 11260623d748SDimitry Andric return; 11270623d748SDimitry Andric 11280623d748SDimitry Andric // Non-static class methods are handled via vtable pointer checks elsewhere. 11290623d748SDimitry Andric if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 11300623d748SDimitry Andric return; 11310623d748SDimitry Andric 11320623d748SDimitry Andric // Additionally, if building with cross-DSO support... 11330623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 11340623d748SDimitry Andric // Skip available_externally functions. They won't be codegen'ed in the 11350623d748SDimitry Andric // current module anyway. 11360623d748SDimitry Andric if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally) 11370623d748SDimitry Andric return; 11380623d748SDimitry Andric } 11390623d748SDimitry Andric 11400623d748SDimitry Andric llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 1141e7145dcbSDimitry Andric F->addTypeMetadata(0, MD); 11420623d748SDimitry Andric 11430623d748SDimitry Andric // Emit a hash-based bit set entry for cross-DSO calls. 1144e7145dcbSDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 1145e7145dcbSDimitry Andric if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 1146e7145dcbSDimitry Andric F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 11470623d748SDimitry Andric } 11480623d748SDimitry Andric 114939d628a0SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 115039d628a0SDimitry Andric bool IsIncompleteFunction, 115139d628a0SDimitry Andric bool IsThunk) { 115233956c43SDimitry Andric if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 11533b0f4066SDimitry Andric // If this is an intrinsic function, set the function's attributes 11543b0f4066SDimitry Andric // to the intrinsic's attributes. 115533956c43SDimitry Andric F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 11563b0f4066SDimitry Andric return; 11573b0f4066SDimitry Andric } 11583b0f4066SDimitry Andric 115959d1ed5bSDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 1160f22ef01cSRoman Divacky 1161f22ef01cSRoman Divacky if (!IsIncompleteFunction) 1162dff0c46cSDimitry Andric SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); 1163f22ef01cSRoman Divacky 116459d1ed5bSDimitry Andric // Add the Returned attribute for "this", except for iOS 5 and earlier 116559d1ed5bSDimitry Andric // where substantial code, including the libstdc++ dylib, was compiled with 116659d1ed5bSDimitry Andric // GCC and does not actually return "this". 116739d628a0SDimitry Andric if (!IsThunk && getCXXABI().HasThisReturn(GD) && 116844290647SDimitry Andric !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { 1169f785676fSDimitry Andric assert(!F->arg_empty() && 1170f785676fSDimitry Andric F->arg_begin()->getType() 1171f785676fSDimitry Andric ->canLosslesslyBitCastTo(F->getReturnType()) && 1172f785676fSDimitry Andric "unexpected this return"); 1173f785676fSDimitry Andric F->addAttribute(1, llvm::Attribute::Returned); 1174f785676fSDimitry Andric } 1175f785676fSDimitry Andric 1176f22ef01cSRoman Divacky // Only a few attributes are set on declarations; these may later be 1177f22ef01cSRoman Divacky // overridden by a definition. 1178f22ef01cSRoman Divacky 117959d1ed5bSDimitry Andric setLinkageAndVisibilityForGV(F, FD); 11802754fe60SDimitry Andric 1181db17bf38SDimitry Andric if (FD->getAttr<PragmaClangTextSectionAttr>()) { 1182db17bf38SDimitry Andric F->addFnAttr("implicit-section-name"); 1183db17bf38SDimitry Andric } 1184db17bf38SDimitry Andric 1185f22ef01cSRoman Divacky if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 1186f22ef01cSRoman Divacky F->setSection(SA->getName()); 1187f785676fSDimitry Andric 1188e7145dcbSDimitry Andric if (FD->isReplaceableGlobalAllocationFunction()) { 1189f785676fSDimitry Andric // A replaceable global allocation function does not act like a builtin by 1190f785676fSDimitry Andric // default, only if it is invoked by a new-expression or delete-expression. 119120e90f04SDimitry Andric F->addAttribute(llvm::AttributeList::FunctionIndex, 1192f785676fSDimitry Andric llvm::Attribute::NoBuiltin); 11930623d748SDimitry Andric 1194e7145dcbSDimitry Andric // A sane operator new returns a non-aliasing pointer. 1195e7145dcbSDimitry Andric // FIXME: Also add NonNull attribute to the return value 1196e7145dcbSDimitry Andric // for the non-nothrow forms? 1197e7145dcbSDimitry Andric auto Kind = FD->getDeclName().getCXXOverloadedOperator(); 1198e7145dcbSDimitry Andric if (getCodeGenOpts().AssumeSaneOperatorNew && 1199e7145dcbSDimitry Andric (Kind == OO_New || Kind == OO_Array_New)) 120020e90f04SDimitry Andric F->addAttribute(llvm::AttributeList::ReturnIndex, 1201e7145dcbSDimitry Andric llvm::Attribute::NoAlias); 1202e7145dcbSDimitry Andric } 1203e7145dcbSDimitry Andric 1204e7145dcbSDimitry Andric if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 1205e7145dcbSDimitry Andric F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1206e7145dcbSDimitry Andric else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 1207e7145dcbSDimitry Andric if (MD->isVirtual()) 1208e7145dcbSDimitry Andric F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1209e7145dcbSDimitry Andric 121044290647SDimitry Andric // Don't emit entries for function declarations in the cross-DSO mode. This 121144290647SDimitry Andric // is handled with better precision by the receiving DSO. 121244290647SDimitry Andric if (!CodeGenOpts.SanitizeCfiCrossDso) 1213e7145dcbSDimitry Andric CreateFunctionTypeMetadata(FD, F); 1214f22ef01cSRoman Divacky } 1215f22ef01cSRoman Divacky 121659d1ed5bSDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 1217f22ef01cSRoman Divacky assert(!GV->isDeclaration() && 1218f22ef01cSRoman Divacky "Only globals with definition can force usage."); 121997bc6c73SDimitry Andric LLVMUsed.emplace_back(GV); 1220f22ef01cSRoman Divacky } 1221f22ef01cSRoman Divacky 122259d1ed5bSDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 122359d1ed5bSDimitry Andric assert(!GV->isDeclaration() && 122459d1ed5bSDimitry Andric "Only globals with definition can force usage."); 122597bc6c73SDimitry Andric LLVMCompilerUsed.emplace_back(GV); 122659d1ed5bSDimitry Andric } 122759d1ed5bSDimitry Andric 122859d1ed5bSDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name, 1229f37b6182SDimitry Andric std::vector<llvm::WeakTrackingVH> &List) { 1230f22ef01cSRoman Divacky // Don't create llvm.used if there is no need. 123159d1ed5bSDimitry Andric if (List.empty()) 1232f22ef01cSRoman Divacky return; 1233f22ef01cSRoman Divacky 123459d1ed5bSDimitry Andric // Convert List to what ConstantArray needs. 1235dff0c46cSDimitry Andric SmallVector<llvm::Constant*, 8> UsedArray; 123659d1ed5bSDimitry Andric UsedArray.resize(List.size()); 123759d1ed5bSDimitry Andric for (unsigned i = 0, e = List.size(); i != e; ++i) { 1238f22ef01cSRoman Divacky UsedArray[i] = 123944f7b0dcSDimitry Andric llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 124044f7b0dcSDimitry Andric cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 1241f22ef01cSRoman Divacky } 1242f22ef01cSRoman Divacky 1243f22ef01cSRoman Divacky if (UsedArray.empty()) 1244f22ef01cSRoman Divacky return; 124559d1ed5bSDimitry Andric llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 1246f22ef01cSRoman Divacky 124759d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 124859d1ed5bSDimitry Andric CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 124959d1ed5bSDimitry Andric llvm::ConstantArray::get(ATy, UsedArray), Name); 1250f22ef01cSRoman Divacky 1251f22ef01cSRoman Divacky GV->setSection("llvm.metadata"); 1252f22ef01cSRoman Divacky } 1253f22ef01cSRoman Divacky 125459d1ed5bSDimitry Andric void CodeGenModule::emitLLVMUsed() { 125559d1ed5bSDimitry Andric emitUsed(*this, "llvm.used", LLVMUsed); 125659d1ed5bSDimitry Andric emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 125759d1ed5bSDimitry Andric } 125859d1ed5bSDimitry Andric 1259f785676fSDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 126039d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 1261f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1262f785676fSDimitry Andric } 1263f785676fSDimitry Andric 1264f785676fSDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 1265f785676fSDimitry Andric llvm::SmallString<32> Opt; 1266f785676fSDimitry Andric getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 126739d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1268f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1269f785676fSDimitry Andric } 1270f785676fSDimitry Andric 1271f785676fSDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) { 1272f785676fSDimitry Andric llvm::SmallString<24> Opt; 1273f785676fSDimitry Andric getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 127439d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1275f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1276f785676fSDimitry Andric } 1277f785676fSDimitry Andric 1278139f7f9bSDimitry Andric /// \brief Add link options implied by the given module, including modules 1279139f7f9bSDimitry Andric /// it depends on, using a postorder walk. 128039d628a0SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 128124d58133SDimitry Andric SmallVectorImpl<llvm::MDNode *> &Metadata, 1282139f7f9bSDimitry Andric llvm::SmallPtrSet<Module *, 16> &Visited) { 1283139f7f9bSDimitry Andric // Import this module's parent. 128439d628a0SDimitry Andric if (Mod->Parent && Visited.insert(Mod->Parent).second) { 1285f785676fSDimitry Andric addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 1286139f7f9bSDimitry Andric } 1287139f7f9bSDimitry Andric 1288139f7f9bSDimitry Andric // Import this module's dependencies. 1289139f7f9bSDimitry Andric for (unsigned I = Mod->Imports.size(); I > 0; --I) { 129039d628a0SDimitry Andric if (Visited.insert(Mod->Imports[I - 1]).second) 1291f785676fSDimitry Andric addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 1292139f7f9bSDimitry Andric } 1293139f7f9bSDimitry Andric 1294139f7f9bSDimitry Andric // Add linker options to link against the libraries/frameworks 1295139f7f9bSDimitry Andric // described by this module. 1296f785676fSDimitry Andric llvm::LLVMContext &Context = CGM.getLLVMContext(); 1297139f7f9bSDimitry Andric for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 1298f785676fSDimitry Andric // Link against a framework. Frameworks are currently Darwin only, so we 1299f785676fSDimitry Andric // don't to ask TargetCodeGenInfo for the spelling of the linker option. 1300139f7f9bSDimitry Andric if (Mod->LinkLibraries[I-1].IsFramework) { 130139d628a0SDimitry Andric llvm::Metadata *Args[2] = { 1302139f7f9bSDimitry Andric llvm::MDString::get(Context, "-framework"), 130339d628a0SDimitry Andric llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)}; 1304139f7f9bSDimitry Andric 1305139f7f9bSDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, Args)); 1306139f7f9bSDimitry Andric continue; 1307139f7f9bSDimitry Andric } 1308139f7f9bSDimitry Andric 1309139f7f9bSDimitry Andric // Link against a library. 1310f785676fSDimitry Andric llvm::SmallString<24> Opt; 1311f785676fSDimitry Andric CGM.getTargetCodeGenInfo().getDependentLibraryOption( 1312f785676fSDimitry Andric Mod->LinkLibraries[I-1].Library, Opt); 131339d628a0SDimitry Andric auto *OptString = llvm::MDString::get(Context, Opt); 1314139f7f9bSDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, OptString)); 1315139f7f9bSDimitry Andric } 1316139f7f9bSDimitry Andric } 1317139f7f9bSDimitry Andric 1318139f7f9bSDimitry Andric void CodeGenModule::EmitModuleLinkOptions() { 1319139f7f9bSDimitry Andric // Collect the set of all of the modules we want to visit to emit link 1320139f7f9bSDimitry Andric // options, which is essentially the imported modules and all of their 1321139f7f9bSDimitry Andric // non-explicit child modules. 1322139f7f9bSDimitry Andric llvm::SetVector<clang::Module *> LinkModules; 1323139f7f9bSDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 1324139f7f9bSDimitry Andric SmallVector<clang::Module *, 16> Stack; 1325139f7f9bSDimitry Andric 1326139f7f9bSDimitry Andric // Seed the stack with imported modules. 1327f1a29dd3SDimitry Andric for (Module *M : ImportedModules) { 1328f1a29dd3SDimitry Andric // Do not add any link flags when an implementation TU of a module imports 1329f1a29dd3SDimitry Andric // a header of that same module. 1330f1a29dd3SDimitry Andric if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && 1331f1a29dd3SDimitry Andric !getLangOpts().isCompilingModule()) 1332f1a29dd3SDimitry Andric continue; 13338f0fd8f6SDimitry Andric if (Visited.insert(M).second) 13348f0fd8f6SDimitry Andric Stack.push_back(M); 1335f1a29dd3SDimitry Andric } 1336139f7f9bSDimitry Andric 1337139f7f9bSDimitry Andric // Find all of the modules to import, making a little effort to prune 1338139f7f9bSDimitry Andric // non-leaf modules. 1339139f7f9bSDimitry Andric while (!Stack.empty()) { 1340f785676fSDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 1341139f7f9bSDimitry Andric 1342139f7f9bSDimitry Andric bool AnyChildren = false; 1343139f7f9bSDimitry Andric 1344139f7f9bSDimitry Andric // Visit the submodules of this module. 1345139f7f9bSDimitry Andric for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 1346139f7f9bSDimitry Andric SubEnd = Mod->submodule_end(); 1347139f7f9bSDimitry Andric Sub != SubEnd; ++Sub) { 1348139f7f9bSDimitry Andric // Skip explicit children; they need to be explicitly imported to be 1349139f7f9bSDimitry Andric // linked against. 1350139f7f9bSDimitry Andric if ((*Sub)->IsExplicit) 1351139f7f9bSDimitry Andric continue; 1352139f7f9bSDimitry Andric 135339d628a0SDimitry Andric if (Visited.insert(*Sub).second) { 1354139f7f9bSDimitry Andric Stack.push_back(*Sub); 1355139f7f9bSDimitry Andric AnyChildren = true; 1356139f7f9bSDimitry Andric } 1357139f7f9bSDimitry Andric } 1358139f7f9bSDimitry Andric 1359139f7f9bSDimitry Andric // We didn't find any children, so add this module to the list of 1360139f7f9bSDimitry Andric // modules to link against. 1361139f7f9bSDimitry Andric if (!AnyChildren) { 1362139f7f9bSDimitry Andric LinkModules.insert(Mod); 1363139f7f9bSDimitry Andric } 1364139f7f9bSDimitry Andric } 1365139f7f9bSDimitry Andric 1366139f7f9bSDimitry Andric // Add link options for all of the imported modules in reverse topological 1367f785676fSDimitry Andric // order. We don't do anything to try to order import link flags with respect 1368f785676fSDimitry Andric // to linker options inserted by things like #pragma comment(). 136924d58133SDimitry Andric SmallVector<llvm::MDNode *, 16> MetadataArgs; 1370139f7f9bSDimitry Andric Visited.clear(); 13718f0fd8f6SDimitry Andric for (Module *M : LinkModules) 13728f0fd8f6SDimitry Andric if (Visited.insert(M).second) 13738f0fd8f6SDimitry Andric addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 1374139f7f9bSDimitry Andric std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 1375f785676fSDimitry Andric LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 1376139f7f9bSDimitry Andric 1377139f7f9bSDimitry Andric // Add the linker options metadata flag. 137824d58133SDimitry Andric auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options"); 137924d58133SDimitry Andric for (auto *MD : LinkerOptionsMetadata) 138024d58133SDimitry Andric NMD->addOperand(MD); 1381139f7f9bSDimitry Andric } 1382139f7f9bSDimitry Andric 1383f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() { 1384f22ef01cSRoman Divacky // Emit code for any potentially referenced deferred decls. Since a 1385f22ef01cSRoman Divacky // previously unused static decl may become used during the generation of code 1386f22ef01cSRoman Divacky // for a static function, iterate until no changes are made. 1387f22ef01cSRoman Divacky 1388f22ef01cSRoman Divacky if (!DeferredVTables.empty()) { 1389139f7f9bSDimitry Andric EmitDeferredVTables(); 1390139f7f9bSDimitry Andric 1391e7145dcbSDimitry Andric // Emitting a vtable doesn't directly cause more vtables to 1392139f7f9bSDimitry Andric // become deferred, although it can cause functions to be 1393e7145dcbSDimitry Andric // emitted that then need those vtables. 1394139f7f9bSDimitry Andric assert(DeferredVTables.empty()); 1395f22ef01cSRoman Divacky } 1396f22ef01cSRoman Divacky 1397e7145dcbSDimitry Andric // Stop if we're out of both deferred vtables and deferred declarations. 139833956c43SDimitry Andric if (DeferredDeclsToEmit.empty()) 139933956c43SDimitry Andric return; 1400139f7f9bSDimitry Andric 140133956c43SDimitry Andric // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 140233956c43SDimitry Andric // work, it will not interfere with this. 1403f37b6182SDimitry Andric std::vector<GlobalDecl> CurDeclsToEmit; 140433956c43SDimitry Andric CurDeclsToEmit.swap(DeferredDeclsToEmit); 140533956c43SDimitry Andric 1406f37b6182SDimitry Andric for (GlobalDecl &D : CurDeclsToEmit) { 14070623d748SDimitry Andric // We should call GetAddrOfGlobal with IsForDefinition set to true in order 14080623d748SDimitry Andric // to get GlobalValue with exactly the type we need, not something that 14090623d748SDimitry Andric // might had been created for another decl with the same mangled name but 14100623d748SDimitry Andric // different type. 1411e7145dcbSDimitry Andric llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 141244290647SDimitry Andric GetAddrOfGlobal(D, ForDefinition)); 1413e7145dcbSDimitry Andric 1414e7145dcbSDimitry Andric // In case of different address spaces, we may still get a cast, even with 1415e7145dcbSDimitry Andric // IsForDefinition equal to true. Query mangled names table to get 1416e7145dcbSDimitry Andric // GlobalValue. 141739d628a0SDimitry Andric if (!GV) 141839d628a0SDimitry Andric GV = GetGlobalValue(getMangledName(D)); 141939d628a0SDimitry Andric 1420e7145dcbSDimitry Andric // Make sure GetGlobalValue returned non-null. 1421e7145dcbSDimitry Andric assert(GV); 1422e7145dcbSDimitry Andric 1423f22ef01cSRoman Divacky // Check to see if we've already emitted this. This is necessary 1424f22ef01cSRoman Divacky // for a couple of reasons: first, decls can end up in the 1425f22ef01cSRoman Divacky // deferred-decls queue multiple times, and second, decls can end 1426f22ef01cSRoman Divacky // up with definitions in unusual ways (e.g. by an extern inline 1427f22ef01cSRoman Divacky // function acquiring a strong function redefinition). Just 1428f22ef01cSRoman Divacky // ignore these cases. 1429e7145dcbSDimitry Andric if (!GV->isDeclaration()) 1430f22ef01cSRoman Divacky continue; 1431f22ef01cSRoman Divacky 1432f22ef01cSRoman Divacky // Otherwise, emit the definition and move on to the next one. 143359d1ed5bSDimitry Andric EmitGlobalDefinition(D, GV); 143433956c43SDimitry Andric 143533956c43SDimitry Andric // If we found out that we need to emit more decls, do that recursively. 143633956c43SDimitry Andric // This has the advantage that the decls are emitted in a DFS and related 143733956c43SDimitry Andric // ones are close together, which is convenient for testing. 143833956c43SDimitry Andric if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 143933956c43SDimitry Andric EmitDeferred(); 144033956c43SDimitry Andric assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 144133956c43SDimitry Andric } 1442f22ef01cSRoman Divacky } 1443f22ef01cSRoman Divacky } 1444f22ef01cSRoman Divacky 1445f9448bf3SDimitry Andric void CodeGenModule::EmitVTablesOpportunistically() { 1446f9448bf3SDimitry Andric // Try to emit external vtables as available_externally if they have emitted 1447f9448bf3SDimitry Andric // all inlined virtual functions. It runs after EmitDeferred() and therefore 1448f9448bf3SDimitry Andric // is not allowed to create new references to things that need to be emitted 1449f9448bf3SDimitry Andric // lazily. Note that it also uses fact that we eagerly emitting RTTI. 1450f9448bf3SDimitry Andric 1451f9448bf3SDimitry Andric assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) 1452f9448bf3SDimitry Andric && "Only emit opportunistic vtables with optimizations"); 1453f9448bf3SDimitry Andric 1454f9448bf3SDimitry Andric for (const CXXRecordDecl *RD : OpportunisticVTables) { 1455f9448bf3SDimitry Andric assert(getVTables().isVTableExternal(RD) && 1456f9448bf3SDimitry Andric "This queue should only contain external vtables"); 1457f9448bf3SDimitry Andric if (getCXXABI().canSpeculativelyEmitVTable(RD)) 1458f9448bf3SDimitry Andric VTables.GenerateClassData(RD); 1459f9448bf3SDimitry Andric } 1460f9448bf3SDimitry Andric OpportunisticVTables.clear(); 1461f9448bf3SDimitry Andric } 1462f9448bf3SDimitry Andric 14636122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() { 14646122f3e6SDimitry Andric if (Annotations.empty()) 14656122f3e6SDimitry Andric return; 14666122f3e6SDimitry Andric 14676122f3e6SDimitry Andric // Create a new global variable for the ConstantStruct in the Module. 14686122f3e6SDimitry Andric llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 14696122f3e6SDimitry Andric Annotations[0]->getType(), Annotations.size()), Annotations); 147059d1ed5bSDimitry Andric auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 147159d1ed5bSDimitry Andric llvm::GlobalValue::AppendingLinkage, 147259d1ed5bSDimitry Andric Array, "llvm.global.annotations"); 14736122f3e6SDimitry Andric gv->setSection(AnnotationSection); 14746122f3e6SDimitry Andric } 14756122f3e6SDimitry Andric 1476139f7f9bSDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 1477f785676fSDimitry Andric llvm::Constant *&AStr = AnnotationStrings[Str]; 1478f785676fSDimitry Andric if (AStr) 1479f785676fSDimitry Andric return AStr; 14806122f3e6SDimitry Andric 14816122f3e6SDimitry Andric // Not found yet, create a new global. 1482dff0c46cSDimitry Andric llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 148359d1ed5bSDimitry Andric auto *gv = 148459d1ed5bSDimitry Andric new llvm::GlobalVariable(getModule(), s->getType(), true, 148559d1ed5bSDimitry Andric llvm::GlobalValue::PrivateLinkage, s, ".str"); 14866122f3e6SDimitry Andric gv->setSection(AnnotationSection); 1487e7145dcbSDimitry Andric gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1488f785676fSDimitry Andric AStr = gv; 14896122f3e6SDimitry Andric return gv; 14906122f3e6SDimitry Andric } 14916122f3e6SDimitry Andric 14926122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 14936122f3e6SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 14946122f3e6SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(Loc); 14956122f3e6SDimitry Andric if (PLoc.isValid()) 14966122f3e6SDimitry Andric return EmitAnnotationString(PLoc.getFilename()); 14976122f3e6SDimitry Andric return EmitAnnotationString(SM.getBufferName(Loc)); 14986122f3e6SDimitry Andric } 14996122f3e6SDimitry Andric 15006122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 15016122f3e6SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 15026122f3e6SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(L); 15036122f3e6SDimitry Andric unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 15046122f3e6SDimitry Andric SM.getExpansionLineNumber(L); 15056122f3e6SDimitry Andric return llvm::ConstantInt::get(Int32Ty, LineNo); 15066122f3e6SDimitry Andric } 15076122f3e6SDimitry Andric 1508f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 1509f22ef01cSRoman Divacky const AnnotateAttr *AA, 15106122f3e6SDimitry Andric SourceLocation L) { 15116122f3e6SDimitry Andric // Get the globals for file name, annotation, and the line number. 15126122f3e6SDimitry Andric llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 15136122f3e6SDimitry Andric *UnitGV = EmitAnnotationUnit(L), 15146122f3e6SDimitry Andric *LineNoCst = EmitAnnotationLineNo(L); 1515f22ef01cSRoman Divacky 1516f22ef01cSRoman Divacky // Create the ConstantStruct for the global annotation. 1517f22ef01cSRoman Divacky llvm::Constant *Fields[4] = { 15186122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 15196122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 15206122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 15216122f3e6SDimitry Andric LineNoCst 1522f22ef01cSRoman Divacky }; 152317a519f9SDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 1524f22ef01cSRoman Divacky } 1525f22ef01cSRoman Divacky 15266122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 15276122f3e6SDimitry Andric llvm::GlobalValue *GV) { 15286122f3e6SDimitry Andric assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 15296122f3e6SDimitry Andric // Get the struct elements for these annotations. 153059d1ed5bSDimitry Andric for (const auto *I : D->specific_attrs<AnnotateAttr>()) 153159d1ed5bSDimitry Andric Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 15326122f3e6SDimitry Andric } 15336122f3e6SDimitry Andric 153439d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn, 153539d628a0SDimitry Andric SourceLocation Loc) const { 153639d628a0SDimitry Andric const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 153739d628a0SDimitry Andric // Blacklist by function name. 153839d628a0SDimitry Andric if (SanitizerBL.isBlacklistedFunction(Fn->getName())) 153939d628a0SDimitry Andric return true; 154039d628a0SDimitry Andric // Blacklist by location. 15410623d748SDimitry Andric if (Loc.isValid()) 154239d628a0SDimitry Andric return SanitizerBL.isBlacklistedLocation(Loc); 154339d628a0SDimitry Andric // If location is unknown, this may be a compiler-generated function. Assume 154439d628a0SDimitry Andric // it's located in the main file. 154539d628a0SDimitry Andric auto &SM = Context.getSourceManager(); 154639d628a0SDimitry Andric if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 154739d628a0SDimitry Andric return SanitizerBL.isBlacklistedFile(MainFile->getName()); 154839d628a0SDimitry Andric } 154939d628a0SDimitry Andric return false; 155039d628a0SDimitry Andric } 155139d628a0SDimitry Andric 155239d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV, 155339d628a0SDimitry Andric SourceLocation Loc, QualType Ty, 155439d628a0SDimitry Andric StringRef Category) const { 15558f0fd8f6SDimitry Andric // For now globals can be blacklisted only in ASan and KASan. 15568f0fd8f6SDimitry Andric if (!LangOpts.Sanitize.hasOneOf( 15578f0fd8f6SDimitry Andric SanitizerKind::Address | SanitizerKind::KernelAddress)) 155839d628a0SDimitry Andric return false; 155939d628a0SDimitry Andric const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 156039d628a0SDimitry Andric if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category)) 156139d628a0SDimitry Andric return true; 156239d628a0SDimitry Andric if (SanitizerBL.isBlacklistedLocation(Loc, Category)) 156339d628a0SDimitry Andric return true; 156439d628a0SDimitry Andric // Check global type. 156539d628a0SDimitry Andric if (!Ty.isNull()) { 156639d628a0SDimitry Andric // Drill down the array types: if global variable of a fixed type is 156739d628a0SDimitry Andric // blacklisted, we also don't instrument arrays of them. 156839d628a0SDimitry Andric while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 156939d628a0SDimitry Andric Ty = AT->getElementType(); 157039d628a0SDimitry Andric Ty = Ty.getCanonicalType().getUnqualifiedType(); 157139d628a0SDimitry Andric // We allow to blacklist only record types (classes, structs etc.) 157239d628a0SDimitry Andric if (Ty->isRecordType()) { 157339d628a0SDimitry Andric std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 157439d628a0SDimitry Andric if (SanitizerBL.isBlacklistedType(TypeStr, Category)) 157539d628a0SDimitry Andric return true; 157639d628a0SDimitry Andric } 157739d628a0SDimitry Andric } 157839d628a0SDimitry Andric return false; 157939d628a0SDimitry Andric } 158039d628a0SDimitry Andric 158120e90f04SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 158220e90f04SDimitry Andric StringRef Category) const { 158320e90f04SDimitry Andric if (!LangOpts.XRayInstrument) 158420e90f04SDimitry Andric return false; 158520e90f04SDimitry Andric const auto &XRayFilter = getContext().getXRayFilter(); 158620e90f04SDimitry Andric using ImbueAttr = XRayFunctionFilter::ImbueAttribute; 158720e90f04SDimitry Andric auto Attr = XRayFunctionFilter::ImbueAttribute::NONE; 158820e90f04SDimitry Andric if (Loc.isValid()) 158920e90f04SDimitry Andric Attr = XRayFilter.shouldImbueLocation(Loc, Category); 159020e90f04SDimitry Andric if (Attr == ImbueAttr::NONE) 159120e90f04SDimitry Andric Attr = XRayFilter.shouldImbueFunction(Fn->getName()); 159220e90f04SDimitry Andric switch (Attr) { 159320e90f04SDimitry Andric case ImbueAttr::NONE: 159420e90f04SDimitry Andric return false; 159520e90f04SDimitry Andric case ImbueAttr::ALWAYS: 159620e90f04SDimitry Andric Fn->addFnAttr("function-instrument", "xray-always"); 159720e90f04SDimitry Andric break; 1598302affcbSDimitry Andric case ImbueAttr::ALWAYS_ARG1: 1599302affcbSDimitry Andric Fn->addFnAttr("function-instrument", "xray-always"); 1600302affcbSDimitry Andric Fn->addFnAttr("xray-log-args", "1"); 1601302affcbSDimitry Andric break; 160220e90f04SDimitry Andric case ImbueAttr::NEVER: 160320e90f04SDimitry Andric Fn->addFnAttr("function-instrument", "xray-never"); 160420e90f04SDimitry Andric break; 160520e90f04SDimitry Andric } 160620e90f04SDimitry Andric return true; 160720e90f04SDimitry Andric } 160820e90f04SDimitry Andric 160939d628a0SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 1610e580952dSDimitry Andric // Never defer when EmitAllDecls is specified. 1611dff0c46cSDimitry Andric if (LangOpts.EmitAllDecls) 161239d628a0SDimitry Andric return true; 161339d628a0SDimitry Andric 161439d628a0SDimitry Andric return getContext().DeclMustBeEmitted(Global); 161539d628a0SDimitry Andric } 161639d628a0SDimitry Andric 161739d628a0SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 161839d628a0SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) 161939d628a0SDimitry Andric if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 162039d628a0SDimitry Andric // Implicit template instantiations may change linkage if they are later 162139d628a0SDimitry Andric // explicitly instantiated, so they should not be emitted eagerly. 1622f22ef01cSRoman Divacky return false; 1623e7145dcbSDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(Global)) 1624e7145dcbSDimitry Andric if (Context.getInlineVariableDefinitionKind(VD) == 1625e7145dcbSDimitry Andric ASTContext::InlineVariableDefinitionKind::WeakUnknown) 1626e7145dcbSDimitry Andric // A definition of an inline constexpr static data member may change 1627e7145dcbSDimitry Andric // linkage later if it's redeclared outside the class. 1628e7145dcbSDimitry Andric return false; 1629875ed548SDimitry Andric // If OpenMP is enabled and threadprivates must be generated like TLS, delay 1630875ed548SDimitry Andric // codegen for global variables, because they may be marked as threadprivate. 1631875ed548SDimitry Andric if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 1632875ed548SDimitry Andric getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global)) 1633875ed548SDimitry Andric return false; 1634f22ef01cSRoman Divacky 163539d628a0SDimitry Andric return true; 1636f22ef01cSRoman Divacky } 1637f22ef01cSRoman Divacky 16380623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor( 16393861d79fSDimitry Andric const CXXUuidofExpr* E) { 16403861d79fSDimitry Andric // Sema has verified that IIDSource has a __declspec(uuid()), and that its 16413861d79fSDimitry Andric // well-formed. 1642e7145dcbSDimitry Andric StringRef Uuid = E->getUuidStr(); 1643f785676fSDimitry Andric std::string Name = "_GUID_" + Uuid.lower(); 1644f785676fSDimitry Andric std::replace(Name.begin(), Name.end(), '-', '_'); 16453861d79fSDimitry Andric 1646e7145dcbSDimitry Andric // The UUID descriptor should be pointer aligned. 1647e7145dcbSDimitry Andric CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 16480623d748SDimitry Andric 16493861d79fSDimitry Andric // Look for an existing global. 16503861d79fSDimitry Andric if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 16510623d748SDimitry Andric return ConstantAddress(GV, Alignment); 16523861d79fSDimitry Andric 165339d628a0SDimitry Andric llvm::Constant *Init = EmitUuidofInitializer(Uuid); 16543861d79fSDimitry Andric assert(Init && "failed to initialize as constant"); 16553861d79fSDimitry Andric 165659d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 1657f785676fSDimitry Andric getModule(), Init->getType(), 1658f785676fSDimitry Andric /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 165933956c43SDimitry Andric if (supportsCOMDAT()) 166033956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 16610623d748SDimitry Andric return ConstantAddress(GV, Alignment); 16623861d79fSDimitry Andric } 16633861d79fSDimitry Andric 16640623d748SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 1665f22ef01cSRoman Divacky const AliasAttr *AA = VD->getAttr<AliasAttr>(); 1666f22ef01cSRoman Divacky assert(AA && "No alias?"); 1667f22ef01cSRoman Divacky 16680623d748SDimitry Andric CharUnits Alignment = getContext().getDeclAlign(VD); 16696122f3e6SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 1670f22ef01cSRoman Divacky 1671f22ef01cSRoman Divacky // See if there is already something with the target's name in the module. 1672f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 16733861d79fSDimitry Andric if (Entry) { 16743861d79fSDimitry Andric unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 16750623d748SDimitry Andric auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 16760623d748SDimitry Andric return ConstantAddress(Ptr, Alignment); 16773861d79fSDimitry Andric } 1678f22ef01cSRoman Divacky 1679f22ef01cSRoman Divacky llvm::Constant *Aliasee; 1680f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(DeclTy)) 16813861d79fSDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 16823861d79fSDimitry Andric GlobalDecl(cast<FunctionDecl>(VD)), 16832754fe60SDimitry Andric /*ForVTable=*/false); 1684f22ef01cSRoman Divacky else 1685f22ef01cSRoman Divacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 168659d1ed5bSDimitry Andric llvm::PointerType::getUnqual(DeclTy), 168759d1ed5bSDimitry Andric nullptr); 16883861d79fSDimitry Andric 168959d1ed5bSDimitry Andric auto *F = cast<llvm::GlobalValue>(Aliasee); 1690f22ef01cSRoman Divacky F->setLinkage(llvm::Function::ExternalWeakLinkage); 1691f22ef01cSRoman Divacky WeakRefReferences.insert(F); 1692f22ef01cSRoman Divacky 16930623d748SDimitry Andric return ConstantAddress(Aliasee, Alignment); 1694f22ef01cSRoman Divacky } 1695f22ef01cSRoman Divacky 1696f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) { 169759d1ed5bSDimitry Andric const auto *Global = cast<ValueDecl>(GD.getDecl()); 1698f22ef01cSRoman Divacky 1699f22ef01cSRoman Divacky // Weak references don't produce any output by themselves. 1700f22ef01cSRoman Divacky if (Global->hasAttr<WeakRefAttr>()) 1701f22ef01cSRoman Divacky return; 1702f22ef01cSRoman Divacky 1703f22ef01cSRoman Divacky // If this is an alias definition (which otherwise looks like a declaration) 1704f22ef01cSRoman Divacky // emit it now. 1705f22ef01cSRoman Divacky if (Global->hasAttr<AliasAttr>()) 1706f22ef01cSRoman Divacky return EmitAliasDefinition(GD); 1707f22ef01cSRoman Divacky 1708e7145dcbSDimitry Andric // IFunc like an alias whose value is resolved at runtime by calling resolver. 1709e7145dcbSDimitry Andric if (Global->hasAttr<IFuncAttr>()) 1710e7145dcbSDimitry Andric return emitIFuncDefinition(GD); 1711e7145dcbSDimitry Andric 17126122f3e6SDimitry Andric // If this is CUDA, be selective about which declarations we emit. 1713dff0c46cSDimitry Andric if (LangOpts.CUDA) { 171433956c43SDimitry Andric if (LangOpts.CUDAIsDevice) { 17156122f3e6SDimitry Andric if (!Global->hasAttr<CUDADeviceAttr>() && 17166122f3e6SDimitry Andric !Global->hasAttr<CUDAGlobalAttr>() && 17176122f3e6SDimitry Andric !Global->hasAttr<CUDAConstantAttr>() && 17186122f3e6SDimitry Andric !Global->hasAttr<CUDASharedAttr>()) 17196122f3e6SDimitry Andric return; 17206122f3e6SDimitry Andric } else { 1721e7145dcbSDimitry Andric // We need to emit host-side 'shadows' for all global 1722e7145dcbSDimitry Andric // device-side variables because the CUDA runtime needs their 1723e7145dcbSDimitry Andric // size and host-side address in order to provide access to 1724e7145dcbSDimitry Andric // their device-side incarnations. 1725e7145dcbSDimitry Andric 1726e7145dcbSDimitry Andric // So device-only functions are the only things we skip. 1727e7145dcbSDimitry Andric if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 1728e7145dcbSDimitry Andric Global->hasAttr<CUDADeviceAttr>()) 17296122f3e6SDimitry Andric return; 1730e7145dcbSDimitry Andric 1731e7145dcbSDimitry Andric assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 1732e7145dcbSDimitry Andric "Expected Variable or Function"); 1733e580952dSDimitry Andric } 1734e580952dSDimitry Andric } 1735e580952dSDimitry Andric 1736e7145dcbSDimitry Andric if (LangOpts.OpenMP) { 1737ea942507SDimitry Andric // If this is OpenMP device, check if it is legal to emit this global 1738ea942507SDimitry Andric // normally. 1739ea942507SDimitry Andric if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 1740ea942507SDimitry Andric return; 1741e7145dcbSDimitry Andric if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 1742e7145dcbSDimitry Andric if (MustBeEmitted(Global)) 1743e7145dcbSDimitry Andric EmitOMPDeclareReduction(DRD); 1744e7145dcbSDimitry Andric return; 1745e7145dcbSDimitry Andric } 1746e7145dcbSDimitry Andric } 1747ea942507SDimitry Andric 17486122f3e6SDimitry Andric // Ignore declarations, they will be emitted on their first use. 174959d1ed5bSDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 1750f22ef01cSRoman Divacky // Forward declarations are emitted lazily on first use. 17516122f3e6SDimitry Andric if (!FD->doesThisDeclarationHaveABody()) { 17526122f3e6SDimitry Andric if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 1753f22ef01cSRoman Divacky return; 17546122f3e6SDimitry Andric 17556122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 175659d1ed5bSDimitry Andric 175759d1ed5bSDimitry Andric // Compute the function info and LLVM type. 175859d1ed5bSDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 175959d1ed5bSDimitry Andric llvm::Type *Ty = getTypes().GetFunctionType(FI); 176059d1ed5bSDimitry Andric 176159d1ed5bSDimitry Andric GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 176259d1ed5bSDimitry Andric /*DontDefer=*/false); 17636122f3e6SDimitry Andric return; 17646122f3e6SDimitry Andric } 1765f22ef01cSRoman Divacky } else { 176659d1ed5bSDimitry Andric const auto *VD = cast<VarDecl>(Global); 1767f22ef01cSRoman Divacky assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 1768e7145dcbSDimitry Andric // We need to emit device-side global CUDA variables even if a 1769e7145dcbSDimitry Andric // variable does not have a definition -- we still need to define 1770e7145dcbSDimitry Andric // host-side shadow for it. 1771e7145dcbSDimitry Andric bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice && 1772e7145dcbSDimitry Andric !VD->hasDefinition() && 1773e7145dcbSDimitry Andric (VD->hasAttr<CUDAConstantAttr>() || 1774e7145dcbSDimitry Andric VD->hasAttr<CUDADeviceAttr>()); 1775e7145dcbSDimitry Andric if (!MustEmitForCuda && 1776e7145dcbSDimitry Andric VD->isThisDeclarationADefinition() != VarDecl::Definition && 1777e7145dcbSDimitry Andric !Context.isMSStaticDataMemberInlineDefinition(VD)) { 1778e7145dcbSDimitry Andric // If this declaration may have caused an inline variable definition to 1779e7145dcbSDimitry Andric // change linkage, make sure that it's emitted. 1780e7145dcbSDimitry Andric if (Context.getInlineVariableDefinitionKind(VD) == 1781e7145dcbSDimitry Andric ASTContext::InlineVariableDefinitionKind::Strong) 1782e7145dcbSDimitry Andric GetAddrOfGlobalVar(VD); 1783f22ef01cSRoman Divacky return; 1784f22ef01cSRoman Divacky } 1785e7145dcbSDimitry Andric } 1786f22ef01cSRoman Divacky 178739d628a0SDimitry Andric // Defer code generation to first use when possible, e.g. if this is an inline 178839d628a0SDimitry Andric // function. If the global must always be emitted, do it eagerly if possible 178939d628a0SDimitry Andric // to benefit from cache locality. 179039d628a0SDimitry Andric if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 1791f22ef01cSRoman Divacky // Emit the definition if it can't be deferred. 1792f22ef01cSRoman Divacky EmitGlobalDefinition(GD); 1793f22ef01cSRoman Divacky return; 1794f22ef01cSRoman Divacky } 1795f22ef01cSRoman Divacky 1796e580952dSDimitry Andric // If we're deferring emission of a C++ variable with an 1797e580952dSDimitry Andric // initializer, remember the order in which it appeared in the file. 1798dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 1799e580952dSDimitry Andric cast<VarDecl>(Global)->hasInit()) { 1800e580952dSDimitry Andric DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 180159d1ed5bSDimitry Andric CXXGlobalInits.push_back(nullptr); 1802e580952dSDimitry Andric } 1803e580952dSDimitry Andric 18046122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 1805f37b6182SDimitry Andric if (GetGlobalValue(MangledName) != nullptr) { 180639d628a0SDimitry Andric // The value has already been used and should therefore be emitted. 1807f37b6182SDimitry Andric addDeferredDeclToEmit(GD); 180839d628a0SDimitry Andric } else if (MustBeEmitted(Global)) { 180939d628a0SDimitry Andric // The value must be emitted, but cannot be emitted eagerly. 181039d628a0SDimitry Andric assert(!MayBeEmittedEagerly(Global)); 1811f37b6182SDimitry Andric addDeferredDeclToEmit(GD); 181239d628a0SDimitry Andric } else { 1813f22ef01cSRoman Divacky // Otherwise, remember that we saw a deferred decl with this name. The 1814f22ef01cSRoman Divacky // first use of the mangled name will cause it to move into 1815f22ef01cSRoman Divacky // DeferredDeclsToEmit. 1816f22ef01cSRoman Divacky DeferredDecls[MangledName] = GD; 1817f22ef01cSRoman Divacky } 1818f22ef01cSRoman Divacky } 1819f22ef01cSRoman Divacky 182020e90f04SDimitry Andric // Check if T is a class type with a destructor that's not dllimport. 182120e90f04SDimitry Andric static bool HasNonDllImportDtor(QualType T) { 182220e90f04SDimitry Andric if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) 182320e90f04SDimitry Andric if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 182420e90f04SDimitry Andric if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) 182520e90f04SDimitry Andric return true; 182620e90f04SDimitry Andric 182720e90f04SDimitry Andric return false; 182820e90f04SDimitry Andric } 182920e90f04SDimitry Andric 1830f8254f43SDimitry Andric namespace { 1831f8254f43SDimitry Andric struct FunctionIsDirectlyRecursive : 1832f8254f43SDimitry Andric public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 1833f8254f43SDimitry Andric const StringRef Name; 1834dff0c46cSDimitry Andric const Builtin::Context &BI; 1835f8254f43SDimitry Andric bool Result; 1836dff0c46cSDimitry Andric FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 1837dff0c46cSDimitry Andric Name(N), BI(C), Result(false) { 1838f8254f43SDimitry Andric } 1839f8254f43SDimitry Andric typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 1840f8254f43SDimitry Andric 1841f8254f43SDimitry Andric bool TraverseCallExpr(CallExpr *E) { 1842dff0c46cSDimitry Andric const FunctionDecl *FD = E->getDirectCallee(); 1843dff0c46cSDimitry Andric if (!FD) 1844f8254f43SDimitry Andric return true; 1845dff0c46cSDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1846dff0c46cSDimitry Andric if (Attr && Name == Attr->getLabel()) { 1847dff0c46cSDimitry Andric Result = true; 1848dff0c46cSDimitry Andric return false; 1849dff0c46cSDimitry Andric } 1850dff0c46cSDimitry Andric unsigned BuiltinID = FD->getBuiltinID(); 18513dac3a9bSDimitry Andric if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 1852f8254f43SDimitry Andric return true; 18530623d748SDimitry Andric StringRef BuiltinName = BI.getName(BuiltinID); 1854dff0c46cSDimitry Andric if (BuiltinName.startswith("__builtin_") && 1855dff0c46cSDimitry Andric Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 1856f8254f43SDimitry Andric Result = true; 1857f8254f43SDimitry Andric return false; 1858f8254f43SDimitry Andric } 1859f8254f43SDimitry Andric return true; 1860f8254f43SDimitry Andric } 1861f8254f43SDimitry Andric }; 18620623d748SDimitry Andric 186320e90f04SDimitry Andric // Make sure we're not referencing non-imported vars or functions. 18640623d748SDimitry Andric struct DLLImportFunctionVisitor 18650623d748SDimitry Andric : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 18660623d748SDimitry Andric bool SafeToInline = true; 18670623d748SDimitry Andric 186844290647SDimitry Andric bool shouldVisitImplicitCode() const { return true; } 186944290647SDimitry Andric 18700623d748SDimitry Andric bool VisitVarDecl(VarDecl *VD) { 187120e90f04SDimitry Andric if (VD->getTLSKind()) { 18720623d748SDimitry Andric // A thread-local variable cannot be imported. 187320e90f04SDimitry Andric SafeToInline = false; 18740623d748SDimitry Andric return SafeToInline; 18750623d748SDimitry Andric } 18760623d748SDimitry Andric 187720e90f04SDimitry Andric // A variable definition might imply a destructor call. 187820e90f04SDimitry Andric if (VD->isThisDeclarationADefinition()) 187920e90f04SDimitry Andric SafeToInline = !HasNonDllImportDtor(VD->getType()); 188020e90f04SDimitry Andric 188120e90f04SDimitry Andric return SafeToInline; 188220e90f04SDimitry Andric } 188320e90f04SDimitry Andric 188420e90f04SDimitry Andric bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 188520e90f04SDimitry Andric if (const auto *D = E->getTemporary()->getDestructor()) 188620e90f04SDimitry Andric SafeToInline = D->hasAttr<DLLImportAttr>(); 188720e90f04SDimitry Andric return SafeToInline; 188820e90f04SDimitry Andric } 188920e90f04SDimitry Andric 18900623d748SDimitry Andric bool VisitDeclRefExpr(DeclRefExpr *E) { 18910623d748SDimitry Andric ValueDecl *VD = E->getDecl(); 18920623d748SDimitry Andric if (isa<FunctionDecl>(VD)) 18930623d748SDimitry Andric SafeToInline = VD->hasAttr<DLLImportAttr>(); 18940623d748SDimitry Andric else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 18950623d748SDimitry Andric SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 18960623d748SDimitry Andric return SafeToInline; 18970623d748SDimitry Andric } 189820e90f04SDimitry Andric 189944290647SDimitry Andric bool VisitCXXConstructExpr(CXXConstructExpr *E) { 190044290647SDimitry Andric SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); 190144290647SDimitry Andric return SafeToInline; 190244290647SDimitry Andric } 190320e90f04SDimitry Andric 190420e90f04SDimitry Andric bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 190520e90f04SDimitry Andric CXXMethodDecl *M = E->getMethodDecl(); 190620e90f04SDimitry Andric if (!M) { 190720e90f04SDimitry Andric // Call through a pointer to member function. This is safe to inline. 190820e90f04SDimitry Andric SafeToInline = true; 190920e90f04SDimitry Andric } else { 191020e90f04SDimitry Andric SafeToInline = M->hasAttr<DLLImportAttr>(); 191120e90f04SDimitry Andric } 191220e90f04SDimitry Andric return SafeToInline; 191320e90f04SDimitry Andric } 191420e90f04SDimitry Andric 19150623d748SDimitry Andric bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 19160623d748SDimitry Andric SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 19170623d748SDimitry Andric return SafeToInline; 19180623d748SDimitry Andric } 191920e90f04SDimitry Andric 19200623d748SDimitry Andric bool VisitCXXNewExpr(CXXNewExpr *E) { 19210623d748SDimitry Andric SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 19220623d748SDimitry Andric return SafeToInline; 19230623d748SDimitry Andric } 19240623d748SDimitry Andric }; 1925f8254f43SDimitry Andric } 1926f8254f43SDimitry Andric 1927dff0c46cSDimitry Andric // isTriviallyRecursive - Check if this function calls another 1928dff0c46cSDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin, 1929dff0c46cSDimitry Andric // ends up pointing to itself. 1930f8254f43SDimitry Andric bool 1931dff0c46cSDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 1932dff0c46cSDimitry Andric StringRef Name; 1933dff0c46cSDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 1934dff0c46cSDimitry Andric // asm labels are a special kind of mangling we have to support. 1935dff0c46cSDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1936dff0c46cSDimitry Andric if (!Attr) 1937f8254f43SDimitry Andric return false; 1938dff0c46cSDimitry Andric Name = Attr->getLabel(); 1939dff0c46cSDimitry Andric } else { 1940dff0c46cSDimitry Andric Name = FD->getName(); 1941dff0c46cSDimitry Andric } 1942f8254f43SDimitry Andric 1943dff0c46cSDimitry Andric FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 1944dff0c46cSDimitry Andric Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 1945f8254f43SDimitry Andric return Walker.Result; 1946f8254f43SDimitry Andric } 1947f8254f43SDimitry Andric 194844290647SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 1949f785676fSDimitry Andric if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 1950f8254f43SDimitry Andric return true; 195159d1ed5bSDimitry Andric const auto *F = cast<FunctionDecl>(GD.getDecl()); 195259d1ed5bSDimitry Andric if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 1953f8254f43SDimitry Andric return false; 19540623d748SDimitry Andric 19550623d748SDimitry Andric if (F->hasAttr<DLLImportAttr>()) { 19560623d748SDimitry Andric // Check whether it would be safe to inline this dllimport function. 19570623d748SDimitry Andric DLLImportFunctionVisitor Visitor; 19580623d748SDimitry Andric Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 19590623d748SDimitry Andric if (!Visitor.SafeToInline) 19600623d748SDimitry Andric return false; 196144290647SDimitry Andric 196244290647SDimitry Andric if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { 196344290647SDimitry Andric // Implicit destructor invocations aren't captured in the AST, so the 196444290647SDimitry Andric // check above can't see them. Check for them manually here. 196544290647SDimitry Andric for (const Decl *Member : Dtor->getParent()->decls()) 196644290647SDimitry Andric if (isa<FieldDecl>(Member)) 196744290647SDimitry Andric if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) 196844290647SDimitry Andric return false; 196944290647SDimitry Andric for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) 197044290647SDimitry Andric if (HasNonDllImportDtor(B.getType())) 197144290647SDimitry Andric return false; 197244290647SDimitry Andric } 19730623d748SDimitry Andric } 19740623d748SDimitry Andric 1975f8254f43SDimitry Andric // PR9614. Avoid cases where the source code is lying to us. An available 1976f8254f43SDimitry Andric // externally function should have an equivalent function somewhere else, 1977f8254f43SDimitry Andric // but a function that calls itself is clearly not equivalent to the real 1978f8254f43SDimitry Andric // implementation. 1979f8254f43SDimitry Andric // This happens in glibc's btowc and in some configure checks. 1980dff0c46cSDimitry Andric return !isTriviallyRecursive(F); 1981f8254f43SDimitry Andric } 1982f8254f43SDimitry Andric 1983f9448bf3SDimitry Andric bool CodeGenModule::shouldOpportunisticallyEmitVTables() { 1984f9448bf3SDimitry Andric return CodeGenOpts.OptimizationLevel > 0; 1985f9448bf3SDimitry Andric } 1986f9448bf3SDimitry Andric 198759d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 198859d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 1989f22ef01cSRoman Divacky 1990f22ef01cSRoman Divacky PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 1991f22ef01cSRoman Divacky Context.getSourceManager(), 1992f22ef01cSRoman Divacky "Generating code for declaration"); 1993f22ef01cSRoman Divacky 1994f785676fSDimitry Andric if (isa<FunctionDecl>(D)) { 1995ffd1746dSEd Schouten // At -O0, don't generate IR for functions with available_externally 1996ffd1746dSEd Schouten // linkage. 1997f785676fSDimitry Andric if (!shouldEmitFunction(GD)) 1998ffd1746dSEd Schouten return; 1999ffd1746dSEd Schouten 200059d1ed5bSDimitry Andric if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 2001bd5abe19SDimitry Andric // Make sure to emit the definition(s) before we emit the thunks. 2002bd5abe19SDimitry Andric // This is necessary for the generation of certain thunks. 200359d1ed5bSDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method)) 200439d628a0SDimitry Andric ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType())); 200559d1ed5bSDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method)) 200639d628a0SDimitry Andric ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType())); 2007bd5abe19SDimitry Andric else 200859d1ed5bSDimitry Andric EmitGlobalFunctionDefinition(GD, GV); 2009bd5abe19SDimitry Andric 2010f22ef01cSRoman Divacky if (Method->isVirtual()) 2011f22ef01cSRoman Divacky getVTables().EmitThunks(GD); 2012f22ef01cSRoman Divacky 2013bd5abe19SDimitry Andric return; 2014ffd1746dSEd Schouten } 2015f22ef01cSRoman Divacky 201659d1ed5bSDimitry Andric return EmitGlobalFunctionDefinition(GD, GV); 2017ffd1746dSEd Schouten } 2018f22ef01cSRoman Divacky 201959d1ed5bSDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 2020e7145dcbSDimitry Andric return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 2021f22ef01cSRoman Divacky 20226122f3e6SDimitry Andric llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 2023f22ef01cSRoman Divacky } 2024f22ef01cSRoman Divacky 20250623d748SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 20260623d748SDimitry Andric llvm::Function *NewFn); 20270623d748SDimitry Andric 2028f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 2029f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there 2030f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially 2031f22ef01cSRoman Divacky /// bitcasted to the right type. 2032f22ef01cSRoman Divacky /// 2033f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this. This is used 2034f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created. 203520e90f04SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( 203620e90f04SDimitry Andric StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, 203720e90f04SDimitry Andric bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, 203844290647SDimitry Andric ForDefinition_t IsForDefinition) { 2039f785676fSDimitry Andric const Decl *D = GD.getDecl(); 2040f785676fSDimitry Andric 2041f22ef01cSRoman Divacky // Lookup the entry, lazily creating it if necessary. 2042f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2043f22ef01cSRoman Divacky if (Entry) { 20443861d79fSDimitry Andric if (WeakRefReferences.erase(Entry)) { 2045f785676fSDimitry Andric const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 2046f22ef01cSRoman Divacky if (FD && !FD->hasAttr<WeakAttr>()) 2047f22ef01cSRoman Divacky Entry->setLinkage(llvm::Function::ExternalLinkage); 2048f22ef01cSRoman Divacky } 2049f22ef01cSRoman Divacky 205039d628a0SDimitry Andric // Handle dropped DLL attributes. 205139d628a0SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 205239d628a0SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 205339d628a0SDimitry Andric 20540623d748SDimitry Andric // If there are two attempts to define the same mangled name, issue an 20550623d748SDimitry Andric // error. 20560623d748SDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 20570623d748SDimitry Andric GlobalDecl OtherGD; 2058e7145dcbSDimitry Andric // Check that GD is not yet in DiagnosedConflictingDefinitions is required 2059e7145dcbSDimitry Andric // to make sure that we issue an error only once. 20600623d748SDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 20610623d748SDimitry Andric (GD.getCanonicalDecl().getDecl() != 20620623d748SDimitry Andric OtherGD.getCanonicalDecl().getDecl()) && 20630623d748SDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 20640623d748SDimitry Andric getDiags().Report(D->getLocation(), 20650623d748SDimitry Andric diag::err_duplicate_mangled_name); 20660623d748SDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 20670623d748SDimitry Andric diag::note_previous_definition); 20680623d748SDimitry Andric } 20690623d748SDimitry Andric } 20700623d748SDimitry Andric 20710623d748SDimitry Andric if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 20720623d748SDimitry Andric (Entry->getType()->getElementType() == Ty)) { 2073f22ef01cSRoman Divacky return Entry; 20740623d748SDimitry Andric } 2075f22ef01cSRoman Divacky 2076f22ef01cSRoman Divacky // Make sure the result is of the correct type. 20770623d748SDimitry Andric // (If function is requested for a definition, we always need to create a new 20780623d748SDimitry Andric // function, not just return a bitcast.) 20790623d748SDimitry Andric if (!IsForDefinition) 208017a519f9SDimitry Andric return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 2081f22ef01cSRoman Divacky } 2082f22ef01cSRoman Divacky 2083f22ef01cSRoman Divacky // This function doesn't have a complete type (for example, the return 2084f22ef01cSRoman Divacky // type is an incomplete struct). Use a fake type instead, and make 2085f22ef01cSRoman Divacky // sure not to try to set attributes. 2086f22ef01cSRoman Divacky bool IsIncompleteFunction = false; 2087f22ef01cSRoman Divacky 20886122f3e6SDimitry Andric llvm::FunctionType *FTy; 2089f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(Ty)) { 2090f22ef01cSRoman Divacky FTy = cast<llvm::FunctionType>(Ty); 2091f22ef01cSRoman Divacky } else { 2092bd5abe19SDimitry Andric FTy = llvm::FunctionType::get(VoidTy, false); 2093f22ef01cSRoman Divacky IsIncompleteFunction = true; 2094f22ef01cSRoman Divacky } 2095ffd1746dSEd Schouten 20960623d748SDimitry Andric llvm::Function *F = 20970623d748SDimitry Andric llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 20980623d748SDimitry Andric Entry ? StringRef() : MangledName, &getModule()); 20990623d748SDimitry Andric 21000623d748SDimitry Andric // If we already created a function with the same mangled name (but different 21010623d748SDimitry Andric // type) before, take its name and add it to the list of functions to be 21020623d748SDimitry Andric // replaced with F at the end of CodeGen. 21030623d748SDimitry Andric // 21040623d748SDimitry Andric // This happens if there is a prototype for a function (e.g. "int f()") and 21050623d748SDimitry Andric // then a definition of a different type (e.g. "int f(int x)"). 21060623d748SDimitry Andric if (Entry) { 21070623d748SDimitry Andric F->takeName(Entry); 21080623d748SDimitry Andric 21090623d748SDimitry Andric // This might be an implementation of a function without a prototype, in 21100623d748SDimitry Andric // which case, try to do special replacement of calls which match the new 21110623d748SDimitry Andric // prototype. The really key thing here is that we also potentially drop 21120623d748SDimitry Andric // arguments from the call site so as to make a direct call, which makes the 21130623d748SDimitry Andric // inliner happier and suppresses a number of optimizer warnings (!) about 21140623d748SDimitry Andric // dropping arguments. 21150623d748SDimitry Andric if (!Entry->use_empty()) { 21160623d748SDimitry Andric ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 21170623d748SDimitry Andric Entry->removeDeadConstantUsers(); 21180623d748SDimitry Andric } 21190623d748SDimitry Andric 21200623d748SDimitry Andric llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 21210623d748SDimitry Andric F, Entry->getType()->getElementType()->getPointerTo()); 21220623d748SDimitry Andric addGlobalValReplacement(Entry, BC); 21230623d748SDimitry Andric } 21240623d748SDimitry Andric 2125f22ef01cSRoman Divacky assert(F->getName() == MangledName && "name was uniqued!"); 2126f785676fSDimitry Andric if (D) 212739d628a0SDimitry Andric SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 212820e90f04SDimitry Andric if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) { 212920e90f04SDimitry Andric llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex); 2130f37b6182SDimitry Andric F->addAttributes(llvm::AttributeList::FunctionIndex, B); 2131139f7f9bSDimitry Andric } 2132f22ef01cSRoman Divacky 213359d1ed5bSDimitry Andric if (!DontDefer) { 213459d1ed5bSDimitry Andric // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 213559d1ed5bSDimitry Andric // each other bottoming out with the base dtor. Therefore we emit non-base 213659d1ed5bSDimitry Andric // dtors on usage, even if there is no dtor definition in the TU. 213759d1ed5bSDimitry Andric if (D && isa<CXXDestructorDecl>(D) && 213859d1ed5bSDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 213959d1ed5bSDimitry Andric GD.getDtorType())) 2140f37b6182SDimitry Andric addDeferredDeclToEmit(GD); 214159d1ed5bSDimitry Andric 2142f22ef01cSRoman Divacky // This is the first use or definition of a mangled name. If there is a 2143f22ef01cSRoman Divacky // deferred decl with this name, remember that we need to emit it at the end 2144f22ef01cSRoman Divacky // of the file. 214559d1ed5bSDimitry Andric auto DDI = DeferredDecls.find(MangledName); 2146f22ef01cSRoman Divacky if (DDI != DeferredDecls.end()) { 214759d1ed5bSDimitry Andric // Move the potentially referenced deferred decl to the 214859d1ed5bSDimitry Andric // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 214959d1ed5bSDimitry Andric // don't need it anymore). 2150f37b6182SDimitry Andric addDeferredDeclToEmit(DDI->second); 2151f22ef01cSRoman Divacky DeferredDecls.erase(DDI); 21522754fe60SDimitry Andric 21532754fe60SDimitry Andric // Otherwise, there are cases we have to worry about where we're 21542754fe60SDimitry Andric // using a declaration for which we must emit a definition but where 21552754fe60SDimitry Andric // we might not find a top-level definition: 21562754fe60SDimitry Andric // - member functions defined inline in their classes 21572754fe60SDimitry Andric // - friend functions defined inline in some class 21582754fe60SDimitry Andric // - special member functions with implicit definitions 21592754fe60SDimitry Andric // If we ever change our AST traversal to walk into class methods, 21602754fe60SDimitry Andric // this will be unnecessary. 21612754fe60SDimitry Andric // 216259d1ed5bSDimitry Andric // We also don't emit a definition for a function if it's going to be an 216339d628a0SDimitry Andric // entry in a vtable, unless it's already marked as used. 2164f785676fSDimitry Andric } else if (getLangOpts().CPlusPlus && D) { 21652754fe60SDimitry Andric // Look for a declaration that's lexically in a record. 216639d628a0SDimitry Andric for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 216739d628a0SDimitry Andric FD = FD->getPreviousDecl()) { 21682754fe60SDimitry Andric if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 216939d628a0SDimitry Andric if (FD->doesThisDeclarationHaveABody()) { 2170f37b6182SDimitry Andric addDeferredDeclToEmit(GD.getWithDecl(FD)); 21712754fe60SDimitry Andric break; 2172f22ef01cSRoman Divacky } 2173f22ef01cSRoman Divacky } 217439d628a0SDimitry Andric } 2175f22ef01cSRoman Divacky } 217659d1ed5bSDimitry Andric } 2177f22ef01cSRoman Divacky 2178f22ef01cSRoman Divacky // Make sure the result is of the requested type. 2179f22ef01cSRoman Divacky if (!IsIncompleteFunction) { 2180f22ef01cSRoman Divacky assert(F->getType()->getElementType() == Ty); 2181f22ef01cSRoman Divacky return F; 2182f22ef01cSRoman Divacky } 2183f22ef01cSRoman Divacky 218417a519f9SDimitry Andric llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 2185f22ef01cSRoman Divacky return llvm::ConstantExpr::getBitCast(F, PTy); 2186f22ef01cSRoman Divacky } 2187f22ef01cSRoman Divacky 2188f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function. If Ty is 2189f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to 2190f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function). 2191f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 21926122f3e6SDimitry Andric llvm::Type *Ty, 219359d1ed5bSDimitry Andric bool ForVTable, 21940623d748SDimitry Andric bool DontDefer, 219544290647SDimitry Andric ForDefinition_t IsForDefinition) { 2196f22ef01cSRoman Divacky // If there was no specific requested type, just convert it now. 21970623d748SDimitry Andric if (!Ty) { 21980623d748SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 21990623d748SDimitry Andric auto CanonTy = Context.getCanonicalType(FD->getType()); 22000623d748SDimitry Andric Ty = getTypes().ConvertFunctionType(CanonTy, FD); 22010623d748SDimitry Andric } 2202ffd1746dSEd Schouten 22036122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 22040623d748SDimitry Andric return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 220520e90f04SDimitry Andric /*IsThunk=*/false, llvm::AttributeList(), 22060623d748SDimitry Andric IsForDefinition); 2207f22ef01cSRoman Divacky } 2208f22ef01cSRoman Divacky 220944290647SDimitry Andric static const FunctionDecl * 221044290647SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { 221144290647SDimitry Andric TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 221244290647SDimitry Andric DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 221344290647SDimitry Andric 221444290647SDimitry Andric IdentifierInfo &CII = C.Idents.get(Name); 221544290647SDimitry Andric for (const auto &Result : DC->lookup(&CII)) 221644290647SDimitry Andric if (const auto FD = dyn_cast<FunctionDecl>(Result)) 221744290647SDimitry Andric return FD; 221844290647SDimitry Andric 221944290647SDimitry Andric if (!C.getLangOpts().CPlusPlus) 222044290647SDimitry Andric return nullptr; 222144290647SDimitry Andric 222244290647SDimitry Andric // Demangle the premangled name from getTerminateFn() 222344290647SDimitry Andric IdentifierInfo &CXXII = 222444290647SDimitry Andric (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ") 222544290647SDimitry Andric ? C.Idents.get("terminate") 222644290647SDimitry Andric : C.Idents.get(Name); 222744290647SDimitry Andric 222844290647SDimitry Andric for (const auto &N : {"__cxxabiv1", "std"}) { 222944290647SDimitry Andric IdentifierInfo &NS = C.Idents.get(N); 223044290647SDimitry Andric for (const auto &Result : DC->lookup(&NS)) { 223144290647SDimitry Andric NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); 223244290647SDimitry Andric if (auto LSD = dyn_cast<LinkageSpecDecl>(Result)) 223344290647SDimitry Andric for (const auto &Result : LSD->lookup(&NS)) 223444290647SDimitry Andric if ((ND = dyn_cast<NamespaceDecl>(Result))) 223544290647SDimitry Andric break; 223644290647SDimitry Andric 223744290647SDimitry Andric if (ND) 223844290647SDimitry Andric for (const auto &Result : ND->lookup(&CXXII)) 223944290647SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 224044290647SDimitry Andric return FD; 224144290647SDimitry Andric } 224244290647SDimitry Andric } 224344290647SDimitry Andric 224444290647SDimitry Andric return nullptr; 224544290647SDimitry Andric } 224644290647SDimitry Andric 2247f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified 2248f22ef01cSRoman Divacky /// type and name. 2249f22ef01cSRoman Divacky llvm::Constant * 225044290647SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, 225120e90f04SDimitry Andric llvm::AttributeList ExtraAttrs, 225244290647SDimitry Andric bool Local) { 225359d1ed5bSDimitry Andric llvm::Constant *C = 225459d1ed5bSDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 225544290647SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, 225644290647SDimitry Andric ExtraAttrs); 225744290647SDimitry Andric 225844290647SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) { 225944290647SDimitry Andric if (F->empty()) { 2260139f7f9bSDimitry Andric F->setCallingConv(getRuntimeCC()); 226144290647SDimitry Andric 226244290647SDimitry Andric if (!Local && getTriple().isOSBinFormatCOFF() && 226344290647SDimitry Andric !getCodeGenOpts().LTOVisibilityPublicStd) { 226444290647SDimitry Andric const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); 226544290647SDimitry Andric if (!FD || FD->hasAttr<DLLImportAttr>()) { 226644290647SDimitry Andric F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 226744290647SDimitry Andric F->setLinkage(llvm::GlobalValue::ExternalLinkage); 226844290647SDimitry Andric } 226944290647SDimitry Andric } 227044290647SDimitry Andric } 227144290647SDimitry Andric } 227244290647SDimitry Andric 2273139f7f9bSDimitry Andric return C; 2274f22ef01cSRoman Divacky } 2275f22ef01cSRoman Divacky 227639d628a0SDimitry Andric /// CreateBuiltinFunction - Create a new builtin function with the specified 227739d628a0SDimitry Andric /// type and name. 227839d628a0SDimitry Andric llvm::Constant * 227920e90f04SDimitry Andric CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name, 228020e90f04SDimitry Andric llvm::AttributeList ExtraAttrs) { 228139d628a0SDimitry Andric llvm::Constant *C = 228239d628a0SDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 228339d628a0SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); 228439d628a0SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) 228539d628a0SDimitry Andric if (F->empty()) 228639d628a0SDimitry Andric F->setCallingConv(getBuiltinCC()); 228739d628a0SDimitry Andric return C; 228839d628a0SDimitry Andric } 228939d628a0SDimitry Andric 2290dff0c46cSDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted 2291dff0c46cSDimitry Andric /// as a constant. 2292dff0c46cSDimitry Andric /// 2293dff0c46cSDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs 2294dff0c46cSDimitry Andric /// will not be considered. The caller will need to verify that the object is 2295dff0c46cSDimitry Andric /// not written to during its construction. 2296dff0c46cSDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 2297dff0c46cSDimitry Andric if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 2298f22ef01cSRoman Divacky return false; 2299bd5abe19SDimitry Andric 2300dff0c46cSDimitry Andric if (Context.getLangOpts().CPlusPlus) { 2301dff0c46cSDimitry Andric if (const CXXRecordDecl *Record 2302dff0c46cSDimitry Andric = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 2303dff0c46cSDimitry Andric return ExcludeCtor && !Record->hasMutableFields() && 2304dff0c46cSDimitry Andric Record->hasTrivialDestructor(); 2305f22ef01cSRoman Divacky } 2306bd5abe19SDimitry Andric 2307f22ef01cSRoman Divacky return true; 2308f22ef01cSRoman Divacky } 2309f22ef01cSRoman Divacky 2310f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 2311f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type. If there 2312f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially 2313f22ef01cSRoman Divacky /// bitcasted to the right type. 2314f22ef01cSRoman Divacky /// 2315f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this. This is used 2316f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created. 2317e7145dcbSDimitry Andric /// 2318e7145dcbSDimitry Andric /// If IsForDefinition is true, it is guranteed that an actual global with 2319e7145dcbSDimitry Andric /// type Ty will be returned, not conversion of a variable with the same 2320e7145dcbSDimitry Andric /// mangled name but some other type. 2321f22ef01cSRoman Divacky llvm::Constant * 23226122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 23236122f3e6SDimitry Andric llvm::PointerType *Ty, 2324e7145dcbSDimitry Andric const VarDecl *D, 232544290647SDimitry Andric ForDefinition_t IsForDefinition) { 2326f22ef01cSRoman Divacky // Lookup the entry, lazily creating it if necessary. 2327f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2328f22ef01cSRoman Divacky if (Entry) { 23293861d79fSDimitry Andric if (WeakRefReferences.erase(Entry)) { 2330f22ef01cSRoman Divacky if (D && !D->hasAttr<WeakAttr>()) 2331f22ef01cSRoman Divacky Entry->setLinkage(llvm::Function::ExternalLinkage); 2332f22ef01cSRoman Divacky } 2333f22ef01cSRoman Divacky 233439d628a0SDimitry Andric // Handle dropped DLL attributes. 233539d628a0SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 233639d628a0SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 233739d628a0SDimitry Andric 2338f22ef01cSRoman Divacky if (Entry->getType() == Ty) 2339f22ef01cSRoman Divacky return Entry; 2340f22ef01cSRoman Divacky 2341e7145dcbSDimitry Andric // If there are two attempts to define the same mangled name, issue an 2342e7145dcbSDimitry Andric // error. 2343e7145dcbSDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 2344e7145dcbSDimitry Andric GlobalDecl OtherGD; 2345e7145dcbSDimitry Andric const VarDecl *OtherD; 2346e7145dcbSDimitry Andric 2347e7145dcbSDimitry Andric // Check that D is not yet in DiagnosedConflictingDefinitions is required 2348e7145dcbSDimitry Andric // to make sure that we issue an error only once. 2349e7145dcbSDimitry Andric if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 2350e7145dcbSDimitry Andric (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 2351e7145dcbSDimitry Andric (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 2352e7145dcbSDimitry Andric OtherD->hasInit() && 2353e7145dcbSDimitry Andric DiagnosedConflictingDefinitions.insert(D).second) { 2354e7145dcbSDimitry Andric getDiags().Report(D->getLocation(), 2355e7145dcbSDimitry Andric diag::err_duplicate_mangled_name); 2356e7145dcbSDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 2357e7145dcbSDimitry Andric diag::note_previous_definition); 2358e7145dcbSDimitry Andric } 2359e7145dcbSDimitry Andric } 2360e7145dcbSDimitry Andric 2361f22ef01cSRoman Divacky // Make sure the result is of the correct type. 2362f785676fSDimitry Andric if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) 2363f785676fSDimitry Andric return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); 2364f785676fSDimitry Andric 2365e7145dcbSDimitry Andric // (If global is requested for a definition, we always need to create a new 2366e7145dcbSDimitry Andric // global, not just return a bitcast.) 2367e7145dcbSDimitry Andric if (!IsForDefinition) 2368f22ef01cSRoman Divacky return llvm::ConstantExpr::getBitCast(Entry, Ty); 2369f22ef01cSRoman Divacky } 2370f22ef01cSRoman Divacky 237159d1ed5bSDimitry Andric unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace()); 237259d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 237359d1ed5bSDimitry Andric getModule(), Ty->getElementType(), false, 237459d1ed5bSDimitry Andric llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr, 237559d1ed5bSDimitry Andric llvm::GlobalVariable::NotThreadLocal, AddrSpace); 237659d1ed5bSDimitry Andric 2377e7145dcbSDimitry Andric // If we already created a global with the same mangled name (but different 2378e7145dcbSDimitry Andric // type) before, take its name and remove it from its parent. 2379e7145dcbSDimitry Andric if (Entry) { 2380e7145dcbSDimitry Andric GV->takeName(Entry); 2381e7145dcbSDimitry Andric 2382e7145dcbSDimitry Andric if (!Entry->use_empty()) { 2383e7145dcbSDimitry Andric llvm::Constant *NewPtrForOldDecl = 2384e7145dcbSDimitry Andric llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 2385e7145dcbSDimitry Andric Entry->replaceAllUsesWith(NewPtrForOldDecl); 2386e7145dcbSDimitry Andric } 2387e7145dcbSDimitry Andric 2388e7145dcbSDimitry Andric Entry->eraseFromParent(); 2389e7145dcbSDimitry Andric } 2390e7145dcbSDimitry Andric 2391f22ef01cSRoman Divacky // This is the first use or definition of a mangled name. If there is a 2392f22ef01cSRoman Divacky // deferred decl with this name, remember that we need to emit it at the end 2393f22ef01cSRoman Divacky // of the file. 239459d1ed5bSDimitry Andric auto DDI = DeferredDecls.find(MangledName); 2395f22ef01cSRoman Divacky if (DDI != DeferredDecls.end()) { 2396f22ef01cSRoman Divacky // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 2397f22ef01cSRoman Divacky // list, and remove it from DeferredDecls (since we don't need it anymore). 2398f37b6182SDimitry Andric addDeferredDeclToEmit(DDI->second); 2399f22ef01cSRoman Divacky DeferredDecls.erase(DDI); 2400f22ef01cSRoman Divacky } 2401f22ef01cSRoman Divacky 2402f22ef01cSRoman Divacky // Handle things which are present even on external declarations. 2403f22ef01cSRoman Divacky if (D) { 2404f22ef01cSRoman Divacky // FIXME: This code is overly simple and should be merged with other global 2405f22ef01cSRoman Divacky // handling. 2406dff0c46cSDimitry Andric GV->setConstant(isTypeConstant(D->getType(), false)); 2407f22ef01cSRoman Divacky 240833956c43SDimitry Andric GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 240933956c43SDimitry Andric 241059d1ed5bSDimitry Andric setLinkageAndVisibilityForGV(GV, D); 24112754fe60SDimitry Andric 2412284c1978SDimitry Andric if (D->getTLSKind()) { 2413284c1978SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 24140623d748SDimitry Andric CXXThreadLocals.push_back(D); 24157ae0e2c9SDimitry Andric setTLSMode(GV, *D); 2416f22ef01cSRoman Divacky } 2417f785676fSDimitry Andric 2418f785676fSDimitry Andric // If required by the ABI, treat declarations of static data members with 2419f785676fSDimitry Andric // inline initializers as definitions. 242059d1ed5bSDimitry Andric if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 2421f785676fSDimitry Andric EmitGlobalVarDefinition(D); 2422284c1978SDimitry Andric } 2423f22ef01cSRoman Divacky 242459d1ed5bSDimitry Andric // Handle XCore specific ABI requirements. 242544290647SDimitry Andric if (getTriple().getArch() == llvm::Triple::xcore && 242659d1ed5bSDimitry Andric D->getLanguageLinkage() == CLanguageLinkage && 242759d1ed5bSDimitry Andric D->getType().isConstant(Context) && 242859d1ed5bSDimitry Andric isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 242959d1ed5bSDimitry Andric GV->setSection(".cp.rodata"); 243059d1ed5bSDimitry Andric } 243159d1ed5bSDimitry Andric 24327ae0e2c9SDimitry Andric if (AddrSpace != Ty->getAddressSpace()) 2433f785676fSDimitry Andric return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty); 2434f785676fSDimitry Andric 2435f22ef01cSRoman Divacky return GV; 2436f22ef01cSRoman Divacky } 2437f22ef01cSRoman Divacky 24380623d748SDimitry Andric llvm::Constant * 24390623d748SDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, 244044290647SDimitry Andric ForDefinition_t IsForDefinition) { 244144290647SDimitry Andric const Decl *D = GD.getDecl(); 244244290647SDimitry Andric if (isa<CXXConstructorDecl>(D)) 244344290647SDimitry Andric return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D), 24440623d748SDimitry Andric getFromCtorType(GD.getCtorType()), 24450623d748SDimitry Andric /*FnInfo=*/nullptr, /*FnType=*/nullptr, 24460623d748SDimitry Andric /*DontDefer=*/false, IsForDefinition); 244744290647SDimitry Andric else if (isa<CXXDestructorDecl>(D)) 244844290647SDimitry Andric return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D), 24490623d748SDimitry Andric getFromDtorType(GD.getDtorType()), 24500623d748SDimitry Andric /*FnInfo=*/nullptr, /*FnType=*/nullptr, 24510623d748SDimitry Andric /*DontDefer=*/false, IsForDefinition); 245244290647SDimitry Andric else if (isa<CXXMethodDecl>(D)) { 24530623d748SDimitry Andric auto FInfo = &getTypes().arrangeCXXMethodDeclaration( 245444290647SDimitry Andric cast<CXXMethodDecl>(D)); 24550623d748SDimitry Andric auto Ty = getTypes().GetFunctionType(*FInfo); 24560623d748SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 24570623d748SDimitry Andric IsForDefinition); 245844290647SDimitry Andric } else if (isa<FunctionDecl>(D)) { 24590623d748SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 24600623d748SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 24610623d748SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 24620623d748SDimitry Andric IsForDefinition); 24630623d748SDimitry Andric } else 246444290647SDimitry Andric return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, 2465e7145dcbSDimitry Andric IsForDefinition); 24660623d748SDimitry Andric } 2467f22ef01cSRoman Divacky 24682754fe60SDimitry Andric llvm::GlobalVariable * 24696122f3e6SDimitry Andric CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 24706122f3e6SDimitry Andric llvm::Type *Ty, 24712754fe60SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage) { 24722754fe60SDimitry Andric llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 247359d1ed5bSDimitry Andric llvm::GlobalVariable *OldGV = nullptr; 24742754fe60SDimitry Andric 24752754fe60SDimitry Andric if (GV) { 24762754fe60SDimitry Andric // Check if the variable has the right type. 24772754fe60SDimitry Andric if (GV->getType()->getElementType() == Ty) 24782754fe60SDimitry Andric return GV; 24792754fe60SDimitry Andric 24802754fe60SDimitry Andric // Because C++ name mangling, the only way we can end up with an already 24812754fe60SDimitry Andric // existing global with the same name is if it has been declared extern "C". 24822754fe60SDimitry Andric assert(GV->isDeclaration() && "Declaration has wrong type!"); 24832754fe60SDimitry Andric OldGV = GV; 24842754fe60SDimitry Andric } 24852754fe60SDimitry Andric 24862754fe60SDimitry Andric // Create a new variable. 24872754fe60SDimitry Andric GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 248859d1ed5bSDimitry Andric Linkage, nullptr, Name); 24892754fe60SDimitry Andric 24902754fe60SDimitry Andric if (OldGV) { 24912754fe60SDimitry Andric // Replace occurrences of the old variable if needed. 24922754fe60SDimitry Andric GV->takeName(OldGV); 24932754fe60SDimitry Andric 24942754fe60SDimitry Andric if (!OldGV->use_empty()) { 24952754fe60SDimitry Andric llvm::Constant *NewPtrForOldDecl = 24962754fe60SDimitry Andric llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 24972754fe60SDimitry Andric OldGV->replaceAllUsesWith(NewPtrForOldDecl); 24982754fe60SDimitry Andric } 24992754fe60SDimitry Andric 25002754fe60SDimitry Andric OldGV->eraseFromParent(); 25012754fe60SDimitry Andric } 25022754fe60SDimitry Andric 250333956c43SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker() && 250433956c43SDimitry Andric !GV->hasAvailableExternallyLinkage()) 250533956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 250633956c43SDimitry Andric 25072754fe60SDimitry Andric return GV; 25082754fe60SDimitry Andric } 25092754fe60SDimitry Andric 2510f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 2511f22ef01cSRoman Divacky /// given global variable. If Ty is non-null and if the global doesn't exist, 2512cb4dff85SDimitry Andric /// then it will be created with the specified type instead of whatever the 2513e7145dcbSDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guranteed 2514e7145dcbSDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a 2515e7145dcbSDimitry Andric /// variable with the same mangled name but some other type. 2516f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 2517e7145dcbSDimitry Andric llvm::Type *Ty, 251844290647SDimitry Andric ForDefinition_t IsForDefinition) { 2519f22ef01cSRoman Divacky assert(D->hasGlobalStorage() && "Not a global variable"); 2520f22ef01cSRoman Divacky QualType ASTTy = D->getType(); 252159d1ed5bSDimitry Andric if (!Ty) 2522f22ef01cSRoman Divacky Ty = getTypes().ConvertTypeForMem(ASTTy); 2523f22ef01cSRoman Divacky 25246122f3e6SDimitry Andric llvm::PointerType *PTy = 25253b0f4066SDimitry Andric llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 2526f22ef01cSRoman Divacky 25276122f3e6SDimitry Andric StringRef MangledName = getMangledName(D); 2528e7145dcbSDimitry Andric return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition); 2529f22ef01cSRoman Divacky } 2530f22ef01cSRoman Divacky 2531f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the 2532f22ef01cSRoman Divacky /// specified type and name. 2533f22ef01cSRoman Divacky llvm::Constant * 25346122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 25356122f3e6SDimitry Andric StringRef Name) { 253659d1ed5bSDimitry Andric return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr); 2537f22ef01cSRoman Divacky } 2538f22ef01cSRoman Divacky 2539f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 2540f22ef01cSRoman Divacky assert(!D->getInit() && "Cannot emit definite definitions here!"); 2541f22ef01cSRoman Divacky 25426122f3e6SDimitry Andric StringRef MangledName = getMangledName(D); 2543e7145dcbSDimitry Andric llvm::GlobalValue *GV = GetGlobalValue(MangledName); 2544e7145dcbSDimitry Andric 2545e7145dcbSDimitry Andric // We already have a definition, not declaration, with the same mangled name. 2546e7145dcbSDimitry Andric // Emitting of declaration is not required (and actually overwrites emitted 2547e7145dcbSDimitry Andric // definition). 2548e7145dcbSDimitry Andric if (GV && !GV->isDeclaration()) 2549e7145dcbSDimitry Andric return; 2550e7145dcbSDimitry Andric 2551e7145dcbSDimitry Andric // If we have not seen a reference to this variable yet, place it into the 2552e7145dcbSDimitry Andric // deferred declarations table to be emitted if needed later. 2553e7145dcbSDimitry Andric if (!MustBeEmitted(D) && !GV) { 2554f22ef01cSRoman Divacky DeferredDecls[MangledName] = D; 2555f22ef01cSRoman Divacky return; 2556f22ef01cSRoman Divacky } 2557f22ef01cSRoman Divacky 2558f22ef01cSRoman Divacky // The tentative definition is the only definition. 2559f22ef01cSRoman Divacky EmitGlobalVarDefinition(D); 2560f22ef01cSRoman Divacky } 2561f22ef01cSRoman Divacky 25626122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 25632754fe60SDimitry Andric return Context.toCharUnitsFromBits( 25640623d748SDimitry Andric getDataLayout().getTypeStoreSizeInBits(Ty)); 2565f22ef01cSRoman Divacky } 2566f22ef01cSRoman Divacky 25677ae0e2c9SDimitry Andric unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D, 25687ae0e2c9SDimitry Andric unsigned AddrSpace) { 2569e7145dcbSDimitry Andric if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) { 25707ae0e2c9SDimitry Andric if (D->hasAttr<CUDAConstantAttr>()) 25717ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant); 25727ae0e2c9SDimitry Andric else if (D->hasAttr<CUDASharedAttr>()) 25737ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared); 25747ae0e2c9SDimitry Andric else 25757ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device); 25767ae0e2c9SDimitry Andric } 25777ae0e2c9SDimitry Andric 25787ae0e2c9SDimitry Andric return AddrSpace; 25797ae0e2c9SDimitry Andric } 25807ae0e2c9SDimitry Andric 2581284c1978SDimitry Andric template<typename SomeDecl> 2582284c1978SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 2583284c1978SDimitry Andric llvm::GlobalValue *GV) { 2584284c1978SDimitry Andric if (!getLangOpts().CPlusPlus) 2585284c1978SDimitry Andric return; 2586284c1978SDimitry Andric 2587284c1978SDimitry Andric // Must have 'used' attribute, or else inline assembly can't rely on 2588284c1978SDimitry Andric // the name existing. 2589284c1978SDimitry Andric if (!D->template hasAttr<UsedAttr>()) 2590284c1978SDimitry Andric return; 2591284c1978SDimitry Andric 2592284c1978SDimitry Andric // Must have internal linkage and an ordinary name. 2593f785676fSDimitry Andric if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 2594284c1978SDimitry Andric return; 2595284c1978SDimitry Andric 2596284c1978SDimitry Andric // Must be in an extern "C" context. Entities declared directly within 2597284c1978SDimitry Andric // a record are not extern "C" even if the record is in such a context. 2598f785676fSDimitry Andric const SomeDecl *First = D->getFirstDecl(); 2599284c1978SDimitry Andric if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 2600284c1978SDimitry Andric return; 2601284c1978SDimitry Andric 2602284c1978SDimitry Andric // OK, this is an internal linkage entity inside an extern "C" linkage 2603284c1978SDimitry Andric // specification. Make a note of that so we can give it the "expected" 2604284c1978SDimitry Andric // mangled name if nothing else is using that name. 2605284c1978SDimitry Andric std::pair<StaticExternCMap::iterator, bool> R = 2606284c1978SDimitry Andric StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 2607284c1978SDimitry Andric 2608284c1978SDimitry Andric // If we have multiple internal linkage entities with the same name 2609284c1978SDimitry Andric // in extern "C" regions, none of them gets that name. 2610284c1978SDimitry Andric if (!R.second) 261159d1ed5bSDimitry Andric R.first->second = nullptr; 2612284c1978SDimitry Andric } 2613284c1978SDimitry Andric 261433956c43SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 261533956c43SDimitry Andric if (!CGM.supportsCOMDAT()) 261633956c43SDimitry Andric return false; 261733956c43SDimitry Andric 261833956c43SDimitry Andric if (D.hasAttr<SelectAnyAttr>()) 261933956c43SDimitry Andric return true; 262033956c43SDimitry Andric 262133956c43SDimitry Andric GVALinkage Linkage; 262233956c43SDimitry Andric if (auto *VD = dyn_cast<VarDecl>(&D)) 262333956c43SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 262433956c43SDimitry Andric else 262533956c43SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 262633956c43SDimitry Andric 262733956c43SDimitry Andric switch (Linkage) { 262833956c43SDimitry Andric case GVA_Internal: 262933956c43SDimitry Andric case GVA_AvailableExternally: 263033956c43SDimitry Andric case GVA_StrongExternal: 263133956c43SDimitry Andric return false; 263233956c43SDimitry Andric case GVA_DiscardableODR: 263333956c43SDimitry Andric case GVA_StrongODR: 263433956c43SDimitry Andric return true; 263533956c43SDimitry Andric } 263633956c43SDimitry Andric llvm_unreachable("No such linkage"); 263733956c43SDimitry Andric } 263833956c43SDimitry Andric 263933956c43SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 264033956c43SDimitry Andric llvm::GlobalObject &GO) { 264133956c43SDimitry Andric if (!shouldBeInCOMDAT(*this, D)) 264233956c43SDimitry Andric return; 264333956c43SDimitry Andric GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 264433956c43SDimitry Andric } 264533956c43SDimitry Andric 2646e7145dcbSDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition. 2647e7145dcbSDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 2648e7145dcbSDimitry Andric bool IsTentative) { 264944290647SDimitry Andric // OpenCL global variables of sampler type are translated to function calls, 265044290647SDimitry Andric // therefore no need to be translated. 2651f22ef01cSRoman Divacky QualType ASTTy = D->getType(); 265244290647SDimitry Andric if (getLangOpts().OpenCL && ASTTy->isSamplerT()) 265344290647SDimitry Andric return; 265444290647SDimitry Andric 265544290647SDimitry Andric llvm::Constant *Init = nullptr; 2656dff0c46cSDimitry Andric CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2657dff0c46cSDimitry Andric bool NeedsGlobalCtor = false; 2658dff0c46cSDimitry Andric bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 2659f22ef01cSRoman Divacky 2660dff0c46cSDimitry Andric const VarDecl *InitDecl; 2661dff0c46cSDimitry Andric const Expr *InitExpr = D->getAnyInitializer(InitDecl); 2662f22ef01cSRoman Divacky 2663e7145dcbSDimitry Andric // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 2664e7145dcbSDimitry Andric // as part of their declaration." Sema has already checked for 2665e7145dcbSDimitry Andric // error cases, so we just need to set Init to UndefValue. 2666e7145dcbSDimitry Andric if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 2667e7145dcbSDimitry Andric D->hasAttr<CUDASharedAttr>()) 26680623d748SDimitry Andric Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy)); 2669e7145dcbSDimitry Andric else if (!InitExpr) { 2670f22ef01cSRoman Divacky // This is a tentative definition; tentative definitions are 2671f22ef01cSRoman Divacky // implicitly initialized with { 0 }. 2672f22ef01cSRoman Divacky // 2673f22ef01cSRoman Divacky // Note that tentative definitions are only emitted at the end of 2674f22ef01cSRoman Divacky // a translation unit, so they should never have incomplete 2675f22ef01cSRoman Divacky // type. In addition, EmitTentativeDefinition makes sure that we 2676f22ef01cSRoman Divacky // never attempt to emit a tentative definition if a real one 2677f22ef01cSRoman Divacky // exists. A use may still exists, however, so we still may need 2678f22ef01cSRoman Divacky // to do a RAUW. 2679f22ef01cSRoman Divacky assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 2680f22ef01cSRoman Divacky Init = EmitNullConstant(D->getType()); 2681f22ef01cSRoman Divacky } else { 26827ae0e2c9SDimitry Andric initializedGlobalDecl = GlobalDecl(D); 2683dff0c46cSDimitry Andric Init = EmitConstantInit(*InitDecl); 2684f785676fSDimitry Andric 2685f22ef01cSRoman Divacky if (!Init) { 2686f22ef01cSRoman Divacky QualType T = InitExpr->getType(); 2687f22ef01cSRoman Divacky if (D->getType()->isReferenceType()) 2688f22ef01cSRoman Divacky T = D->getType(); 2689f22ef01cSRoman Divacky 2690dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus) { 2691f22ef01cSRoman Divacky Init = EmitNullConstant(T); 2692dff0c46cSDimitry Andric NeedsGlobalCtor = true; 2693f22ef01cSRoman Divacky } else { 2694f22ef01cSRoman Divacky ErrorUnsupported(D, "static initializer"); 2695f22ef01cSRoman Divacky Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 2696f22ef01cSRoman Divacky } 2697e580952dSDimitry Andric } else { 2698e580952dSDimitry Andric // We don't need an initializer, so remove the entry for the delayed 2699dff0c46cSDimitry Andric // initializer position (just in case this entry was delayed) if we 2700dff0c46cSDimitry Andric // also don't need to register a destructor. 2701dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 2702e580952dSDimitry Andric DelayedCXXInitPosition.erase(D); 2703f22ef01cSRoman Divacky } 2704f22ef01cSRoman Divacky } 2705f22ef01cSRoman Divacky 27066122f3e6SDimitry Andric llvm::Type* InitType = Init->getType(); 2707e7145dcbSDimitry Andric llvm::Constant *Entry = 270844290647SDimitry Andric GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); 2709f22ef01cSRoman Divacky 2710f22ef01cSRoman Divacky // Strip off a bitcast if we got one back. 271159d1ed5bSDimitry Andric if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 2712f22ef01cSRoman Divacky assert(CE->getOpcode() == llvm::Instruction::BitCast || 2713f785676fSDimitry Andric CE->getOpcode() == llvm::Instruction::AddrSpaceCast || 2714f785676fSDimitry Andric // All zero index gep. 2715f22ef01cSRoman Divacky CE->getOpcode() == llvm::Instruction::GetElementPtr); 2716f22ef01cSRoman Divacky Entry = CE->getOperand(0); 2717f22ef01cSRoman Divacky } 2718f22ef01cSRoman Divacky 2719f22ef01cSRoman Divacky // Entry is now either a Function or GlobalVariable. 272059d1ed5bSDimitry Andric auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 2721f22ef01cSRoman Divacky 2722f22ef01cSRoman Divacky // We have a definition after a declaration with the wrong type. 2723f22ef01cSRoman Divacky // We must make a new GlobalVariable* and update everything that used OldGV 2724f22ef01cSRoman Divacky // (a declaration or tentative definition) with the new GlobalVariable* 2725f22ef01cSRoman Divacky // (which will be a definition). 2726f22ef01cSRoman Divacky // 2727f22ef01cSRoman Divacky // This happens if there is a prototype for a global (e.g. 2728f22ef01cSRoman Divacky // "extern int x[];") and then a definition of a different type (e.g. 2729f22ef01cSRoman Divacky // "int x[10];"). This also happens when an initializer has a different type 2730f22ef01cSRoman Divacky // from the type of the global (this happens with unions). 273159d1ed5bSDimitry Andric if (!GV || 2732f22ef01cSRoman Divacky GV->getType()->getElementType() != InitType || 27333b0f4066SDimitry Andric GV->getType()->getAddressSpace() != 27347ae0e2c9SDimitry Andric GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) { 2735f22ef01cSRoman Divacky 2736f22ef01cSRoman Divacky // Move the old entry aside so that we'll create a new one. 27376122f3e6SDimitry Andric Entry->setName(StringRef()); 2738f22ef01cSRoman Divacky 2739f22ef01cSRoman Divacky // Make a new global with the correct type, this is now guaranteed to work. 2740e7145dcbSDimitry Andric GV = cast<llvm::GlobalVariable>( 274144290647SDimitry Andric GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))); 2742f22ef01cSRoman Divacky 2743f22ef01cSRoman Divacky // Replace all uses of the old global with the new global 2744f22ef01cSRoman Divacky llvm::Constant *NewPtrForOldDecl = 2745f22ef01cSRoman Divacky llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 2746f22ef01cSRoman Divacky Entry->replaceAllUsesWith(NewPtrForOldDecl); 2747f22ef01cSRoman Divacky 2748f22ef01cSRoman Divacky // Erase the old global, since it is no longer used. 2749f22ef01cSRoman Divacky cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 2750f22ef01cSRoman Divacky } 2751f22ef01cSRoman Divacky 2752284c1978SDimitry Andric MaybeHandleStaticInExternC(D, GV); 2753284c1978SDimitry Andric 27546122f3e6SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 27556122f3e6SDimitry Andric AddGlobalAnnotations(D, GV); 2756f22ef01cSRoman Divacky 2757e7145dcbSDimitry Andric // Set the llvm linkage type as appropriate. 2758e7145dcbSDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 2759e7145dcbSDimitry Andric getLLVMLinkageVarDefinition(D, GV->isConstant()); 2760e7145dcbSDimitry Andric 27610623d748SDimitry Andric // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 27620623d748SDimitry Andric // the device. [...]" 27630623d748SDimitry Andric // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 27640623d748SDimitry Andric // __device__, declares a variable that: [...] 27650623d748SDimitry Andric // Is accessible from all the threads within the grid and from the host 27660623d748SDimitry Andric // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 27670623d748SDimitry Andric // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 2768e7145dcbSDimitry Andric if (GV && LangOpts.CUDA) { 2769e7145dcbSDimitry Andric if (LangOpts.CUDAIsDevice) { 2770e7145dcbSDimitry Andric if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) 27710623d748SDimitry Andric GV->setExternallyInitialized(true); 2772e7145dcbSDimitry Andric } else { 2773e7145dcbSDimitry Andric // Host-side shadows of external declarations of device-side 2774e7145dcbSDimitry Andric // global variables become internal definitions. These have to 2775e7145dcbSDimitry Andric // be internal in order to prevent name conflicts with global 2776e7145dcbSDimitry Andric // host variables with the same name in a different TUs. 2777e7145dcbSDimitry Andric if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) { 2778e7145dcbSDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 2779e7145dcbSDimitry Andric 2780e7145dcbSDimitry Andric // Shadow variables and their properties must be registered 2781e7145dcbSDimitry Andric // with CUDA runtime. 2782e7145dcbSDimitry Andric unsigned Flags = 0; 2783e7145dcbSDimitry Andric if (!D->hasDefinition()) 2784e7145dcbSDimitry Andric Flags |= CGCUDARuntime::ExternDeviceVar; 2785e7145dcbSDimitry Andric if (D->hasAttr<CUDAConstantAttr>()) 2786e7145dcbSDimitry Andric Flags |= CGCUDARuntime::ConstantDeviceVar; 2787e7145dcbSDimitry Andric getCUDARuntime().registerDeviceVar(*GV, Flags); 2788e7145dcbSDimitry Andric } else if (D->hasAttr<CUDASharedAttr>()) 2789e7145dcbSDimitry Andric // __shared__ variables are odd. Shadows do get created, but 2790e7145dcbSDimitry Andric // they are not registered with the CUDA runtime, so they 2791e7145dcbSDimitry Andric // can't really be used to access their device-side 2792e7145dcbSDimitry Andric // counterparts. It's not clear yet whether it's nvcc's bug or 2793e7145dcbSDimitry Andric // a feature, but we've got to do the same for compatibility. 2794e7145dcbSDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 2795e7145dcbSDimitry Andric } 27960623d748SDimitry Andric } 2797f22ef01cSRoman Divacky GV->setInitializer(Init); 2798f22ef01cSRoman Divacky 2799f22ef01cSRoman Divacky // If it is safe to mark the global 'constant', do so now. 2800dff0c46cSDimitry Andric GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 2801dff0c46cSDimitry Andric isTypeConstant(D->getType(), true)); 2802f22ef01cSRoman Divacky 280339d628a0SDimitry Andric // If it is in a read-only section, mark it 'constant'. 280439d628a0SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 280539d628a0SDimitry Andric const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 280639d628a0SDimitry Andric if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 280739d628a0SDimitry Andric GV->setConstant(true); 280839d628a0SDimitry Andric } 280939d628a0SDimitry Andric 2810f22ef01cSRoman Divacky GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 2811f22ef01cSRoman Divacky 2812f785676fSDimitry Andric 28130623d748SDimitry Andric // On Darwin, if the normal linkage of a C++ thread_local variable is 28140623d748SDimitry Andric // LinkOnce or Weak, we keep the normal linkage to prevent multiple 28150623d748SDimitry Andric // copies within a linkage unit; otherwise, the backing variable has 28160623d748SDimitry Andric // internal linkage and all accesses should just be calls to the 281759d1ed5bSDimitry Andric // Itanium-specified entry point, which has the normal linkage of the 28180623d748SDimitry Andric // variable. This is to preserve the ability to change the implementation 28190623d748SDimitry Andric // behind the scenes. 282039d628a0SDimitry Andric if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic && 28210623d748SDimitry Andric Context.getTargetInfo().getTriple().isOSDarwin() && 28220623d748SDimitry Andric !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) && 28230623d748SDimitry Andric !llvm::GlobalVariable::isWeakLinkage(Linkage)) 282459d1ed5bSDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 282559d1ed5bSDimitry Andric 282659d1ed5bSDimitry Andric GV->setLinkage(Linkage); 282759d1ed5bSDimitry Andric if (D->hasAttr<DLLImportAttr>()) 282859d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 282959d1ed5bSDimitry Andric else if (D->hasAttr<DLLExportAttr>()) 283059d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 283139d628a0SDimitry Andric else 283239d628a0SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 2833f785676fSDimitry Andric 283444290647SDimitry Andric if (Linkage == llvm::GlobalVariable::CommonLinkage) { 2835f22ef01cSRoman Divacky // common vars aren't constant even if declared const. 2836f22ef01cSRoman Divacky GV->setConstant(false); 283744290647SDimitry Andric // Tentative definition of global variables may be initialized with 283844290647SDimitry Andric // non-zero null pointers. In this case they should have weak linkage 283944290647SDimitry Andric // since common linkage must have zero initializer and must not have 284044290647SDimitry Andric // explicit section therefore cannot have non-zero initial value. 284144290647SDimitry Andric if (!GV->getInitializer()->isNullValue()) 284244290647SDimitry Andric GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 284344290647SDimitry Andric } 2844f22ef01cSRoman Divacky 284559d1ed5bSDimitry Andric setNonAliasAttributes(D, GV); 2846f22ef01cSRoman Divacky 284739d628a0SDimitry Andric if (D->getTLSKind() && !GV->isThreadLocal()) { 284839d628a0SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 28490623d748SDimitry Andric CXXThreadLocals.push_back(D); 285039d628a0SDimitry Andric setTLSMode(GV, *D); 285139d628a0SDimitry Andric } 285239d628a0SDimitry Andric 285333956c43SDimitry Andric maybeSetTrivialComdat(*D, *GV); 285433956c43SDimitry Andric 28552754fe60SDimitry Andric // Emit the initializer function if necessary. 2856dff0c46cSDimitry Andric if (NeedsGlobalCtor || NeedsGlobalDtor) 2857dff0c46cSDimitry Andric EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 28582754fe60SDimitry Andric 285939d628a0SDimitry Andric SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); 28603861d79fSDimitry Andric 2861f22ef01cSRoman Divacky // Emit global variable debug information. 28626122f3e6SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 2863e7145dcbSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) 2864f22ef01cSRoman Divacky DI->EmitGlobalVariable(GV, D); 2865f22ef01cSRoman Divacky } 2866f22ef01cSRoman Divacky 286739d628a0SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context, 286833956c43SDimitry Andric CodeGenModule &CGM, const VarDecl *D, 286933956c43SDimitry Andric bool NoCommon) { 287059d1ed5bSDimitry Andric // Don't give variables common linkage if -fno-common was specified unless it 287159d1ed5bSDimitry Andric // was overridden by a NoCommon attribute. 287259d1ed5bSDimitry Andric if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 287359d1ed5bSDimitry Andric return true; 287459d1ed5bSDimitry Andric 287559d1ed5bSDimitry Andric // C11 6.9.2/2: 287659d1ed5bSDimitry Andric // A declaration of an identifier for an object that has file scope without 287759d1ed5bSDimitry Andric // an initializer, and without a storage-class specifier or with the 287859d1ed5bSDimitry Andric // storage-class specifier static, constitutes a tentative definition. 287959d1ed5bSDimitry Andric if (D->getInit() || D->hasExternalStorage()) 288059d1ed5bSDimitry Andric return true; 288159d1ed5bSDimitry Andric 288259d1ed5bSDimitry Andric // A variable cannot be both common and exist in a section. 288359d1ed5bSDimitry Andric if (D->hasAttr<SectionAttr>()) 288459d1ed5bSDimitry Andric return true; 288559d1ed5bSDimitry Andric 2886db17bf38SDimitry Andric // A variable cannot be both common and exist in a section. 2887db17bf38SDimitry Andric // We dont try to determine which is the right section in the front-end. 2888db17bf38SDimitry Andric // If no specialized section name is applicable, it will resort to default. 2889db17bf38SDimitry Andric if (D->hasAttr<PragmaClangBSSSectionAttr>() || 2890db17bf38SDimitry Andric D->hasAttr<PragmaClangDataSectionAttr>() || 2891db17bf38SDimitry Andric D->hasAttr<PragmaClangRodataSectionAttr>()) 2892db17bf38SDimitry Andric return true; 2893db17bf38SDimitry Andric 289459d1ed5bSDimitry Andric // Thread local vars aren't considered common linkage. 289559d1ed5bSDimitry Andric if (D->getTLSKind()) 289659d1ed5bSDimitry Andric return true; 289759d1ed5bSDimitry Andric 289859d1ed5bSDimitry Andric // Tentative definitions marked with WeakImportAttr are true definitions. 289959d1ed5bSDimitry Andric if (D->hasAttr<WeakImportAttr>()) 290059d1ed5bSDimitry Andric return true; 290159d1ed5bSDimitry Andric 290233956c43SDimitry Andric // A variable cannot be both common and exist in a comdat. 290333956c43SDimitry Andric if (shouldBeInCOMDAT(CGM, *D)) 290433956c43SDimitry Andric return true; 290533956c43SDimitry Andric 2906e7145dcbSDimitry Andric // Declarations with a required alignment do not have common linkage in MSVC 290739d628a0SDimitry Andric // mode. 29080623d748SDimitry Andric if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 290933956c43SDimitry Andric if (D->hasAttr<AlignedAttr>()) 291039d628a0SDimitry Andric return true; 291133956c43SDimitry Andric QualType VarType = D->getType(); 291233956c43SDimitry Andric if (Context.isAlignmentRequired(VarType)) 291333956c43SDimitry Andric return true; 291433956c43SDimitry Andric 291533956c43SDimitry Andric if (const auto *RT = VarType->getAs<RecordType>()) { 291633956c43SDimitry Andric const RecordDecl *RD = RT->getDecl(); 291733956c43SDimitry Andric for (const FieldDecl *FD : RD->fields()) { 291833956c43SDimitry Andric if (FD->isBitField()) 291933956c43SDimitry Andric continue; 292033956c43SDimitry Andric if (FD->hasAttr<AlignedAttr>()) 292133956c43SDimitry Andric return true; 292233956c43SDimitry Andric if (Context.isAlignmentRequired(FD->getType())) 292333956c43SDimitry Andric return true; 292433956c43SDimitry Andric } 292533956c43SDimitry Andric } 292633956c43SDimitry Andric } 292739d628a0SDimitry Andric 292859d1ed5bSDimitry Andric return false; 292959d1ed5bSDimitry Andric } 293059d1ed5bSDimitry Andric 293159d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 293259d1ed5bSDimitry Andric const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 29332754fe60SDimitry Andric if (Linkage == GVA_Internal) 29342754fe60SDimitry Andric return llvm::Function::InternalLinkage; 293559d1ed5bSDimitry Andric 293659d1ed5bSDimitry Andric if (D->hasAttr<WeakAttr>()) { 293759d1ed5bSDimitry Andric if (IsConstantVariable) 293859d1ed5bSDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 293959d1ed5bSDimitry Andric else 294059d1ed5bSDimitry Andric return llvm::GlobalVariable::WeakAnyLinkage; 294159d1ed5bSDimitry Andric } 294259d1ed5bSDimitry Andric 294359d1ed5bSDimitry Andric // We are guaranteed to have a strong definition somewhere else, 294459d1ed5bSDimitry Andric // so we can use available_externally linkage. 294559d1ed5bSDimitry Andric if (Linkage == GVA_AvailableExternally) 294620e90f04SDimitry Andric return llvm::GlobalValue::AvailableExternallyLinkage; 294759d1ed5bSDimitry Andric 294859d1ed5bSDimitry Andric // Note that Apple's kernel linker doesn't support symbol 294959d1ed5bSDimitry Andric // coalescing, so we need to avoid linkonce and weak linkages there. 295059d1ed5bSDimitry Andric // Normally, this means we just map to internal, but for explicit 295159d1ed5bSDimitry Andric // instantiations we'll map to external. 295259d1ed5bSDimitry Andric 295359d1ed5bSDimitry Andric // In C++, the compiler has to emit a definition in every translation unit 295459d1ed5bSDimitry Andric // that references the function. We should use linkonce_odr because 295559d1ed5bSDimitry Andric // a) if all references in this translation unit are optimized away, we 295659d1ed5bSDimitry Andric // don't need to codegen it. b) if the function persists, it needs to be 295759d1ed5bSDimitry Andric // merged with other definitions. c) C++ has the ODR, so we know the 295859d1ed5bSDimitry Andric // definition is dependable. 295959d1ed5bSDimitry Andric if (Linkage == GVA_DiscardableODR) 296059d1ed5bSDimitry Andric return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 296159d1ed5bSDimitry Andric : llvm::Function::InternalLinkage; 296259d1ed5bSDimitry Andric 296359d1ed5bSDimitry Andric // An explicit instantiation of a template has weak linkage, since 296459d1ed5bSDimitry Andric // explicit instantiations can occur in multiple translation units 296559d1ed5bSDimitry Andric // and must all be equivalent. However, we are not allowed to 296659d1ed5bSDimitry Andric // throw away these explicit instantiations. 2967e7145dcbSDimitry Andric // 2968e7145dcbSDimitry Andric // We don't currently support CUDA device code spread out across multiple TUs, 2969e7145dcbSDimitry Andric // so say that CUDA templates are either external (for kernels) or internal. 2970e7145dcbSDimitry Andric // This lets llvm perform aggressive inter-procedural optimizations. 2971e7145dcbSDimitry Andric if (Linkage == GVA_StrongODR) { 2972e7145dcbSDimitry Andric if (Context.getLangOpts().AppleKext) 2973e7145dcbSDimitry Andric return llvm::Function::ExternalLinkage; 2974e7145dcbSDimitry Andric if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) 2975e7145dcbSDimitry Andric return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage 2976e7145dcbSDimitry Andric : llvm::Function::InternalLinkage; 2977e7145dcbSDimitry Andric return llvm::Function::WeakODRLinkage; 2978e7145dcbSDimitry Andric } 297959d1ed5bSDimitry Andric 298059d1ed5bSDimitry Andric // C++ doesn't have tentative definitions and thus cannot have common 298159d1ed5bSDimitry Andric // linkage. 298259d1ed5bSDimitry Andric if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 298333956c43SDimitry Andric !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 298439d628a0SDimitry Andric CodeGenOpts.NoCommon)) 298559d1ed5bSDimitry Andric return llvm::GlobalVariable::CommonLinkage; 298659d1ed5bSDimitry Andric 2987f785676fSDimitry Andric // selectany symbols are externally visible, so use weak instead of 2988f785676fSDimitry Andric // linkonce. MSVC optimizes away references to const selectany globals, so 2989f785676fSDimitry Andric // all definitions should be the same and ODR linkage should be used. 2990f785676fSDimitry Andric // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 299159d1ed5bSDimitry Andric if (D->hasAttr<SelectAnyAttr>()) 2992f785676fSDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 299359d1ed5bSDimitry Andric 299459d1ed5bSDimitry Andric // Otherwise, we have strong external linkage. 299559d1ed5bSDimitry Andric assert(Linkage == GVA_StrongExternal); 29962754fe60SDimitry Andric return llvm::GlobalVariable::ExternalLinkage; 29972754fe60SDimitry Andric } 29982754fe60SDimitry Andric 299959d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 300059d1ed5bSDimitry Andric const VarDecl *VD, bool IsConstant) { 300159d1ed5bSDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 300259d1ed5bSDimitry Andric return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 300359d1ed5bSDimitry Andric } 300459d1ed5bSDimitry Andric 3005139f7f9bSDimitry Andric /// Replace the uses of a function that was declared with a non-proto type. 3006139f7f9bSDimitry Andric /// We want to silently drop extra arguments from call sites 3007139f7f9bSDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 3008139f7f9bSDimitry Andric llvm::Function *newFn) { 3009139f7f9bSDimitry Andric // Fast path. 3010139f7f9bSDimitry Andric if (old->use_empty()) return; 3011139f7f9bSDimitry Andric 3012139f7f9bSDimitry Andric llvm::Type *newRetTy = newFn->getReturnType(); 3013139f7f9bSDimitry Andric SmallVector<llvm::Value*, 4> newArgs; 30140623d748SDimitry Andric SmallVector<llvm::OperandBundleDef, 1> newBundles; 3015139f7f9bSDimitry Andric 3016139f7f9bSDimitry Andric for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 3017139f7f9bSDimitry Andric ui != ue; ) { 3018139f7f9bSDimitry Andric llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 301959d1ed5bSDimitry Andric llvm::User *user = use->getUser(); 3020139f7f9bSDimitry Andric 3021139f7f9bSDimitry Andric // Recognize and replace uses of bitcasts. Most calls to 3022139f7f9bSDimitry Andric // unprototyped functions will use bitcasts. 302359d1ed5bSDimitry Andric if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 3024139f7f9bSDimitry Andric if (bitcast->getOpcode() == llvm::Instruction::BitCast) 3025139f7f9bSDimitry Andric replaceUsesOfNonProtoConstant(bitcast, newFn); 3026139f7f9bSDimitry Andric continue; 3027139f7f9bSDimitry Andric } 3028139f7f9bSDimitry Andric 3029139f7f9bSDimitry Andric // Recognize calls to the function. 3030139f7f9bSDimitry Andric llvm::CallSite callSite(user); 3031139f7f9bSDimitry Andric if (!callSite) continue; 303259d1ed5bSDimitry Andric if (!callSite.isCallee(&*use)) continue; 3033139f7f9bSDimitry Andric 3034139f7f9bSDimitry Andric // If the return types don't match exactly, then we can't 3035139f7f9bSDimitry Andric // transform this call unless it's dead. 3036139f7f9bSDimitry Andric if (callSite->getType() != newRetTy && !callSite->use_empty()) 3037139f7f9bSDimitry Andric continue; 3038139f7f9bSDimitry Andric 3039139f7f9bSDimitry Andric // Get the call site's attribute list. 304020e90f04SDimitry Andric SmallVector<llvm::AttributeSet, 8> newArgAttrs; 304120e90f04SDimitry Andric llvm::AttributeList oldAttrs = callSite.getAttributes(); 3042139f7f9bSDimitry Andric 3043139f7f9bSDimitry Andric // If the function was passed too few arguments, don't transform. 3044139f7f9bSDimitry Andric unsigned newNumArgs = newFn->arg_size(); 3045139f7f9bSDimitry Andric if (callSite.arg_size() < newNumArgs) continue; 3046139f7f9bSDimitry Andric 3047139f7f9bSDimitry Andric // If extra arguments were passed, we silently drop them. 3048139f7f9bSDimitry Andric // If any of the types mismatch, we don't transform. 3049139f7f9bSDimitry Andric unsigned argNo = 0; 3050139f7f9bSDimitry Andric bool dontTransform = false; 305120e90f04SDimitry Andric for (llvm::Argument &A : newFn->args()) { 305220e90f04SDimitry Andric if (callSite.getArgument(argNo)->getType() != A.getType()) { 3053139f7f9bSDimitry Andric dontTransform = true; 3054139f7f9bSDimitry Andric break; 3055139f7f9bSDimitry Andric } 3056139f7f9bSDimitry Andric 3057139f7f9bSDimitry Andric // Add any parameter attributes. 305820e90f04SDimitry Andric newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo)); 305920e90f04SDimitry Andric argNo++; 3060139f7f9bSDimitry Andric } 3061139f7f9bSDimitry Andric if (dontTransform) 3062139f7f9bSDimitry Andric continue; 3063139f7f9bSDimitry Andric 3064139f7f9bSDimitry Andric // Okay, we can transform this. Create the new call instruction and copy 3065139f7f9bSDimitry Andric // over the required information. 3066139f7f9bSDimitry Andric newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo); 3067139f7f9bSDimitry Andric 30680623d748SDimitry Andric // Copy over any operand bundles. 30690623d748SDimitry Andric callSite.getOperandBundlesAsDefs(newBundles); 30700623d748SDimitry Andric 3071139f7f9bSDimitry Andric llvm::CallSite newCall; 3072139f7f9bSDimitry Andric if (callSite.isCall()) { 30730623d748SDimitry Andric newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "", 3074139f7f9bSDimitry Andric callSite.getInstruction()); 3075139f7f9bSDimitry Andric } else { 307659d1ed5bSDimitry Andric auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction()); 3077139f7f9bSDimitry Andric newCall = llvm::InvokeInst::Create(newFn, 3078139f7f9bSDimitry Andric oldInvoke->getNormalDest(), 3079139f7f9bSDimitry Andric oldInvoke->getUnwindDest(), 30800623d748SDimitry Andric newArgs, newBundles, "", 3081139f7f9bSDimitry Andric callSite.getInstruction()); 3082139f7f9bSDimitry Andric } 3083139f7f9bSDimitry Andric newArgs.clear(); // for the next iteration 3084139f7f9bSDimitry Andric 3085139f7f9bSDimitry Andric if (!newCall->getType()->isVoidTy()) 3086139f7f9bSDimitry Andric newCall->takeName(callSite.getInstruction()); 308720e90f04SDimitry Andric newCall.setAttributes(llvm::AttributeList::get( 308820e90f04SDimitry Andric newFn->getContext(), oldAttrs.getFnAttributes(), 308920e90f04SDimitry Andric oldAttrs.getRetAttributes(), newArgAttrs)); 3090139f7f9bSDimitry Andric newCall.setCallingConv(callSite.getCallingConv()); 3091139f7f9bSDimitry Andric 3092139f7f9bSDimitry Andric // Finally, remove the old call, replacing any uses with the new one. 3093139f7f9bSDimitry Andric if (!callSite->use_empty()) 3094139f7f9bSDimitry Andric callSite->replaceAllUsesWith(newCall.getInstruction()); 3095139f7f9bSDimitry Andric 3096139f7f9bSDimitry Andric // Copy debug location attached to CI. 309733956c43SDimitry Andric if (callSite->getDebugLoc()) 3098139f7f9bSDimitry Andric newCall->setDebugLoc(callSite->getDebugLoc()); 30990623d748SDimitry Andric 3100139f7f9bSDimitry Andric callSite->eraseFromParent(); 3101139f7f9bSDimitry Andric } 3102139f7f9bSDimitry Andric } 3103139f7f9bSDimitry Andric 3104f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 3105f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}". If there are 3106f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to 3107f22ef01cSRoman Divacky /// call the new function directly. 3108f22ef01cSRoman Divacky /// 3109f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to 3110f22ef01cSRoman Divacky /// functions to be able to inline them. If there is a bitcast in the way, it 3111f22ef01cSRoman Divacky /// won't inline them. Instcombine normally deletes these calls, but it isn't 3112f22ef01cSRoman Divacky /// run at -O0. 3113f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 3114f22ef01cSRoman Divacky llvm::Function *NewFn) { 3115f22ef01cSRoman Divacky // If we're redefining a global as a function, don't transform it. 3116139f7f9bSDimitry Andric if (!isa<llvm::Function>(Old)) return; 3117f22ef01cSRoman Divacky 3118139f7f9bSDimitry Andric replaceUsesOfNonProtoConstant(Old, NewFn); 3119f22ef01cSRoman Divacky } 3120f22ef01cSRoman Divacky 3121dff0c46cSDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 3122e7145dcbSDimitry Andric auto DK = VD->isThisDeclarationADefinition(); 3123e7145dcbSDimitry Andric if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) 3124e7145dcbSDimitry Andric return; 3125e7145dcbSDimitry Andric 3126dff0c46cSDimitry Andric TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 3127dff0c46cSDimitry Andric // If we have a definition, this might be a deferred decl. If the 3128dff0c46cSDimitry Andric // instantiation is explicit, make sure we emit it at the end. 3129dff0c46cSDimitry Andric if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 3130dff0c46cSDimitry Andric GetAddrOfGlobalVar(VD); 3131139f7f9bSDimitry Andric 3132139f7f9bSDimitry Andric EmitTopLevelDecl(VD); 3133dff0c46cSDimitry Andric } 3134f22ef01cSRoman Divacky 313559d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 313659d1ed5bSDimitry Andric llvm::GlobalValue *GV) { 313759d1ed5bSDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 31383b0f4066SDimitry Andric 31393b0f4066SDimitry Andric // Compute the function info and LLVM type. 3140dff0c46cSDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 3141dff0c46cSDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 31423b0f4066SDimitry Andric 3143f22ef01cSRoman Divacky // Get or create the prototype for the function. 31440623d748SDimitry Andric if (!GV || (GV->getType()->getElementType() != Ty)) 31450623d748SDimitry Andric GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 31460623d748SDimitry Andric /*DontDefer=*/true, 314744290647SDimitry Andric ForDefinition)); 3148f22ef01cSRoman Divacky 31490623d748SDimitry Andric // Already emitted. 31500623d748SDimitry Andric if (!GV->isDeclaration()) 3151f785676fSDimitry Andric return; 3152f22ef01cSRoman Divacky 31532754fe60SDimitry Andric // We need to set linkage and visibility on the function before 31542754fe60SDimitry Andric // generating code for it because various parts of IR generation 31552754fe60SDimitry Andric // want to propagate this information down (e.g. to local static 31562754fe60SDimitry Andric // declarations). 315759d1ed5bSDimitry Andric auto *Fn = cast<llvm::Function>(GV); 3158f785676fSDimitry Andric setFunctionLinkage(GD, Fn); 315997bc6c73SDimitry Andric setFunctionDLLStorageClass(GD, Fn); 3160f22ef01cSRoman Divacky 316159d1ed5bSDimitry Andric // FIXME: this is redundant with part of setFunctionDefinitionAttributes 31622754fe60SDimitry Andric setGlobalVisibility(Fn, D); 31632754fe60SDimitry Andric 3164284c1978SDimitry Andric MaybeHandleStaticInExternC(D, Fn); 3165284c1978SDimitry Andric 316633956c43SDimitry Andric maybeSetTrivialComdat(*D, *Fn); 316733956c43SDimitry Andric 31683b0f4066SDimitry Andric CodeGenFunction(*this).GenerateCode(D, Fn, FI); 3169f22ef01cSRoman Divacky 317059d1ed5bSDimitry Andric setFunctionDefinitionAttributes(D, Fn); 3171f22ef01cSRoman Divacky SetLLVMFunctionAttributesForDefinition(D, Fn); 3172f22ef01cSRoman Divacky 3173f22ef01cSRoman Divacky if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 3174f22ef01cSRoman Divacky AddGlobalCtor(Fn, CA->getPriority()); 3175f22ef01cSRoman Divacky if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 3176f22ef01cSRoman Divacky AddGlobalDtor(Fn, DA->getPriority()); 31776122f3e6SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 31786122f3e6SDimitry Andric AddGlobalAnnotations(D, Fn); 3179f22ef01cSRoman Divacky } 3180f22ef01cSRoman Divacky 3181f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 318259d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 3183f22ef01cSRoman Divacky const AliasAttr *AA = D->getAttr<AliasAttr>(); 3184f22ef01cSRoman Divacky assert(AA && "Not an alias?"); 3185f22ef01cSRoman Divacky 31866122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 3187f22ef01cSRoman Divacky 31889a4b3118SDimitry Andric if (AA->getAliasee() == MangledName) { 3189e7145dcbSDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 31909a4b3118SDimitry Andric return; 31919a4b3118SDimitry Andric } 31929a4b3118SDimitry Andric 3193f22ef01cSRoman Divacky // If there is a definition in the module, then it wins over the alias. 3194f22ef01cSRoman Divacky // This is dubious, but allow it to be safe. Just ignore the alias. 3195f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3196f22ef01cSRoman Divacky if (Entry && !Entry->isDeclaration()) 3197f22ef01cSRoman Divacky return; 3198f22ef01cSRoman Divacky 3199f785676fSDimitry Andric Aliases.push_back(GD); 3200f785676fSDimitry Andric 32016122f3e6SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 3202f22ef01cSRoman Divacky 3203f22ef01cSRoman Divacky // Create a reference to the named value. This ensures that it is emitted 3204f22ef01cSRoman Divacky // if a deferred decl. 3205f22ef01cSRoman Divacky llvm::Constant *Aliasee; 3206f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(DeclTy)) 32073861d79fSDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 32082754fe60SDimitry Andric /*ForVTable=*/false); 3209f22ef01cSRoman Divacky else 3210f22ef01cSRoman Divacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 321159d1ed5bSDimitry Andric llvm::PointerType::getUnqual(DeclTy), 321239d628a0SDimitry Andric /*D=*/nullptr); 3213f22ef01cSRoman Divacky 3214f22ef01cSRoman Divacky // Create the new alias itself, but don't set a name yet. 321559d1ed5bSDimitry Andric auto *GA = llvm::GlobalAlias::create( 32160623d748SDimitry Andric DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule()); 3217f22ef01cSRoman Divacky 3218f22ef01cSRoman Divacky if (Entry) { 321959d1ed5bSDimitry Andric if (GA->getAliasee() == Entry) { 3220e7145dcbSDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 322159d1ed5bSDimitry Andric return; 322259d1ed5bSDimitry Andric } 322359d1ed5bSDimitry Andric 3224f22ef01cSRoman Divacky assert(Entry->isDeclaration()); 3225f22ef01cSRoman Divacky 3226f22ef01cSRoman Divacky // If there is a declaration in the module, then we had an extern followed 3227f22ef01cSRoman Divacky // by the alias, as in: 3228f22ef01cSRoman Divacky // extern int test6(); 3229f22ef01cSRoman Divacky // ... 3230f22ef01cSRoman Divacky // int test6() __attribute__((alias("test7"))); 3231f22ef01cSRoman Divacky // 3232f22ef01cSRoman Divacky // Remove it and replace uses of it with the alias. 3233f22ef01cSRoman Divacky GA->takeName(Entry); 3234f22ef01cSRoman Divacky 3235f22ef01cSRoman Divacky Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 3236f22ef01cSRoman Divacky Entry->getType())); 3237f22ef01cSRoman Divacky Entry->eraseFromParent(); 3238f22ef01cSRoman Divacky } else { 3239ffd1746dSEd Schouten GA->setName(MangledName); 3240f22ef01cSRoman Divacky } 3241f22ef01cSRoman Divacky 3242f22ef01cSRoman Divacky // Set attributes which are particular to an alias; this is a 3243f22ef01cSRoman Divacky // specialization of the attributes which may be set on a global 3244f22ef01cSRoman Divacky // variable/function. 324539d628a0SDimitry Andric if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 32463b0f4066SDimitry Andric D->isWeakImported()) { 3247f22ef01cSRoman Divacky GA->setLinkage(llvm::Function::WeakAnyLinkage); 3248f22ef01cSRoman Divacky } 3249f22ef01cSRoman Divacky 325039d628a0SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 325139d628a0SDimitry Andric if (VD->getTLSKind()) 325239d628a0SDimitry Andric setTLSMode(GA, *VD); 325339d628a0SDimitry Andric 325439d628a0SDimitry Andric setAliasAttributes(D, GA); 3255f22ef01cSRoman Divacky } 3256f22ef01cSRoman Divacky 3257e7145dcbSDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 3258e7145dcbSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 3259e7145dcbSDimitry Andric const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 3260e7145dcbSDimitry Andric assert(IFA && "Not an ifunc?"); 3261e7145dcbSDimitry Andric 3262e7145dcbSDimitry Andric StringRef MangledName = getMangledName(GD); 3263e7145dcbSDimitry Andric 3264e7145dcbSDimitry Andric if (IFA->getResolver() == MangledName) { 3265e7145dcbSDimitry Andric Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 3266e7145dcbSDimitry Andric return; 3267e7145dcbSDimitry Andric } 3268e7145dcbSDimitry Andric 3269e7145dcbSDimitry Andric // Report an error if some definition overrides ifunc. 3270e7145dcbSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3271e7145dcbSDimitry Andric if (Entry && !Entry->isDeclaration()) { 3272e7145dcbSDimitry Andric GlobalDecl OtherGD; 3273e7145dcbSDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 3274e7145dcbSDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 3275e7145dcbSDimitry Andric Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name); 3276e7145dcbSDimitry Andric Diags.Report(OtherGD.getDecl()->getLocation(), 3277e7145dcbSDimitry Andric diag::note_previous_definition); 3278e7145dcbSDimitry Andric } 3279e7145dcbSDimitry Andric return; 3280e7145dcbSDimitry Andric } 3281e7145dcbSDimitry Andric 3282e7145dcbSDimitry Andric Aliases.push_back(GD); 3283e7145dcbSDimitry Andric 3284e7145dcbSDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 3285e7145dcbSDimitry Andric llvm::Constant *Resolver = 3286e7145dcbSDimitry Andric GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD, 3287e7145dcbSDimitry Andric /*ForVTable=*/false); 3288e7145dcbSDimitry Andric llvm::GlobalIFunc *GIF = 3289e7145dcbSDimitry Andric llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 3290e7145dcbSDimitry Andric "", Resolver, &getModule()); 3291e7145dcbSDimitry Andric if (Entry) { 3292e7145dcbSDimitry Andric if (GIF->getResolver() == Entry) { 3293e7145dcbSDimitry Andric Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 3294e7145dcbSDimitry Andric return; 3295e7145dcbSDimitry Andric } 3296e7145dcbSDimitry Andric assert(Entry->isDeclaration()); 3297e7145dcbSDimitry Andric 3298e7145dcbSDimitry Andric // If there is a declaration in the module, then we had an extern followed 3299e7145dcbSDimitry Andric // by the ifunc, as in: 3300e7145dcbSDimitry Andric // extern int test(); 3301e7145dcbSDimitry Andric // ... 3302e7145dcbSDimitry Andric // int test() __attribute__((ifunc("resolver"))); 3303e7145dcbSDimitry Andric // 3304e7145dcbSDimitry Andric // Remove it and replace uses of it with the ifunc. 3305e7145dcbSDimitry Andric GIF->takeName(Entry); 3306e7145dcbSDimitry Andric 3307e7145dcbSDimitry Andric Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF, 3308e7145dcbSDimitry Andric Entry->getType())); 3309e7145dcbSDimitry Andric Entry->eraseFromParent(); 3310e7145dcbSDimitry Andric } else 3311e7145dcbSDimitry Andric GIF->setName(MangledName); 3312e7145dcbSDimitry Andric 3313e7145dcbSDimitry Andric SetCommonAttributes(D, GIF); 3314e7145dcbSDimitry Andric } 3315e7145dcbSDimitry Andric 331617a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 33176122f3e6SDimitry Andric ArrayRef<llvm::Type*> Tys) { 331817a519f9SDimitry Andric return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 331917a519f9SDimitry Andric Tys); 3320f22ef01cSRoman Divacky } 3321f22ef01cSRoman Divacky 332233956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> & 332333956c43SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 332433956c43SDimitry Andric const StringLiteral *Literal, bool TargetIsLSB, 332533956c43SDimitry Andric bool &IsUTF16, unsigned &StringLength) { 33266122f3e6SDimitry Andric StringRef String = Literal->getString(); 3327e580952dSDimitry Andric unsigned NumBytes = String.size(); 3328f22ef01cSRoman Divacky 3329f22ef01cSRoman Divacky // Check for simple case. 3330f22ef01cSRoman Divacky if (!Literal->containsNonAsciiOrNull()) { 3331f22ef01cSRoman Divacky StringLength = NumBytes; 333239d628a0SDimitry Andric return *Map.insert(std::make_pair(String, nullptr)).first; 3333f22ef01cSRoman Divacky } 3334f22ef01cSRoman Divacky 3335dff0c46cSDimitry Andric // Otherwise, convert the UTF8 literals into a string of shorts. 3336dff0c46cSDimitry Andric IsUTF16 = true; 3337dff0c46cSDimitry Andric 333844290647SDimitry Andric SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 333944290647SDimitry Andric const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 334044290647SDimitry Andric llvm::UTF16 *ToPtr = &ToBuf[0]; 3341f22ef01cSRoman Divacky 334244290647SDimitry Andric (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 334344290647SDimitry Andric ToPtr + NumBytes, llvm::strictConversion); 3344f22ef01cSRoman Divacky 3345f22ef01cSRoman Divacky // ConvertUTF8toUTF16 returns the length in ToPtr. 3346f22ef01cSRoman Divacky StringLength = ToPtr - &ToBuf[0]; 3347f22ef01cSRoman Divacky 3348dff0c46cSDimitry Andric // Add an explicit null. 3349dff0c46cSDimitry Andric *ToPtr = 0; 335039d628a0SDimitry Andric return *Map.insert(std::make_pair( 335139d628a0SDimitry Andric StringRef(reinterpret_cast<const char *>(ToBuf.data()), 335239d628a0SDimitry Andric (StringLength + 1) * 2), 335339d628a0SDimitry Andric nullptr)).first; 3354f22ef01cSRoman Divacky } 3355f22ef01cSRoman Divacky 33560623d748SDimitry Andric ConstantAddress 3357f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 3358f22ef01cSRoman Divacky unsigned StringLength = 0; 3359f22ef01cSRoman Divacky bool isUTF16 = false; 336033956c43SDimitry Andric llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 3361f22ef01cSRoman Divacky GetConstantCFStringEntry(CFConstantStringMap, Literal, 336233956c43SDimitry Andric getDataLayout().isLittleEndian(), isUTF16, 336333956c43SDimitry Andric StringLength); 3364f22ef01cSRoman Divacky 336539d628a0SDimitry Andric if (auto *C = Entry.second) 33660623d748SDimitry Andric return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 3367f22ef01cSRoman Divacky 3368dff0c46cSDimitry Andric llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 3369f22ef01cSRoman Divacky llvm::Constant *Zeros[] = { Zero, Zero }; 3370f22ef01cSRoman Divacky 3371f22ef01cSRoman Divacky // If we don't already have it, get __CFConstantStringClassReference. 3372f22ef01cSRoman Divacky if (!CFConstantStringClassRef) { 33736122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 3374f22ef01cSRoman Divacky Ty = llvm::ArrayType::get(Ty, 0); 3375e7145dcbSDimitry Andric llvm::Constant *GV = 3376e7145dcbSDimitry Andric CreateRuntimeVariable(Ty, "__CFConstantStringClassReference"); 3377e7145dcbSDimitry Andric 337844290647SDimitry Andric if (getTriple().isOSBinFormatCOFF()) { 3379e7145dcbSDimitry Andric IdentifierInfo &II = getContext().Idents.get(GV->getName()); 3380e7145dcbSDimitry Andric TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl(); 3381e7145dcbSDimitry Andric DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 3382e7145dcbSDimitry Andric llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV); 3383e7145dcbSDimitry Andric 3384e7145dcbSDimitry Andric const VarDecl *VD = nullptr; 3385e7145dcbSDimitry Andric for (const auto &Result : DC->lookup(&II)) 3386e7145dcbSDimitry Andric if ((VD = dyn_cast<VarDecl>(Result))) 3387e7145dcbSDimitry Andric break; 3388e7145dcbSDimitry Andric 3389e7145dcbSDimitry Andric if (!VD || !VD->hasAttr<DLLExportAttr>()) { 3390e7145dcbSDimitry Andric CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 3391e7145dcbSDimitry Andric CGV->setLinkage(llvm::GlobalValue::ExternalLinkage); 3392e7145dcbSDimitry Andric } else { 3393e7145dcbSDimitry Andric CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 3394e7145dcbSDimitry Andric CGV->setLinkage(llvm::GlobalValue::ExternalLinkage); 3395e7145dcbSDimitry Andric } 3396e7145dcbSDimitry Andric } 3397e7145dcbSDimitry Andric 3398f22ef01cSRoman Divacky // Decay array -> ptr 339944290647SDimitry Andric CFConstantStringClassRef = 340044290647SDimitry Andric llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros); 3401e7145dcbSDimitry Andric } 3402f22ef01cSRoman Divacky 3403f22ef01cSRoman Divacky QualType CFTy = getContext().getCFConstantStringType(); 3404f22ef01cSRoman Divacky 340559d1ed5bSDimitry Andric auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 3406f22ef01cSRoman Divacky 340744290647SDimitry Andric ConstantInitBuilder Builder(*this); 340844290647SDimitry Andric auto Fields = Builder.beginStruct(STy); 3409f22ef01cSRoman Divacky 3410f22ef01cSRoman Divacky // Class pointer. 341144290647SDimitry Andric Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef)); 3412f22ef01cSRoman Divacky 3413f22ef01cSRoman Divacky // Flags. 341444290647SDimitry Andric Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); 3415f22ef01cSRoman Divacky 3416f22ef01cSRoman Divacky // String pointer. 341759d1ed5bSDimitry Andric llvm::Constant *C = nullptr; 3418dff0c46cSDimitry Andric if (isUTF16) { 34190623d748SDimitry Andric auto Arr = llvm::makeArrayRef( 342039d628a0SDimitry Andric reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 342139d628a0SDimitry Andric Entry.first().size() / 2); 3422dff0c46cSDimitry Andric C = llvm::ConstantDataArray::get(VMContext, Arr); 3423dff0c46cSDimitry Andric } else { 342439d628a0SDimitry Andric C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 3425dff0c46cSDimitry Andric } 3426f22ef01cSRoman Divacky 3427dff0c46cSDimitry Andric // Note: -fwritable-strings doesn't make the backing store strings of 3428dff0c46cSDimitry Andric // CFStrings writable. (See <rdar://problem/10657500>) 342959d1ed5bSDimitry Andric auto *GV = 3430dff0c46cSDimitry Andric new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 343159d1ed5bSDimitry Andric llvm::GlobalValue::PrivateLinkage, C, ".str"); 3432e7145dcbSDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3433284c1978SDimitry Andric // Don't enforce the target's minimum global alignment, since the only use 3434284c1978SDimitry Andric // of the string is via this class initializer. 3435e7145dcbSDimitry Andric CharUnits Align = isUTF16 3436e7145dcbSDimitry Andric ? getContext().getTypeAlignInChars(getContext().ShortTy) 3437e7145dcbSDimitry Andric : getContext().getTypeAlignInChars(getContext().CharTy); 3438f22ef01cSRoman Divacky GV->setAlignment(Align.getQuantity()); 3439e7145dcbSDimitry Andric 3440e7145dcbSDimitry Andric // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 3441e7145dcbSDimitry Andric // Without it LLVM can merge the string with a non unnamed_addr one during 3442e7145dcbSDimitry Andric // LTO. Doing that changes the section it ends in, which surprises ld64. 344344290647SDimitry Andric if (getTriple().isOSBinFormatMachO()) 3444e7145dcbSDimitry Andric GV->setSection(isUTF16 ? "__TEXT,__ustring" 3445e7145dcbSDimitry Andric : "__TEXT,__cstring,cstring_literals"); 3446dff0c46cSDimitry Andric 3447dff0c46cSDimitry Andric // String. 344844290647SDimitry Andric llvm::Constant *Str = 344933956c43SDimitry Andric llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 3450f22ef01cSRoman Divacky 3451dff0c46cSDimitry Andric if (isUTF16) 3452dff0c46cSDimitry Andric // Cast the UTF16 string to the correct type. 345344290647SDimitry Andric Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy); 345444290647SDimitry Andric Fields.add(Str); 3455dff0c46cSDimitry Andric 3456f22ef01cSRoman Divacky // String length. 345744290647SDimitry Andric auto Ty = getTypes().ConvertType(getContext().LongTy); 345844290647SDimitry Andric Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength); 3459f22ef01cSRoman Divacky 34600623d748SDimitry Andric CharUnits Alignment = getPointerAlign(); 34610623d748SDimitry Andric 3462f22ef01cSRoman Divacky // The struct. 346344290647SDimitry Andric GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, 346444290647SDimitry Andric /*isConstant=*/false, 346544290647SDimitry Andric llvm::GlobalVariable::PrivateLinkage); 346644290647SDimitry Andric switch (getTriple().getObjectFormat()) { 3467e7145dcbSDimitry Andric case llvm::Triple::UnknownObjectFormat: 3468e7145dcbSDimitry Andric llvm_unreachable("unknown file format"); 3469e7145dcbSDimitry Andric case llvm::Triple::COFF: 3470e7145dcbSDimitry Andric case llvm::Triple::ELF: 347120e90f04SDimitry Andric case llvm::Triple::Wasm: 3472e7145dcbSDimitry Andric GV->setSection("cfstring"); 3473e7145dcbSDimitry Andric break; 3474e7145dcbSDimitry Andric case llvm::Triple::MachO: 3475e7145dcbSDimitry Andric GV->setSection("__DATA,__cfstring"); 3476e7145dcbSDimitry Andric break; 3477e7145dcbSDimitry Andric } 347839d628a0SDimitry Andric Entry.second = GV; 3479f22ef01cSRoman Divacky 34800623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3481f22ef01cSRoman Divacky } 3482f22ef01cSRoman Divacky 34836122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() { 34846122f3e6SDimitry Andric if (ObjCFastEnumerationStateType.isNull()) { 348559d1ed5bSDimitry Andric RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 34866122f3e6SDimitry Andric D->startDefinition(); 34876122f3e6SDimitry Andric 34886122f3e6SDimitry Andric QualType FieldTypes[] = { 34896122f3e6SDimitry Andric Context.UnsignedLongTy, 34906122f3e6SDimitry Andric Context.getPointerType(Context.getObjCIdType()), 34916122f3e6SDimitry Andric Context.getPointerType(Context.UnsignedLongTy), 34926122f3e6SDimitry Andric Context.getConstantArrayType(Context.UnsignedLongTy, 34936122f3e6SDimitry Andric llvm::APInt(32, 5), ArrayType::Normal, 0) 34946122f3e6SDimitry Andric }; 34956122f3e6SDimitry Andric 34966122f3e6SDimitry Andric for (size_t i = 0; i < 4; ++i) { 34976122f3e6SDimitry Andric FieldDecl *Field = FieldDecl::Create(Context, 34986122f3e6SDimitry Andric D, 34996122f3e6SDimitry Andric SourceLocation(), 350059d1ed5bSDimitry Andric SourceLocation(), nullptr, 350159d1ed5bSDimitry Andric FieldTypes[i], /*TInfo=*/nullptr, 350259d1ed5bSDimitry Andric /*BitWidth=*/nullptr, 35036122f3e6SDimitry Andric /*Mutable=*/false, 35047ae0e2c9SDimitry Andric ICIS_NoInit); 35056122f3e6SDimitry Andric Field->setAccess(AS_public); 35066122f3e6SDimitry Andric D->addDecl(Field); 35076122f3e6SDimitry Andric } 35086122f3e6SDimitry Andric 35096122f3e6SDimitry Andric D->completeDefinition(); 35106122f3e6SDimitry Andric ObjCFastEnumerationStateType = Context.getTagDeclType(D); 35116122f3e6SDimitry Andric } 35126122f3e6SDimitry Andric 35136122f3e6SDimitry Andric return ObjCFastEnumerationStateType; 35146122f3e6SDimitry Andric } 35156122f3e6SDimitry Andric 3516dff0c46cSDimitry Andric llvm::Constant * 3517dff0c46cSDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 3518dff0c46cSDimitry Andric assert(!E->getType()->isPointerType() && "Strings are always arrays"); 3519f22ef01cSRoman Divacky 3520dff0c46cSDimitry Andric // Don't emit it as the address of the string, emit the string data itself 3521dff0c46cSDimitry Andric // as an inline array. 3522dff0c46cSDimitry Andric if (E->getCharByteWidth() == 1) { 3523dff0c46cSDimitry Andric SmallString<64> Str(E->getString()); 3524f22ef01cSRoman Divacky 3525dff0c46cSDimitry Andric // Resize the string to the right size, which is indicated by its type. 3526dff0c46cSDimitry Andric const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 3527dff0c46cSDimitry Andric Str.resize(CAT->getSize().getZExtValue()); 3528dff0c46cSDimitry Andric return llvm::ConstantDataArray::getString(VMContext, Str, false); 35296122f3e6SDimitry Andric } 3530f22ef01cSRoman Divacky 353159d1ed5bSDimitry Andric auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 3532dff0c46cSDimitry Andric llvm::Type *ElemTy = AType->getElementType(); 3533dff0c46cSDimitry Andric unsigned NumElements = AType->getNumElements(); 3534f22ef01cSRoman Divacky 3535dff0c46cSDimitry Andric // Wide strings have either 2-byte or 4-byte elements. 3536dff0c46cSDimitry Andric if (ElemTy->getPrimitiveSizeInBits() == 16) { 3537dff0c46cSDimitry Andric SmallVector<uint16_t, 32> Elements; 3538dff0c46cSDimitry Andric Elements.reserve(NumElements); 3539dff0c46cSDimitry Andric 3540dff0c46cSDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 3541dff0c46cSDimitry Andric Elements.push_back(E->getCodeUnit(i)); 3542dff0c46cSDimitry Andric Elements.resize(NumElements); 3543dff0c46cSDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 3544dff0c46cSDimitry Andric } 3545dff0c46cSDimitry Andric 3546dff0c46cSDimitry Andric assert(ElemTy->getPrimitiveSizeInBits() == 32); 3547dff0c46cSDimitry Andric SmallVector<uint32_t, 32> Elements; 3548dff0c46cSDimitry Andric Elements.reserve(NumElements); 3549dff0c46cSDimitry Andric 3550dff0c46cSDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 3551dff0c46cSDimitry Andric Elements.push_back(E->getCodeUnit(i)); 3552dff0c46cSDimitry Andric Elements.resize(NumElements); 3553dff0c46cSDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 3554f22ef01cSRoman Divacky } 3555f22ef01cSRoman Divacky 355659d1ed5bSDimitry Andric static llvm::GlobalVariable * 355759d1ed5bSDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 355859d1ed5bSDimitry Andric CodeGenModule &CGM, StringRef GlobalName, 35590623d748SDimitry Andric CharUnits Alignment) { 356059d1ed5bSDimitry Andric // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 356159d1ed5bSDimitry Andric unsigned AddrSpace = 0; 356259d1ed5bSDimitry Andric if (CGM.getLangOpts().OpenCL) 356359d1ed5bSDimitry Andric AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant); 3564dff0c46cSDimitry Andric 356533956c43SDimitry Andric llvm::Module &M = CGM.getModule(); 356659d1ed5bSDimitry Andric // Create a global variable for this string 356759d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 356833956c43SDimitry Andric M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 356933956c43SDimitry Andric nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 35700623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 3571e7145dcbSDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 357233956c43SDimitry Andric if (GV->isWeakForLinker()) { 357333956c43SDimitry Andric assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 357433956c43SDimitry Andric GV->setComdat(M.getOrInsertComdat(GV->getName())); 357533956c43SDimitry Andric } 357633956c43SDimitry Andric 357759d1ed5bSDimitry Andric return GV; 3578f22ef01cSRoman Divacky } 3579dff0c46cSDimitry Andric 358059d1ed5bSDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 358159d1ed5bSDimitry Andric /// constant array for the given string literal. 35820623d748SDimitry Andric ConstantAddress 358339d628a0SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 358439d628a0SDimitry Andric StringRef Name) { 35850623d748SDimitry Andric CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 3586dff0c46cSDimitry Andric 358759d1ed5bSDimitry Andric llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 358859d1ed5bSDimitry Andric llvm::GlobalVariable **Entry = nullptr; 358959d1ed5bSDimitry Andric if (!LangOpts.WritableStrings) { 359059d1ed5bSDimitry Andric Entry = &ConstantStringMap[C]; 359159d1ed5bSDimitry Andric if (auto GV = *Entry) { 35920623d748SDimitry Andric if (Alignment.getQuantity() > GV->getAlignment()) 35930623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 35940623d748SDimitry Andric return ConstantAddress(GV, Alignment); 359559d1ed5bSDimitry Andric } 359659d1ed5bSDimitry Andric } 359759d1ed5bSDimitry Andric 359859d1ed5bSDimitry Andric SmallString<256> MangledNameBuffer; 359959d1ed5bSDimitry Andric StringRef GlobalVariableName; 360059d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes LT; 360159d1ed5bSDimitry Andric 360259d1ed5bSDimitry Andric // Mangle the string literal if the ABI allows for it. However, we cannot 360359d1ed5bSDimitry Andric // do this if we are compiling with ASan or -fwritable-strings because they 360459d1ed5bSDimitry Andric // rely on strings having normal linkage. 360539d628a0SDimitry Andric if (!LangOpts.WritableStrings && 360639d628a0SDimitry Andric !LangOpts.Sanitize.has(SanitizerKind::Address) && 360759d1ed5bSDimitry Andric getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) { 360859d1ed5bSDimitry Andric llvm::raw_svector_ostream Out(MangledNameBuffer); 360959d1ed5bSDimitry Andric getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 361059d1ed5bSDimitry Andric 361159d1ed5bSDimitry Andric LT = llvm::GlobalValue::LinkOnceODRLinkage; 361259d1ed5bSDimitry Andric GlobalVariableName = MangledNameBuffer; 361359d1ed5bSDimitry Andric } else { 361459d1ed5bSDimitry Andric LT = llvm::GlobalValue::PrivateLinkage; 361539d628a0SDimitry Andric GlobalVariableName = Name; 361659d1ed5bSDimitry Andric } 361759d1ed5bSDimitry Andric 361859d1ed5bSDimitry Andric auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 361959d1ed5bSDimitry Andric if (Entry) 362059d1ed5bSDimitry Andric *Entry = GV; 362159d1ed5bSDimitry Andric 362239d628a0SDimitry Andric SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>", 362339d628a0SDimitry Andric QualType()); 36240623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3625f22ef01cSRoman Divacky } 3626f22ef01cSRoman Divacky 3627f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 3628f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node. 36290623d748SDimitry Andric ConstantAddress 3630f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 3631f22ef01cSRoman Divacky std::string Str; 3632f22ef01cSRoman Divacky getContext().getObjCEncodingForType(E->getEncodedType(), Str); 3633f22ef01cSRoman Divacky 3634f22ef01cSRoman Divacky return GetAddrOfConstantCString(Str); 3635f22ef01cSRoman Divacky } 3636f22ef01cSRoman Divacky 363759d1ed5bSDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing 363859d1ed5bSDimitry Andric /// the literal and a terminating '\0' character. 363959d1ed5bSDimitry Andric /// The result has pointer to array type. 36400623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString( 36410623d748SDimitry Andric const std::string &Str, const char *GlobalName) { 364259d1ed5bSDimitry Andric StringRef StrWithNull(Str.c_str(), Str.size() + 1); 36430623d748SDimitry Andric CharUnits Alignment = 36440623d748SDimitry Andric getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 3645f22ef01cSRoman Divacky 364659d1ed5bSDimitry Andric llvm::Constant *C = 364759d1ed5bSDimitry Andric llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 364859d1ed5bSDimitry Andric 364959d1ed5bSDimitry Andric // Don't share any string literals if strings aren't constant. 365059d1ed5bSDimitry Andric llvm::GlobalVariable **Entry = nullptr; 365159d1ed5bSDimitry Andric if (!LangOpts.WritableStrings) { 365259d1ed5bSDimitry Andric Entry = &ConstantStringMap[C]; 365359d1ed5bSDimitry Andric if (auto GV = *Entry) { 36540623d748SDimitry Andric if (Alignment.getQuantity() > GV->getAlignment()) 36550623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 36560623d748SDimitry Andric return ConstantAddress(GV, Alignment); 365759d1ed5bSDimitry Andric } 365859d1ed5bSDimitry Andric } 365959d1ed5bSDimitry Andric 3660f22ef01cSRoman Divacky // Get the default prefix if a name wasn't specified. 3661f22ef01cSRoman Divacky if (!GlobalName) 3662f22ef01cSRoman Divacky GlobalName = ".str"; 3663f22ef01cSRoman Divacky // Create a global variable for this. 366459d1ed5bSDimitry Andric auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 366559d1ed5bSDimitry Andric GlobalName, Alignment); 366659d1ed5bSDimitry Andric if (Entry) 366759d1ed5bSDimitry Andric *Entry = GV; 36680623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3669f22ef01cSRoman Divacky } 3670f22ef01cSRoman Divacky 36710623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 3672f785676fSDimitry Andric const MaterializeTemporaryExpr *E, const Expr *Init) { 3673f785676fSDimitry Andric assert((E->getStorageDuration() == SD_Static || 3674f785676fSDimitry Andric E->getStorageDuration() == SD_Thread) && "not a global temporary"); 367559d1ed5bSDimitry Andric const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 3676f785676fSDimitry Andric 3677f785676fSDimitry Andric // If we're not materializing a subobject of the temporary, keep the 3678f785676fSDimitry Andric // cv-qualifiers from the type of the MaterializeTemporaryExpr. 3679f785676fSDimitry Andric QualType MaterializedType = Init->getType(); 3680f785676fSDimitry Andric if (Init == E->GetTemporaryExpr()) 3681f785676fSDimitry Andric MaterializedType = E->getType(); 3682f785676fSDimitry Andric 36830623d748SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 36840623d748SDimitry Andric 36850623d748SDimitry Andric if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E]) 36860623d748SDimitry Andric return ConstantAddress(Slot, Align); 3687f785676fSDimitry Andric 3688f785676fSDimitry Andric // FIXME: If an externally-visible declaration extends multiple temporaries, 3689f785676fSDimitry Andric // we need to give each temporary the same name in every translation unit (and 3690f785676fSDimitry Andric // we also need to make the temporaries externally-visible). 3691f785676fSDimitry Andric SmallString<256> Name; 3692f785676fSDimitry Andric llvm::raw_svector_ostream Out(Name); 369359d1ed5bSDimitry Andric getCXXABI().getMangleContext().mangleReferenceTemporary( 369459d1ed5bSDimitry Andric VD, E->getManglingNumber(), Out); 3695f785676fSDimitry Andric 369659d1ed5bSDimitry Andric APValue *Value = nullptr; 3697f785676fSDimitry Andric if (E->getStorageDuration() == SD_Static) { 3698f785676fSDimitry Andric // We might have a cached constant initializer for this temporary. Note 3699f785676fSDimitry Andric // that this might have a different value from the value computed by 3700f785676fSDimitry Andric // evaluating the initializer if the surrounding constant expression 3701f785676fSDimitry Andric // modifies the temporary. 3702f785676fSDimitry Andric Value = getContext().getMaterializedTemporaryValue(E, false); 3703f785676fSDimitry Andric if (Value && Value->isUninit()) 370459d1ed5bSDimitry Andric Value = nullptr; 3705f785676fSDimitry Andric } 3706f785676fSDimitry Andric 3707f785676fSDimitry Andric // Try evaluating it now, it might have a constant initializer. 3708f785676fSDimitry Andric Expr::EvalResult EvalResult; 3709f785676fSDimitry Andric if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 3710f785676fSDimitry Andric !EvalResult.hasSideEffects()) 3711f785676fSDimitry Andric Value = &EvalResult.Val; 3712f785676fSDimitry Andric 371359d1ed5bSDimitry Andric llvm::Constant *InitialValue = nullptr; 3714f785676fSDimitry Andric bool Constant = false; 3715f785676fSDimitry Andric llvm::Type *Type; 3716f785676fSDimitry Andric if (Value) { 3717f785676fSDimitry Andric // The temporary has a constant initializer, use it. 371859d1ed5bSDimitry Andric InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr); 3719f785676fSDimitry Andric Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 3720f785676fSDimitry Andric Type = InitialValue->getType(); 3721f785676fSDimitry Andric } else { 3722f785676fSDimitry Andric // No initializer, the initialization will be provided when we 3723f785676fSDimitry Andric // initialize the declaration which performed lifetime extension. 3724f785676fSDimitry Andric Type = getTypes().ConvertTypeForMem(MaterializedType); 3725f785676fSDimitry Andric } 3726f785676fSDimitry Andric 3727f785676fSDimitry Andric // Create a global variable for this lifetime-extended temporary. 372859d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 372959d1ed5bSDimitry Andric getLLVMLinkageVarDefinition(VD, Constant); 373033956c43SDimitry Andric if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 373133956c43SDimitry Andric const VarDecl *InitVD; 373233956c43SDimitry Andric if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 373333956c43SDimitry Andric isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 373433956c43SDimitry Andric // Temporaries defined inside a class get linkonce_odr linkage because the 373533956c43SDimitry Andric // class can be defined in multipe translation units. 373633956c43SDimitry Andric Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 373733956c43SDimitry Andric } else { 373833956c43SDimitry Andric // There is no need for this temporary to have external linkage if the 373933956c43SDimitry Andric // VarDecl has external linkage. 374033956c43SDimitry Andric Linkage = llvm::GlobalVariable::InternalLinkage; 374133956c43SDimitry Andric } 374233956c43SDimitry Andric } 374359d1ed5bSDimitry Andric unsigned AddrSpace = GetGlobalVarAddressSpace( 374459d1ed5bSDimitry Andric VD, getContext().getTargetAddressSpace(MaterializedType)); 374559d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 374659d1ed5bSDimitry Andric getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 374759d1ed5bSDimitry Andric /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, 374859d1ed5bSDimitry Andric AddrSpace); 374959d1ed5bSDimitry Andric setGlobalVisibility(GV, VD); 37500623d748SDimitry Andric GV->setAlignment(Align.getQuantity()); 375133956c43SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker()) 375233956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3753f785676fSDimitry Andric if (VD->getTLSKind()) 3754f785676fSDimitry Andric setTLSMode(GV, *VD); 37550623d748SDimitry Andric MaterializedGlobalTemporaryMap[E] = GV; 37560623d748SDimitry Andric return ConstantAddress(GV, Align); 3757f785676fSDimitry Andric } 3758f785676fSDimitry Andric 3759f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized 3760f22ef01cSRoman Divacky /// properties for an implementation. 3761f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const 3762f22ef01cSRoman Divacky ObjCImplementationDecl *D) { 376359d1ed5bSDimitry Andric for (const auto *PID : D->property_impls()) { 3764f22ef01cSRoman Divacky // Dynamic is just for type-checking. 3765f22ef01cSRoman Divacky if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 3766f22ef01cSRoman Divacky ObjCPropertyDecl *PD = PID->getPropertyDecl(); 3767f22ef01cSRoman Divacky 3768f22ef01cSRoman Divacky // Determine which methods need to be implemented, some may have 37693861d79fSDimitry Andric // been overridden. Note that ::isPropertyAccessor is not the method 3770f22ef01cSRoman Divacky // we want, that just indicates if the decl came from a 3771f22ef01cSRoman Divacky // property. What we want to know is if the method is defined in 3772f22ef01cSRoman Divacky // this implementation. 3773f22ef01cSRoman Divacky if (!D->getInstanceMethod(PD->getGetterName())) 3774f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCGetter( 3775f22ef01cSRoman Divacky const_cast<ObjCImplementationDecl *>(D), PID); 3776f22ef01cSRoman Divacky if (!PD->isReadOnly() && 3777f22ef01cSRoman Divacky !D->getInstanceMethod(PD->getSetterName())) 3778f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCSetter( 3779f22ef01cSRoman Divacky const_cast<ObjCImplementationDecl *>(D), PID); 3780f22ef01cSRoman Divacky } 3781f22ef01cSRoman Divacky } 3782f22ef01cSRoman Divacky } 3783f22ef01cSRoman Divacky 37843b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) { 37856122f3e6SDimitry Andric const ObjCInterfaceDecl *iface = impl->getClassInterface(); 37866122f3e6SDimitry Andric for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 37873b0f4066SDimitry Andric ivar; ivar = ivar->getNextIvar()) 37883b0f4066SDimitry Andric if (ivar->getType().isDestructedType()) 37893b0f4066SDimitry Andric return true; 37903b0f4066SDimitry Andric 37913b0f4066SDimitry Andric return false; 37923b0f4066SDimitry Andric } 37933b0f4066SDimitry Andric 379439d628a0SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM, 379539d628a0SDimitry Andric ObjCImplementationDecl *D) { 379639d628a0SDimitry Andric CodeGenFunction CGF(CGM); 379739d628a0SDimitry Andric for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 379839d628a0SDimitry Andric E = D->init_end(); B != E; ++B) { 379939d628a0SDimitry Andric CXXCtorInitializer *CtorInitExp = *B; 380039d628a0SDimitry Andric Expr *Init = CtorInitExp->getInit(); 380139d628a0SDimitry Andric if (!CGF.isTrivialInitializer(Init)) 380239d628a0SDimitry Andric return false; 380339d628a0SDimitry Andric } 380439d628a0SDimitry Andric return true; 380539d628a0SDimitry Andric } 380639d628a0SDimitry Andric 3807f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization 3808f22ef01cSRoman Divacky /// for an implementation. 3809f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 38103b0f4066SDimitry Andric // We might need a .cxx_destruct even if we don't have any ivar initializers. 38113b0f4066SDimitry Andric if (needsDestructMethod(D)) { 3812f22ef01cSRoman Divacky IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 3813f22ef01cSRoman Divacky Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 38143b0f4066SDimitry Andric ObjCMethodDecl *DTORMethod = 38153b0f4066SDimitry Andric ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 381659d1ed5bSDimitry Andric cxxSelector, getContext().VoidTy, nullptr, D, 38176122f3e6SDimitry Andric /*isInstance=*/true, /*isVariadic=*/false, 38183861d79fSDimitry Andric /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 38196122f3e6SDimitry Andric /*isDefined=*/false, ObjCMethodDecl::Required); 3820f22ef01cSRoman Divacky D->addInstanceMethod(DTORMethod); 3821f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 38223861d79fSDimitry Andric D->setHasDestructors(true); 38233b0f4066SDimitry Andric } 3824f22ef01cSRoman Divacky 38253b0f4066SDimitry Andric // If the implementation doesn't have any ivar initializers, we don't need 38263b0f4066SDimitry Andric // a .cxx_construct. 382739d628a0SDimitry Andric if (D->getNumIvarInitializers() == 0 || 382839d628a0SDimitry Andric AllTrivialInitializers(*this, D)) 38293b0f4066SDimitry Andric return; 38303b0f4066SDimitry Andric 38313b0f4066SDimitry Andric IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 38323b0f4066SDimitry Andric Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 3833f22ef01cSRoman Divacky // The constructor returns 'self'. 3834f22ef01cSRoman Divacky ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 3835f22ef01cSRoman Divacky D->getLocation(), 38366122f3e6SDimitry Andric D->getLocation(), 38376122f3e6SDimitry Andric cxxSelector, 383859d1ed5bSDimitry Andric getContext().getObjCIdType(), 383959d1ed5bSDimitry Andric nullptr, D, /*isInstance=*/true, 38406122f3e6SDimitry Andric /*isVariadic=*/false, 38413861d79fSDimitry Andric /*isPropertyAccessor=*/true, 38426122f3e6SDimitry Andric /*isImplicitlyDeclared=*/true, 38436122f3e6SDimitry Andric /*isDefined=*/false, 3844f22ef01cSRoman Divacky ObjCMethodDecl::Required); 3845f22ef01cSRoman Divacky D->addInstanceMethod(CTORMethod); 3846f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 38473861d79fSDimitry Andric D->setHasNonZeroConstructors(true); 3848f22ef01cSRoman Divacky } 3849f22ef01cSRoman Divacky 3850f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec. 3851f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 3852f22ef01cSRoman Divacky if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 3853f22ef01cSRoman Divacky LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 3854f22ef01cSRoman Divacky ErrorUnsupported(LSD, "linkage spec"); 3855f22ef01cSRoman Divacky return; 3856f22ef01cSRoman Divacky } 3857f22ef01cSRoman Divacky 385844290647SDimitry Andric EmitDeclContext(LSD); 385944290647SDimitry Andric } 386044290647SDimitry Andric 386144290647SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) { 386244290647SDimitry Andric for (auto *I : DC->decls()) { 386344290647SDimitry Andric // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope 386444290647SDimitry Andric // are themselves considered "top-level", so EmitTopLevelDecl on an 386544290647SDimitry Andric // ObjCImplDecl does not recursively visit them. We need to do that in 386644290647SDimitry Andric // case they're nested inside another construct (LinkageSpecDecl / 386744290647SDimitry Andric // ExportDecl) that does stop them from being considered "top-level". 386859d1ed5bSDimitry Andric if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 386959d1ed5bSDimitry Andric for (auto *M : OID->methods()) 387059d1ed5bSDimitry Andric EmitTopLevelDecl(M); 38713861d79fSDimitry Andric } 387244290647SDimitry Andric 387359d1ed5bSDimitry Andric EmitTopLevelDecl(I); 3874f22ef01cSRoman Divacky } 38753861d79fSDimitry Andric } 3876f22ef01cSRoman Divacky 3877f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration. 3878f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) { 3879f22ef01cSRoman Divacky // Ignore dependent declarations. 3880f22ef01cSRoman Divacky if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 3881f22ef01cSRoman Divacky return; 3882f22ef01cSRoman Divacky 3883f22ef01cSRoman Divacky switch (D->getKind()) { 3884f22ef01cSRoman Divacky case Decl::CXXConversion: 3885f22ef01cSRoman Divacky case Decl::CXXMethod: 3886f22ef01cSRoman Divacky case Decl::Function: 3887f22ef01cSRoman Divacky // Skip function templates 38883b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 38893b0f4066SDimitry Andric cast<FunctionDecl>(D)->isLateTemplateParsed()) 3890f22ef01cSRoman Divacky return; 3891f22ef01cSRoman Divacky 3892f22ef01cSRoman Divacky EmitGlobal(cast<FunctionDecl>(D)); 389339d628a0SDimitry Andric // Always provide some coverage mapping 389439d628a0SDimitry Andric // even for the functions that aren't emitted. 389539d628a0SDimitry Andric AddDeferredUnusedCoverageMapping(D); 3896f22ef01cSRoman Divacky break; 3897f22ef01cSRoman Divacky 38986bc11b14SDimitry Andric case Decl::CXXDeductionGuide: 38996bc11b14SDimitry Andric // Function-like, but does not result in code emission. 39006bc11b14SDimitry Andric break; 39016bc11b14SDimitry Andric 3902f22ef01cSRoman Divacky case Decl::Var: 390344290647SDimitry Andric case Decl::Decomposition: 3904f785676fSDimitry Andric // Skip variable templates 3905f785676fSDimitry Andric if (cast<VarDecl>(D)->getDescribedVarTemplate()) 3906f785676fSDimitry Andric return; 39076d97bb29SDimitry Andric LLVM_FALLTHROUGH; 3908f785676fSDimitry Andric case Decl::VarTemplateSpecialization: 3909f22ef01cSRoman Divacky EmitGlobal(cast<VarDecl>(D)); 391044290647SDimitry Andric if (auto *DD = dyn_cast<DecompositionDecl>(D)) 391144290647SDimitry Andric for (auto *B : DD->bindings()) 391244290647SDimitry Andric if (auto *HD = B->getHoldingVar()) 391344290647SDimitry Andric EmitGlobal(HD); 3914f22ef01cSRoman Divacky break; 3915f22ef01cSRoman Divacky 39163b0f4066SDimitry Andric // Indirect fields from global anonymous structs and unions can be 39173b0f4066SDimitry Andric // ignored; only the actual variable requires IR gen support. 39183b0f4066SDimitry Andric case Decl::IndirectField: 39193b0f4066SDimitry Andric break; 39203b0f4066SDimitry Andric 3921f22ef01cSRoman Divacky // C++ Decls 3922f22ef01cSRoman Divacky case Decl::Namespace: 392344290647SDimitry Andric EmitDeclContext(cast<NamespaceDecl>(D)); 3924f22ef01cSRoman Divacky break; 3925e7145dcbSDimitry Andric case Decl::CXXRecord: 392620e90f04SDimitry Andric if (DebugInfo) { 392720e90f04SDimitry Andric if (auto *ES = D->getASTContext().getExternalSource()) 392820e90f04SDimitry Andric if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) 392920e90f04SDimitry Andric DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D)); 393020e90f04SDimitry Andric } 3931e7145dcbSDimitry Andric // Emit any static data members, they may be definitions. 3932e7145dcbSDimitry Andric for (auto *I : cast<CXXRecordDecl>(D)->decls()) 3933e7145dcbSDimitry Andric if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) 3934e7145dcbSDimitry Andric EmitTopLevelDecl(I); 3935e7145dcbSDimitry Andric break; 3936f22ef01cSRoman Divacky // No code generation needed. 3937f22ef01cSRoman Divacky case Decl::UsingShadow: 3938f22ef01cSRoman Divacky case Decl::ClassTemplate: 3939f785676fSDimitry Andric case Decl::VarTemplate: 3940f785676fSDimitry Andric case Decl::VarTemplatePartialSpecialization: 3941f22ef01cSRoman Divacky case Decl::FunctionTemplate: 3942bd5abe19SDimitry Andric case Decl::TypeAliasTemplate: 3943bd5abe19SDimitry Andric case Decl::Block: 3944139f7f9bSDimitry Andric case Decl::Empty: 3945f22ef01cSRoman Divacky break; 394659d1ed5bSDimitry Andric case Decl::Using: // using X; [C++] 394759d1ed5bSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 394859d1ed5bSDimitry Andric DI->EmitUsingDecl(cast<UsingDecl>(*D)); 394959d1ed5bSDimitry Andric return; 3950f785676fSDimitry Andric case Decl::NamespaceAlias: 3951f785676fSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3952f785676fSDimitry Andric DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 3953f785676fSDimitry Andric return; 3954284c1978SDimitry Andric case Decl::UsingDirective: // using namespace X; [C++] 3955284c1978SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3956284c1978SDimitry Andric DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 3957284c1978SDimitry Andric return; 3958f22ef01cSRoman Divacky case Decl::CXXConstructor: 3959f22ef01cSRoman Divacky // Skip function templates 39603b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 39613b0f4066SDimitry Andric cast<FunctionDecl>(D)->isLateTemplateParsed()) 3962f22ef01cSRoman Divacky return; 3963f22ef01cSRoman Divacky 3964f785676fSDimitry Andric getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 3965f22ef01cSRoman Divacky break; 3966f22ef01cSRoman Divacky case Decl::CXXDestructor: 39673b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 39683b0f4066SDimitry Andric return; 3969f785676fSDimitry Andric getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 3970f22ef01cSRoman Divacky break; 3971f22ef01cSRoman Divacky 3972f22ef01cSRoman Divacky case Decl::StaticAssert: 3973f22ef01cSRoman Divacky // Nothing to do. 3974f22ef01cSRoman Divacky break; 3975f22ef01cSRoman Divacky 3976f22ef01cSRoman Divacky // Objective-C Decls 3977f22ef01cSRoman Divacky 3978f22ef01cSRoman Divacky // Forward declarations, no (immediate) code generation. 3979f22ef01cSRoman Divacky case Decl::ObjCInterface: 39807ae0e2c9SDimitry Andric case Decl::ObjCCategory: 3981f22ef01cSRoman Divacky break; 3982f22ef01cSRoman Divacky 3983dff0c46cSDimitry Andric case Decl::ObjCProtocol: { 398459d1ed5bSDimitry Andric auto *Proto = cast<ObjCProtocolDecl>(D); 3985dff0c46cSDimitry Andric if (Proto->isThisDeclarationADefinition()) 3986dff0c46cSDimitry Andric ObjCRuntime->GenerateProtocol(Proto); 3987f22ef01cSRoman Divacky break; 3988dff0c46cSDimitry Andric } 3989f22ef01cSRoman Divacky 3990f22ef01cSRoman Divacky case Decl::ObjCCategoryImpl: 3991f22ef01cSRoman Divacky // Categories have properties but don't support synthesize so we 3992f22ef01cSRoman Divacky // can ignore them here. 39936122f3e6SDimitry Andric ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 3994f22ef01cSRoman Divacky break; 3995f22ef01cSRoman Divacky 3996f22ef01cSRoman Divacky case Decl::ObjCImplementation: { 399759d1ed5bSDimitry Andric auto *OMD = cast<ObjCImplementationDecl>(D); 3998f22ef01cSRoman Divacky EmitObjCPropertyImplementations(OMD); 3999f22ef01cSRoman Divacky EmitObjCIvarInitializations(OMD); 40006122f3e6SDimitry Andric ObjCRuntime->GenerateClass(OMD); 4001dff0c46cSDimitry Andric // Emit global variable debug information. 4002dff0c46cSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 4003e7145dcbSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) 4004139f7f9bSDimitry Andric DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 4005139f7f9bSDimitry Andric OMD->getClassInterface()), OMD->getLocation()); 4006f22ef01cSRoman Divacky break; 4007f22ef01cSRoman Divacky } 4008f22ef01cSRoman Divacky case Decl::ObjCMethod: { 400959d1ed5bSDimitry Andric auto *OMD = cast<ObjCMethodDecl>(D); 4010f22ef01cSRoman Divacky // If this is not a prototype, emit the body. 4011f22ef01cSRoman Divacky if (OMD->getBody()) 4012f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCMethod(OMD); 4013f22ef01cSRoman Divacky break; 4014f22ef01cSRoman Divacky } 4015f22ef01cSRoman Divacky case Decl::ObjCCompatibleAlias: 4016dff0c46cSDimitry Andric ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 4017f22ef01cSRoman Divacky break; 4018f22ef01cSRoman Divacky 4019e7145dcbSDimitry Andric case Decl::PragmaComment: { 4020e7145dcbSDimitry Andric const auto *PCD = cast<PragmaCommentDecl>(D); 4021e7145dcbSDimitry Andric switch (PCD->getCommentKind()) { 4022e7145dcbSDimitry Andric case PCK_Unknown: 4023e7145dcbSDimitry Andric llvm_unreachable("unexpected pragma comment kind"); 4024e7145dcbSDimitry Andric case PCK_Linker: 4025e7145dcbSDimitry Andric AppendLinkerOptions(PCD->getArg()); 4026e7145dcbSDimitry Andric break; 4027e7145dcbSDimitry Andric case PCK_Lib: 4028e7145dcbSDimitry Andric AddDependentLib(PCD->getArg()); 4029e7145dcbSDimitry Andric break; 4030e7145dcbSDimitry Andric case PCK_Compiler: 4031e7145dcbSDimitry Andric case PCK_ExeStr: 4032e7145dcbSDimitry Andric case PCK_User: 4033e7145dcbSDimitry Andric break; // We ignore all of these. 4034e7145dcbSDimitry Andric } 4035e7145dcbSDimitry Andric break; 4036e7145dcbSDimitry Andric } 4037e7145dcbSDimitry Andric 4038e7145dcbSDimitry Andric case Decl::PragmaDetectMismatch: { 4039e7145dcbSDimitry Andric const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 4040e7145dcbSDimitry Andric AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 4041e7145dcbSDimitry Andric break; 4042e7145dcbSDimitry Andric } 4043e7145dcbSDimitry Andric 4044f22ef01cSRoman Divacky case Decl::LinkageSpec: 4045f22ef01cSRoman Divacky EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 4046f22ef01cSRoman Divacky break; 4047f22ef01cSRoman Divacky 4048f22ef01cSRoman Divacky case Decl::FileScopeAsm: { 404933956c43SDimitry Andric // File-scope asm is ignored during device-side CUDA compilation. 405033956c43SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 405133956c43SDimitry Andric break; 4052ea942507SDimitry Andric // File-scope asm is ignored during device-side OpenMP compilation. 4053ea942507SDimitry Andric if (LangOpts.OpenMPIsDevice) 4054ea942507SDimitry Andric break; 405559d1ed5bSDimitry Andric auto *AD = cast<FileScopeAsmDecl>(D); 405633956c43SDimitry Andric getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 4057f22ef01cSRoman Divacky break; 4058f22ef01cSRoman Divacky } 4059f22ef01cSRoman Divacky 4060139f7f9bSDimitry Andric case Decl::Import: { 406159d1ed5bSDimitry Andric auto *Import = cast<ImportDecl>(D); 4062139f7f9bSDimitry Andric 406344290647SDimitry Andric // If we've already imported this module, we're done. 406444290647SDimitry Andric if (!ImportedModules.insert(Import->getImportedModule())) 4065139f7f9bSDimitry Andric break; 406644290647SDimitry Andric 406744290647SDimitry Andric // Emit debug information for direct imports. 406844290647SDimitry Andric if (!Import->getImportedOwningModule()) { 40693dac3a9bSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 40703dac3a9bSDimitry Andric DI->EmitImportDecl(*Import); 407144290647SDimitry Andric } 4072139f7f9bSDimitry Andric 407344290647SDimitry Andric // Find all of the submodules and emit the module initializers. 407444290647SDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 407544290647SDimitry Andric SmallVector<clang::Module *, 16> Stack; 407644290647SDimitry Andric Visited.insert(Import->getImportedModule()); 407744290647SDimitry Andric Stack.push_back(Import->getImportedModule()); 407844290647SDimitry Andric 407944290647SDimitry Andric while (!Stack.empty()) { 408044290647SDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 408144290647SDimitry Andric if (!EmittedModuleInitializers.insert(Mod).second) 408244290647SDimitry Andric continue; 408344290647SDimitry Andric 408444290647SDimitry Andric for (auto *D : Context.getModuleInitializers(Mod)) 408544290647SDimitry Andric EmitTopLevelDecl(D); 408644290647SDimitry Andric 408744290647SDimitry Andric // Visit the submodules of this module. 408844290647SDimitry Andric for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 408944290647SDimitry Andric SubEnd = Mod->submodule_end(); 409044290647SDimitry Andric Sub != SubEnd; ++Sub) { 409144290647SDimitry Andric // Skip explicit children; they need to be explicitly imported to emit 409244290647SDimitry Andric // the initializers. 409344290647SDimitry Andric if ((*Sub)->IsExplicit) 409444290647SDimitry Andric continue; 409544290647SDimitry Andric 409644290647SDimitry Andric if (Visited.insert(*Sub).second) 409744290647SDimitry Andric Stack.push_back(*Sub); 409844290647SDimitry Andric } 409944290647SDimitry Andric } 4100139f7f9bSDimitry Andric break; 4101139f7f9bSDimitry Andric } 4102139f7f9bSDimitry Andric 410344290647SDimitry Andric case Decl::Export: 410444290647SDimitry Andric EmitDeclContext(cast<ExportDecl>(D)); 410544290647SDimitry Andric break; 410644290647SDimitry Andric 410739d628a0SDimitry Andric case Decl::OMPThreadPrivate: 410839d628a0SDimitry Andric EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 410939d628a0SDimitry Andric break; 411039d628a0SDimitry Andric 411159d1ed5bSDimitry Andric case Decl::ClassTemplateSpecialization: { 411259d1ed5bSDimitry Andric const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 411359d1ed5bSDimitry Andric if (DebugInfo && 411439d628a0SDimitry Andric Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition && 411539d628a0SDimitry Andric Spec->hasDefinition()) 411659d1ed5bSDimitry Andric DebugInfo->completeTemplateDefinition(*Spec); 411739d628a0SDimitry Andric break; 411859d1ed5bSDimitry Andric } 411959d1ed5bSDimitry Andric 4120e7145dcbSDimitry Andric case Decl::OMPDeclareReduction: 4121e7145dcbSDimitry Andric EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 4122e7145dcbSDimitry Andric break; 4123e7145dcbSDimitry Andric 4124f22ef01cSRoman Divacky default: 4125f22ef01cSRoman Divacky // Make sure we handled everything we should, every other kind is a 4126f22ef01cSRoman Divacky // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 4127f22ef01cSRoman Divacky // function. Need to recode Decl::Kind to do that easily. 4128f22ef01cSRoman Divacky assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 412939d628a0SDimitry Andric break; 413039d628a0SDimitry Andric } 413139d628a0SDimitry Andric } 413239d628a0SDimitry Andric 413339d628a0SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 413439d628a0SDimitry Andric // Do we need to generate coverage mapping? 413539d628a0SDimitry Andric if (!CodeGenOpts.CoverageMapping) 413639d628a0SDimitry Andric return; 413739d628a0SDimitry Andric switch (D->getKind()) { 413839d628a0SDimitry Andric case Decl::CXXConversion: 413939d628a0SDimitry Andric case Decl::CXXMethod: 414039d628a0SDimitry Andric case Decl::Function: 414139d628a0SDimitry Andric case Decl::ObjCMethod: 414239d628a0SDimitry Andric case Decl::CXXConstructor: 414339d628a0SDimitry Andric case Decl::CXXDestructor: { 41440623d748SDimitry Andric if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 414539d628a0SDimitry Andric return; 414639d628a0SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 414739d628a0SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 414839d628a0SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = true; 414939d628a0SDimitry Andric break; 415039d628a0SDimitry Andric } 415139d628a0SDimitry Andric default: 415239d628a0SDimitry Andric break; 415339d628a0SDimitry Andric }; 415439d628a0SDimitry Andric } 415539d628a0SDimitry Andric 415639d628a0SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 415739d628a0SDimitry Andric // Do we need to generate coverage mapping? 415839d628a0SDimitry Andric if (!CodeGenOpts.CoverageMapping) 415939d628a0SDimitry Andric return; 416039d628a0SDimitry Andric if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 416139d628a0SDimitry Andric if (Fn->isTemplateInstantiation()) 416239d628a0SDimitry Andric ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 416339d628a0SDimitry Andric } 416439d628a0SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 416539d628a0SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 416639d628a0SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = false; 416739d628a0SDimitry Andric else 416839d628a0SDimitry Andric I->second = false; 416939d628a0SDimitry Andric } 417039d628a0SDimitry Andric 417139d628a0SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 417239d628a0SDimitry Andric std::vector<const Decl *> DeferredDecls; 417333956c43SDimitry Andric for (const auto &I : DeferredEmptyCoverageMappingDecls) { 417439d628a0SDimitry Andric if (!I.second) 417539d628a0SDimitry Andric continue; 417639d628a0SDimitry Andric DeferredDecls.push_back(I.first); 417739d628a0SDimitry Andric } 417839d628a0SDimitry Andric // Sort the declarations by their location to make sure that the tests get a 417939d628a0SDimitry Andric // predictable order for the coverage mapping for the unused declarations. 418039d628a0SDimitry Andric if (CodeGenOpts.DumpCoverageMapping) 418139d628a0SDimitry Andric std::sort(DeferredDecls.begin(), DeferredDecls.end(), 418239d628a0SDimitry Andric [] (const Decl *LHS, const Decl *RHS) { 418339d628a0SDimitry Andric return LHS->getLocStart() < RHS->getLocStart(); 418439d628a0SDimitry Andric }); 418539d628a0SDimitry Andric for (const auto *D : DeferredDecls) { 418639d628a0SDimitry Andric switch (D->getKind()) { 418739d628a0SDimitry Andric case Decl::CXXConversion: 418839d628a0SDimitry Andric case Decl::CXXMethod: 418939d628a0SDimitry Andric case Decl::Function: 419039d628a0SDimitry Andric case Decl::ObjCMethod: { 419139d628a0SDimitry Andric CodeGenPGO PGO(*this); 419239d628a0SDimitry Andric GlobalDecl GD(cast<FunctionDecl>(D)); 419339d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 419439d628a0SDimitry Andric getFunctionLinkage(GD)); 419539d628a0SDimitry Andric break; 419639d628a0SDimitry Andric } 419739d628a0SDimitry Andric case Decl::CXXConstructor: { 419839d628a0SDimitry Andric CodeGenPGO PGO(*this); 419939d628a0SDimitry Andric GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 420039d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 420139d628a0SDimitry Andric getFunctionLinkage(GD)); 420239d628a0SDimitry Andric break; 420339d628a0SDimitry Andric } 420439d628a0SDimitry Andric case Decl::CXXDestructor: { 420539d628a0SDimitry Andric CodeGenPGO PGO(*this); 420639d628a0SDimitry Andric GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 420739d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 420839d628a0SDimitry Andric getFunctionLinkage(GD)); 420939d628a0SDimitry Andric break; 421039d628a0SDimitry Andric } 421139d628a0SDimitry Andric default: 421239d628a0SDimitry Andric break; 421339d628a0SDimitry Andric }; 4214f22ef01cSRoman Divacky } 4215f22ef01cSRoman Divacky } 4216ffd1746dSEd Schouten 4217ffd1746dSEd Schouten /// Turns the given pointer into a constant. 4218ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 4219ffd1746dSEd Schouten const void *Ptr) { 4220ffd1746dSEd Schouten uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 42216122f3e6SDimitry Andric llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 4222ffd1746dSEd Schouten return llvm::ConstantInt::get(i64, PtrInt); 4223ffd1746dSEd Schouten } 4224ffd1746dSEd Schouten 4225ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 4226ffd1746dSEd Schouten llvm::NamedMDNode *&GlobalMetadata, 4227ffd1746dSEd Schouten GlobalDecl D, 4228ffd1746dSEd Schouten llvm::GlobalValue *Addr) { 4229ffd1746dSEd Schouten if (!GlobalMetadata) 4230ffd1746dSEd Schouten GlobalMetadata = 4231ffd1746dSEd Schouten CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 4232ffd1746dSEd Schouten 4233ffd1746dSEd Schouten // TODO: should we report variant information for ctors/dtors? 423439d628a0SDimitry Andric llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 423539d628a0SDimitry Andric llvm::ConstantAsMetadata::get(GetPointerConstant( 423639d628a0SDimitry Andric CGM.getLLVMContext(), D.getDecl()))}; 42373b0f4066SDimitry Andric GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 4238ffd1746dSEd Schouten } 4239ffd1746dSEd Schouten 4240284c1978SDimitry Andric /// For each function which is declared within an extern "C" region and marked 4241284c1978SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled 4242284c1978SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer 4243284c1978SDimitry Andric /// to such functions with an unmangled name from inline assembly within the 4244284c1978SDimitry Andric /// same translation unit. 4245284c1978SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() { 4246e7145dcbSDimitry Andric // Don't do anything if we're generating CUDA device code -- the NVPTX 4247e7145dcbSDimitry Andric // assembly target doesn't support aliases. 4248e7145dcbSDimitry Andric if (Context.getTargetInfo().getTriple().isNVPTX()) 4249e7145dcbSDimitry Andric return; 42508f0fd8f6SDimitry Andric for (auto &I : StaticExternCValues) { 42518f0fd8f6SDimitry Andric IdentifierInfo *Name = I.first; 42528f0fd8f6SDimitry Andric llvm::GlobalValue *Val = I.second; 4253284c1978SDimitry Andric if (Val && !getModule().getNamedValue(Name->getName())) 425459d1ed5bSDimitry Andric addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 4255284c1978SDimitry Andric } 4256284c1978SDimitry Andric } 4257284c1978SDimitry Andric 425859d1ed5bSDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 425959d1ed5bSDimitry Andric GlobalDecl &Result) const { 426059d1ed5bSDimitry Andric auto Res = Manglings.find(MangledName); 426159d1ed5bSDimitry Andric if (Res == Manglings.end()) 426259d1ed5bSDimitry Andric return false; 426359d1ed5bSDimitry Andric Result = Res->getValue(); 426459d1ed5bSDimitry Andric return true; 426559d1ed5bSDimitry Andric } 426659d1ed5bSDimitry Andric 4267ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the 4268ffd1746dSEd Schouten /// current module with the Decls they came from. This is useful for 4269ffd1746dSEd Schouten /// projects using IR gen as a subroutine. 4270ffd1746dSEd Schouten /// 4271ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly 4272ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata 4273ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'. 4274ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() { 427559d1ed5bSDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 4276ffd1746dSEd Schouten 427759d1ed5bSDimitry Andric for (auto &I : MangledDeclNames) { 427859d1ed5bSDimitry Andric llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 42790623d748SDimitry Andric // Some mangled names don't necessarily have an associated GlobalValue 42800623d748SDimitry Andric // in this module, e.g. if we mangled it for DebugInfo. 42810623d748SDimitry Andric if (Addr) 428259d1ed5bSDimitry Andric EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 4283ffd1746dSEd Schouten } 4284ffd1746dSEd Schouten } 4285ffd1746dSEd Schouten 4286ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current 4287ffd1746dSEd Schouten /// function. 4288ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() { 4289ffd1746dSEd Schouten if (LocalDeclMap.empty()) return; 4290ffd1746dSEd Schouten 4291ffd1746dSEd Schouten llvm::LLVMContext &Context = getLLVMContext(); 4292ffd1746dSEd Schouten 4293ffd1746dSEd Schouten // Find the unique metadata ID for this name. 4294ffd1746dSEd Schouten unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 4295ffd1746dSEd Schouten 429659d1ed5bSDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 4297ffd1746dSEd Schouten 429859d1ed5bSDimitry Andric for (auto &I : LocalDeclMap) { 429959d1ed5bSDimitry Andric const Decl *D = I.first; 43000623d748SDimitry Andric llvm::Value *Addr = I.second.getPointer(); 430159d1ed5bSDimitry Andric if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 4302ffd1746dSEd Schouten llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 430339d628a0SDimitry Andric Alloca->setMetadata( 430439d628a0SDimitry Andric DeclPtrKind, llvm::MDNode::get( 430539d628a0SDimitry Andric Context, llvm::ValueAsMetadata::getConstant(DAddr))); 430659d1ed5bSDimitry Andric } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 4307ffd1746dSEd Schouten GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 4308ffd1746dSEd Schouten EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 4309ffd1746dSEd Schouten } 4310ffd1746dSEd Schouten } 4311ffd1746dSEd Schouten } 4312e580952dSDimitry Andric 4313f785676fSDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() { 4314f785676fSDimitry Andric llvm::NamedMDNode *IdentMetadata = 4315f785676fSDimitry Andric TheModule.getOrInsertNamedMetadata("llvm.ident"); 4316f785676fSDimitry Andric std::string Version = getClangFullVersion(); 4317f785676fSDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 4318f785676fSDimitry Andric 431939d628a0SDimitry Andric llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 4320f785676fSDimitry Andric IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 4321f785676fSDimitry Andric } 4322f785676fSDimitry Andric 432359d1ed5bSDimitry Andric void CodeGenModule::EmitTargetMetadata() { 432439d628a0SDimitry Andric // Warning, new MangledDeclNames may be appended within this loop. 432539d628a0SDimitry Andric // We rely on MapVector insertions adding new elements to the end 432639d628a0SDimitry Andric // of the container. 432739d628a0SDimitry Andric // FIXME: Move this loop into the one target that needs it, and only 432839d628a0SDimitry Andric // loop over those declarations for which we couldn't emit the target 432939d628a0SDimitry Andric // metadata when we emitted the declaration. 433039d628a0SDimitry Andric for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 433139d628a0SDimitry Andric auto Val = *(MangledDeclNames.begin() + I); 433239d628a0SDimitry Andric const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 433339d628a0SDimitry Andric llvm::GlobalValue *GV = GetGlobalValue(Val.second); 433459d1ed5bSDimitry Andric getTargetCodeGenInfo().emitTargetMD(D, GV, *this); 433559d1ed5bSDimitry Andric } 433659d1ed5bSDimitry Andric } 433759d1ed5bSDimitry Andric 4338bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() { 433944290647SDimitry Andric if (getCodeGenOpts().CoverageDataFile.empty() && 434044290647SDimitry Andric getCodeGenOpts().CoverageNotesFile.empty()) 434144290647SDimitry Andric return; 434244290647SDimitry Andric 434344290647SDimitry Andric llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); 434444290647SDimitry Andric if (!CUNode) 434544290647SDimitry Andric return; 434644290647SDimitry Andric 4347bd5abe19SDimitry Andric llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 4348bd5abe19SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 434944290647SDimitry Andric auto *CoverageDataFile = 435044290647SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); 435144290647SDimitry Andric auto *CoverageNotesFile = 435244290647SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); 4353bd5abe19SDimitry Andric for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 4354bd5abe19SDimitry Andric llvm::MDNode *CU = CUNode->getOperand(i); 435544290647SDimitry Andric llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; 435639d628a0SDimitry Andric GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 4357bd5abe19SDimitry Andric } 4358bd5abe19SDimitry Andric } 43593861d79fSDimitry Andric 436039d628a0SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) { 43613861d79fSDimitry Andric // Sema has checked that all uuid strings are of the form 43623861d79fSDimitry Andric // "12345678-1234-1234-1234-1234567890ab". 43633861d79fSDimitry Andric assert(Uuid.size() == 36); 4364f785676fSDimitry Andric for (unsigned i = 0; i < 36; ++i) { 4365f785676fSDimitry Andric if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-'); 4366f785676fSDimitry Andric else assert(isHexDigit(Uuid[i])); 43673861d79fSDimitry Andric } 43683861d79fSDimitry Andric 436939d628a0SDimitry Andric // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab". 4370f785676fSDimitry Andric const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 43713861d79fSDimitry Andric 4372f785676fSDimitry Andric llvm::Constant *Field3[8]; 4373f785676fSDimitry Andric for (unsigned Idx = 0; Idx < 8; ++Idx) 4374f785676fSDimitry Andric Field3[Idx] = llvm::ConstantInt::get( 4375f785676fSDimitry Andric Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16); 43763861d79fSDimitry Andric 4377f785676fSDimitry Andric llvm::Constant *Fields[4] = { 4378f785676fSDimitry Andric llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16), 4379f785676fSDimitry Andric llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16), 4380f785676fSDimitry Andric llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16), 4381f785676fSDimitry Andric llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3) 4382f785676fSDimitry Andric }; 4383f785676fSDimitry Andric 4384f785676fSDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 43853861d79fSDimitry Andric } 438659d1ed5bSDimitry Andric 438759d1ed5bSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 438859d1ed5bSDimitry Andric bool ForEH) { 438959d1ed5bSDimitry Andric // Return a bogus pointer if RTTI is disabled, unless it's for EH. 439059d1ed5bSDimitry Andric // FIXME: should we even be calling this method if RTTI is disabled 439159d1ed5bSDimitry Andric // and it's not for EH? 439259d1ed5bSDimitry Andric if (!ForEH && !getLangOpts().RTTI) 439359d1ed5bSDimitry Andric return llvm::Constant::getNullValue(Int8PtrTy); 439459d1ed5bSDimitry Andric 439559d1ed5bSDimitry Andric if (ForEH && Ty->isObjCObjectPointerType() && 439659d1ed5bSDimitry Andric LangOpts.ObjCRuntime.isGNUFamily()) 439759d1ed5bSDimitry Andric return ObjCRuntime->GetEHType(Ty); 439859d1ed5bSDimitry Andric 439959d1ed5bSDimitry Andric return getCXXABI().getAddrOfRTTIDescriptor(Ty); 440059d1ed5bSDimitry Andric } 440159d1ed5bSDimitry Andric 440239d628a0SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 440339d628a0SDimitry Andric for (auto RefExpr : D->varlists()) { 440439d628a0SDimitry Andric auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 440539d628a0SDimitry Andric bool PerformInit = 440639d628a0SDimitry Andric VD->getAnyInitializer() && 440739d628a0SDimitry Andric !VD->getAnyInitializer()->isConstantInitializer(getContext(), 440839d628a0SDimitry Andric /*ForRef=*/false); 44090623d748SDimitry Andric 44100623d748SDimitry Andric Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD)); 441133956c43SDimitry Andric if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 44120623d748SDimitry Andric VD, Addr, RefExpr->getLocStart(), PerformInit)) 441339d628a0SDimitry Andric CXXGlobalInits.push_back(InitFunction); 441439d628a0SDimitry Andric } 441539d628a0SDimitry Andric } 44168f0fd8f6SDimitry Andric 44170623d748SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 44180623d748SDimitry Andric llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()]; 44190623d748SDimitry Andric if (InternalId) 44200623d748SDimitry Andric return InternalId; 44210623d748SDimitry Andric 44220623d748SDimitry Andric if (isExternallyVisible(T->getLinkage())) { 44238f0fd8f6SDimitry Andric std::string OutName; 44248f0fd8f6SDimitry Andric llvm::raw_string_ostream Out(OutName); 44250623d748SDimitry Andric getCXXABI().getMangleContext().mangleTypeName(T, Out); 44268f0fd8f6SDimitry Andric 44270623d748SDimitry Andric InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 44280623d748SDimitry Andric } else { 44290623d748SDimitry Andric InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 44300623d748SDimitry Andric llvm::ArrayRef<llvm::Metadata *>()); 44310623d748SDimitry Andric } 44320623d748SDimitry Andric 44330623d748SDimitry Andric return InternalId; 44340623d748SDimitry Andric } 44350623d748SDimitry Andric 4436e7145dcbSDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier. 4437e7145dcbSDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const { 4438e7145dcbSDimitry Andric // Returns true if at least one of vtable-based CFI checkers is enabled and 4439e7145dcbSDimitry Andric // is not in the trapping mode. 4440e7145dcbSDimitry Andric return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 4441e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 4442e7145dcbSDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 4443e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 4444e7145dcbSDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 4445e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 4446e7145dcbSDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 4447e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 4448e7145dcbSDimitry Andric } 4449e7145dcbSDimitry Andric 4450e7145dcbSDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 44510623d748SDimitry Andric CharUnits Offset, 44520623d748SDimitry Andric const CXXRecordDecl *RD) { 44530623d748SDimitry Andric llvm::Metadata *MD = 44540623d748SDimitry Andric CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 4455e7145dcbSDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), MD); 44560623d748SDimitry Andric 4457e7145dcbSDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 4458e7145dcbSDimitry Andric if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 4459e7145dcbSDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), 4460e7145dcbSDimitry Andric llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 4461e7145dcbSDimitry Andric 4462e7145dcbSDimitry Andric if (NeedAllVtablesTypeId()) { 4463e7145dcbSDimitry Andric llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 4464e7145dcbSDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), MD); 44650623d748SDimitry Andric } 44660623d748SDimitry Andric } 44670623d748SDimitry Andric 44680623d748SDimitry Andric // Fills in the supplied string map with the set of target features for the 44690623d748SDimitry Andric // passed in function. 44700623d748SDimitry Andric void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 44710623d748SDimitry Andric const FunctionDecl *FD) { 44720623d748SDimitry Andric StringRef TargetCPU = Target.getTargetOpts().CPU; 44730623d748SDimitry Andric if (const auto *TD = FD->getAttr<TargetAttr>()) { 44740623d748SDimitry Andric // If we have a TargetAttr build up the feature map based on that. 44750623d748SDimitry Andric TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse(); 44760623d748SDimitry Andric 44770623d748SDimitry Andric // Make a copy of the features as passed on the command line into the 44780623d748SDimitry Andric // beginning of the additional features from the function to override. 44790623d748SDimitry Andric ParsedAttr.first.insert(ParsedAttr.first.begin(), 44800623d748SDimitry Andric Target.getTargetOpts().FeaturesAsWritten.begin(), 44810623d748SDimitry Andric Target.getTargetOpts().FeaturesAsWritten.end()); 44820623d748SDimitry Andric 44830623d748SDimitry Andric if (ParsedAttr.second != "") 44840623d748SDimitry Andric TargetCPU = ParsedAttr.second; 44850623d748SDimitry Andric 44860623d748SDimitry Andric // Now populate the feature map, first with the TargetCPU which is either 44870623d748SDimitry Andric // the default or a new one from the target attribute string. Then we'll use 44880623d748SDimitry Andric // the passed in features (FeaturesAsWritten) along with the new ones from 44890623d748SDimitry Andric // the attribute. 44900623d748SDimitry Andric Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first); 44910623d748SDimitry Andric } else { 44920623d748SDimitry Andric Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, 44930623d748SDimitry Andric Target.getTargetOpts().Features); 44940623d748SDimitry Andric } 44958f0fd8f6SDimitry Andric } 4496e7145dcbSDimitry Andric 4497e7145dcbSDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 4498e7145dcbSDimitry Andric if (!SanStats) 4499e7145dcbSDimitry Andric SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule()); 4500e7145dcbSDimitry Andric 4501e7145dcbSDimitry Andric return *SanStats; 4502e7145dcbSDimitry Andric } 450344290647SDimitry Andric llvm::Value * 450444290647SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, 450544290647SDimitry Andric CodeGenFunction &CGF) { 450644290647SDimitry Andric llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF); 450744290647SDimitry Andric auto SamplerT = getOpenCLRuntime().getSamplerType(); 450844290647SDimitry Andric auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); 450944290647SDimitry Andric return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy, 451044290647SDimitry Andric "__translate_sampler_initializer"), 451144290647SDimitry Andric {C}); 451244290647SDimitry Andric } 4513