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); 101dff0c46cSDimitry Andric FloatTy = llvm::Type::getFloatTy(LLVMContext); 102dff0c46cSDimitry Andric DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 103dff0c46cSDimitry Andric PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 104dff0c46cSDimitry Andric PointerAlignInBytes = 105dff0c46cSDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 10644290647SDimitry Andric SizeSizeInBytes = 10744290647SDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity(); 1080623d748SDimitry Andric IntAlignInBytes = 1090623d748SDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity(); 110dff0c46cSDimitry Andric IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 11144290647SDimitry Andric IntPtrTy = llvm::IntegerType::get(LLVMContext, 11244290647SDimitry Andric C.getTargetInfo().getMaxPointerWidth()); 113dff0c46cSDimitry Andric Int8PtrTy = Int8Ty->getPointerTo(0); 114dff0c46cSDimitry Andric Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 1156bc11b14SDimitry Andric AllocaInt8PtrTy = Int8Ty->getPointerTo( 1166bc11b14SDimitry Andric M.getDataLayout().getAllocaAddrSpace()); 117d8866befSDimitry Andric ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace(); 118dff0c46cSDimitry Andric 119139f7f9bSDimitry Andric RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 12039d628a0SDimitry Andric BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC(); 121139f7f9bSDimitry Andric 122dff0c46cSDimitry Andric if (LangOpts.ObjC1) 1233b0f4066SDimitry Andric createObjCRuntime(); 124dff0c46cSDimitry Andric if (LangOpts.OpenCL) 1256122f3e6SDimitry Andric createOpenCLRuntime(); 12659d1ed5bSDimitry Andric if (LangOpts.OpenMP) 12759d1ed5bSDimitry Andric createOpenMPRuntime(); 128dff0c46cSDimitry Andric if (LangOpts.CUDA) 1296122f3e6SDimitry Andric createCUDARuntime(); 130f22ef01cSRoman Divacky 1317ae0e2c9SDimitry Andric // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 13239d628a0SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::Thread) || 1337ae0e2c9SDimitry Andric (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 134e7145dcbSDimitry Andric TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(), 135e7145dcbSDimitry Andric getCXXABI().getMangleContext())); 1362754fe60SDimitry Andric 1373b0f4066SDimitry Andric // If debug info or coverage generation is enabled, create the CGDebugInfo 1383b0f4066SDimitry Andric // object. 139e7145dcbSDimitry Andric if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo || 140e7145dcbSDimitry Andric CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) 141e7145dcbSDimitry Andric DebugInfo.reset(new CGDebugInfo(*this)); 1422754fe60SDimitry Andric 1432754fe60SDimitry Andric Block.GlobalUniqueCount = 0; 1442754fe60SDimitry Andric 1450623d748SDimitry Andric if (C.getLangOpts().ObjC1) 146e7145dcbSDimitry Andric ObjCData.reset(new ObjCEntrypoints()); 14759d1ed5bSDimitry Andric 148e7145dcbSDimitry Andric if (CodeGenOpts.hasProfileClangUse()) { 149e7145dcbSDimitry Andric auto ReaderOrErr = llvm::IndexedInstrProfReader::create( 150e7145dcbSDimitry Andric CodeGenOpts.ProfileInstrumentUsePath); 151e7145dcbSDimitry Andric if (auto E = ReaderOrErr.takeError()) { 15259d1ed5bSDimitry Andric unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 1533dac3a9bSDimitry Andric "Could not read profile %0: %1"); 154e7145dcbSDimitry Andric llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) { 155e7145dcbSDimitry Andric getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath 156e7145dcbSDimitry Andric << EI.message(); 157e7145dcbSDimitry Andric }); 15833956c43SDimitry Andric } else 15933956c43SDimitry Andric PGOReader = std::move(ReaderOrErr.get()); 16059d1ed5bSDimitry Andric } 16139d628a0SDimitry Andric 16239d628a0SDimitry Andric // If coverage mapping generation is enabled, create the 16339d628a0SDimitry Andric // CoverageMappingModuleGen object. 16439d628a0SDimitry Andric if (CodeGenOpts.CoverageMapping) 16539d628a0SDimitry Andric CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); 166f22ef01cSRoman Divacky } 167f22ef01cSRoman Divacky 168e7145dcbSDimitry Andric CodeGenModule::~CodeGenModule() {} 169f22ef01cSRoman Divacky 170f22ef01cSRoman Divacky void CodeGenModule::createObjCRuntime() { 1717ae0e2c9SDimitry Andric // This is just isGNUFamily(), but we want to force implementors of 1727ae0e2c9SDimitry Andric // new ABIs to decide how best to do this. 1737ae0e2c9SDimitry Andric switch (LangOpts.ObjCRuntime.getKind()) { 1747ae0e2c9SDimitry Andric case ObjCRuntime::GNUstep: 1757ae0e2c9SDimitry Andric case ObjCRuntime::GCC: 1767ae0e2c9SDimitry Andric case ObjCRuntime::ObjFW: 177e7145dcbSDimitry Andric ObjCRuntime.reset(CreateGNUObjCRuntime(*this)); 1787ae0e2c9SDimitry Andric return; 1797ae0e2c9SDimitry Andric 1807ae0e2c9SDimitry Andric case ObjCRuntime::FragileMacOSX: 1817ae0e2c9SDimitry Andric case ObjCRuntime::MacOSX: 1827ae0e2c9SDimitry Andric case ObjCRuntime::iOS: 1830623d748SDimitry Andric case ObjCRuntime::WatchOS: 184e7145dcbSDimitry Andric ObjCRuntime.reset(CreateMacObjCRuntime(*this)); 1857ae0e2c9SDimitry Andric return; 1867ae0e2c9SDimitry Andric } 1877ae0e2c9SDimitry Andric llvm_unreachable("bad runtime kind"); 1886122f3e6SDimitry Andric } 1896122f3e6SDimitry Andric 1906122f3e6SDimitry Andric void CodeGenModule::createOpenCLRuntime() { 191e7145dcbSDimitry Andric OpenCLRuntime.reset(new CGOpenCLRuntime(*this)); 1926122f3e6SDimitry Andric } 1936122f3e6SDimitry Andric 19459d1ed5bSDimitry Andric void CodeGenModule::createOpenMPRuntime() { 195e7145dcbSDimitry Andric // Select a specialized code generation class based on the target, if any. 196e7145dcbSDimitry Andric // If it does not exist use the default implementation. 19744290647SDimitry Andric switch (getTriple().getArch()) { 198e7145dcbSDimitry Andric case llvm::Triple::nvptx: 199e7145dcbSDimitry Andric case llvm::Triple::nvptx64: 200e7145dcbSDimitry Andric assert(getLangOpts().OpenMPIsDevice && 201e7145dcbSDimitry Andric "OpenMP NVPTX is only prepared to deal with device code."); 202e7145dcbSDimitry Andric OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this)); 203e7145dcbSDimitry Andric break; 204e7145dcbSDimitry Andric default: 205e7145dcbSDimitry Andric OpenMPRuntime.reset(new CGOpenMPRuntime(*this)); 206e7145dcbSDimitry Andric break; 207e7145dcbSDimitry Andric } 20859d1ed5bSDimitry Andric } 20959d1ed5bSDimitry Andric 2106122f3e6SDimitry Andric void CodeGenModule::createCUDARuntime() { 211e7145dcbSDimitry Andric CUDARuntime.reset(CreateNVCUDARuntime(*this)); 212f22ef01cSRoman Divacky } 213f22ef01cSRoman Divacky 21439d628a0SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { 21539d628a0SDimitry Andric Replacements[Name] = C; 21639d628a0SDimitry Andric } 21739d628a0SDimitry Andric 218f785676fSDimitry Andric void CodeGenModule::applyReplacements() { 2198f0fd8f6SDimitry Andric for (auto &I : Replacements) { 2208f0fd8f6SDimitry Andric StringRef MangledName = I.first(); 2218f0fd8f6SDimitry Andric llvm::Constant *Replacement = I.second; 222f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 223f785676fSDimitry Andric if (!Entry) 224f785676fSDimitry Andric continue; 22559d1ed5bSDimitry Andric auto *OldF = cast<llvm::Function>(Entry); 22659d1ed5bSDimitry Andric auto *NewF = dyn_cast<llvm::Function>(Replacement); 227f785676fSDimitry Andric if (!NewF) { 22859d1ed5bSDimitry Andric if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 22959d1ed5bSDimitry Andric NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 23059d1ed5bSDimitry Andric } else { 23159d1ed5bSDimitry Andric auto *CE = cast<llvm::ConstantExpr>(Replacement); 232f785676fSDimitry Andric assert(CE->getOpcode() == llvm::Instruction::BitCast || 233f785676fSDimitry Andric CE->getOpcode() == llvm::Instruction::GetElementPtr); 234f785676fSDimitry Andric NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 235f785676fSDimitry Andric } 23659d1ed5bSDimitry Andric } 237f785676fSDimitry Andric 238f785676fSDimitry Andric // Replace old with new, but keep the old order. 239f785676fSDimitry Andric OldF->replaceAllUsesWith(Replacement); 240f785676fSDimitry Andric if (NewF) { 241f785676fSDimitry Andric NewF->removeFromParent(); 2420623d748SDimitry Andric OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(), 2430623d748SDimitry Andric NewF); 244f785676fSDimitry Andric } 245f785676fSDimitry Andric OldF->eraseFromParent(); 246f785676fSDimitry Andric } 247f785676fSDimitry Andric } 248f785676fSDimitry Andric 2490623d748SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { 2500623d748SDimitry Andric GlobalValReplacements.push_back(std::make_pair(GV, C)); 2510623d748SDimitry Andric } 2520623d748SDimitry Andric 2530623d748SDimitry Andric void CodeGenModule::applyGlobalValReplacements() { 2540623d748SDimitry Andric for (auto &I : GlobalValReplacements) { 2550623d748SDimitry Andric llvm::GlobalValue *GV = I.first; 2560623d748SDimitry Andric llvm::Constant *C = I.second; 2570623d748SDimitry Andric 2580623d748SDimitry Andric GV->replaceAllUsesWith(C); 2590623d748SDimitry Andric GV->eraseFromParent(); 2600623d748SDimitry Andric } 2610623d748SDimitry Andric } 2620623d748SDimitry Andric 26359d1ed5bSDimitry Andric // This is only used in aliases that we created and we know they have a 26459d1ed5bSDimitry Andric // linear structure. 265e7145dcbSDimitry Andric static const llvm::GlobalObject *getAliasedGlobal( 266e7145dcbSDimitry Andric const llvm::GlobalIndirectSymbol &GIS) { 267e7145dcbSDimitry Andric llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited; 268e7145dcbSDimitry Andric const llvm::Constant *C = &GIS; 26959d1ed5bSDimitry Andric for (;;) { 27059d1ed5bSDimitry Andric C = C->stripPointerCasts(); 27159d1ed5bSDimitry Andric if (auto *GO = dyn_cast<llvm::GlobalObject>(C)) 27259d1ed5bSDimitry Andric return GO; 27359d1ed5bSDimitry Andric // stripPointerCasts will not walk over weak aliases. 274e7145dcbSDimitry Andric auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C); 275e7145dcbSDimitry Andric if (!GIS2) 27659d1ed5bSDimitry Andric return nullptr; 277e7145dcbSDimitry Andric if (!Visited.insert(GIS2).second) 27859d1ed5bSDimitry Andric return nullptr; 279e7145dcbSDimitry Andric C = GIS2->getIndirectSymbol(); 28059d1ed5bSDimitry Andric } 28159d1ed5bSDimitry Andric } 28259d1ed5bSDimitry Andric 283f785676fSDimitry Andric void CodeGenModule::checkAliases() { 28459d1ed5bSDimitry Andric // Check if the constructed aliases are well formed. It is really unfortunate 28559d1ed5bSDimitry Andric // that we have to do this in CodeGen, but we only construct mangled names 28659d1ed5bSDimitry Andric // and aliases during codegen. 287f785676fSDimitry Andric bool Error = false; 28859d1ed5bSDimitry Andric DiagnosticsEngine &Diags = getDiags(); 2898f0fd8f6SDimitry Andric for (const GlobalDecl &GD : Aliases) { 29059d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 291e7145dcbSDimitry Andric SourceLocation Location; 292e7145dcbSDimitry Andric bool IsIFunc = D->hasAttr<IFuncAttr>(); 293e7145dcbSDimitry Andric if (const Attr *A = D->getDefiningAttr()) 294e7145dcbSDimitry Andric Location = A->getLocation(); 295e7145dcbSDimitry Andric else 296e7145dcbSDimitry Andric llvm_unreachable("Not an alias or ifunc?"); 297f785676fSDimitry Andric StringRef MangledName = getMangledName(GD); 298f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 299e7145dcbSDimitry Andric auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry); 30059d1ed5bSDimitry Andric const llvm::GlobalValue *GV = getAliasedGlobal(*Alias); 30159d1ed5bSDimitry Andric if (!GV) { 302f785676fSDimitry Andric Error = true; 303e7145dcbSDimitry Andric Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc; 30459d1ed5bSDimitry Andric } else if (GV->isDeclaration()) { 305f785676fSDimitry Andric Error = true; 306e7145dcbSDimitry Andric Diags.Report(Location, diag::err_alias_to_undefined) 307e7145dcbSDimitry Andric << IsIFunc << IsIFunc; 308e7145dcbSDimitry Andric } else if (IsIFunc) { 309e7145dcbSDimitry Andric // Check resolver function type. 310e7145dcbSDimitry Andric llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>( 311e7145dcbSDimitry Andric GV->getType()->getPointerElementType()); 312e7145dcbSDimitry Andric assert(FTy); 313e7145dcbSDimitry Andric if (!FTy->getReturnType()->isPointerTy()) 314e7145dcbSDimitry Andric Diags.Report(Location, diag::err_ifunc_resolver_return); 315e7145dcbSDimitry Andric if (FTy->getNumParams()) 316e7145dcbSDimitry Andric Diags.Report(Location, diag::err_ifunc_resolver_params); 31759d1ed5bSDimitry Andric } 31859d1ed5bSDimitry Andric 319e7145dcbSDimitry Andric llvm::Constant *Aliasee = Alias->getIndirectSymbol(); 32059d1ed5bSDimitry Andric llvm::GlobalValue *AliaseeGV; 32159d1ed5bSDimitry Andric if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 32259d1ed5bSDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 32359d1ed5bSDimitry Andric else 32459d1ed5bSDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 32559d1ed5bSDimitry Andric 32659d1ed5bSDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 32759d1ed5bSDimitry Andric StringRef AliasSection = SA->getName(); 32859d1ed5bSDimitry Andric if (AliasSection != AliaseeGV->getSection()) 32959d1ed5bSDimitry Andric Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 330e7145dcbSDimitry Andric << AliasSection << IsIFunc << IsIFunc; 33159d1ed5bSDimitry Andric } 33259d1ed5bSDimitry Andric 33359d1ed5bSDimitry Andric // We have to handle alias to weak aliases in here. LLVM itself disallows 33459d1ed5bSDimitry Andric // this since the object semantics would not match the IL one. For 33559d1ed5bSDimitry Andric // compatibility with gcc we implement it by just pointing the alias 33659d1ed5bSDimitry Andric // to its aliasee's aliasee. We also warn, since the user is probably 33759d1ed5bSDimitry Andric // expecting the link to be weak. 338e7145dcbSDimitry Andric if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) { 339e7145dcbSDimitry Andric if (GA->isInterposable()) { 340e7145dcbSDimitry Andric Diags.Report(Location, diag::warn_alias_to_weak_alias) 341e7145dcbSDimitry Andric << GV->getName() << GA->getName() << IsIFunc; 34259d1ed5bSDimitry Andric Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 343e7145dcbSDimitry Andric GA->getIndirectSymbol(), Alias->getType()); 344e7145dcbSDimitry Andric Alias->setIndirectSymbol(Aliasee); 34559d1ed5bSDimitry Andric } 346f785676fSDimitry Andric } 347f785676fSDimitry Andric } 348f785676fSDimitry Andric if (!Error) 349f785676fSDimitry Andric return; 350f785676fSDimitry Andric 3518f0fd8f6SDimitry Andric for (const GlobalDecl &GD : Aliases) { 352f785676fSDimitry Andric StringRef MangledName = getMangledName(GD); 353f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 354e7145dcbSDimitry Andric auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry); 355f785676fSDimitry Andric Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 356f785676fSDimitry Andric Alias->eraseFromParent(); 357f785676fSDimitry Andric } 358f785676fSDimitry Andric } 359f785676fSDimitry Andric 36059d1ed5bSDimitry Andric void CodeGenModule::clear() { 36159d1ed5bSDimitry Andric DeferredDeclsToEmit.clear(); 36233956c43SDimitry Andric if (OpenMPRuntime) 36333956c43SDimitry Andric OpenMPRuntime->clear(); 36459d1ed5bSDimitry Andric } 36559d1ed5bSDimitry Andric 36659d1ed5bSDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 36759d1ed5bSDimitry Andric StringRef MainFile) { 36859d1ed5bSDimitry Andric if (!hasDiagnostics()) 36959d1ed5bSDimitry Andric return; 37059d1ed5bSDimitry Andric if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 37159d1ed5bSDimitry Andric if (MainFile.empty()) 37259d1ed5bSDimitry Andric MainFile = "<stdin>"; 37359d1ed5bSDimitry Andric Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 374f37b6182SDimitry Andric } else { 375f37b6182SDimitry Andric if (Mismatched > 0) 376f37b6182SDimitry Andric Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched; 377f37b6182SDimitry Andric 378f37b6182SDimitry Andric if (Missing > 0) 379f37b6182SDimitry Andric Diags.Report(diag::warn_profile_data_missing) << Visited << Missing; 380f37b6182SDimitry Andric } 38159d1ed5bSDimitry Andric } 38259d1ed5bSDimitry Andric 383f22ef01cSRoman Divacky void CodeGenModule::Release() { 384f22ef01cSRoman Divacky EmitDeferred(); 385f9448bf3SDimitry Andric EmitVTablesOpportunistically(); 3860623d748SDimitry Andric applyGlobalValReplacements(); 387f785676fSDimitry Andric applyReplacements(); 388f785676fSDimitry Andric checkAliases(); 389f22ef01cSRoman Divacky EmitCXXGlobalInitFunc(); 390f22ef01cSRoman Divacky EmitCXXGlobalDtorFunc(); 391284c1978SDimitry Andric EmitCXXThreadLocalInitFunc(); 3926122f3e6SDimitry Andric if (ObjCRuntime) 3936122f3e6SDimitry Andric if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 394f22ef01cSRoman Divacky AddGlobalCtor(ObjCInitFunction); 39533956c43SDimitry Andric if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice && 39633956c43SDimitry Andric CUDARuntime) { 39733956c43SDimitry Andric if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction()) 39833956c43SDimitry Andric AddGlobalCtor(CudaCtorFunction); 39933956c43SDimitry Andric if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction()) 40033956c43SDimitry Andric AddGlobalDtor(CudaDtorFunction); 40133956c43SDimitry Andric } 402ea942507SDimitry Andric if (OpenMPRuntime) 403ea942507SDimitry Andric if (llvm::Function *OpenMPRegistrationFunction = 404302affcbSDimitry Andric OpenMPRuntime->emitRegistrationFunction()) { 405302affcbSDimitry Andric auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ? 406302affcbSDimitry Andric OpenMPRegistrationFunction : nullptr; 407302affcbSDimitry Andric AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey); 408302affcbSDimitry Andric } 4090623d748SDimitry Andric if (PGOReader) { 410e7145dcbSDimitry Andric getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext)); 4110623d748SDimitry Andric if (PGOStats.hasDiagnostics()) 41259d1ed5bSDimitry Andric PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 4130623d748SDimitry Andric } 414f22ef01cSRoman Divacky EmitCtorList(GlobalCtors, "llvm.global_ctors"); 415f22ef01cSRoman Divacky EmitCtorList(GlobalDtors, "llvm.global_dtors"); 4166122f3e6SDimitry Andric EmitGlobalAnnotations(); 417284c1978SDimitry Andric EmitStaticExternCAliases(); 41839d628a0SDimitry Andric EmitDeferredUnusedCoverageMappings(); 41939d628a0SDimitry Andric if (CoverageMapping) 42039d628a0SDimitry Andric CoverageMapping->emit(); 42120e90f04SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 422e7145dcbSDimitry Andric CodeGenFunction(*this).EmitCfiCheckFail(); 42320e90f04SDimitry Andric CodeGenFunction(*this).EmitCfiCheckStub(); 42420e90f04SDimitry Andric } 42520e90f04SDimitry Andric emitAtAvailableLinkGuard(); 42659d1ed5bSDimitry Andric emitLLVMUsed(); 427e7145dcbSDimitry Andric if (SanStats) 428e7145dcbSDimitry Andric SanStats->finish(); 429ffd1746dSEd Schouten 430f785676fSDimitry Andric if (CodeGenOpts.Autolink && 431f785676fSDimitry Andric (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 432139f7f9bSDimitry Andric EmitModuleLinkOptions(); 433139f7f9bSDimitry Andric } 43420e90f04SDimitry Andric 43520e90f04SDimitry Andric // Record mregparm value now so it is visible through rest of codegen. 43620e90f04SDimitry Andric if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) 43720e90f04SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters", 43820e90f04SDimitry Andric CodeGenOpts.NumRegisterParameters); 43920e90f04SDimitry Andric 4400623d748SDimitry Andric if (CodeGenOpts.DwarfVersion) { 441f785676fSDimitry Andric // We actually want the latest version when there are conflicts. 442f785676fSDimitry Andric // We can change from Warning to Latest if such mode is supported. 443f785676fSDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version", 444f785676fSDimitry Andric CodeGenOpts.DwarfVersion); 4450623d748SDimitry Andric } 4460623d748SDimitry Andric if (CodeGenOpts.EmitCodeView) { 4470623d748SDimitry Andric // Indicate that we want CodeView in the metadata. 4480623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); 4490623d748SDimitry Andric } 4500623d748SDimitry Andric if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { 4510623d748SDimitry Andric // We don't support LTO with 2 with different StrictVTablePointers 4520623d748SDimitry Andric // FIXME: we could support it by stripping all the information introduced 4530623d748SDimitry Andric // by StrictVTablePointers. 4540623d748SDimitry Andric 4550623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); 4560623d748SDimitry Andric 4570623d748SDimitry Andric llvm::Metadata *Ops[2] = { 4580623d748SDimitry Andric llvm::MDString::get(VMContext, "StrictVTablePointers"), 4590623d748SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 4600623d748SDimitry Andric llvm::Type::getInt32Ty(VMContext), 1))}; 4610623d748SDimitry Andric 4620623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Require, 4630623d748SDimitry Andric "StrictVTablePointersRequirement", 4640623d748SDimitry Andric llvm::MDNode::get(VMContext, Ops)); 4650623d748SDimitry Andric } 466f785676fSDimitry Andric if (DebugInfo) 46759d1ed5bSDimitry Andric // We support a single version in the linked module. The LLVM 46859d1ed5bSDimitry Andric // parser will drop debug info with a different version number 46959d1ed5bSDimitry Andric // (and warn about it, too). 47059d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 471f785676fSDimitry Andric llvm::DEBUG_METADATA_VERSION); 472139f7f9bSDimitry Andric 473d8866befSDimitry Andric // Width of wchar_t in bytes 474d8866befSDimitry Andric uint64_t WCharWidth = 475d8866befSDimitry Andric Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 476f9448bf3SDimitry Andric assert((LangOpts.ShortWChar || 477d8866befSDimitry Andric llvm::TargetLibraryInfoImpl::getTargetWCharSize(Target.getTriple()) == 478f9448bf3SDimitry Andric Target.getWCharWidth() / 8) && 479d8866befSDimitry Andric "LLVM wchar_t size out of sync"); 480d8866befSDimitry Andric 48159d1ed5bSDimitry Andric // We need to record the widths of enums and wchar_t, so that we can generate 482d8866befSDimitry Andric // the correct build attributes in the ARM backend. wchar_size is also used by 483d8866befSDimitry Andric // TargetLibraryInfo. 484d8866befSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 485d8866befSDimitry Andric 48659d1ed5bSDimitry Andric llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 48759d1ed5bSDimitry Andric if ( Arch == llvm::Triple::arm 48859d1ed5bSDimitry Andric || Arch == llvm::Triple::armeb 48959d1ed5bSDimitry Andric || Arch == llvm::Triple::thumb 49059d1ed5bSDimitry Andric || Arch == llvm::Triple::thumbeb) { 49159d1ed5bSDimitry Andric // The minimum width of an enum in bytes 49259d1ed5bSDimitry Andric uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 49359d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 49459d1ed5bSDimitry Andric } 49559d1ed5bSDimitry Andric 4960623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 4970623d748SDimitry Andric // Indicate that we want cross-DSO control flow integrity checks. 4980623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); 4990623d748SDimitry Andric } 5000623d748SDimitry Andric 50144290647SDimitry Andric if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) { 502e7145dcbSDimitry Andric // Indicate whether __nvvm_reflect should be configured to flush denormal 503e7145dcbSDimitry Andric // floating point values to 0. (This corresponds to its "__CUDA_FTZ" 504e7145dcbSDimitry Andric // property.) 505e7145dcbSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", 506e7145dcbSDimitry Andric LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0); 50739d628a0SDimitry Andric } 50839d628a0SDimitry Andric 509e7145dcbSDimitry Andric if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 510e7145dcbSDimitry Andric assert(PLevel < 3 && "Invalid PIC Level"); 511e7145dcbSDimitry Andric getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel)); 512e7145dcbSDimitry Andric if (Context.getLangOpts().PIE) 513e7145dcbSDimitry Andric getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel)); 51439d628a0SDimitry Andric } 51539d628a0SDimitry Andric 5162754fe60SDimitry Andric SimplifyPersonality(); 5172754fe60SDimitry Andric 518ffd1746dSEd Schouten if (getCodeGenOpts().EmitDeclMetadata) 519ffd1746dSEd Schouten EmitDeclMetadata(); 520bd5abe19SDimitry Andric 521bd5abe19SDimitry Andric if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 522bd5abe19SDimitry Andric EmitCoverageFile(); 5236122f3e6SDimitry Andric 5246122f3e6SDimitry Andric if (DebugInfo) 5256122f3e6SDimitry Andric DebugInfo->finalize(); 526f785676fSDimitry Andric 527f785676fSDimitry Andric EmitVersionIdentMetadata(); 52859d1ed5bSDimitry Andric 52959d1ed5bSDimitry Andric EmitTargetMetadata(); 530f22ef01cSRoman Divacky } 531f22ef01cSRoman Divacky 5323b0f4066SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 5333b0f4066SDimitry Andric // Make sure that this type is translated. 5343b0f4066SDimitry Andric Types.UpdateCompletedType(TD); 5353b0f4066SDimitry Andric } 5363b0f4066SDimitry Andric 537e7145dcbSDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { 538e7145dcbSDimitry Andric // Make sure that this type is translated. 539e7145dcbSDimitry Andric Types.RefreshTypeCacheForClass(RD); 540e7145dcbSDimitry Andric } 541e7145dcbSDimitry Andric 5422754fe60SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 5432754fe60SDimitry Andric if (!TBAA) 54459d1ed5bSDimitry Andric return nullptr; 5452754fe60SDimitry Andric return TBAA->getTBAAInfo(QTy); 5462754fe60SDimitry Andric } 5472754fe60SDimitry Andric 548dff0c46cSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() { 549dff0c46cSDimitry Andric if (!TBAA) 55059d1ed5bSDimitry Andric return nullptr; 551dff0c46cSDimitry Andric return TBAA->getTBAAInfoForVTablePtr(); 552dff0c46cSDimitry Andric } 553dff0c46cSDimitry Andric 5543861d79fSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 5553861d79fSDimitry Andric if (!TBAA) 55659d1ed5bSDimitry Andric return nullptr; 5573861d79fSDimitry Andric return TBAA->getTBAAStructInfo(QTy); 5583861d79fSDimitry Andric } 5593861d79fSDimitry Andric 560139f7f9bSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy, 561139f7f9bSDimitry Andric llvm::MDNode *AccessN, 562139f7f9bSDimitry Andric uint64_t O) { 563139f7f9bSDimitry Andric if (!TBAA) 56459d1ed5bSDimitry Andric return nullptr; 565139f7f9bSDimitry Andric return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O); 566139f7f9bSDimitry Andric } 567139f7f9bSDimitry Andric 568f785676fSDimitry Andric /// Decorate the instruction with a TBAA tag. For both scalar TBAA 569f785676fSDimitry Andric /// and struct-path aware TBAA, the tag has the same format: 570f785676fSDimitry Andric /// base type, access type and offset. 571284c1978SDimitry Andric /// When ConvertTypeToTag is true, we create a tag based on the scalar type. 5720623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, 573284c1978SDimitry Andric llvm::MDNode *TBAAInfo, 574284c1978SDimitry Andric bool ConvertTypeToTag) { 575f785676fSDimitry Andric if (ConvertTypeToTag && TBAA) 576284c1978SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, 577284c1978SDimitry Andric TBAA->getTBAAScalarTagInfo(TBAAInfo)); 578284c1978SDimitry Andric else 5792754fe60SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 5802754fe60SDimitry Andric } 5812754fe60SDimitry Andric 5820623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup( 5830623d748SDimitry Andric llvm::Instruction *I, const CXXRecordDecl *RD) { 58451690af2SDimitry Andric I->setMetadata(llvm::LLVMContext::MD_invariant_group, 58551690af2SDimitry Andric llvm::MDNode::get(getLLVMContext(), {})); 5860623d748SDimitry Andric } 5870623d748SDimitry Andric 58859d1ed5bSDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) { 58959d1ed5bSDimitry Andric unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 59059d1ed5bSDimitry Andric getDiags().Report(Context.getFullLoc(loc), diagID) << message; 591f22ef01cSRoman Divacky } 592f22ef01cSRoman Divacky 593f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 594f22ef01cSRoman Divacky /// specified stmt yet. 595f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 5966122f3e6SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 597f22ef01cSRoman Divacky "cannot compile this %0 yet"); 598f22ef01cSRoman Divacky std::string Msg = Type; 599f22ef01cSRoman Divacky getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 600f22ef01cSRoman Divacky << Msg << S->getSourceRange(); 601f22ef01cSRoman Divacky } 602f22ef01cSRoman Divacky 603f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 604f22ef01cSRoman Divacky /// specified decl yet. 605f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 6066122f3e6SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 607f22ef01cSRoman Divacky "cannot compile this %0 yet"); 608f22ef01cSRoman Divacky std::string Msg = Type; 609f22ef01cSRoman Divacky getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 610f22ef01cSRoman Divacky } 611f22ef01cSRoman Divacky 61217a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 61317a519f9SDimitry Andric return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 61417a519f9SDimitry Andric } 61517a519f9SDimitry Andric 616f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 6172754fe60SDimitry Andric const NamedDecl *D) const { 618f22ef01cSRoman Divacky // Internal definitions always have default visibility. 619f22ef01cSRoman Divacky if (GV->hasLocalLinkage()) { 620f22ef01cSRoman Divacky GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 621f22ef01cSRoman Divacky return; 622f22ef01cSRoman Divacky } 623f22ef01cSRoman Divacky 6242754fe60SDimitry Andric // Set visibility for definitions. 625139f7f9bSDimitry Andric LinkageInfo LV = D->getLinkageAndVisibility(); 626139f7f9bSDimitry Andric if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 627139f7f9bSDimitry Andric GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 628f22ef01cSRoman Divacky } 629f22ef01cSRoman Divacky 6307ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 6317ae0e2c9SDimitry Andric return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 6327ae0e2c9SDimitry Andric .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 6337ae0e2c9SDimitry Andric .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 6347ae0e2c9SDimitry Andric .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 6357ae0e2c9SDimitry Andric .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 6367ae0e2c9SDimitry Andric } 6377ae0e2c9SDimitry Andric 6387ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel( 6397ae0e2c9SDimitry Andric CodeGenOptions::TLSModel M) { 6407ae0e2c9SDimitry Andric switch (M) { 6417ae0e2c9SDimitry Andric case CodeGenOptions::GeneralDynamicTLSModel: 6427ae0e2c9SDimitry Andric return llvm::GlobalVariable::GeneralDynamicTLSModel; 6437ae0e2c9SDimitry Andric case CodeGenOptions::LocalDynamicTLSModel: 6447ae0e2c9SDimitry Andric return llvm::GlobalVariable::LocalDynamicTLSModel; 6457ae0e2c9SDimitry Andric case CodeGenOptions::InitialExecTLSModel: 6467ae0e2c9SDimitry Andric return llvm::GlobalVariable::InitialExecTLSModel; 6477ae0e2c9SDimitry Andric case CodeGenOptions::LocalExecTLSModel: 6487ae0e2c9SDimitry Andric return llvm::GlobalVariable::LocalExecTLSModel; 6497ae0e2c9SDimitry Andric } 6507ae0e2c9SDimitry Andric llvm_unreachable("Invalid TLS model!"); 6517ae0e2c9SDimitry Andric } 6527ae0e2c9SDimitry Andric 65339d628a0SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 654284c1978SDimitry Andric assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 6557ae0e2c9SDimitry Andric 65639d628a0SDimitry Andric llvm::GlobalValue::ThreadLocalMode TLM; 6573861d79fSDimitry Andric TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel()); 6587ae0e2c9SDimitry Andric 6597ae0e2c9SDimitry Andric // Override the TLS model if it is explicitly specified. 66059d1ed5bSDimitry Andric if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 6617ae0e2c9SDimitry Andric TLM = GetLLVMTLSModel(Attr->getModel()); 6627ae0e2c9SDimitry Andric } 6637ae0e2c9SDimitry Andric 6647ae0e2c9SDimitry Andric GV->setThreadLocalMode(TLM); 6657ae0e2c9SDimitry Andric } 6667ae0e2c9SDimitry Andric 6676122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 668444ed5c5SDimitry Andric GlobalDecl CanonicalGD = GD.getCanonicalDecl(); 669444ed5c5SDimitry Andric 670444ed5c5SDimitry Andric // Some ABIs don't have constructor variants. Make sure that base and 671444ed5c5SDimitry Andric // complete constructors get mangled the same. 672444ed5c5SDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { 673444ed5c5SDimitry Andric if (!getTarget().getCXXABI().hasConstructorVariants()) { 674444ed5c5SDimitry Andric CXXCtorType OrigCtorType = GD.getCtorType(); 675444ed5c5SDimitry Andric assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); 676444ed5c5SDimitry Andric if (OrigCtorType == Ctor_Base) 677444ed5c5SDimitry Andric CanonicalGD = GlobalDecl(CD, Ctor_Complete); 678444ed5c5SDimitry Andric } 679444ed5c5SDimitry Andric } 680444ed5c5SDimitry Andric 681444ed5c5SDimitry Andric StringRef &FoundStr = MangledDeclNames[CanonicalGD]; 68259d1ed5bSDimitry Andric if (!FoundStr.empty()) 68359d1ed5bSDimitry Andric return FoundStr; 684f22ef01cSRoman Divacky 68559d1ed5bSDimitry Andric const auto *ND = cast<NamedDecl>(GD.getDecl()); 686dff0c46cSDimitry Andric SmallString<256> Buffer; 68759d1ed5bSDimitry Andric StringRef Str; 68859d1ed5bSDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 6892754fe60SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 69059d1ed5bSDimitry Andric if (const auto *D = dyn_cast<CXXConstructorDecl>(ND)) 6912754fe60SDimitry Andric getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 69259d1ed5bSDimitry Andric else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND)) 6932754fe60SDimitry Andric getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 694ffd1746dSEd Schouten else 6952754fe60SDimitry Andric getCXXABI().getMangleContext().mangleName(ND, Out); 69659d1ed5bSDimitry Andric Str = Out.str(); 69759d1ed5bSDimitry Andric } else { 69859d1ed5bSDimitry Andric IdentifierInfo *II = ND->getIdentifier(); 69959d1ed5bSDimitry Andric assert(II && "Attempt to mangle unnamed decl."); 70044290647SDimitry Andric const auto *FD = dyn_cast<FunctionDecl>(ND); 70144290647SDimitry Andric 70244290647SDimitry Andric if (FD && 70344290647SDimitry Andric FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { 70444290647SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 70544290647SDimitry Andric Out << "__regcall3__" << II->getName(); 70644290647SDimitry Andric Str = Out.str(); 70744290647SDimitry Andric } else { 70859d1ed5bSDimitry Andric Str = II->getName(); 709ffd1746dSEd Schouten } 71044290647SDimitry Andric } 711ffd1746dSEd Schouten 71239d628a0SDimitry Andric // Keep the first result in the case of a mangling collision. 71339d628a0SDimitry Andric auto Result = Manglings.insert(std::make_pair(Str, GD)); 71439d628a0SDimitry Andric return FoundStr = Result.first->first(); 71559d1ed5bSDimitry Andric } 71659d1ed5bSDimitry Andric 71759d1ed5bSDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 718ffd1746dSEd Schouten const BlockDecl *BD) { 7192754fe60SDimitry Andric MangleContext &MangleCtx = getCXXABI().getMangleContext(); 7202754fe60SDimitry Andric const Decl *D = GD.getDecl(); 72159d1ed5bSDimitry Andric 72259d1ed5bSDimitry Andric SmallString<256> Buffer; 72359d1ed5bSDimitry Andric llvm::raw_svector_ostream Out(Buffer); 72459d1ed5bSDimitry Andric if (!D) 7257ae0e2c9SDimitry Andric MangleCtx.mangleGlobalBlock(BD, 7267ae0e2c9SDimitry Andric dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 72759d1ed5bSDimitry Andric else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 7282754fe60SDimitry Andric MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 72959d1ed5bSDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 7302754fe60SDimitry Andric MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 7312754fe60SDimitry Andric else 7322754fe60SDimitry Andric MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 73359d1ed5bSDimitry Andric 73439d628a0SDimitry Andric auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 73539d628a0SDimitry Andric return Result.first->first(); 736f22ef01cSRoman Divacky } 737f22ef01cSRoman Divacky 7386122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 739f22ef01cSRoman Divacky return getModule().getNamedValue(Name); 740f22ef01cSRoman Divacky } 741f22ef01cSRoman Divacky 742f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before 743f22ef01cSRoman Divacky /// main() runs. 74459d1ed5bSDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 74559d1ed5bSDimitry Andric llvm::Constant *AssociatedData) { 746f22ef01cSRoman Divacky // FIXME: Type coercion of void()* types. 74759d1ed5bSDimitry Andric GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); 748f22ef01cSRoman Divacky } 749f22ef01cSRoman Divacky 750f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called 751f22ef01cSRoman Divacky /// when the module is unloaded. 752f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) { 753f22ef01cSRoman Divacky // FIXME: Type coercion of void()* types. 75459d1ed5bSDimitry Andric GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); 755f22ef01cSRoman Divacky } 756f22ef01cSRoman Divacky 75744290647SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { 75844290647SDimitry Andric if (Fns.empty()) return; 75944290647SDimitry Andric 760f22ef01cSRoman Divacky // Ctor function type is void()*. 761bd5abe19SDimitry Andric llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 762f22ef01cSRoman Divacky llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 763f22ef01cSRoman Divacky 76459d1ed5bSDimitry Andric // Get the type of a ctor entry, { i32, void ()*, i8* }. 76559d1ed5bSDimitry Andric llvm::StructType *CtorStructTy = llvm::StructType::get( 7665517e702SDimitry Andric Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy); 767f22ef01cSRoman Divacky 768f22ef01cSRoman Divacky // Construct the constructor and destructor arrays. 76944290647SDimitry Andric ConstantInitBuilder builder(*this); 77044290647SDimitry Andric auto ctors = builder.beginArray(CtorStructTy); 7718f0fd8f6SDimitry Andric for (const auto &I : Fns) { 77244290647SDimitry Andric auto ctor = ctors.beginStruct(CtorStructTy); 77344290647SDimitry Andric ctor.addInt(Int32Ty, I.Priority); 77444290647SDimitry Andric ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy)); 77544290647SDimitry Andric if (I.AssociatedData) 77644290647SDimitry Andric ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)); 77744290647SDimitry Andric else 77844290647SDimitry Andric ctor.addNullPointer(VoidPtrTy); 77944290647SDimitry Andric ctor.finishAndAddTo(ctors); 780f22ef01cSRoman Divacky } 781f22ef01cSRoman Divacky 78244290647SDimitry Andric auto list = 78344290647SDimitry Andric ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(), 78444290647SDimitry Andric /*constant*/ false, 78544290647SDimitry Andric llvm::GlobalValue::AppendingLinkage); 78644290647SDimitry Andric 78744290647SDimitry Andric // The LTO linker doesn't seem to like it when we set an alignment 78844290647SDimitry Andric // on appending variables. Take it off as a workaround. 78944290647SDimitry Andric list->setAlignment(0); 79044290647SDimitry Andric 79144290647SDimitry Andric Fns.clear(); 792f22ef01cSRoman Divacky } 793f22ef01cSRoman Divacky 794f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes 795f785676fSDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 79659d1ed5bSDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 797f785676fSDimitry Andric 798e580952dSDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 799f22ef01cSRoman Divacky 80059d1ed5bSDimitry Andric if (isa<CXXDestructorDecl>(D) && 80159d1ed5bSDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 80259d1ed5bSDimitry Andric GD.getDtorType())) { 80359d1ed5bSDimitry Andric // Destructor variants in the Microsoft C++ ABI are always internal or 80459d1ed5bSDimitry Andric // linkonce_odr thunks emitted on an as-needed basis. 80559d1ed5bSDimitry Andric return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage 80659d1ed5bSDimitry Andric : llvm::GlobalValue::LinkOnceODRLinkage; 807f22ef01cSRoman Divacky } 808f22ef01cSRoman Divacky 809e7145dcbSDimitry Andric if (isa<CXXConstructorDecl>(D) && 810e7145dcbSDimitry Andric cast<CXXConstructorDecl>(D)->isInheritingConstructor() && 811e7145dcbSDimitry Andric Context.getTargetInfo().getCXXABI().isMicrosoft()) { 812e7145dcbSDimitry Andric // Our approach to inheriting constructors is fundamentally different from 813e7145dcbSDimitry Andric // that used by the MS ABI, so keep our inheriting constructor thunks 814e7145dcbSDimitry Andric // internal rather than trying to pick an unambiguous mangling for them. 815e7145dcbSDimitry Andric return llvm::GlobalValue::InternalLinkage; 816e7145dcbSDimitry Andric } 817e7145dcbSDimitry Andric 81859d1ed5bSDimitry Andric return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false); 81959d1ed5bSDimitry Andric } 820f22ef01cSRoman Divacky 82197bc6c73SDimitry Andric void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) { 82297bc6c73SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 82397bc6c73SDimitry Andric 82497bc6c73SDimitry Andric if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) { 82597bc6c73SDimitry Andric if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) { 82697bc6c73SDimitry Andric // Don't dllexport/import destructor thunks. 82797bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 82897bc6c73SDimitry Andric return; 82997bc6c73SDimitry Andric } 83097bc6c73SDimitry Andric } 83197bc6c73SDimitry Andric 83297bc6c73SDimitry Andric if (FD->hasAttr<DLLImportAttr>()) 83397bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 83497bc6c73SDimitry Andric else if (FD->hasAttr<DLLExportAttr>()) 83597bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 83697bc6c73SDimitry Andric else 83797bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 83897bc6c73SDimitry Andric } 83997bc6c73SDimitry Andric 840e7145dcbSDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { 8410623d748SDimitry Andric llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 8420623d748SDimitry Andric if (!MDS) return nullptr; 8430623d748SDimitry Andric 84444290647SDimitry Andric return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString())); 8450623d748SDimitry Andric } 8460623d748SDimitry Andric 84759d1ed5bSDimitry Andric void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D, 84859d1ed5bSDimitry Andric llvm::Function *F) { 84959d1ed5bSDimitry Andric setNonAliasAttributes(D, F); 850f22ef01cSRoman Divacky } 851f22ef01cSRoman Divacky 852f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 853f22ef01cSRoman Divacky const CGFunctionInfo &Info, 854f22ef01cSRoman Divacky llvm::Function *F) { 855f22ef01cSRoman Divacky unsigned CallingConv; 8566bc11b14SDimitry Andric llvm::AttributeList PAL; 8576bc11b14SDimitry Andric ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false); 8586bc11b14SDimitry Andric F->setAttributes(PAL); 859f22ef01cSRoman Divacky F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 860f22ef01cSRoman Divacky } 861f22ef01cSRoman Divacky 8626122f3e6SDimitry Andric /// Determines whether the language options require us to model 8636122f3e6SDimitry Andric /// unwind exceptions. We treat -fexceptions as mandating this 8646122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions 8656122f3e6SDimitry Andric /// enabled. This means, for example, that C with -fexceptions 8666122f3e6SDimitry Andric /// enables this. 867dff0c46cSDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) { 8686122f3e6SDimitry Andric // If exceptions are completely disabled, obviously this is false. 869dff0c46cSDimitry Andric if (!LangOpts.Exceptions) return false; 8706122f3e6SDimitry Andric 8716122f3e6SDimitry Andric // If C++ exceptions are enabled, this is true. 872dff0c46cSDimitry Andric if (LangOpts.CXXExceptions) return true; 8736122f3e6SDimitry Andric 8746122f3e6SDimitry Andric // If ObjC exceptions are enabled, this depends on the ABI. 875dff0c46cSDimitry Andric if (LangOpts.ObjCExceptions) { 8767ae0e2c9SDimitry Andric return LangOpts.ObjCRuntime.hasUnwindExceptions(); 8776122f3e6SDimitry Andric } 8786122f3e6SDimitry Andric 8796122f3e6SDimitry Andric return true; 8806122f3e6SDimitry Andric } 8816122f3e6SDimitry Andric 882f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 883f22ef01cSRoman Divacky llvm::Function *F) { 884f785676fSDimitry Andric llvm::AttrBuilder B; 885f785676fSDimitry Andric 886bd5abe19SDimitry Andric if (CodeGenOpts.UnwindTables) 887f785676fSDimitry Andric B.addAttribute(llvm::Attribute::UWTable); 888bd5abe19SDimitry Andric 889dff0c46cSDimitry Andric if (!hasUnwindExceptions(LangOpts)) 890f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoUnwind); 891f22ef01cSRoman Divacky 8920623d748SDimitry Andric if (LangOpts.getStackProtector() == LangOptions::SSPOn) 8930623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtect); 8940623d748SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 8950623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectStrong); 8960623d748SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 8970623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectReq); 8980623d748SDimitry Andric 8990623d748SDimitry Andric if (!D) { 90044290647SDimitry Andric // If we don't have a declaration to control inlining, the function isn't 90144290647SDimitry Andric // explicitly marked as alwaysinline for semantic reasons, and inlining is 90244290647SDimitry Andric // disabled, mark the function as noinline. 90344290647SDimitry Andric if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 90444290647SDimitry Andric CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) 90544290647SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 90644290647SDimitry Andric 907f37b6182SDimitry Andric F->addAttributes(llvm::AttributeList::FunctionIndex, B); 9080623d748SDimitry Andric return; 9090623d748SDimitry Andric } 9100623d748SDimitry Andric 911302affcbSDimitry Andric // Track whether we need to add the optnone LLVM attribute, 912302affcbSDimitry Andric // starting with the default for this optimization level. 913302affcbSDimitry Andric bool ShouldAddOptNone = 914302affcbSDimitry Andric !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0; 915302affcbSDimitry Andric // We can't add optnone in the following cases, it won't pass the verifier. 916302affcbSDimitry Andric ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>(); 917302affcbSDimitry Andric ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline); 918302affcbSDimitry Andric ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>(); 919302affcbSDimitry Andric 920302affcbSDimitry Andric if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) { 92144290647SDimitry Andric B.addAttribute(llvm::Attribute::OptimizeNone); 92244290647SDimitry Andric 92344290647SDimitry Andric // OptimizeNone implies noinline; we should not be inlining such functions. 92444290647SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 92544290647SDimitry Andric assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 92644290647SDimitry Andric "OptimizeNone and AlwaysInline on same function!"); 92744290647SDimitry Andric 92844290647SDimitry Andric // We still need to handle naked functions even though optnone subsumes 92944290647SDimitry Andric // much of their semantics. 93044290647SDimitry Andric if (D->hasAttr<NakedAttr>()) 93144290647SDimitry Andric B.addAttribute(llvm::Attribute::Naked); 93244290647SDimitry Andric 93344290647SDimitry Andric // OptimizeNone wins over OptimizeForSize and MinSize. 93444290647SDimitry Andric F->removeFnAttr(llvm::Attribute::OptimizeForSize); 93544290647SDimitry Andric F->removeFnAttr(llvm::Attribute::MinSize); 93644290647SDimitry Andric } else if (D->hasAttr<NakedAttr>()) { 9376122f3e6SDimitry Andric // Naked implies noinline: we should not be inlining such functions. 938f785676fSDimitry Andric B.addAttribute(llvm::Attribute::Naked); 939f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 94059d1ed5bSDimitry Andric } else if (D->hasAttr<NoDuplicateAttr>()) { 94159d1ed5bSDimitry Andric B.addAttribute(llvm::Attribute::NoDuplicate); 942f785676fSDimitry Andric } else if (D->hasAttr<NoInlineAttr>()) { 943f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 94459d1ed5bSDimitry Andric } else if (D->hasAttr<AlwaysInlineAttr>() && 94544290647SDimitry Andric !F->hasFnAttribute(llvm::Attribute::NoInline)) { 946f785676fSDimitry Andric // (noinline wins over always_inline, and we can't specify both in IR) 947f785676fSDimitry Andric B.addAttribute(llvm::Attribute::AlwaysInline); 94844290647SDimitry Andric } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { 94944290647SDimitry Andric // If we're not inlining, then force everything that isn't always_inline to 95044290647SDimitry Andric // carry an explicit noinline attribute. 95144290647SDimitry Andric if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) 95244290647SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 95344290647SDimitry Andric } else { 95444290647SDimitry Andric // Otherwise, propagate the inline hint attribute and potentially use its 95544290647SDimitry Andric // absence to mark things as noinline. 95644290647SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) { 95744290647SDimitry Andric if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) { 95844290647SDimitry Andric return Redecl->isInlineSpecified(); 95944290647SDimitry Andric })) { 96044290647SDimitry Andric B.addAttribute(llvm::Attribute::InlineHint); 96144290647SDimitry Andric } else if (CodeGenOpts.getInlining() == 96244290647SDimitry Andric CodeGenOptions::OnlyHintInlining && 96344290647SDimitry Andric !FD->isInlined() && 96444290647SDimitry Andric !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 96544290647SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 96644290647SDimitry Andric } 96744290647SDimitry Andric } 9686122f3e6SDimitry Andric } 9692754fe60SDimitry Andric 97044290647SDimitry Andric // Add other optimization related attributes if we are optimizing this 97144290647SDimitry Andric // function. 97244290647SDimitry Andric if (!D->hasAttr<OptimizeNoneAttr>()) { 973f785676fSDimitry Andric if (D->hasAttr<ColdAttr>()) { 974302affcbSDimitry Andric if (!ShouldAddOptNone) 975f785676fSDimitry Andric B.addAttribute(llvm::Attribute::OptimizeForSize); 976f785676fSDimitry Andric B.addAttribute(llvm::Attribute::Cold); 977f785676fSDimitry Andric } 9783861d79fSDimitry Andric 9793861d79fSDimitry Andric if (D->hasAttr<MinSizeAttr>()) 980f785676fSDimitry Andric B.addAttribute(llvm::Attribute::MinSize); 98144290647SDimitry Andric } 982f22ef01cSRoman Divacky 983f37b6182SDimitry Andric F->addAttributes(llvm::AttributeList::FunctionIndex, B); 984f785676fSDimitry Andric 985e580952dSDimitry Andric unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 986e580952dSDimitry Andric if (alignment) 987e580952dSDimitry Andric F->setAlignment(alignment); 988e580952dSDimitry Andric 9890623d748SDimitry Andric // Some C++ ABIs require 2-byte alignment for member functions, in order to 9900623d748SDimitry Andric // reserve a bit for differentiating between virtual and non-virtual member 9910623d748SDimitry Andric // functions. If the current target's C++ ABI requires this and this is a 9920623d748SDimitry Andric // member function, set its alignment accordingly. 9930623d748SDimitry Andric if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 994f22ef01cSRoman Divacky if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 995f22ef01cSRoman Divacky F->setAlignment(2); 996f22ef01cSRoman Divacky } 99744290647SDimitry Andric 99844290647SDimitry Andric // In the cross-dso CFI mode, we want !type attributes on definitions only. 99944290647SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 100044290647SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) 100144290647SDimitry Andric CreateFunctionTypeMetadata(FD, F); 10020623d748SDimitry Andric } 1003f22ef01cSRoman Divacky 1004f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D, 1005f22ef01cSRoman Divacky llvm::GlobalValue *GV) { 10060623d748SDimitry Andric if (const auto *ND = dyn_cast_or_null<NamedDecl>(D)) 10072754fe60SDimitry Andric setGlobalVisibility(GV, ND); 10082754fe60SDimitry Andric else 10092754fe60SDimitry Andric GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 1010f22ef01cSRoman Divacky 10110623d748SDimitry Andric if (D && D->hasAttr<UsedAttr>()) 101259d1ed5bSDimitry Andric addUsedGlobal(GV); 101359d1ed5bSDimitry Andric } 101459d1ed5bSDimitry Andric 101539d628a0SDimitry Andric void CodeGenModule::setAliasAttributes(const Decl *D, 101639d628a0SDimitry Andric llvm::GlobalValue *GV) { 101739d628a0SDimitry Andric SetCommonAttributes(D, GV); 101839d628a0SDimitry Andric 101939d628a0SDimitry Andric // Process the dllexport attribute based on whether the original definition 102039d628a0SDimitry Andric // (not necessarily the aliasee) was exported. 102139d628a0SDimitry Andric if (D->hasAttr<DLLExportAttr>()) 102239d628a0SDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 102339d628a0SDimitry Andric } 102439d628a0SDimitry Andric 102559d1ed5bSDimitry Andric void CodeGenModule::setNonAliasAttributes(const Decl *D, 102659d1ed5bSDimitry Andric llvm::GlobalObject *GO) { 102759d1ed5bSDimitry Andric SetCommonAttributes(D, GO); 1028f22ef01cSRoman Divacky 1029db17bf38SDimitry Andric if (D) { 1030db17bf38SDimitry Andric if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) { 1031db17bf38SDimitry Andric if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) 1032db17bf38SDimitry Andric GV->addAttribute("bss-section", SA->getName()); 1033db17bf38SDimitry Andric if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) 1034db17bf38SDimitry Andric GV->addAttribute("data-section", SA->getName()); 1035db17bf38SDimitry Andric if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) 1036db17bf38SDimitry Andric GV->addAttribute("rodata-section", SA->getName()); 1037db17bf38SDimitry Andric } 1038db17bf38SDimitry Andric 1039db17bf38SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(GO)) { 1040db17bf38SDimitry Andric if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) 1041db17bf38SDimitry Andric if (!D->getAttr<SectionAttr>()) 1042db17bf38SDimitry Andric F->addFnAttr("implicit-section-name", SA->getName()); 1043db17bf38SDimitry Andric } 1044db17bf38SDimitry Andric 1045f22ef01cSRoman Divacky if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 104659d1ed5bSDimitry Andric GO->setSection(SA->getName()); 1047db17bf38SDimitry Andric } 1048f22ef01cSRoman Divacky 104997bc6c73SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 1050f22ef01cSRoman Divacky } 1051f22ef01cSRoman Divacky 1052f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 1053f22ef01cSRoman Divacky llvm::Function *F, 1054f22ef01cSRoman Divacky const CGFunctionInfo &FI) { 1055f22ef01cSRoman Divacky SetLLVMFunctionAttributes(D, FI, F); 1056f22ef01cSRoman Divacky SetLLVMFunctionAttributesForDefinition(D, F); 1057f22ef01cSRoman Divacky 1058f22ef01cSRoman Divacky F->setLinkage(llvm::Function::InternalLinkage); 1059f22ef01cSRoman Divacky 106059d1ed5bSDimitry Andric setNonAliasAttributes(D, F); 106159d1ed5bSDimitry Andric } 106259d1ed5bSDimitry Andric 106359d1ed5bSDimitry Andric static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV, 106459d1ed5bSDimitry Andric const NamedDecl *ND) { 106559d1ed5bSDimitry Andric // Set linkage and visibility in case we never see a definition. 106659d1ed5bSDimitry Andric LinkageInfo LV = ND->getLinkageAndVisibility(); 106759d1ed5bSDimitry Andric if (LV.getLinkage() != ExternalLinkage) { 106859d1ed5bSDimitry Andric // Don't set internal linkage on declarations. 106959d1ed5bSDimitry Andric } else { 107059d1ed5bSDimitry Andric if (ND->hasAttr<DLLImportAttr>()) { 107159d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 107259d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 107359d1ed5bSDimitry Andric } else if (ND->hasAttr<DLLExportAttr>()) { 107459d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 107559d1ed5bSDimitry Andric } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) { 107659d1ed5bSDimitry Andric // "extern_weak" is overloaded in LLVM; we probably should have 107759d1ed5bSDimitry Andric // separate linkage types for this. 107859d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 107959d1ed5bSDimitry Andric } 108059d1ed5bSDimitry Andric 108159d1ed5bSDimitry Andric // Set visibility on a declaration only if it's explicit. 108259d1ed5bSDimitry Andric if (LV.isVisibilityExplicit()) 108359d1ed5bSDimitry Andric GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility())); 108459d1ed5bSDimitry Andric } 1085f22ef01cSRoman Divacky } 1086f22ef01cSRoman Divacky 1087e7145dcbSDimitry Andric void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD, 10880623d748SDimitry Andric llvm::Function *F) { 10890623d748SDimitry Andric // Only if we are checking indirect calls. 10900623d748SDimitry Andric if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 10910623d748SDimitry Andric return; 10920623d748SDimitry Andric 10930623d748SDimitry Andric // Non-static class methods are handled via vtable pointer checks elsewhere. 10940623d748SDimitry Andric if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 10950623d748SDimitry Andric return; 10960623d748SDimitry Andric 10970623d748SDimitry Andric // Additionally, if building with cross-DSO support... 10980623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 10990623d748SDimitry Andric // Skip available_externally functions. They won't be codegen'ed in the 11000623d748SDimitry Andric // current module anyway. 11010623d748SDimitry Andric if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally) 11020623d748SDimitry Andric return; 11030623d748SDimitry Andric } 11040623d748SDimitry Andric 11050623d748SDimitry Andric llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 1106e7145dcbSDimitry Andric F->addTypeMetadata(0, MD); 11070623d748SDimitry Andric 11080623d748SDimitry Andric // Emit a hash-based bit set entry for cross-DSO calls. 1109e7145dcbSDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 1110e7145dcbSDimitry Andric if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 1111e7145dcbSDimitry Andric F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 11120623d748SDimitry Andric } 11130623d748SDimitry Andric 111439d628a0SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 111539d628a0SDimitry Andric bool IsIncompleteFunction, 111639d628a0SDimitry Andric bool IsThunk) { 111733956c43SDimitry Andric if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 11183b0f4066SDimitry Andric // If this is an intrinsic function, set the function's attributes 11193b0f4066SDimitry Andric // to the intrinsic's attributes. 112033956c43SDimitry Andric F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 11213b0f4066SDimitry Andric return; 11223b0f4066SDimitry Andric } 11233b0f4066SDimitry Andric 112459d1ed5bSDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 1125f22ef01cSRoman Divacky 1126f22ef01cSRoman Divacky if (!IsIncompleteFunction) 1127dff0c46cSDimitry Andric SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); 1128f22ef01cSRoman Divacky 112959d1ed5bSDimitry Andric // Add the Returned attribute for "this", except for iOS 5 and earlier 113059d1ed5bSDimitry Andric // where substantial code, including the libstdc++ dylib, was compiled with 113159d1ed5bSDimitry Andric // GCC and does not actually return "this". 113239d628a0SDimitry Andric if (!IsThunk && getCXXABI().HasThisReturn(GD) && 113344290647SDimitry Andric !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { 1134f785676fSDimitry Andric assert(!F->arg_empty() && 1135f785676fSDimitry Andric F->arg_begin()->getType() 1136f785676fSDimitry Andric ->canLosslesslyBitCastTo(F->getReturnType()) && 1137f785676fSDimitry Andric "unexpected this return"); 1138f785676fSDimitry Andric F->addAttribute(1, llvm::Attribute::Returned); 1139f785676fSDimitry Andric } 1140f785676fSDimitry Andric 1141f22ef01cSRoman Divacky // Only a few attributes are set on declarations; these may later be 1142f22ef01cSRoman Divacky // overridden by a definition. 1143f22ef01cSRoman Divacky 114459d1ed5bSDimitry Andric setLinkageAndVisibilityForGV(F, FD); 11452754fe60SDimitry Andric 1146db17bf38SDimitry Andric if (FD->getAttr<PragmaClangTextSectionAttr>()) { 1147db17bf38SDimitry Andric F->addFnAttr("implicit-section-name"); 1148db17bf38SDimitry Andric } 1149db17bf38SDimitry Andric 1150f22ef01cSRoman Divacky if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 1151f22ef01cSRoman Divacky F->setSection(SA->getName()); 1152f785676fSDimitry Andric 1153e7145dcbSDimitry Andric if (FD->isReplaceableGlobalAllocationFunction()) { 1154f785676fSDimitry Andric // A replaceable global allocation function does not act like a builtin by 1155f785676fSDimitry Andric // default, only if it is invoked by a new-expression or delete-expression. 115620e90f04SDimitry Andric F->addAttribute(llvm::AttributeList::FunctionIndex, 1157f785676fSDimitry Andric llvm::Attribute::NoBuiltin); 11580623d748SDimitry Andric 1159e7145dcbSDimitry Andric // A sane operator new returns a non-aliasing pointer. 1160e7145dcbSDimitry Andric // FIXME: Also add NonNull attribute to the return value 1161e7145dcbSDimitry Andric // for the non-nothrow forms? 1162e7145dcbSDimitry Andric auto Kind = FD->getDeclName().getCXXOverloadedOperator(); 1163e7145dcbSDimitry Andric if (getCodeGenOpts().AssumeSaneOperatorNew && 1164e7145dcbSDimitry Andric (Kind == OO_New || Kind == OO_Array_New)) 116520e90f04SDimitry Andric F->addAttribute(llvm::AttributeList::ReturnIndex, 1166e7145dcbSDimitry Andric llvm::Attribute::NoAlias); 1167e7145dcbSDimitry Andric } 1168e7145dcbSDimitry Andric 1169e7145dcbSDimitry Andric if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 1170e7145dcbSDimitry Andric F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1171e7145dcbSDimitry Andric else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 1172e7145dcbSDimitry Andric if (MD->isVirtual()) 1173e7145dcbSDimitry Andric F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1174e7145dcbSDimitry Andric 117544290647SDimitry Andric // Don't emit entries for function declarations in the cross-DSO mode. This 117644290647SDimitry Andric // is handled with better precision by the receiving DSO. 117744290647SDimitry Andric if (!CodeGenOpts.SanitizeCfiCrossDso) 1178e7145dcbSDimitry Andric CreateFunctionTypeMetadata(FD, F); 1179f22ef01cSRoman Divacky } 1180f22ef01cSRoman Divacky 118159d1ed5bSDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 1182f22ef01cSRoman Divacky assert(!GV->isDeclaration() && 1183f22ef01cSRoman Divacky "Only globals with definition can force usage."); 118497bc6c73SDimitry Andric LLVMUsed.emplace_back(GV); 1185f22ef01cSRoman Divacky } 1186f22ef01cSRoman Divacky 118759d1ed5bSDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 118859d1ed5bSDimitry Andric assert(!GV->isDeclaration() && 118959d1ed5bSDimitry Andric "Only globals with definition can force usage."); 119097bc6c73SDimitry Andric LLVMCompilerUsed.emplace_back(GV); 119159d1ed5bSDimitry Andric } 119259d1ed5bSDimitry Andric 119359d1ed5bSDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name, 1194f37b6182SDimitry Andric std::vector<llvm::WeakTrackingVH> &List) { 1195f22ef01cSRoman Divacky // Don't create llvm.used if there is no need. 119659d1ed5bSDimitry Andric if (List.empty()) 1197f22ef01cSRoman Divacky return; 1198f22ef01cSRoman Divacky 119959d1ed5bSDimitry Andric // Convert List to what ConstantArray needs. 1200dff0c46cSDimitry Andric SmallVector<llvm::Constant*, 8> UsedArray; 120159d1ed5bSDimitry Andric UsedArray.resize(List.size()); 120259d1ed5bSDimitry Andric for (unsigned i = 0, e = List.size(); i != e; ++i) { 1203f22ef01cSRoman Divacky UsedArray[i] = 120444f7b0dcSDimitry Andric llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 120544f7b0dcSDimitry Andric cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 1206f22ef01cSRoman Divacky } 1207f22ef01cSRoman Divacky 1208f22ef01cSRoman Divacky if (UsedArray.empty()) 1209f22ef01cSRoman Divacky return; 121059d1ed5bSDimitry Andric llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 1211f22ef01cSRoman Divacky 121259d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 121359d1ed5bSDimitry Andric CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 121459d1ed5bSDimitry Andric llvm::ConstantArray::get(ATy, UsedArray), Name); 1215f22ef01cSRoman Divacky 1216f22ef01cSRoman Divacky GV->setSection("llvm.metadata"); 1217f22ef01cSRoman Divacky } 1218f22ef01cSRoman Divacky 121959d1ed5bSDimitry Andric void CodeGenModule::emitLLVMUsed() { 122059d1ed5bSDimitry Andric emitUsed(*this, "llvm.used", LLVMUsed); 122159d1ed5bSDimitry Andric emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 122259d1ed5bSDimitry Andric } 122359d1ed5bSDimitry Andric 1224f785676fSDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 122539d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 1226f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1227f785676fSDimitry Andric } 1228f785676fSDimitry Andric 1229f785676fSDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 1230f785676fSDimitry Andric llvm::SmallString<32> Opt; 1231f785676fSDimitry Andric getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 123239d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1233f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1234f785676fSDimitry Andric } 1235f785676fSDimitry Andric 1236f785676fSDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) { 1237f785676fSDimitry Andric llvm::SmallString<24> Opt; 1238f785676fSDimitry Andric getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 123939d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1240f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1241f785676fSDimitry Andric } 1242f785676fSDimitry Andric 1243139f7f9bSDimitry Andric /// \brief Add link options implied by the given module, including modules 1244139f7f9bSDimitry Andric /// it depends on, using a postorder walk. 124539d628a0SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 124639d628a0SDimitry Andric SmallVectorImpl<llvm::Metadata *> &Metadata, 1247139f7f9bSDimitry Andric llvm::SmallPtrSet<Module *, 16> &Visited) { 1248139f7f9bSDimitry Andric // Import this module's parent. 124939d628a0SDimitry Andric if (Mod->Parent && Visited.insert(Mod->Parent).second) { 1250f785676fSDimitry Andric addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 1251139f7f9bSDimitry Andric } 1252139f7f9bSDimitry Andric 1253139f7f9bSDimitry Andric // Import this module's dependencies. 1254139f7f9bSDimitry Andric for (unsigned I = Mod->Imports.size(); I > 0; --I) { 125539d628a0SDimitry Andric if (Visited.insert(Mod->Imports[I - 1]).second) 1256f785676fSDimitry Andric addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 1257139f7f9bSDimitry Andric } 1258139f7f9bSDimitry Andric 1259139f7f9bSDimitry Andric // Add linker options to link against the libraries/frameworks 1260139f7f9bSDimitry Andric // described by this module. 1261f785676fSDimitry Andric llvm::LLVMContext &Context = CGM.getLLVMContext(); 1262139f7f9bSDimitry Andric for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 1263f785676fSDimitry Andric // Link against a framework. Frameworks are currently Darwin only, so we 1264f785676fSDimitry Andric // don't to ask TargetCodeGenInfo for the spelling of the linker option. 1265139f7f9bSDimitry Andric if (Mod->LinkLibraries[I-1].IsFramework) { 126639d628a0SDimitry Andric llvm::Metadata *Args[2] = { 1267139f7f9bSDimitry Andric llvm::MDString::get(Context, "-framework"), 126839d628a0SDimitry Andric llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)}; 1269139f7f9bSDimitry Andric 1270139f7f9bSDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, Args)); 1271139f7f9bSDimitry Andric continue; 1272139f7f9bSDimitry Andric } 1273139f7f9bSDimitry Andric 1274139f7f9bSDimitry Andric // Link against a library. 1275f785676fSDimitry Andric llvm::SmallString<24> Opt; 1276f785676fSDimitry Andric CGM.getTargetCodeGenInfo().getDependentLibraryOption( 1277f785676fSDimitry Andric Mod->LinkLibraries[I-1].Library, Opt); 127839d628a0SDimitry Andric auto *OptString = llvm::MDString::get(Context, Opt); 1279139f7f9bSDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, OptString)); 1280139f7f9bSDimitry Andric } 1281139f7f9bSDimitry Andric } 1282139f7f9bSDimitry Andric 1283139f7f9bSDimitry Andric void CodeGenModule::EmitModuleLinkOptions() { 1284139f7f9bSDimitry Andric // Collect the set of all of the modules we want to visit to emit link 1285139f7f9bSDimitry Andric // options, which is essentially the imported modules and all of their 1286139f7f9bSDimitry Andric // non-explicit child modules. 1287139f7f9bSDimitry Andric llvm::SetVector<clang::Module *> LinkModules; 1288139f7f9bSDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 1289139f7f9bSDimitry Andric SmallVector<clang::Module *, 16> Stack; 1290139f7f9bSDimitry Andric 1291139f7f9bSDimitry Andric // Seed the stack with imported modules. 1292f1a29dd3SDimitry Andric for (Module *M : ImportedModules) { 1293f1a29dd3SDimitry Andric // Do not add any link flags when an implementation TU of a module imports 1294f1a29dd3SDimitry Andric // a header of that same module. 1295f1a29dd3SDimitry Andric if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && 1296f1a29dd3SDimitry Andric !getLangOpts().isCompilingModule()) 1297f1a29dd3SDimitry Andric continue; 12988f0fd8f6SDimitry Andric if (Visited.insert(M).second) 12998f0fd8f6SDimitry Andric Stack.push_back(M); 1300f1a29dd3SDimitry Andric } 1301139f7f9bSDimitry Andric 1302139f7f9bSDimitry Andric // Find all of the modules to import, making a little effort to prune 1303139f7f9bSDimitry Andric // non-leaf modules. 1304139f7f9bSDimitry Andric while (!Stack.empty()) { 1305f785676fSDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 1306139f7f9bSDimitry Andric 1307139f7f9bSDimitry Andric bool AnyChildren = false; 1308139f7f9bSDimitry Andric 1309139f7f9bSDimitry Andric // Visit the submodules of this module. 1310139f7f9bSDimitry Andric for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 1311139f7f9bSDimitry Andric SubEnd = Mod->submodule_end(); 1312139f7f9bSDimitry Andric Sub != SubEnd; ++Sub) { 1313139f7f9bSDimitry Andric // Skip explicit children; they need to be explicitly imported to be 1314139f7f9bSDimitry Andric // linked against. 1315139f7f9bSDimitry Andric if ((*Sub)->IsExplicit) 1316139f7f9bSDimitry Andric continue; 1317139f7f9bSDimitry Andric 131839d628a0SDimitry Andric if (Visited.insert(*Sub).second) { 1319139f7f9bSDimitry Andric Stack.push_back(*Sub); 1320139f7f9bSDimitry Andric AnyChildren = true; 1321139f7f9bSDimitry Andric } 1322139f7f9bSDimitry Andric } 1323139f7f9bSDimitry Andric 1324139f7f9bSDimitry Andric // We didn't find any children, so add this module to the list of 1325139f7f9bSDimitry Andric // modules to link against. 1326139f7f9bSDimitry Andric if (!AnyChildren) { 1327139f7f9bSDimitry Andric LinkModules.insert(Mod); 1328139f7f9bSDimitry Andric } 1329139f7f9bSDimitry Andric } 1330139f7f9bSDimitry Andric 1331139f7f9bSDimitry Andric // Add link options for all of the imported modules in reverse topological 1332f785676fSDimitry Andric // order. We don't do anything to try to order import link flags with respect 1333f785676fSDimitry Andric // to linker options inserted by things like #pragma comment(). 133439d628a0SDimitry Andric SmallVector<llvm::Metadata *, 16> MetadataArgs; 1335139f7f9bSDimitry Andric Visited.clear(); 13368f0fd8f6SDimitry Andric for (Module *M : LinkModules) 13378f0fd8f6SDimitry Andric if (Visited.insert(M).second) 13388f0fd8f6SDimitry Andric addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 1339139f7f9bSDimitry Andric std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 1340f785676fSDimitry Andric LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 1341139f7f9bSDimitry Andric 1342139f7f9bSDimitry Andric // Add the linker options metadata flag. 1343139f7f9bSDimitry Andric getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options", 1344f785676fSDimitry Andric llvm::MDNode::get(getLLVMContext(), 1345f785676fSDimitry Andric LinkerOptionsMetadata)); 1346139f7f9bSDimitry Andric } 1347139f7f9bSDimitry Andric 1348f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() { 1349f22ef01cSRoman Divacky // Emit code for any potentially referenced deferred decls. Since a 1350f22ef01cSRoman Divacky // previously unused static decl may become used during the generation of code 1351f22ef01cSRoman Divacky // for a static function, iterate until no changes are made. 1352f22ef01cSRoman Divacky 1353f22ef01cSRoman Divacky if (!DeferredVTables.empty()) { 1354139f7f9bSDimitry Andric EmitDeferredVTables(); 1355139f7f9bSDimitry Andric 1356e7145dcbSDimitry Andric // Emitting a vtable doesn't directly cause more vtables to 1357139f7f9bSDimitry Andric // become deferred, although it can cause functions to be 1358e7145dcbSDimitry Andric // emitted that then need those vtables. 1359139f7f9bSDimitry Andric assert(DeferredVTables.empty()); 1360f22ef01cSRoman Divacky } 1361f22ef01cSRoman Divacky 1362e7145dcbSDimitry Andric // Stop if we're out of both deferred vtables and deferred declarations. 136333956c43SDimitry Andric if (DeferredDeclsToEmit.empty()) 136433956c43SDimitry Andric return; 1365139f7f9bSDimitry Andric 136633956c43SDimitry Andric // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 136733956c43SDimitry Andric // work, it will not interfere with this. 1368f37b6182SDimitry Andric std::vector<GlobalDecl> CurDeclsToEmit; 136933956c43SDimitry Andric CurDeclsToEmit.swap(DeferredDeclsToEmit); 137033956c43SDimitry Andric 1371f37b6182SDimitry Andric for (GlobalDecl &D : CurDeclsToEmit) { 13720623d748SDimitry Andric // We should call GetAddrOfGlobal with IsForDefinition set to true in order 13730623d748SDimitry Andric // to get GlobalValue with exactly the type we need, not something that 13740623d748SDimitry Andric // might had been created for another decl with the same mangled name but 13750623d748SDimitry Andric // different type. 1376e7145dcbSDimitry Andric llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 137744290647SDimitry Andric GetAddrOfGlobal(D, ForDefinition)); 1378e7145dcbSDimitry Andric 1379e7145dcbSDimitry Andric // In case of different address spaces, we may still get a cast, even with 1380e7145dcbSDimitry Andric // IsForDefinition equal to true. Query mangled names table to get 1381e7145dcbSDimitry Andric // GlobalValue. 138239d628a0SDimitry Andric if (!GV) 138339d628a0SDimitry Andric GV = GetGlobalValue(getMangledName(D)); 138439d628a0SDimitry Andric 1385e7145dcbSDimitry Andric // Make sure GetGlobalValue returned non-null. 1386e7145dcbSDimitry Andric assert(GV); 1387e7145dcbSDimitry Andric 1388f22ef01cSRoman Divacky // Check to see if we've already emitted this. This is necessary 1389f22ef01cSRoman Divacky // for a couple of reasons: first, decls can end up in the 1390f22ef01cSRoman Divacky // deferred-decls queue multiple times, and second, decls can end 1391f22ef01cSRoman Divacky // up with definitions in unusual ways (e.g. by an extern inline 1392f22ef01cSRoman Divacky // function acquiring a strong function redefinition). Just 1393f22ef01cSRoman Divacky // ignore these cases. 1394e7145dcbSDimitry Andric if (!GV->isDeclaration()) 1395f22ef01cSRoman Divacky continue; 1396f22ef01cSRoman Divacky 1397f22ef01cSRoman Divacky // Otherwise, emit the definition and move on to the next one. 139859d1ed5bSDimitry Andric EmitGlobalDefinition(D, GV); 139933956c43SDimitry Andric 140033956c43SDimitry Andric // If we found out that we need to emit more decls, do that recursively. 140133956c43SDimitry Andric // This has the advantage that the decls are emitted in a DFS and related 140233956c43SDimitry Andric // ones are close together, which is convenient for testing. 140333956c43SDimitry Andric if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 140433956c43SDimitry Andric EmitDeferred(); 140533956c43SDimitry Andric assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 140633956c43SDimitry Andric } 1407f22ef01cSRoman Divacky } 1408f22ef01cSRoman Divacky } 1409f22ef01cSRoman Divacky 1410f9448bf3SDimitry Andric void CodeGenModule::EmitVTablesOpportunistically() { 1411f9448bf3SDimitry Andric // Try to emit external vtables as available_externally if they have emitted 1412f9448bf3SDimitry Andric // all inlined virtual functions. It runs after EmitDeferred() and therefore 1413f9448bf3SDimitry Andric // is not allowed to create new references to things that need to be emitted 1414f9448bf3SDimitry Andric // lazily. Note that it also uses fact that we eagerly emitting RTTI. 1415f9448bf3SDimitry Andric 1416f9448bf3SDimitry Andric assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) 1417f9448bf3SDimitry Andric && "Only emit opportunistic vtables with optimizations"); 1418f9448bf3SDimitry Andric 1419f9448bf3SDimitry Andric for (const CXXRecordDecl *RD : OpportunisticVTables) { 1420f9448bf3SDimitry Andric assert(getVTables().isVTableExternal(RD) && 1421f9448bf3SDimitry Andric "This queue should only contain external vtables"); 1422f9448bf3SDimitry Andric if (getCXXABI().canSpeculativelyEmitVTable(RD)) 1423f9448bf3SDimitry Andric VTables.GenerateClassData(RD); 1424f9448bf3SDimitry Andric } 1425f9448bf3SDimitry Andric OpportunisticVTables.clear(); 1426f9448bf3SDimitry Andric } 1427f9448bf3SDimitry Andric 14286122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() { 14296122f3e6SDimitry Andric if (Annotations.empty()) 14306122f3e6SDimitry Andric return; 14316122f3e6SDimitry Andric 14326122f3e6SDimitry Andric // Create a new global variable for the ConstantStruct in the Module. 14336122f3e6SDimitry Andric llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 14346122f3e6SDimitry Andric Annotations[0]->getType(), Annotations.size()), Annotations); 143559d1ed5bSDimitry Andric auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 143659d1ed5bSDimitry Andric llvm::GlobalValue::AppendingLinkage, 143759d1ed5bSDimitry Andric Array, "llvm.global.annotations"); 14386122f3e6SDimitry Andric gv->setSection(AnnotationSection); 14396122f3e6SDimitry Andric } 14406122f3e6SDimitry Andric 1441139f7f9bSDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 1442f785676fSDimitry Andric llvm::Constant *&AStr = AnnotationStrings[Str]; 1443f785676fSDimitry Andric if (AStr) 1444f785676fSDimitry Andric return AStr; 14456122f3e6SDimitry Andric 14466122f3e6SDimitry Andric // Not found yet, create a new global. 1447dff0c46cSDimitry Andric llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 144859d1ed5bSDimitry Andric auto *gv = 144959d1ed5bSDimitry Andric new llvm::GlobalVariable(getModule(), s->getType(), true, 145059d1ed5bSDimitry Andric llvm::GlobalValue::PrivateLinkage, s, ".str"); 14516122f3e6SDimitry Andric gv->setSection(AnnotationSection); 1452e7145dcbSDimitry Andric gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1453f785676fSDimitry Andric AStr = gv; 14546122f3e6SDimitry Andric return gv; 14556122f3e6SDimitry Andric } 14566122f3e6SDimitry Andric 14576122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 14586122f3e6SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 14596122f3e6SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(Loc); 14606122f3e6SDimitry Andric if (PLoc.isValid()) 14616122f3e6SDimitry Andric return EmitAnnotationString(PLoc.getFilename()); 14626122f3e6SDimitry Andric return EmitAnnotationString(SM.getBufferName(Loc)); 14636122f3e6SDimitry Andric } 14646122f3e6SDimitry Andric 14656122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 14666122f3e6SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 14676122f3e6SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(L); 14686122f3e6SDimitry Andric unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 14696122f3e6SDimitry Andric SM.getExpansionLineNumber(L); 14706122f3e6SDimitry Andric return llvm::ConstantInt::get(Int32Ty, LineNo); 14716122f3e6SDimitry Andric } 14726122f3e6SDimitry Andric 1473f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 1474f22ef01cSRoman Divacky const AnnotateAttr *AA, 14756122f3e6SDimitry Andric SourceLocation L) { 14766122f3e6SDimitry Andric // Get the globals for file name, annotation, and the line number. 14776122f3e6SDimitry Andric llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 14786122f3e6SDimitry Andric *UnitGV = EmitAnnotationUnit(L), 14796122f3e6SDimitry Andric *LineNoCst = EmitAnnotationLineNo(L); 1480f22ef01cSRoman Divacky 1481f22ef01cSRoman Divacky // Create the ConstantStruct for the global annotation. 1482f22ef01cSRoman Divacky llvm::Constant *Fields[4] = { 14836122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 14846122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 14856122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 14866122f3e6SDimitry Andric LineNoCst 1487f22ef01cSRoman Divacky }; 148817a519f9SDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 1489f22ef01cSRoman Divacky } 1490f22ef01cSRoman Divacky 14916122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 14926122f3e6SDimitry Andric llvm::GlobalValue *GV) { 14936122f3e6SDimitry Andric assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 14946122f3e6SDimitry Andric // Get the struct elements for these annotations. 149559d1ed5bSDimitry Andric for (const auto *I : D->specific_attrs<AnnotateAttr>()) 149659d1ed5bSDimitry Andric Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 14976122f3e6SDimitry Andric } 14986122f3e6SDimitry Andric 149939d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn, 150039d628a0SDimitry Andric SourceLocation Loc) const { 150139d628a0SDimitry Andric const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 150239d628a0SDimitry Andric // Blacklist by function name. 150339d628a0SDimitry Andric if (SanitizerBL.isBlacklistedFunction(Fn->getName())) 150439d628a0SDimitry Andric return true; 150539d628a0SDimitry Andric // Blacklist by location. 15060623d748SDimitry Andric if (Loc.isValid()) 150739d628a0SDimitry Andric return SanitizerBL.isBlacklistedLocation(Loc); 150839d628a0SDimitry Andric // If location is unknown, this may be a compiler-generated function. Assume 150939d628a0SDimitry Andric // it's located in the main file. 151039d628a0SDimitry Andric auto &SM = Context.getSourceManager(); 151139d628a0SDimitry Andric if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 151239d628a0SDimitry Andric return SanitizerBL.isBlacklistedFile(MainFile->getName()); 151339d628a0SDimitry Andric } 151439d628a0SDimitry Andric return false; 151539d628a0SDimitry Andric } 151639d628a0SDimitry Andric 151739d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV, 151839d628a0SDimitry Andric SourceLocation Loc, QualType Ty, 151939d628a0SDimitry Andric StringRef Category) const { 15208f0fd8f6SDimitry Andric // For now globals can be blacklisted only in ASan and KASan. 15218f0fd8f6SDimitry Andric if (!LangOpts.Sanitize.hasOneOf( 15228f0fd8f6SDimitry Andric SanitizerKind::Address | SanitizerKind::KernelAddress)) 152339d628a0SDimitry Andric return false; 152439d628a0SDimitry Andric const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 152539d628a0SDimitry Andric if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category)) 152639d628a0SDimitry Andric return true; 152739d628a0SDimitry Andric if (SanitizerBL.isBlacklistedLocation(Loc, Category)) 152839d628a0SDimitry Andric return true; 152939d628a0SDimitry Andric // Check global type. 153039d628a0SDimitry Andric if (!Ty.isNull()) { 153139d628a0SDimitry Andric // Drill down the array types: if global variable of a fixed type is 153239d628a0SDimitry Andric // blacklisted, we also don't instrument arrays of them. 153339d628a0SDimitry Andric while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 153439d628a0SDimitry Andric Ty = AT->getElementType(); 153539d628a0SDimitry Andric Ty = Ty.getCanonicalType().getUnqualifiedType(); 153639d628a0SDimitry Andric // We allow to blacklist only record types (classes, structs etc.) 153739d628a0SDimitry Andric if (Ty->isRecordType()) { 153839d628a0SDimitry Andric std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 153939d628a0SDimitry Andric if (SanitizerBL.isBlacklistedType(TypeStr, Category)) 154039d628a0SDimitry Andric return true; 154139d628a0SDimitry Andric } 154239d628a0SDimitry Andric } 154339d628a0SDimitry Andric return false; 154439d628a0SDimitry Andric } 154539d628a0SDimitry Andric 154620e90f04SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 154720e90f04SDimitry Andric StringRef Category) const { 154820e90f04SDimitry Andric if (!LangOpts.XRayInstrument) 154920e90f04SDimitry Andric return false; 155020e90f04SDimitry Andric const auto &XRayFilter = getContext().getXRayFilter(); 155120e90f04SDimitry Andric using ImbueAttr = XRayFunctionFilter::ImbueAttribute; 155220e90f04SDimitry Andric auto Attr = XRayFunctionFilter::ImbueAttribute::NONE; 155320e90f04SDimitry Andric if (Loc.isValid()) 155420e90f04SDimitry Andric Attr = XRayFilter.shouldImbueLocation(Loc, Category); 155520e90f04SDimitry Andric if (Attr == ImbueAttr::NONE) 155620e90f04SDimitry Andric Attr = XRayFilter.shouldImbueFunction(Fn->getName()); 155720e90f04SDimitry Andric switch (Attr) { 155820e90f04SDimitry Andric case ImbueAttr::NONE: 155920e90f04SDimitry Andric return false; 156020e90f04SDimitry Andric case ImbueAttr::ALWAYS: 156120e90f04SDimitry Andric Fn->addFnAttr("function-instrument", "xray-always"); 156220e90f04SDimitry Andric break; 1563302affcbSDimitry Andric case ImbueAttr::ALWAYS_ARG1: 1564302affcbSDimitry Andric Fn->addFnAttr("function-instrument", "xray-always"); 1565302affcbSDimitry Andric Fn->addFnAttr("xray-log-args", "1"); 1566302affcbSDimitry Andric break; 156720e90f04SDimitry Andric case ImbueAttr::NEVER: 156820e90f04SDimitry Andric Fn->addFnAttr("function-instrument", "xray-never"); 156920e90f04SDimitry Andric break; 157020e90f04SDimitry Andric } 157120e90f04SDimitry Andric return true; 157220e90f04SDimitry Andric } 157320e90f04SDimitry Andric 157439d628a0SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 1575e580952dSDimitry Andric // Never defer when EmitAllDecls is specified. 1576dff0c46cSDimitry Andric if (LangOpts.EmitAllDecls) 157739d628a0SDimitry Andric return true; 157839d628a0SDimitry Andric 157939d628a0SDimitry Andric return getContext().DeclMustBeEmitted(Global); 158039d628a0SDimitry Andric } 158139d628a0SDimitry Andric 158239d628a0SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 158339d628a0SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) 158439d628a0SDimitry Andric if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 158539d628a0SDimitry Andric // Implicit template instantiations may change linkage if they are later 158639d628a0SDimitry Andric // explicitly instantiated, so they should not be emitted eagerly. 1587f22ef01cSRoman Divacky return false; 1588e7145dcbSDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(Global)) 1589e7145dcbSDimitry Andric if (Context.getInlineVariableDefinitionKind(VD) == 1590e7145dcbSDimitry Andric ASTContext::InlineVariableDefinitionKind::WeakUnknown) 1591e7145dcbSDimitry Andric // A definition of an inline constexpr static data member may change 1592e7145dcbSDimitry Andric // linkage later if it's redeclared outside the class. 1593e7145dcbSDimitry Andric return false; 1594875ed548SDimitry Andric // If OpenMP is enabled and threadprivates must be generated like TLS, delay 1595875ed548SDimitry Andric // codegen for global variables, because they may be marked as threadprivate. 1596875ed548SDimitry Andric if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 1597875ed548SDimitry Andric getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global)) 1598875ed548SDimitry Andric return false; 1599f22ef01cSRoman Divacky 160039d628a0SDimitry Andric return true; 1601f22ef01cSRoman Divacky } 1602f22ef01cSRoman Divacky 16030623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor( 16043861d79fSDimitry Andric const CXXUuidofExpr* E) { 16053861d79fSDimitry Andric // Sema has verified that IIDSource has a __declspec(uuid()), and that its 16063861d79fSDimitry Andric // well-formed. 1607e7145dcbSDimitry Andric StringRef Uuid = E->getUuidStr(); 1608f785676fSDimitry Andric std::string Name = "_GUID_" + Uuid.lower(); 1609f785676fSDimitry Andric std::replace(Name.begin(), Name.end(), '-', '_'); 16103861d79fSDimitry Andric 1611e7145dcbSDimitry Andric // The UUID descriptor should be pointer aligned. 1612e7145dcbSDimitry Andric CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 16130623d748SDimitry Andric 16143861d79fSDimitry Andric // Look for an existing global. 16153861d79fSDimitry Andric if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 16160623d748SDimitry Andric return ConstantAddress(GV, Alignment); 16173861d79fSDimitry Andric 161839d628a0SDimitry Andric llvm::Constant *Init = EmitUuidofInitializer(Uuid); 16193861d79fSDimitry Andric assert(Init && "failed to initialize as constant"); 16203861d79fSDimitry Andric 162159d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 1622f785676fSDimitry Andric getModule(), Init->getType(), 1623f785676fSDimitry Andric /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 162433956c43SDimitry Andric if (supportsCOMDAT()) 162533956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 16260623d748SDimitry Andric return ConstantAddress(GV, Alignment); 16273861d79fSDimitry Andric } 16283861d79fSDimitry Andric 16290623d748SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 1630f22ef01cSRoman Divacky const AliasAttr *AA = VD->getAttr<AliasAttr>(); 1631f22ef01cSRoman Divacky assert(AA && "No alias?"); 1632f22ef01cSRoman Divacky 16330623d748SDimitry Andric CharUnits Alignment = getContext().getDeclAlign(VD); 16346122f3e6SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 1635f22ef01cSRoman Divacky 1636f22ef01cSRoman Divacky // See if there is already something with the target's name in the module. 1637f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 16383861d79fSDimitry Andric if (Entry) { 16393861d79fSDimitry Andric unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 16400623d748SDimitry Andric auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 16410623d748SDimitry Andric return ConstantAddress(Ptr, Alignment); 16423861d79fSDimitry Andric } 1643f22ef01cSRoman Divacky 1644f22ef01cSRoman Divacky llvm::Constant *Aliasee; 1645f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(DeclTy)) 16463861d79fSDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 16473861d79fSDimitry Andric GlobalDecl(cast<FunctionDecl>(VD)), 16482754fe60SDimitry Andric /*ForVTable=*/false); 1649f22ef01cSRoman Divacky else 1650f22ef01cSRoman Divacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 165159d1ed5bSDimitry Andric llvm::PointerType::getUnqual(DeclTy), 165259d1ed5bSDimitry Andric nullptr); 16533861d79fSDimitry Andric 165459d1ed5bSDimitry Andric auto *F = cast<llvm::GlobalValue>(Aliasee); 1655f22ef01cSRoman Divacky F->setLinkage(llvm::Function::ExternalWeakLinkage); 1656f22ef01cSRoman Divacky WeakRefReferences.insert(F); 1657f22ef01cSRoman Divacky 16580623d748SDimitry Andric return ConstantAddress(Aliasee, Alignment); 1659f22ef01cSRoman Divacky } 1660f22ef01cSRoman Divacky 1661f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) { 166259d1ed5bSDimitry Andric const auto *Global = cast<ValueDecl>(GD.getDecl()); 1663f22ef01cSRoman Divacky 1664f22ef01cSRoman Divacky // Weak references don't produce any output by themselves. 1665f22ef01cSRoman Divacky if (Global->hasAttr<WeakRefAttr>()) 1666f22ef01cSRoman Divacky return; 1667f22ef01cSRoman Divacky 1668f22ef01cSRoman Divacky // If this is an alias definition (which otherwise looks like a declaration) 1669f22ef01cSRoman Divacky // emit it now. 1670f22ef01cSRoman Divacky if (Global->hasAttr<AliasAttr>()) 1671f22ef01cSRoman Divacky return EmitAliasDefinition(GD); 1672f22ef01cSRoman Divacky 1673e7145dcbSDimitry Andric // IFunc like an alias whose value is resolved at runtime by calling resolver. 1674e7145dcbSDimitry Andric if (Global->hasAttr<IFuncAttr>()) 1675e7145dcbSDimitry Andric return emitIFuncDefinition(GD); 1676e7145dcbSDimitry Andric 16776122f3e6SDimitry Andric // If this is CUDA, be selective about which declarations we emit. 1678dff0c46cSDimitry Andric if (LangOpts.CUDA) { 167933956c43SDimitry Andric if (LangOpts.CUDAIsDevice) { 16806122f3e6SDimitry Andric if (!Global->hasAttr<CUDADeviceAttr>() && 16816122f3e6SDimitry Andric !Global->hasAttr<CUDAGlobalAttr>() && 16826122f3e6SDimitry Andric !Global->hasAttr<CUDAConstantAttr>() && 16836122f3e6SDimitry Andric !Global->hasAttr<CUDASharedAttr>()) 16846122f3e6SDimitry Andric return; 16856122f3e6SDimitry Andric } else { 1686e7145dcbSDimitry Andric // We need to emit host-side 'shadows' for all global 1687e7145dcbSDimitry Andric // device-side variables because the CUDA runtime needs their 1688e7145dcbSDimitry Andric // size and host-side address in order to provide access to 1689e7145dcbSDimitry Andric // their device-side incarnations. 1690e7145dcbSDimitry Andric 1691e7145dcbSDimitry Andric // So device-only functions are the only things we skip. 1692e7145dcbSDimitry Andric if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 1693e7145dcbSDimitry Andric Global->hasAttr<CUDADeviceAttr>()) 16946122f3e6SDimitry Andric return; 1695e7145dcbSDimitry Andric 1696e7145dcbSDimitry Andric assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 1697e7145dcbSDimitry Andric "Expected Variable or Function"); 1698e580952dSDimitry Andric } 1699e580952dSDimitry Andric } 1700e580952dSDimitry Andric 1701e7145dcbSDimitry Andric if (LangOpts.OpenMP) { 1702ea942507SDimitry Andric // If this is OpenMP device, check if it is legal to emit this global 1703ea942507SDimitry Andric // normally. 1704ea942507SDimitry Andric if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 1705ea942507SDimitry Andric return; 1706e7145dcbSDimitry Andric if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 1707e7145dcbSDimitry Andric if (MustBeEmitted(Global)) 1708e7145dcbSDimitry Andric EmitOMPDeclareReduction(DRD); 1709e7145dcbSDimitry Andric return; 1710e7145dcbSDimitry Andric } 1711e7145dcbSDimitry Andric } 1712ea942507SDimitry Andric 17136122f3e6SDimitry Andric // Ignore declarations, they will be emitted on their first use. 171459d1ed5bSDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 1715f22ef01cSRoman Divacky // Forward declarations are emitted lazily on first use. 17166122f3e6SDimitry Andric if (!FD->doesThisDeclarationHaveABody()) { 17176122f3e6SDimitry Andric if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 1718f22ef01cSRoman Divacky return; 17196122f3e6SDimitry Andric 17206122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 172159d1ed5bSDimitry Andric 172259d1ed5bSDimitry Andric // Compute the function info and LLVM type. 172359d1ed5bSDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 172459d1ed5bSDimitry Andric llvm::Type *Ty = getTypes().GetFunctionType(FI); 172559d1ed5bSDimitry Andric 172659d1ed5bSDimitry Andric GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 172759d1ed5bSDimitry Andric /*DontDefer=*/false); 17286122f3e6SDimitry Andric return; 17296122f3e6SDimitry Andric } 1730f22ef01cSRoman Divacky } else { 173159d1ed5bSDimitry Andric const auto *VD = cast<VarDecl>(Global); 1732f22ef01cSRoman Divacky assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 1733e7145dcbSDimitry Andric // We need to emit device-side global CUDA variables even if a 1734e7145dcbSDimitry Andric // variable does not have a definition -- we still need to define 1735e7145dcbSDimitry Andric // host-side shadow for it. 1736e7145dcbSDimitry Andric bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice && 1737e7145dcbSDimitry Andric !VD->hasDefinition() && 1738e7145dcbSDimitry Andric (VD->hasAttr<CUDAConstantAttr>() || 1739e7145dcbSDimitry Andric VD->hasAttr<CUDADeviceAttr>()); 1740e7145dcbSDimitry Andric if (!MustEmitForCuda && 1741e7145dcbSDimitry Andric VD->isThisDeclarationADefinition() != VarDecl::Definition && 1742e7145dcbSDimitry Andric !Context.isMSStaticDataMemberInlineDefinition(VD)) { 1743e7145dcbSDimitry Andric // If this declaration may have caused an inline variable definition to 1744e7145dcbSDimitry Andric // change linkage, make sure that it's emitted. 1745e7145dcbSDimitry Andric if (Context.getInlineVariableDefinitionKind(VD) == 1746e7145dcbSDimitry Andric ASTContext::InlineVariableDefinitionKind::Strong) 1747e7145dcbSDimitry Andric GetAddrOfGlobalVar(VD); 1748f22ef01cSRoman Divacky return; 1749f22ef01cSRoman Divacky } 1750e7145dcbSDimitry Andric } 1751f22ef01cSRoman Divacky 175239d628a0SDimitry Andric // Defer code generation to first use when possible, e.g. if this is an inline 175339d628a0SDimitry Andric // function. If the global must always be emitted, do it eagerly if possible 175439d628a0SDimitry Andric // to benefit from cache locality. 175539d628a0SDimitry Andric if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 1756f22ef01cSRoman Divacky // Emit the definition if it can't be deferred. 1757f22ef01cSRoman Divacky EmitGlobalDefinition(GD); 1758f22ef01cSRoman Divacky return; 1759f22ef01cSRoman Divacky } 1760f22ef01cSRoman Divacky 1761e580952dSDimitry Andric // If we're deferring emission of a C++ variable with an 1762e580952dSDimitry Andric // initializer, remember the order in which it appeared in the file. 1763dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 1764e580952dSDimitry Andric cast<VarDecl>(Global)->hasInit()) { 1765e580952dSDimitry Andric DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 176659d1ed5bSDimitry Andric CXXGlobalInits.push_back(nullptr); 1767e580952dSDimitry Andric } 1768e580952dSDimitry Andric 17696122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 1770f37b6182SDimitry Andric if (GetGlobalValue(MangledName) != nullptr) { 177139d628a0SDimitry Andric // The value has already been used and should therefore be emitted. 1772f37b6182SDimitry Andric addDeferredDeclToEmit(GD); 177339d628a0SDimitry Andric } else if (MustBeEmitted(Global)) { 177439d628a0SDimitry Andric // The value must be emitted, but cannot be emitted eagerly. 177539d628a0SDimitry Andric assert(!MayBeEmittedEagerly(Global)); 1776f37b6182SDimitry Andric addDeferredDeclToEmit(GD); 177739d628a0SDimitry Andric } else { 1778f22ef01cSRoman Divacky // Otherwise, remember that we saw a deferred decl with this name. The 1779f22ef01cSRoman Divacky // first use of the mangled name will cause it to move into 1780f22ef01cSRoman Divacky // DeferredDeclsToEmit. 1781f22ef01cSRoman Divacky DeferredDecls[MangledName] = GD; 1782f22ef01cSRoman Divacky } 1783f22ef01cSRoman Divacky } 1784f22ef01cSRoman Divacky 178520e90f04SDimitry Andric // Check if T is a class type with a destructor that's not dllimport. 178620e90f04SDimitry Andric static bool HasNonDllImportDtor(QualType T) { 178720e90f04SDimitry Andric if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) 178820e90f04SDimitry Andric if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 178920e90f04SDimitry Andric if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) 179020e90f04SDimitry Andric return true; 179120e90f04SDimitry Andric 179220e90f04SDimitry Andric return false; 179320e90f04SDimitry Andric } 179420e90f04SDimitry Andric 1795f8254f43SDimitry Andric namespace { 1796f8254f43SDimitry Andric struct FunctionIsDirectlyRecursive : 1797f8254f43SDimitry Andric public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 1798f8254f43SDimitry Andric const StringRef Name; 1799dff0c46cSDimitry Andric const Builtin::Context &BI; 1800f8254f43SDimitry Andric bool Result; 1801dff0c46cSDimitry Andric FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 1802dff0c46cSDimitry Andric Name(N), BI(C), Result(false) { 1803f8254f43SDimitry Andric } 1804f8254f43SDimitry Andric typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 1805f8254f43SDimitry Andric 1806f8254f43SDimitry Andric bool TraverseCallExpr(CallExpr *E) { 1807dff0c46cSDimitry Andric const FunctionDecl *FD = E->getDirectCallee(); 1808dff0c46cSDimitry Andric if (!FD) 1809f8254f43SDimitry Andric return true; 1810dff0c46cSDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1811dff0c46cSDimitry Andric if (Attr && Name == Attr->getLabel()) { 1812dff0c46cSDimitry Andric Result = true; 1813dff0c46cSDimitry Andric return false; 1814dff0c46cSDimitry Andric } 1815dff0c46cSDimitry Andric unsigned BuiltinID = FD->getBuiltinID(); 18163dac3a9bSDimitry Andric if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 1817f8254f43SDimitry Andric return true; 18180623d748SDimitry Andric StringRef BuiltinName = BI.getName(BuiltinID); 1819dff0c46cSDimitry Andric if (BuiltinName.startswith("__builtin_") && 1820dff0c46cSDimitry Andric Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 1821f8254f43SDimitry Andric Result = true; 1822f8254f43SDimitry Andric return false; 1823f8254f43SDimitry Andric } 1824f8254f43SDimitry Andric return true; 1825f8254f43SDimitry Andric } 1826f8254f43SDimitry Andric }; 18270623d748SDimitry Andric 182820e90f04SDimitry Andric // Make sure we're not referencing non-imported vars or functions. 18290623d748SDimitry Andric struct DLLImportFunctionVisitor 18300623d748SDimitry Andric : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 18310623d748SDimitry Andric bool SafeToInline = true; 18320623d748SDimitry Andric 183344290647SDimitry Andric bool shouldVisitImplicitCode() const { return true; } 183444290647SDimitry Andric 18350623d748SDimitry Andric bool VisitVarDecl(VarDecl *VD) { 183620e90f04SDimitry Andric if (VD->getTLSKind()) { 18370623d748SDimitry Andric // A thread-local variable cannot be imported. 183820e90f04SDimitry Andric SafeToInline = false; 18390623d748SDimitry Andric return SafeToInline; 18400623d748SDimitry Andric } 18410623d748SDimitry Andric 184220e90f04SDimitry Andric // A variable definition might imply a destructor call. 184320e90f04SDimitry Andric if (VD->isThisDeclarationADefinition()) 184420e90f04SDimitry Andric SafeToInline = !HasNonDllImportDtor(VD->getType()); 184520e90f04SDimitry Andric 184620e90f04SDimitry Andric return SafeToInline; 184720e90f04SDimitry Andric } 184820e90f04SDimitry Andric 184920e90f04SDimitry Andric bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 185020e90f04SDimitry Andric if (const auto *D = E->getTemporary()->getDestructor()) 185120e90f04SDimitry Andric SafeToInline = D->hasAttr<DLLImportAttr>(); 185220e90f04SDimitry Andric return SafeToInline; 185320e90f04SDimitry Andric } 185420e90f04SDimitry Andric 18550623d748SDimitry Andric bool VisitDeclRefExpr(DeclRefExpr *E) { 18560623d748SDimitry Andric ValueDecl *VD = E->getDecl(); 18570623d748SDimitry Andric if (isa<FunctionDecl>(VD)) 18580623d748SDimitry Andric SafeToInline = VD->hasAttr<DLLImportAttr>(); 18590623d748SDimitry Andric else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 18600623d748SDimitry Andric SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 18610623d748SDimitry Andric return SafeToInline; 18620623d748SDimitry Andric } 186320e90f04SDimitry Andric 186444290647SDimitry Andric bool VisitCXXConstructExpr(CXXConstructExpr *E) { 186544290647SDimitry Andric SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); 186644290647SDimitry Andric return SafeToInline; 186744290647SDimitry Andric } 186820e90f04SDimitry Andric 186920e90f04SDimitry Andric bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 187020e90f04SDimitry Andric CXXMethodDecl *M = E->getMethodDecl(); 187120e90f04SDimitry Andric if (!M) { 187220e90f04SDimitry Andric // Call through a pointer to member function. This is safe to inline. 187320e90f04SDimitry Andric SafeToInline = true; 187420e90f04SDimitry Andric } else { 187520e90f04SDimitry Andric SafeToInline = M->hasAttr<DLLImportAttr>(); 187620e90f04SDimitry Andric } 187720e90f04SDimitry Andric return SafeToInline; 187820e90f04SDimitry Andric } 187920e90f04SDimitry Andric 18800623d748SDimitry Andric bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 18810623d748SDimitry Andric SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 18820623d748SDimitry Andric return SafeToInline; 18830623d748SDimitry Andric } 188420e90f04SDimitry Andric 18850623d748SDimitry Andric bool VisitCXXNewExpr(CXXNewExpr *E) { 18860623d748SDimitry Andric SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 18870623d748SDimitry Andric return SafeToInline; 18880623d748SDimitry Andric } 18890623d748SDimitry Andric }; 1890f8254f43SDimitry Andric } 1891f8254f43SDimitry Andric 1892dff0c46cSDimitry Andric // isTriviallyRecursive - Check if this function calls another 1893dff0c46cSDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin, 1894dff0c46cSDimitry Andric // ends up pointing to itself. 1895f8254f43SDimitry Andric bool 1896dff0c46cSDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 1897dff0c46cSDimitry Andric StringRef Name; 1898dff0c46cSDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 1899dff0c46cSDimitry Andric // asm labels are a special kind of mangling we have to support. 1900dff0c46cSDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1901dff0c46cSDimitry Andric if (!Attr) 1902f8254f43SDimitry Andric return false; 1903dff0c46cSDimitry Andric Name = Attr->getLabel(); 1904dff0c46cSDimitry Andric } else { 1905dff0c46cSDimitry Andric Name = FD->getName(); 1906dff0c46cSDimitry Andric } 1907f8254f43SDimitry Andric 1908dff0c46cSDimitry Andric FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 1909dff0c46cSDimitry Andric Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 1910f8254f43SDimitry Andric return Walker.Result; 1911f8254f43SDimitry Andric } 1912f8254f43SDimitry Andric 191344290647SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 1914f785676fSDimitry Andric if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 1915f8254f43SDimitry Andric return true; 191659d1ed5bSDimitry Andric const auto *F = cast<FunctionDecl>(GD.getDecl()); 191759d1ed5bSDimitry Andric if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 1918f8254f43SDimitry Andric return false; 19190623d748SDimitry Andric 19200623d748SDimitry Andric if (F->hasAttr<DLLImportAttr>()) { 19210623d748SDimitry Andric // Check whether it would be safe to inline this dllimport function. 19220623d748SDimitry Andric DLLImportFunctionVisitor Visitor; 19230623d748SDimitry Andric Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 19240623d748SDimitry Andric if (!Visitor.SafeToInline) 19250623d748SDimitry Andric return false; 192644290647SDimitry Andric 192744290647SDimitry Andric if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { 192844290647SDimitry Andric // Implicit destructor invocations aren't captured in the AST, so the 192944290647SDimitry Andric // check above can't see them. Check for them manually here. 193044290647SDimitry Andric for (const Decl *Member : Dtor->getParent()->decls()) 193144290647SDimitry Andric if (isa<FieldDecl>(Member)) 193244290647SDimitry Andric if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) 193344290647SDimitry Andric return false; 193444290647SDimitry Andric for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) 193544290647SDimitry Andric if (HasNonDllImportDtor(B.getType())) 193644290647SDimitry Andric return false; 193744290647SDimitry Andric } 19380623d748SDimitry Andric } 19390623d748SDimitry Andric 1940f8254f43SDimitry Andric // PR9614. Avoid cases where the source code is lying to us. An available 1941f8254f43SDimitry Andric // externally function should have an equivalent function somewhere else, 1942f8254f43SDimitry Andric // but a function that calls itself is clearly not equivalent to the real 1943f8254f43SDimitry Andric // implementation. 1944f8254f43SDimitry Andric // This happens in glibc's btowc and in some configure checks. 1945dff0c46cSDimitry Andric return !isTriviallyRecursive(F); 1946f8254f43SDimitry Andric } 1947f8254f43SDimitry Andric 1948f9448bf3SDimitry Andric bool CodeGenModule::shouldOpportunisticallyEmitVTables() { 1949f9448bf3SDimitry Andric return CodeGenOpts.OptimizationLevel > 0; 1950f9448bf3SDimitry Andric } 1951f9448bf3SDimitry Andric 195259d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 195359d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 1954f22ef01cSRoman Divacky 1955f22ef01cSRoman Divacky PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 1956f22ef01cSRoman Divacky Context.getSourceManager(), 1957f22ef01cSRoman Divacky "Generating code for declaration"); 1958f22ef01cSRoman Divacky 1959f785676fSDimitry Andric if (isa<FunctionDecl>(D)) { 1960ffd1746dSEd Schouten // At -O0, don't generate IR for functions with available_externally 1961ffd1746dSEd Schouten // linkage. 1962f785676fSDimitry Andric if (!shouldEmitFunction(GD)) 1963ffd1746dSEd Schouten return; 1964ffd1746dSEd Schouten 196559d1ed5bSDimitry Andric if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 1966bd5abe19SDimitry Andric // Make sure to emit the definition(s) before we emit the thunks. 1967bd5abe19SDimitry Andric // This is necessary for the generation of certain thunks. 196859d1ed5bSDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method)) 196939d628a0SDimitry Andric ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType())); 197059d1ed5bSDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method)) 197139d628a0SDimitry Andric ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType())); 1972bd5abe19SDimitry Andric else 197359d1ed5bSDimitry Andric EmitGlobalFunctionDefinition(GD, GV); 1974bd5abe19SDimitry Andric 1975f22ef01cSRoman Divacky if (Method->isVirtual()) 1976f22ef01cSRoman Divacky getVTables().EmitThunks(GD); 1977f22ef01cSRoman Divacky 1978bd5abe19SDimitry Andric return; 1979ffd1746dSEd Schouten } 1980f22ef01cSRoman Divacky 198159d1ed5bSDimitry Andric return EmitGlobalFunctionDefinition(GD, GV); 1982ffd1746dSEd Schouten } 1983f22ef01cSRoman Divacky 198459d1ed5bSDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 1985e7145dcbSDimitry Andric return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 1986f22ef01cSRoman Divacky 19876122f3e6SDimitry Andric llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 1988f22ef01cSRoman Divacky } 1989f22ef01cSRoman Divacky 19900623d748SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 19910623d748SDimitry Andric llvm::Function *NewFn); 19920623d748SDimitry Andric 1993f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 1994f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there 1995f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially 1996f22ef01cSRoman Divacky /// bitcasted to the right type. 1997f22ef01cSRoman Divacky /// 1998f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this. This is used 1999f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created. 200020e90f04SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( 200120e90f04SDimitry Andric StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, 200220e90f04SDimitry Andric bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, 200344290647SDimitry Andric ForDefinition_t IsForDefinition) { 2004f785676fSDimitry Andric const Decl *D = GD.getDecl(); 2005f785676fSDimitry Andric 2006f22ef01cSRoman Divacky // Lookup the entry, lazily creating it if necessary. 2007f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2008f22ef01cSRoman Divacky if (Entry) { 20093861d79fSDimitry Andric if (WeakRefReferences.erase(Entry)) { 2010f785676fSDimitry Andric const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 2011f22ef01cSRoman Divacky if (FD && !FD->hasAttr<WeakAttr>()) 2012f22ef01cSRoman Divacky Entry->setLinkage(llvm::Function::ExternalLinkage); 2013f22ef01cSRoman Divacky } 2014f22ef01cSRoman Divacky 201539d628a0SDimitry Andric // Handle dropped DLL attributes. 201639d628a0SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 201739d628a0SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 201839d628a0SDimitry Andric 20190623d748SDimitry Andric // If there are two attempts to define the same mangled name, issue an 20200623d748SDimitry Andric // error. 20210623d748SDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 20220623d748SDimitry Andric GlobalDecl OtherGD; 2023e7145dcbSDimitry Andric // Check that GD is not yet in DiagnosedConflictingDefinitions is required 2024e7145dcbSDimitry Andric // to make sure that we issue an error only once. 20250623d748SDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 20260623d748SDimitry Andric (GD.getCanonicalDecl().getDecl() != 20270623d748SDimitry Andric OtherGD.getCanonicalDecl().getDecl()) && 20280623d748SDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 20290623d748SDimitry Andric getDiags().Report(D->getLocation(), 20300623d748SDimitry Andric diag::err_duplicate_mangled_name); 20310623d748SDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 20320623d748SDimitry Andric diag::note_previous_definition); 20330623d748SDimitry Andric } 20340623d748SDimitry Andric } 20350623d748SDimitry Andric 20360623d748SDimitry Andric if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 20370623d748SDimitry Andric (Entry->getType()->getElementType() == Ty)) { 2038f22ef01cSRoman Divacky return Entry; 20390623d748SDimitry Andric } 2040f22ef01cSRoman Divacky 2041f22ef01cSRoman Divacky // Make sure the result is of the correct type. 20420623d748SDimitry Andric // (If function is requested for a definition, we always need to create a new 20430623d748SDimitry Andric // function, not just return a bitcast.) 20440623d748SDimitry Andric if (!IsForDefinition) 204517a519f9SDimitry Andric return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 2046f22ef01cSRoman Divacky } 2047f22ef01cSRoman Divacky 2048f22ef01cSRoman Divacky // This function doesn't have a complete type (for example, the return 2049f22ef01cSRoman Divacky // type is an incomplete struct). Use a fake type instead, and make 2050f22ef01cSRoman Divacky // sure not to try to set attributes. 2051f22ef01cSRoman Divacky bool IsIncompleteFunction = false; 2052f22ef01cSRoman Divacky 20536122f3e6SDimitry Andric llvm::FunctionType *FTy; 2054f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(Ty)) { 2055f22ef01cSRoman Divacky FTy = cast<llvm::FunctionType>(Ty); 2056f22ef01cSRoman Divacky } else { 2057bd5abe19SDimitry Andric FTy = llvm::FunctionType::get(VoidTy, false); 2058f22ef01cSRoman Divacky IsIncompleteFunction = true; 2059f22ef01cSRoman Divacky } 2060ffd1746dSEd Schouten 20610623d748SDimitry Andric llvm::Function *F = 20620623d748SDimitry Andric llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 20630623d748SDimitry Andric Entry ? StringRef() : MangledName, &getModule()); 20640623d748SDimitry Andric 20650623d748SDimitry Andric // If we already created a function with the same mangled name (but different 20660623d748SDimitry Andric // type) before, take its name and add it to the list of functions to be 20670623d748SDimitry Andric // replaced with F at the end of CodeGen. 20680623d748SDimitry Andric // 20690623d748SDimitry Andric // This happens if there is a prototype for a function (e.g. "int f()") and 20700623d748SDimitry Andric // then a definition of a different type (e.g. "int f(int x)"). 20710623d748SDimitry Andric if (Entry) { 20720623d748SDimitry Andric F->takeName(Entry); 20730623d748SDimitry Andric 20740623d748SDimitry Andric // This might be an implementation of a function without a prototype, in 20750623d748SDimitry Andric // which case, try to do special replacement of calls which match the new 20760623d748SDimitry Andric // prototype. The really key thing here is that we also potentially drop 20770623d748SDimitry Andric // arguments from the call site so as to make a direct call, which makes the 20780623d748SDimitry Andric // inliner happier and suppresses a number of optimizer warnings (!) about 20790623d748SDimitry Andric // dropping arguments. 20800623d748SDimitry Andric if (!Entry->use_empty()) { 20810623d748SDimitry Andric ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 20820623d748SDimitry Andric Entry->removeDeadConstantUsers(); 20830623d748SDimitry Andric } 20840623d748SDimitry Andric 20850623d748SDimitry Andric llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 20860623d748SDimitry Andric F, Entry->getType()->getElementType()->getPointerTo()); 20870623d748SDimitry Andric addGlobalValReplacement(Entry, BC); 20880623d748SDimitry Andric } 20890623d748SDimitry Andric 2090f22ef01cSRoman Divacky assert(F->getName() == MangledName && "name was uniqued!"); 2091f785676fSDimitry Andric if (D) 209239d628a0SDimitry Andric SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 209320e90f04SDimitry Andric if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) { 209420e90f04SDimitry Andric llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex); 2095f37b6182SDimitry Andric F->addAttributes(llvm::AttributeList::FunctionIndex, B); 2096139f7f9bSDimitry Andric } 2097f22ef01cSRoman Divacky 209859d1ed5bSDimitry Andric if (!DontDefer) { 209959d1ed5bSDimitry Andric // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 210059d1ed5bSDimitry Andric // each other bottoming out with the base dtor. Therefore we emit non-base 210159d1ed5bSDimitry Andric // dtors on usage, even if there is no dtor definition in the TU. 210259d1ed5bSDimitry Andric if (D && isa<CXXDestructorDecl>(D) && 210359d1ed5bSDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 210459d1ed5bSDimitry Andric GD.getDtorType())) 2105f37b6182SDimitry Andric addDeferredDeclToEmit(GD); 210659d1ed5bSDimitry Andric 2107f22ef01cSRoman Divacky // This is the first use or definition of a mangled name. If there is a 2108f22ef01cSRoman Divacky // deferred decl with this name, remember that we need to emit it at the end 2109f22ef01cSRoman Divacky // of the file. 211059d1ed5bSDimitry Andric auto DDI = DeferredDecls.find(MangledName); 2111f22ef01cSRoman Divacky if (DDI != DeferredDecls.end()) { 211259d1ed5bSDimitry Andric // Move the potentially referenced deferred decl to the 211359d1ed5bSDimitry Andric // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 211459d1ed5bSDimitry Andric // don't need it anymore). 2115f37b6182SDimitry Andric addDeferredDeclToEmit(DDI->second); 2116f22ef01cSRoman Divacky DeferredDecls.erase(DDI); 21172754fe60SDimitry Andric 21182754fe60SDimitry Andric // Otherwise, there are cases we have to worry about where we're 21192754fe60SDimitry Andric // using a declaration for which we must emit a definition but where 21202754fe60SDimitry Andric // we might not find a top-level definition: 21212754fe60SDimitry Andric // - member functions defined inline in their classes 21222754fe60SDimitry Andric // - friend functions defined inline in some class 21232754fe60SDimitry Andric // - special member functions with implicit definitions 21242754fe60SDimitry Andric // If we ever change our AST traversal to walk into class methods, 21252754fe60SDimitry Andric // this will be unnecessary. 21262754fe60SDimitry Andric // 212759d1ed5bSDimitry Andric // We also don't emit a definition for a function if it's going to be an 212839d628a0SDimitry Andric // entry in a vtable, unless it's already marked as used. 2129f785676fSDimitry Andric } else if (getLangOpts().CPlusPlus && D) { 21302754fe60SDimitry Andric // Look for a declaration that's lexically in a record. 213139d628a0SDimitry Andric for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 213239d628a0SDimitry Andric FD = FD->getPreviousDecl()) { 21332754fe60SDimitry Andric if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 213439d628a0SDimitry Andric if (FD->doesThisDeclarationHaveABody()) { 2135f37b6182SDimitry Andric addDeferredDeclToEmit(GD.getWithDecl(FD)); 21362754fe60SDimitry Andric break; 2137f22ef01cSRoman Divacky } 2138f22ef01cSRoman Divacky } 213939d628a0SDimitry Andric } 2140f22ef01cSRoman Divacky } 214159d1ed5bSDimitry Andric } 2142f22ef01cSRoman Divacky 2143f22ef01cSRoman Divacky // Make sure the result is of the requested type. 2144f22ef01cSRoman Divacky if (!IsIncompleteFunction) { 2145f22ef01cSRoman Divacky assert(F->getType()->getElementType() == Ty); 2146f22ef01cSRoman Divacky return F; 2147f22ef01cSRoman Divacky } 2148f22ef01cSRoman Divacky 214917a519f9SDimitry Andric llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 2150f22ef01cSRoman Divacky return llvm::ConstantExpr::getBitCast(F, PTy); 2151f22ef01cSRoman Divacky } 2152f22ef01cSRoman Divacky 2153f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function. If Ty is 2154f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to 2155f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function). 2156f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 21576122f3e6SDimitry Andric llvm::Type *Ty, 215859d1ed5bSDimitry Andric bool ForVTable, 21590623d748SDimitry Andric bool DontDefer, 216044290647SDimitry Andric ForDefinition_t IsForDefinition) { 2161f22ef01cSRoman Divacky // If there was no specific requested type, just convert it now. 21620623d748SDimitry Andric if (!Ty) { 21630623d748SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 21640623d748SDimitry Andric auto CanonTy = Context.getCanonicalType(FD->getType()); 21650623d748SDimitry Andric Ty = getTypes().ConvertFunctionType(CanonTy, FD); 21660623d748SDimitry Andric } 2167ffd1746dSEd Schouten 21686122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 21690623d748SDimitry Andric return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 217020e90f04SDimitry Andric /*IsThunk=*/false, llvm::AttributeList(), 21710623d748SDimitry Andric IsForDefinition); 2172f22ef01cSRoman Divacky } 2173f22ef01cSRoman Divacky 217444290647SDimitry Andric static const FunctionDecl * 217544290647SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { 217644290647SDimitry Andric TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 217744290647SDimitry Andric DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 217844290647SDimitry Andric 217944290647SDimitry Andric IdentifierInfo &CII = C.Idents.get(Name); 218044290647SDimitry Andric for (const auto &Result : DC->lookup(&CII)) 218144290647SDimitry Andric if (const auto FD = dyn_cast<FunctionDecl>(Result)) 218244290647SDimitry Andric return FD; 218344290647SDimitry Andric 218444290647SDimitry Andric if (!C.getLangOpts().CPlusPlus) 218544290647SDimitry Andric return nullptr; 218644290647SDimitry Andric 218744290647SDimitry Andric // Demangle the premangled name from getTerminateFn() 218844290647SDimitry Andric IdentifierInfo &CXXII = 218944290647SDimitry Andric (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ") 219044290647SDimitry Andric ? C.Idents.get("terminate") 219144290647SDimitry Andric : C.Idents.get(Name); 219244290647SDimitry Andric 219344290647SDimitry Andric for (const auto &N : {"__cxxabiv1", "std"}) { 219444290647SDimitry Andric IdentifierInfo &NS = C.Idents.get(N); 219544290647SDimitry Andric for (const auto &Result : DC->lookup(&NS)) { 219644290647SDimitry Andric NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); 219744290647SDimitry Andric if (auto LSD = dyn_cast<LinkageSpecDecl>(Result)) 219844290647SDimitry Andric for (const auto &Result : LSD->lookup(&NS)) 219944290647SDimitry Andric if ((ND = dyn_cast<NamespaceDecl>(Result))) 220044290647SDimitry Andric break; 220144290647SDimitry Andric 220244290647SDimitry Andric if (ND) 220344290647SDimitry Andric for (const auto &Result : ND->lookup(&CXXII)) 220444290647SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 220544290647SDimitry Andric return FD; 220644290647SDimitry Andric } 220744290647SDimitry Andric } 220844290647SDimitry Andric 220944290647SDimitry Andric return nullptr; 221044290647SDimitry Andric } 221144290647SDimitry Andric 2212f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified 2213f22ef01cSRoman Divacky /// type and name. 2214f22ef01cSRoman Divacky llvm::Constant * 221544290647SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, 221620e90f04SDimitry Andric llvm::AttributeList ExtraAttrs, 221744290647SDimitry Andric bool Local) { 221859d1ed5bSDimitry Andric llvm::Constant *C = 221959d1ed5bSDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 222044290647SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, 222144290647SDimitry Andric ExtraAttrs); 222244290647SDimitry Andric 222344290647SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) { 222444290647SDimitry Andric if (F->empty()) { 2225139f7f9bSDimitry Andric F->setCallingConv(getRuntimeCC()); 222644290647SDimitry Andric 222744290647SDimitry Andric if (!Local && getTriple().isOSBinFormatCOFF() && 222844290647SDimitry Andric !getCodeGenOpts().LTOVisibilityPublicStd) { 222944290647SDimitry Andric const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); 223044290647SDimitry Andric if (!FD || FD->hasAttr<DLLImportAttr>()) { 223144290647SDimitry Andric F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 223244290647SDimitry Andric F->setLinkage(llvm::GlobalValue::ExternalLinkage); 223344290647SDimitry Andric } 223444290647SDimitry Andric } 223544290647SDimitry Andric } 223644290647SDimitry Andric } 223744290647SDimitry Andric 2238139f7f9bSDimitry Andric return C; 2239f22ef01cSRoman Divacky } 2240f22ef01cSRoman Divacky 224139d628a0SDimitry Andric /// CreateBuiltinFunction - Create a new builtin function with the specified 224239d628a0SDimitry Andric /// type and name. 224339d628a0SDimitry Andric llvm::Constant * 224420e90f04SDimitry Andric CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name, 224520e90f04SDimitry Andric llvm::AttributeList ExtraAttrs) { 224639d628a0SDimitry Andric llvm::Constant *C = 224739d628a0SDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 224839d628a0SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); 224939d628a0SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) 225039d628a0SDimitry Andric if (F->empty()) 225139d628a0SDimitry Andric F->setCallingConv(getBuiltinCC()); 225239d628a0SDimitry Andric return C; 225339d628a0SDimitry Andric } 225439d628a0SDimitry Andric 2255dff0c46cSDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted 2256dff0c46cSDimitry Andric /// as a constant. 2257dff0c46cSDimitry Andric /// 2258dff0c46cSDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs 2259dff0c46cSDimitry Andric /// will not be considered. The caller will need to verify that the object is 2260dff0c46cSDimitry Andric /// not written to during its construction. 2261dff0c46cSDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 2262dff0c46cSDimitry Andric if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 2263f22ef01cSRoman Divacky return false; 2264bd5abe19SDimitry Andric 2265dff0c46cSDimitry Andric if (Context.getLangOpts().CPlusPlus) { 2266dff0c46cSDimitry Andric if (const CXXRecordDecl *Record 2267dff0c46cSDimitry Andric = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 2268dff0c46cSDimitry Andric return ExcludeCtor && !Record->hasMutableFields() && 2269dff0c46cSDimitry Andric Record->hasTrivialDestructor(); 2270f22ef01cSRoman Divacky } 2271bd5abe19SDimitry Andric 2272f22ef01cSRoman Divacky return true; 2273f22ef01cSRoman Divacky } 2274f22ef01cSRoman Divacky 2275f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 2276f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type. If there 2277f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially 2278f22ef01cSRoman Divacky /// bitcasted to the right type. 2279f22ef01cSRoman Divacky /// 2280f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this. This is used 2281f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created. 2282e7145dcbSDimitry Andric /// 2283e7145dcbSDimitry Andric /// If IsForDefinition is true, it is guranteed that an actual global with 2284e7145dcbSDimitry Andric /// type Ty will be returned, not conversion of a variable with the same 2285e7145dcbSDimitry Andric /// mangled name but some other type. 2286f22ef01cSRoman Divacky llvm::Constant * 22876122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 22886122f3e6SDimitry Andric llvm::PointerType *Ty, 2289e7145dcbSDimitry Andric const VarDecl *D, 229044290647SDimitry Andric ForDefinition_t IsForDefinition) { 2291f22ef01cSRoman Divacky // Lookup the entry, lazily creating it if necessary. 2292f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2293f22ef01cSRoman Divacky if (Entry) { 22943861d79fSDimitry Andric if (WeakRefReferences.erase(Entry)) { 2295f22ef01cSRoman Divacky if (D && !D->hasAttr<WeakAttr>()) 2296f22ef01cSRoman Divacky Entry->setLinkage(llvm::Function::ExternalLinkage); 2297f22ef01cSRoman Divacky } 2298f22ef01cSRoman Divacky 229939d628a0SDimitry Andric // Handle dropped DLL attributes. 230039d628a0SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 230139d628a0SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 230239d628a0SDimitry Andric 2303f22ef01cSRoman Divacky if (Entry->getType() == Ty) 2304f22ef01cSRoman Divacky return Entry; 2305f22ef01cSRoman Divacky 2306e7145dcbSDimitry Andric // If there are two attempts to define the same mangled name, issue an 2307e7145dcbSDimitry Andric // error. 2308e7145dcbSDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 2309e7145dcbSDimitry Andric GlobalDecl OtherGD; 2310e7145dcbSDimitry Andric const VarDecl *OtherD; 2311e7145dcbSDimitry Andric 2312e7145dcbSDimitry Andric // Check that D is not yet in DiagnosedConflictingDefinitions is required 2313e7145dcbSDimitry Andric // to make sure that we issue an error only once. 2314e7145dcbSDimitry Andric if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 2315e7145dcbSDimitry Andric (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 2316e7145dcbSDimitry Andric (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 2317e7145dcbSDimitry Andric OtherD->hasInit() && 2318e7145dcbSDimitry Andric DiagnosedConflictingDefinitions.insert(D).second) { 2319e7145dcbSDimitry Andric getDiags().Report(D->getLocation(), 2320e7145dcbSDimitry Andric diag::err_duplicate_mangled_name); 2321e7145dcbSDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 2322e7145dcbSDimitry Andric diag::note_previous_definition); 2323e7145dcbSDimitry Andric } 2324e7145dcbSDimitry Andric } 2325e7145dcbSDimitry Andric 2326f22ef01cSRoman Divacky // Make sure the result is of the correct type. 2327f785676fSDimitry Andric if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) 2328f785676fSDimitry Andric return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); 2329f785676fSDimitry Andric 2330e7145dcbSDimitry Andric // (If global is requested for a definition, we always need to create a new 2331e7145dcbSDimitry Andric // global, not just return a bitcast.) 2332e7145dcbSDimitry Andric if (!IsForDefinition) 2333f22ef01cSRoman Divacky return llvm::ConstantExpr::getBitCast(Entry, Ty); 2334f22ef01cSRoman Divacky } 2335f22ef01cSRoman Divacky 233659d1ed5bSDimitry Andric unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace()); 233759d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 233859d1ed5bSDimitry Andric getModule(), Ty->getElementType(), false, 233959d1ed5bSDimitry Andric llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr, 234059d1ed5bSDimitry Andric llvm::GlobalVariable::NotThreadLocal, AddrSpace); 234159d1ed5bSDimitry Andric 2342e7145dcbSDimitry Andric // If we already created a global with the same mangled name (but different 2343e7145dcbSDimitry Andric // type) before, take its name and remove it from its parent. 2344e7145dcbSDimitry Andric if (Entry) { 2345e7145dcbSDimitry Andric GV->takeName(Entry); 2346e7145dcbSDimitry Andric 2347e7145dcbSDimitry Andric if (!Entry->use_empty()) { 2348e7145dcbSDimitry Andric llvm::Constant *NewPtrForOldDecl = 2349e7145dcbSDimitry Andric llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 2350e7145dcbSDimitry Andric Entry->replaceAllUsesWith(NewPtrForOldDecl); 2351e7145dcbSDimitry Andric } 2352e7145dcbSDimitry Andric 2353e7145dcbSDimitry Andric Entry->eraseFromParent(); 2354e7145dcbSDimitry Andric } 2355e7145dcbSDimitry Andric 2356f22ef01cSRoman Divacky // This is the first use or definition of a mangled name. If there is a 2357f22ef01cSRoman Divacky // deferred decl with this name, remember that we need to emit it at the end 2358f22ef01cSRoman Divacky // of the file. 235959d1ed5bSDimitry Andric auto DDI = DeferredDecls.find(MangledName); 2360f22ef01cSRoman Divacky if (DDI != DeferredDecls.end()) { 2361f22ef01cSRoman Divacky // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 2362f22ef01cSRoman Divacky // list, and remove it from DeferredDecls (since we don't need it anymore). 2363f37b6182SDimitry Andric addDeferredDeclToEmit(DDI->second); 2364f22ef01cSRoman Divacky DeferredDecls.erase(DDI); 2365f22ef01cSRoman Divacky } 2366f22ef01cSRoman Divacky 2367f22ef01cSRoman Divacky // Handle things which are present even on external declarations. 2368f22ef01cSRoman Divacky if (D) { 2369f22ef01cSRoman Divacky // FIXME: This code is overly simple and should be merged with other global 2370f22ef01cSRoman Divacky // handling. 2371dff0c46cSDimitry Andric GV->setConstant(isTypeConstant(D->getType(), false)); 2372f22ef01cSRoman Divacky 237333956c43SDimitry Andric GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 237433956c43SDimitry Andric 237559d1ed5bSDimitry Andric setLinkageAndVisibilityForGV(GV, D); 23762754fe60SDimitry Andric 2377284c1978SDimitry Andric if (D->getTLSKind()) { 2378284c1978SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 23790623d748SDimitry Andric CXXThreadLocals.push_back(D); 23807ae0e2c9SDimitry Andric setTLSMode(GV, *D); 2381f22ef01cSRoman Divacky } 2382f785676fSDimitry Andric 2383f785676fSDimitry Andric // If required by the ABI, treat declarations of static data members with 2384f785676fSDimitry Andric // inline initializers as definitions. 238559d1ed5bSDimitry Andric if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 2386f785676fSDimitry Andric EmitGlobalVarDefinition(D); 2387284c1978SDimitry Andric } 2388f22ef01cSRoman Divacky 238959d1ed5bSDimitry Andric // Handle XCore specific ABI requirements. 239044290647SDimitry Andric if (getTriple().getArch() == llvm::Triple::xcore && 239159d1ed5bSDimitry Andric D->getLanguageLinkage() == CLanguageLinkage && 239259d1ed5bSDimitry Andric D->getType().isConstant(Context) && 239359d1ed5bSDimitry Andric isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 239459d1ed5bSDimitry Andric GV->setSection(".cp.rodata"); 239559d1ed5bSDimitry Andric } 239659d1ed5bSDimitry Andric 23977ae0e2c9SDimitry Andric if (AddrSpace != Ty->getAddressSpace()) 2398f785676fSDimitry Andric return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty); 2399f785676fSDimitry Andric 2400f22ef01cSRoman Divacky return GV; 2401f22ef01cSRoman Divacky } 2402f22ef01cSRoman Divacky 24030623d748SDimitry Andric llvm::Constant * 24040623d748SDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, 240544290647SDimitry Andric ForDefinition_t IsForDefinition) { 240644290647SDimitry Andric const Decl *D = GD.getDecl(); 240744290647SDimitry Andric if (isa<CXXConstructorDecl>(D)) 240844290647SDimitry Andric return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D), 24090623d748SDimitry Andric getFromCtorType(GD.getCtorType()), 24100623d748SDimitry Andric /*FnInfo=*/nullptr, /*FnType=*/nullptr, 24110623d748SDimitry Andric /*DontDefer=*/false, IsForDefinition); 241244290647SDimitry Andric else if (isa<CXXDestructorDecl>(D)) 241344290647SDimitry Andric return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D), 24140623d748SDimitry Andric getFromDtorType(GD.getDtorType()), 24150623d748SDimitry Andric /*FnInfo=*/nullptr, /*FnType=*/nullptr, 24160623d748SDimitry Andric /*DontDefer=*/false, IsForDefinition); 241744290647SDimitry Andric else if (isa<CXXMethodDecl>(D)) { 24180623d748SDimitry Andric auto FInfo = &getTypes().arrangeCXXMethodDeclaration( 241944290647SDimitry Andric cast<CXXMethodDecl>(D)); 24200623d748SDimitry Andric auto Ty = getTypes().GetFunctionType(*FInfo); 24210623d748SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 24220623d748SDimitry Andric IsForDefinition); 242344290647SDimitry Andric } else if (isa<FunctionDecl>(D)) { 24240623d748SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 24250623d748SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 24260623d748SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 24270623d748SDimitry Andric IsForDefinition); 24280623d748SDimitry Andric } else 242944290647SDimitry Andric return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, 2430e7145dcbSDimitry Andric IsForDefinition); 24310623d748SDimitry Andric } 2432f22ef01cSRoman Divacky 24332754fe60SDimitry Andric llvm::GlobalVariable * 24346122f3e6SDimitry Andric CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 24356122f3e6SDimitry Andric llvm::Type *Ty, 24362754fe60SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage) { 24372754fe60SDimitry Andric llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 243859d1ed5bSDimitry Andric llvm::GlobalVariable *OldGV = nullptr; 24392754fe60SDimitry Andric 24402754fe60SDimitry Andric if (GV) { 24412754fe60SDimitry Andric // Check if the variable has the right type. 24422754fe60SDimitry Andric if (GV->getType()->getElementType() == Ty) 24432754fe60SDimitry Andric return GV; 24442754fe60SDimitry Andric 24452754fe60SDimitry Andric // Because C++ name mangling, the only way we can end up with an already 24462754fe60SDimitry Andric // existing global with the same name is if it has been declared extern "C". 24472754fe60SDimitry Andric assert(GV->isDeclaration() && "Declaration has wrong type!"); 24482754fe60SDimitry Andric OldGV = GV; 24492754fe60SDimitry Andric } 24502754fe60SDimitry Andric 24512754fe60SDimitry Andric // Create a new variable. 24522754fe60SDimitry Andric GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 245359d1ed5bSDimitry Andric Linkage, nullptr, Name); 24542754fe60SDimitry Andric 24552754fe60SDimitry Andric if (OldGV) { 24562754fe60SDimitry Andric // Replace occurrences of the old variable if needed. 24572754fe60SDimitry Andric GV->takeName(OldGV); 24582754fe60SDimitry Andric 24592754fe60SDimitry Andric if (!OldGV->use_empty()) { 24602754fe60SDimitry Andric llvm::Constant *NewPtrForOldDecl = 24612754fe60SDimitry Andric llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 24622754fe60SDimitry Andric OldGV->replaceAllUsesWith(NewPtrForOldDecl); 24632754fe60SDimitry Andric } 24642754fe60SDimitry Andric 24652754fe60SDimitry Andric OldGV->eraseFromParent(); 24662754fe60SDimitry Andric } 24672754fe60SDimitry Andric 246833956c43SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker() && 246933956c43SDimitry Andric !GV->hasAvailableExternallyLinkage()) 247033956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 247133956c43SDimitry Andric 24722754fe60SDimitry Andric return GV; 24732754fe60SDimitry Andric } 24742754fe60SDimitry Andric 2475f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 2476f22ef01cSRoman Divacky /// given global variable. If Ty is non-null and if the global doesn't exist, 2477cb4dff85SDimitry Andric /// then it will be created with the specified type instead of whatever the 2478e7145dcbSDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guranteed 2479e7145dcbSDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a 2480e7145dcbSDimitry Andric /// variable with the same mangled name but some other type. 2481f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 2482e7145dcbSDimitry Andric llvm::Type *Ty, 248344290647SDimitry Andric ForDefinition_t IsForDefinition) { 2484f22ef01cSRoman Divacky assert(D->hasGlobalStorage() && "Not a global variable"); 2485f22ef01cSRoman Divacky QualType ASTTy = D->getType(); 248659d1ed5bSDimitry Andric if (!Ty) 2487f22ef01cSRoman Divacky Ty = getTypes().ConvertTypeForMem(ASTTy); 2488f22ef01cSRoman Divacky 24896122f3e6SDimitry Andric llvm::PointerType *PTy = 24903b0f4066SDimitry Andric llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 2491f22ef01cSRoman Divacky 24926122f3e6SDimitry Andric StringRef MangledName = getMangledName(D); 2493e7145dcbSDimitry Andric return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition); 2494f22ef01cSRoman Divacky } 2495f22ef01cSRoman Divacky 2496f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the 2497f22ef01cSRoman Divacky /// specified type and name. 2498f22ef01cSRoman Divacky llvm::Constant * 24996122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 25006122f3e6SDimitry Andric StringRef Name) { 250159d1ed5bSDimitry Andric return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr); 2502f22ef01cSRoman Divacky } 2503f22ef01cSRoman Divacky 2504f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 2505f22ef01cSRoman Divacky assert(!D->getInit() && "Cannot emit definite definitions here!"); 2506f22ef01cSRoman Divacky 25076122f3e6SDimitry Andric StringRef MangledName = getMangledName(D); 2508e7145dcbSDimitry Andric llvm::GlobalValue *GV = GetGlobalValue(MangledName); 2509e7145dcbSDimitry Andric 2510e7145dcbSDimitry Andric // We already have a definition, not declaration, with the same mangled name. 2511e7145dcbSDimitry Andric // Emitting of declaration is not required (and actually overwrites emitted 2512e7145dcbSDimitry Andric // definition). 2513e7145dcbSDimitry Andric if (GV && !GV->isDeclaration()) 2514e7145dcbSDimitry Andric return; 2515e7145dcbSDimitry Andric 2516e7145dcbSDimitry Andric // If we have not seen a reference to this variable yet, place it into the 2517e7145dcbSDimitry Andric // deferred declarations table to be emitted if needed later. 2518e7145dcbSDimitry Andric if (!MustBeEmitted(D) && !GV) { 2519f22ef01cSRoman Divacky DeferredDecls[MangledName] = D; 2520f22ef01cSRoman Divacky return; 2521f22ef01cSRoman Divacky } 2522f22ef01cSRoman Divacky 2523f22ef01cSRoman Divacky // The tentative definition is the only definition. 2524f22ef01cSRoman Divacky EmitGlobalVarDefinition(D); 2525f22ef01cSRoman Divacky } 2526f22ef01cSRoman Divacky 25276122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 25282754fe60SDimitry Andric return Context.toCharUnitsFromBits( 25290623d748SDimitry Andric getDataLayout().getTypeStoreSizeInBits(Ty)); 2530f22ef01cSRoman Divacky } 2531f22ef01cSRoman Divacky 25327ae0e2c9SDimitry Andric unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D, 25337ae0e2c9SDimitry Andric unsigned AddrSpace) { 2534e7145dcbSDimitry Andric if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) { 25357ae0e2c9SDimitry Andric if (D->hasAttr<CUDAConstantAttr>()) 25367ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant); 25377ae0e2c9SDimitry Andric else if (D->hasAttr<CUDASharedAttr>()) 25387ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared); 25397ae0e2c9SDimitry Andric else 25407ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device); 25417ae0e2c9SDimitry Andric } 25427ae0e2c9SDimitry Andric 25437ae0e2c9SDimitry Andric return AddrSpace; 25447ae0e2c9SDimitry Andric } 25457ae0e2c9SDimitry Andric 2546284c1978SDimitry Andric template<typename SomeDecl> 2547284c1978SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 2548284c1978SDimitry Andric llvm::GlobalValue *GV) { 2549284c1978SDimitry Andric if (!getLangOpts().CPlusPlus) 2550284c1978SDimitry Andric return; 2551284c1978SDimitry Andric 2552284c1978SDimitry Andric // Must have 'used' attribute, or else inline assembly can't rely on 2553284c1978SDimitry Andric // the name existing. 2554284c1978SDimitry Andric if (!D->template hasAttr<UsedAttr>()) 2555284c1978SDimitry Andric return; 2556284c1978SDimitry Andric 2557284c1978SDimitry Andric // Must have internal linkage and an ordinary name. 2558f785676fSDimitry Andric if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 2559284c1978SDimitry Andric return; 2560284c1978SDimitry Andric 2561284c1978SDimitry Andric // Must be in an extern "C" context. Entities declared directly within 2562284c1978SDimitry Andric // a record are not extern "C" even if the record is in such a context. 2563f785676fSDimitry Andric const SomeDecl *First = D->getFirstDecl(); 2564284c1978SDimitry Andric if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 2565284c1978SDimitry Andric return; 2566284c1978SDimitry Andric 2567284c1978SDimitry Andric // OK, this is an internal linkage entity inside an extern "C" linkage 2568284c1978SDimitry Andric // specification. Make a note of that so we can give it the "expected" 2569284c1978SDimitry Andric // mangled name if nothing else is using that name. 2570284c1978SDimitry Andric std::pair<StaticExternCMap::iterator, bool> R = 2571284c1978SDimitry Andric StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 2572284c1978SDimitry Andric 2573284c1978SDimitry Andric // If we have multiple internal linkage entities with the same name 2574284c1978SDimitry Andric // in extern "C" regions, none of them gets that name. 2575284c1978SDimitry Andric if (!R.second) 257659d1ed5bSDimitry Andric R.first->second = nullptr; 2577284c1978SDimitry Andric } 2578284c1978SDimitry Andric 257933956c43SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 258033956c43SDimitry Andric if (!CGM.supportsCOMDAT()) 258133956c43SDimitry Andric return false; 258233956c43SDimitry Andric 258333956c43SDimitry Andric if (D.hasAttr<SelectAnyAttr>()) 258433956c43SDimitry Andric return true; 258533956c43SDimitry Andric 258633956c43SDimitry Andric GVALinkage Linkage; 258733956c43SDimitry Andric if (auto *VD = dyn_cast<VarDecl>(&D)) 258833956c43SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 258933956c43SDimitry Andric else 259033956c43SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 259133956c43SDimitry Andric 259233956c43SDimitry Andric switch (Linkage) { 259333956c43SDimitry Andric case GVA_Internal: 259433956c43SDimitry Andric case GVA_AvailableExternally: 259533956c43SDimitry Andric case GVA_StrongExternal: 259633956c43SDimitry Andric return false; 259733956c43SDimitry Andric case GVA_DiscardableODR: 259833956c43SDimitry Andric case GVA_StrongODR: 259933956c43SDimitry Andric return true; 260033956c43SDimitry Andric } 260133956c43SDimitry Andric llvm_unreachable("No such linkage"); 260233956c43SDimitry Andric } 260333956c43SDimitry Andric 260433956c43SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 260533956c43SDimitry Andric llvm::GlobalObject &GO) { 260633956c43SDimitry Andric if (!shouldBeInCOMDAT(*this, D)) 260733956c43SDimitry Andric return; 260833956c43SDimitry Andric GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 260933956c43SDimitry Andric } 261033956c43SDimitry Andric 2611e7145dcbSDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition. 2612e7145dcbSDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 2613e7145dcbSDimitry Andric bool IsTentative) { 261444290647SDimitry Andric // OpenCL global variables of sampler type are translated to function calls, 261544290647SDimitry Andric // therefore no need to be translated. 2616f22ef01cSRoman Divacky QualType ASTTy = D->getType(); 261744290647SDimitry Andric if (getLangOpts().OpenCL && ASTTy->isSamplerT()) 261844290647SDimitry Andric return; 261944290647SDimitry Andric 262044290647SDimitry Andric llvm::Constant *Init = nullptr; 2621dff0c46cSDimitry Andric CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2622dff0c46cSDimitry Andric bool NeedsGlobalCtor = false; 2623dff0c46cSDimitry Andric bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 2624f22ef01cSRoman Divacky 2625dff0c46cSDimitry Andric const VarDecl *InitDecl; 2626dff0c46cSDimitry Andric const Expr *InitExpr = D->getAnyInitializer(InitDecl); 2627f22ef01cSRoman Divacky 2628e7145dcbSDimitry Andric // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 2629e7145dcbSDimitry Andric // as part of their declaration." Sema has already checked for 2630e7145dcbSDimitry Andric // error cases, so we just need to set Init to UndefValue. 2631e7145dcbSDimitry Andric if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 2632e7145dcbSDimitry Andric D->hasAttr<CUDASharedAttr>()) 26330623d748SDimitry Andric Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy)); 2634e7145dcbSDimitry Andric else if (!InitExpr) { 2635f22ef01cSRoman Divacky // This is a tentative definition; tentative definitions are 2636f22ef01cSRoman Divacky // implicitly initialized with { 0 }. 2637f22ef01cSRoman Divacky // 2638f22ef01cSRoman Divacky // Note that tentative definitions are only emitted at the end of 2639f22ef01cSRoman Divacky // a translation unit, so they should never have incomplete 2640f22ef01cSRoman Divacky // type. In addition, EmitTentativeDefinition makes sure that we 2641f22ef01cSRoman Divacky // never attempt to emit a tentative definition if a real one 2642f22ef01cSRoman Divacky // exists. A use may still exists, however, so we still may need 2643f22ef01cSRoman Divacky // to do a RAUW. 2644f22ef01cSRoman Divacky assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 2645f22ef01cSRoman Divacky Init = EmitNullConstant(D->getType()); 2646f22ef01cSRoman Divacky } else { 26477ae0e2c9SDimitry Andric initializedGlobalDecl = GlobalDecl(D); 2648dff0c46cSDimitry Andric Init = EmitConstantInit(*InitDecl); 2649f785676fSDimitry Andric 2650f22ef01cSRoman Divacky if (!Init) { 2651f22ef01cSRoman Divacky QualType T = InitExpr->getType(); 2652f22ef01cSRoman Divacky if (D->getType()->isReferenceType()) 2653f22ef01cSRoman Divacky T = D->getType(); 2654f22ef01cSRoman Divacky 2655dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus) { 2656f22ef01cSRoman Divacky Init = EmitNullConstant(T); 2657dff0c46cSDimitry Andric NeedsGlobalCtor = true; 2658f22ef01cSRoman Divacky } else { 2659f22ef01cSRoman Divacky ErrorUnsupported(D, "static initializer"); 2660f22ef01cSRoman Divacky Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 2661f22ef01cSRoman Divacky } 2662e580952dSDimitry Andric } else { 2663e580952dSDimitry Andric // We don't need an initializer, so remove the entry for the delayed 2664dff0c46cSDimitry Andric // initializer position (just in case this entry was delayed) if we 2665dff0c46cSDimitry Andric // also don't need to register a destructor. 2666dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 2667e580952dSDimitry Andric DelayedCXXInitPosition.erase(D); 2668f22ef01cSRoman Divacky } 2669f22ef01cSRoman Divacky } 2670f22ef01cSRoman Divacky 26716122f3e6SDimitry Andric llvm::Type* InitType = Init->getType(); 2672e7145dcbSDimitry Andric llvm::Constant *Entry = 267344290647SDimitry Andric GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); 2674f22ef01cSRoman Divacky 2675f22ef01cSRoman Divacky // Strip off a bitcast if we got one back. 267659d1ed5bSDimitry Andric if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 2677f22ef01cSRoman Divacky assert(CE->getOpcode() == llvm::Instruction::BitCast || 2678f785676fSDimitry Andric CE->getOpcode() == llvm::Instruction::AddrSpaceCast || 2679f785676fSDimitry Andric // All zero index gep. 2680f22ef01cSRoman Divacky CE->getOpcode() == llvm::Instruction::GetElementPtr); 2681f22ef01cSRoman Divacky Entry = CE->getOperand(0); 2682f22ef01cSRoman Divacky } 2683f22ef01cSRoman Divacky 2684f22ef01cSRoman Divacky // Entry is now either a Function or GlobalVariable. 268559d1ed5bSDimitry Andric auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 2686f22ef01cSRoman Divacky 2687f22ef01cSRoman Divacky // We have a definition after a declaration with the wrong type. 2688f22ef01cSRoman Divacky // We must make a new GlobalVariable* and update everything that used OldGV 2689f22ef01cSRoman Divacky // (a declaration or tentative definition) with the new GlobalVariable* 2690f22ef01cSRoman Divacky // (which will be a definition). 2691f22ef01cSRoman Divacky // 2692f22ef01cSRoman Divacky // This happens if there is a prototype for a global (e.g. 2693f22ef01cSRoman Divacky // "extern int x[];") and then a definition of a different type (e.g. 2694f22ef01cSRoman Divacky // "int x[10];"). This also happens when an initializer has a different type 2695f22ef01cSRoman Divacky // from the type of the global (this happens with unions). 269659d1ed5bSDimitry Andric if (!GV || 2697f22ef01cSRoman Divacky GV->getType()->getElementType() != InitType || 26983b0f4066SDimitry Andric GV->getType()->getAddressSpace() != 26997ae0e2c9SDimitry Andric GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) { 2700f22ef01cSRoman Divacky 2701f22ef01cSRoman Divacky // Move the old entry aside so that we'll create a new one. 27026122f3e6SDimitry Andric Entry->setName(StringRef()); 2703f22ef01cSRoman Divacky 2704f22ef01cSRoman Divacky // Make a new global with the correct type, this is now guaranteed to work. 2705e7145dcbSDimitry Andric GV = cast<llvm::GlobalVariable>( 270644290647SDimitry Andric GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))); 2707f22ef01cSRoman Divacky 2708f22ef01cSRoman Divacky // Replace all uses of the old global with the new global 2709f22ef01cSRoman Divacky llvm::Constant *NewPtrForOldDecl = 2710f22ef01cSRoman Divacky llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 2711f22ef01cSRoman Divacky Entry->replaceAllUsesWith(NewPtrForOldDecl); 2712f22ef01cSRoman Divacky 2713f22ef01cSRoman Divacky // Erase the old global, since it is no longer used. 2714f22ef01cSRoman Divacky cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 2715f22ef01cSRoman Divacky } 2716f22ef01cSRoman Divacky 2717284c1978SDimitry Andric MaybeHandleStaticInExternC(D, GV); 2718284c1978SDimitry Andric 27196122f3e6SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 27206122f3e6SDimitry Andric AddGlobalAnnotations(D, GV); 2721f22ef01cSRoman Divacky 2722e7145dcbSDimitry Andric // Set the llvm linkage type as appropriate. 2723e7145dcbSDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 2724e7145dcbSDimitry Andric getLLVMLinkageVarDefinition(D, GV->isConstant()); 2725e7145dcbSDimitry Andric 27260623d748SDimitry Andric // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 27270623d748SDimitry Andric // the device. [...]" 27280623d748SDimitry Andric // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 27290623d748SDimitry Andric // __device__, declares a variable that: [...] 27300623d748SDimitry Andric // Is accessible from all the threads within the grid and from the host 27310623d748SDimitry Andric // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 27320623d748SDimitry Andric // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 2733e7145dcbSDimitry Andric if (GV && LangOpts.CUDA) { 2734e7145dcbSDimitry Andric if (LangOpts.CUDAIsDevice) { 2735e7145dcbSDimitry Andric if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) 27360623d748SDimitry Andric GV->setExternallyInitialized(true); 2737e7145dcbSDimitry Andric } else { 2738e7145dcbSDimitry Andric // Host-side shadows of external declarations of device-side 2739e7145dcbSDimitry Andric // global variables become internal definitions. These have to 2740e7145dcbSDimitry Andric // be internal in order to prevent name conflicts with global 2741e7145dcbSDimitry Andric // host variables with the same name in a different TUs. 2742e7145dcbSDimitry Andric if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) { 2743e7145dcbSDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 2744e7145dcbSDimitry Andric 2745e7145dcbSDimitry Andric // Shadow variables and their properties must be registered 2746e7145dcbSDimitry Andric // with CUDA runtime. 2747e7145dcbSDimitry Andric unsigned Flags = 0; 2748e7145dcbSDimitry Andric if (!D->hasDefinition()) 2749e7145dcbSDimitry Andric Flags |= CGCUDARuntime::ExternDeviceVar; 2750e7145dcbSDimitry Andric if (D->hasAttr<CUDAConstantAttr>()) 2751e7145dcbSDimitry Andric Flags |= CGCUDARuntime::ConstantDeviceVar; 2752e7145dcbSDimitry Andric getCUDARuntime().registerDeviceVar(*GV, Flags); 2753e7145dcbSDimitry Andric } else if (D->hasAttr<CUDASharedAttr>()) 2754e7145dcbSDimitry Andric // __shared__ variables are odd. Shadows do get created, but 2755e7145dcbSDimitry Andric // they are not registered with the CUDA runtime, so they 2756e7145dcbSDimitry Andric // can't really be used to access their device-side 2757e7145dcbSDimitry Andric // counterparts. It's not clear yet whether it's nvcc's bug or 2758e7145dcbSDimitry Andric // a feature, but we've got to do the same for compatibility. 2759e7145dcbSDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 2760e7145dcbSDimitry Andric } 27610623d748SDimitry Andric } 2762f22ef01cSRoman Divacky GV->setInitializer(Init); 2763f22ef01cSRoman Divacky 2764f22ef01cSRoman Divacky // If it is safe to mark the global 'constant', do so now. 2765dff0c46cSDimitry Andric GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 2766dff0c46cSDimitry Andric isTypeConstant(D->getType(), true)); 2767f22ef01cSRoman Divacky 276839d628a0SDimitry Andric // If it is in a read-only section, mark it 'constant'. 276939d628a0SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 277039d628a0SDimitry Andric const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 277139d628a0SDimitry Andric if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 277239d628a0SDimitry Andric GV->setConstant(true); 277339d628a0SDimitry Andric } 277439d628a0SDimitry Andric 2775f22ef01cSRoman Divacky GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 2776f22ef01cSRoman Divacky 2777f785676fSDimitry Andric 27780623d748SDimitry Andric // On Darwin, if the normal linkage of a C++ thread_local variable is 27790623d748SDimitry Andric // LinkOnce or Weak, we keep the normal linkage to prevent multiple 27800623d748SDimitry Andric // copies within a linkage unit; otherwise, the backing variable has 27810623d748SDimitry Andric // internal linkage and all accesses should just be calls to the 278259d1ed5bSDimitry Andric // Itanium-specified entry point, which has the normal linkage of the 27830623d748SDimitry Andric // variable. This is to preserve the ability to change the implementation 27840623d748SDimitry Andric // behind the scenes. 278539d628a0SDimitry Andric if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic && 27860623d748SDimitry Andric Context.getTargetInfo().getTriple().isOSDarwin() && 27870623d748SDimitry Andric !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) && 27880623d748SDimitry Andric !llvm::GlobalVariable::isWeakLinkage(Linkage)) 278959d1ed5bSDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 279059d1ed5bSDimitry Andric 279159d1ed5bSDimitry Andric GV->setLinkage(Linkage); 279259d1ed5bSDimitry Andric if (D->hasAttr<DLLImportAttr>()) 279359d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 279459d1ed5bSDimitry Andric else if (D->hasAttr<DLLExportAttr>()) 279559d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 279639d628a0SDimitry Andric else 279739d628a0SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 2798f785676fSDimitry Andric 279944290647SDimitry Andric if (Linkage == llvm::GlobalVariable::CommonLinkage) { 2800f22ef01cSRoman Divacky // common vars aren't constant even if declared const. 2801f22ef01cSRoman Divacky GV->setConstant(false); 280244290647SDimitry Andric // Tentative definition of global variables may be initialized with 280344290647SDimitry Andric // non-zero null pointers. In this case they should have weak linkage 280444290647SDimitry Andric // since common linkage must have zero initializer and must not have 280544290647SDimitry Andric // explicit section therefore cannot have non-zero initial value. 280644290647SDimitry Andric if (!GV->getInitializer()->isNullValue()) 280744290647SDimitry Andric GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 280844290647SDimitry Andric } 2809f22ef01cSRoman Divacky 281059d1ed5bSDimitry Andric setNonAliasAttributes(D, GV); 2811f22ef01cSRoman Divacky 281239d628a0SDimitry Andric if (D->getTLSKind() && !GV->isThreadLocal()) { 281339d628a0SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 28140623d748SDimitry Andric CXXThreadLocals.push_back(D); 281539d628a0SDimitry Andric setTLSMode(GV, *D); 281639d628a0SDimitry Andric } 281739d628a0SDimitry Andric 281833956c43SDimitry Andric maybeSetTrivialComdat(*D, *GV); 281933956c43SDimitry Andric 28202754fe60SDimitry Andric // Emit the initializer function if necessary. 2821dff0c46cSDimitry Andric if (NeedsGlobalCtor || NeedsGlobalDtor) 2822dff0c46cSDimitry Andric EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 28232754fe60SDimitry Andric 282439d628a0SDimitry Andric SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); 28253861d79fSDimitry Andric 2826f22ef01cSRoman Divacky // Emit global variable debug information. 28276122f3e6SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 2828e7145dcbSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) 2829f22ef01cSRoman Divacky DI->EmitGlobalVariable(GV, D); 2830f22ef01cSRoman Divacky } 2831f22ef01cSRoman Divacky 283239d628a0SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context, 283333956c43SDimitry Andric CodeGenModule &CGM, const VarDecl *D, 283433956c43SDimitry Andric bool NoCommon) { 283559d1ed5bSDimitry Andric // Don't give variables common linkage if -fno-common was specified unless it 283659d1ed5bSDimitry Andric // was overridden by a NoCommon attribute. 283759d1ed5bSDimitry Andric if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 283859d1ed5bSDimitry Andric return true; 283959d1ed5bSDimitry Andric 284059d1ed5bSDimitry Andric // C11 6.9.2/2: 284159d1ed5bSDimitry Andric // A declaration of an identifier for an object that has file scope without 284259d1ed5bSDimitry Andric // an initializer, and without a storage-class specifier or with the 284359d1ed5bSDimitry Andric // storage-class specifier static, constitutes a tentative definition. 284459d1ed5bSDimitry Andric if (D->getInit() || D->hasExternalStorage()) 284559d1ed5bSDimitry Andric return true; 284659d1ed5bSDimitry Andric 284759d1ed5bSDimitry Andric // A variable cannot be both common and exist in a section. 284859d1ed5bSDimitry Andric if (D->hasAttr<SectionAttr>()) 284959d1ed5bSDimitry Andric return true; 285059d1ed5bSDimitry Andric 2851db17bf38SDimitry Andric // A variable cannot be both common and exist in a section. 2852db17bf38SDimitry Andric // We dont try to determine which is the right section in the front-end. 2853db17bf38SDimitry Andric // If no specialized section name is applicable, it will resort to default. 2854db17bf38SDimitry Andric if (D->hasAttr<PragmaClangBSSSectionAttr>() || 2855db17bf38SDimitry Andric D->hasAttr<PragmaClangDataSectionAttr>() || 2856db17bf38SDimitry Andric D->hasAttr<PragmaClangRodataSectionAttr>()) 2857db17bf38SDimitry Andric return true; 2858db17bf38SDimitry Andric 285959d1ed5bSDimitry Andric // Thread local vars aren't considered common linkage. 286059d1ed5bSDimitry Andric if (D->getTLSKind()) 286159d1ed5bSDimitry Andric return true; 286259d1ed5bSDimitry Andric 286359d1ed5bSDimitry Andric // Tentative definitions marked with WeakImportAttr are true definitions. 286459d1ed5bSDimitry Andric if (D->hasAttr<WeakImportAttr>()) 286559d1ed5bSDimitry Andric return true; 286659d1ed5bSDimitry Andric 286733956c43SDimitry Andric // A variable cannot be both common and exist in a comdat. 286833956c43SDimitry Andric if (shouldBeInCOMDAT(CGM, *D)) 286933956c43SDimitry Andric return true; 287033956c43SDimitry Andric 2871e7145dcbSDimitry Andric // Declarations with a required alignment do not have common linkage in MSVC 287239d628a0SDimitry Andric // mode. 28730623d748SDimitry Andric if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 287433956c43SDimitry Andric if (D->hasAttr<AlignedAttr>()) 287539d628a0SDimitry Andric return true; 287633956c43SDimitry Andric QualType VarType = D->getType(); 287733956c43SDimitry Andric if (Context.isAlignmentRequired(VarType)) 287833956c43SDimitry Andric return true; 287933956c43SDimitry Andric 288033956c43SDimitry Andric if (const auto *RT = VarType->getAs<RecordType>()) { 288133956c43SDimitry Andric const RecordDecl *RD = RT->getDecl(); 288233956c43SDimitry Andric for (const FieldDecl *FD : RD->fields()) { 288333956c43SDimitry Andric if (FD->isBitField()) 288433956c43SDimitry Andric continue; 288533956c43SDimitry Andric if (FD->hasAttr<AlignedAttr>()) 288633956c43SDimitry Andric return true; 288733956c43SDimitry Andric if (Context.isAlignmentRequired(FD->getType())) 288833956c43SDimitry Andric return true; 288933956c43SDimitry Andric } 289033956c43SDimitry Andric } 289133956c43SDimitry Andric } 289239d628a0SDimitry Andric 289359d1ed5bSDimitry Andric return false; 289459d1ed5bSDimitry Andric } 289559d1ed5bSDimitry Andric 289659d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 289759d1ed5bSDimitry Andric const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 28982754fe60SDimitry Andric if (Linkage == GVA_Internal) 28992754fe60SDimitry Andric return llvm::Function::InternalLinkage; 290059d1ed5bSDimitry Andric 290159d1ed5bSDimitry Andric if (D->hasAttr<WeakAttr>()) { 290259d1ed5bSDimitry Andric if (IsConstantVariable) 290359d1ed5bSDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 290459d1ed5bSDimitry Andric else 290559d1ed5bSDimitry Andric return llvm::GlobalVariable::WeakAnyLinkage; 290659d1ed5bSDimitry Andric } 290759d1ed5bSDimitry Andric 290859d1ed5bSDimitry Andric // We are guaranteed to have a strong definition somewhere else, 290959d1ed5bSDimitry Andric // so we can use available_externally linkage. 291059d1ed5bSDimitry Andric if (Linkage == GVA_AvailableExternally) 291120e90f04SDimitry Andric return llvm::GlobalValue::AvailableExternallyLinkage; 291259d1ed5bSDimitry Andric 291359d1ed5bSDimitry Andric // Note that Apple's kernel linker doesn't support symbol 291459d1ed5bSDimitry Andric // coalescing, so we need to avoid linkonce and weak linkages there. 291559d1ed5bSDimitry Andric // Normally, this means we just map to internal, but for explicit 291659d1ed5bSDimitry Andric // instantiations we'll map to external. 291759d1ed5bSDimitry Andric 291859d1ed5bSDimitry Andric // In C++, the compiler has to emit a definition in every translation unit 291959d1ed5bSDimitry Andric // that references the function. We should use linkonce_odr because 292059d1ed5bSDimitry Andric // a) if all references in this translation unit are optimized away, we 292159d1ed5bSDimitry Andric // don't need to codegen it. b) if the function persists, it needs to be 292259d1ed5bSDimitry Andric // merged with other definitions. c) C++ has the ODR, so we know the 292359d1ed5bSDimitry Andric // definition is dependable. 292459d1ed5bSDimitry Andric if (Linkage == GVA_DiscardableODR) 292559d1ed5bSDimitry Andric return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 292659d1ed5bSDimitry Andric : llvm::Function::InternalLinkage; 292759d1ed5bSDimitry Andric 292859d1ed5bSDimitry Andric // An explicit instantiation of a template has weak linkage, since 292959d1ed5bSDimitry Andric // explicit instantiations can occur in multiple translation units 293059d1ed5bSDimitry Andric // and must all be equivalent. However, we are not allowed to 293159d1ed5bSDimitry Andric // throw away these explicit instantiations. 2932e7145dcbSDimitry Andric // 2933e7145dcbSDimitry Andric // We don't currently support CUDA device code spread out across multiple TUs, 2934e7145dcbSDimitry Andric // so say that CUDA templates are either external (for kernels) or internal. 2935e7145dcbSDimitry Andric // This lets llvm perform aggressive inter-procedural optimizations. 2936e7145dcbSDimitry Andric if (Linkage == GVA_StrongODR) { 2937e7145dcbSDimitry Andric if (Context.getLangOpts().AppleKext) 2938e7145dcbSDimitry Andric return llvm::Function::ExternalLinkage; 2939e7145dcbSDimitry Andric if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) 2940e7145dcbSDimitry Andric return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage 2941e7145dcbSDimitry Andric : llvm::Function::InternalLinkage; 2942e7145dcbSDimitry Andric return llvm::Function::WeakODRLinkage; 2943e7145dcbSDimitry Andric } 294459d1ed5bSDimitry Andric 294559d1ed5bSDimitry Andric // C++ doesn't have tentative definitions and thus cannot have common 294659d1ed5bSDimitry Andric // linkage. 294759d1ed5bSDimitry Andric if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 294833956c43SDimitry Andric !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 294939d628a0SDimitry Andric CodeGenOpts.NoCommon)) 295059d1ed5bSDimitry Andric return llvm::GlobalVariable::CommonLinkage; 295159d1ed5bSDimitry Andric 2952f785676fSDimitry Andric // selectany symbols are externally visible, so use weak instead of 2953f785676fSDimitry Andric // linkonce. MSVC optimizes away references to const selectany globals, so 2954f785676fSDimitry Andric // all definitions should be the same and ODR linkage should be used. 2955f785676fSDimitry Andric // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 295659d1ed5bSDimitry Andric if (D->hasAttr<SelectAnyAttr>()) 2957f785676fSDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 295859d1ed5bSDimitry Andric 295959d1ed5bSDimitry Andric // Otherwise, we have strong external linkage. 296059d1ed5bSDimitry Andric assert(Linkage == GVA_StrongExternal); 29612754fe60SDimitry Andric return llvm::GlobalVariable::ExternalLinkage; 29622754fe60SDimitry Andric } 29632754fe60SDimitry Andric 296459d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 296559d1ed5bSDimitry Andric const VarDecl *VD, bool IsConstant) { 296659d1ed5bSDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 296759d1ed5bSDimitry Andric return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 296859d1ed5bSDimitry Andric } 296959d1ed5bSDimitry Andric 2970139f7f9bSDimitry Andric /// Replace the uses of a function that was declared with a non-proto type. 2971139f7f9bSDimitry Andric /// We want to silently drop extra arguments from call sites 2972139f7f9bSDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 2973139f7f9bSDimitry Andric llvm::Function *newFn) { 2974139f7f9bSDimitry Andric // Fast path. 2975139f7f9bSDimitry Andric if (old->use_empty()) return; 2976139f7f9bSDimitry Andric 2977139f7f9bSDimitry Andric llvm::Type *newRetTy = newFn->getReturnType(); 2978139f7f9bSDimitry Andric SmallVector<llvm::Value*, 4> newArgs; 29790623d748SDimitry Andric SmallVector<llvm::OperandBundleDef, 1> newBundles; 2980139f7f9bSDimitry Andric 2981139f7f9bSDimitry Andric for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 2982139f7f9bSDimitry Andric ui != ue; ) { 2983139f7f9bSDimitry Andric llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 298459d1ed5bSDimitry Andric llvm::User *user = use->getUser(); 2985139f7f9bSDimitry Andric 2986139f7f9bSDimitry Andric // Recognize and replace uses of bitcasts. Most calls to 2987139f7f9bSDimitry Andric // unprototyped functions will use bitcasts. 298859d1ed5bSDimitry Andric if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 2989139f7f9bSDimitry Andric if (bitcast->getOpcode() == llvm::Instruction::BitCast) 2990139f7f9bSDimitry Andric replaceUsesOfNonProtoConstant(bitcast, newFn); 2991139f7f9bSDimitry Andric continue; 2992139f7f9bSDimitry Andric } 2993139f7f9bSDimitry Andric 2994139f7f9bSDimitry Andric // Recognize calls to the function. 2995139f7f9bSDimitry Andric llvm::CallSite callSite(user); 2996139f7f9bSDimitry Andric if (!callSite) continue; 299759d1ed5bSDimitry Andric if (!callSite.isCallee(&*use)) continue; 2998139f7f9bSDimitry Andric 2999139f7f9bSDimitry Andric // If the return types don't match exactly, then we can't 3000139f7f9bSDimitry Andric // transform this call unless it's dead. 3001139f7f9bSDimitry Andric if (callSite->getType() != newRetTy && !callSite->use_empty()) 3002139f7f9bSDimitry Andric continue; 3003139f7f9bSDimitry Andric 3004139f7f9bSDimitry Andric // Get the call site's attribute list. 300520e90f04SDimitry Andric SmallVector<llvm::AttributeSet, 8> newArgAttrs; 300620e90f04SDimitry Andric llvm::AttributeList oldAttrs = callSite.getAttributes(); 3007139f7f9bSDimitry Andric 3008139f7f9bSDimitry Andric // If the function was passed too few arguments, don't transform. 3009139f7f9bSDimitry Andric unsigned newNumArgs = newFn->arg_size(); 3010139f7f9bSDimitry Andric if (callSite.arg_size() < newNumArgs) continue; 3011139f7f9bSDimitry Andric 3012139f7f9bSDimitry Andric // If extra arguments were passed, we silently drop them. 3013139f7f9bSDimitry Andric // If any of the types mismatch, we don't transform. 3014139f7f9bSDimitry Andric unsigned argNo = 0; 3015139f7f9bSDimitry Andric bool dontTransform = false; 301620e90f04SDimitry Andric for (llvm::Argument &A : newFn->args()) { 301720e90f04SDimitry Andric if (callSite.getArgument(argNo)->getType() != A.getType()) { 3018139f7f9bSDimitry Andric dontTransform = true; 3019139f7f9bSDimitry Andric break; 3020139f7f9bSDimitry Andric } 3021139f7f9bSDimitry Andric 3022139f7f9bSDimitry Andric // Add any parameter attributes. 302320e90f04SDimitry Andric newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo)); 302420e90f04SDimitry Andric argNo++; 3025139f7f9bSDimitry Andric } 3026139f7f9bSDimitry Andric if (dontTransform) 3027139f7f9bSDimitry Andric continue; 3028139f7f9bSDimitry Andric 3029139f7f9bSDimitry Andric // Okay, we can transform this. Create the new call instruction and copy 3030139f7f9bSDimitry Andric // over the required information. 3031139f7f9bSDimitry Andric newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo); 3032139f7f9bSDimitry Andric 30330623d748SDimitry Andric // Copy over any operand bundles. 30340623d748SDimitry Andric callSite.getOperandBundlesAsDefs(newBundles); 30350623d748SDimitry Andric 3036139f7f9bSDimitry Andric llvm::CallSite newCall; 3037139f7f9bSDimitry Andric if (callSite.isCall()) { 30380623d748SDimitry Andric newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "", 3039139f7f9bSDimitry Andric callSite.getInstruction()); 3040139f7f9bSDimitry Andric } else { 304159d1ed5bSDimitry Andric auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction()); 3042139f7f9bSDimitry Andric newCall = llvm::InvokeInst::Create(newFn, 3043139f7f9bSDimitry Andric oldInvoke->getNormalDest(), 3044139f7f9bSDimitry Andric oldInvoke->getUnwindDest(), 30450623d748SDimitry Andric newArgs, newBundles, "", 3046139f7f9bSDimitry Andric callSite.getInstruction()); 3047139f7f9bSDimitry Andric } 3048139f7f9bSDimitry Andric newArgs.clear(); // for the next iteration 3049139f7f9bSDimitry Andric 3050139f7f9bSDimitry Andric if (!newCall->getType()->isVoidTy()) 3051139f7f9bSDimitry Andric newCall->takeName(callSite.getInstruction()); 305220e90f04SDimitry Andric newCall.setAttributes(llvm::AttributeList::get( 305320e90f04SDimitry Andric newFn->getContext(), oldAttrs.getFnAttributes(), 305420e90f04SDimitry Andric oldAttrs.getRetAttributes(), newArgAttrs)); 3055139f7f9bSDimitry Andric newCall.setCallingConv(callSite.getCallingConv()); 3056139f7f9bSDimitry Andric 3057139f7f9bSDimitry Andric // Finally, remove the old call, replacing any uses with the new one. 3058139f7f9bSDimitry Andric if (!callSite->use_empty()) 3059139f7f9bSDimitry Andric callSite->replaceAllUsesWith(newCall.getInstruction()); 3060139f7f9bSDimitry Andric 3061139f7f9bSDimitry Andric // Copy debug location attached to CI. 306233956c43SDimitry Andric if (callSite->getDebugLoc()) 3063139f7f9bSDimitry Andric newCall->setDebugLoc(callSite->getDebugLoc()); 30640623d748SDimitry Andric 3065139f7f9bSDimitry Andric callSite->eraseFromParent(); 3066139f7f9bSDimitry Andric } 3067139f7f9bSDimitry Andric } 3068139f7f9bSDimitry Andric 3069f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 3070f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}". If there are 3071f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to 3072f22ef01cSRoman Divacky /// call the new function directly. 3073f22ef01cSRoman Divacky /// 3074f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to 3075f22ef01cSRoman Divacky /// functions to be able to inline them. If there is a bitcast in the way, it 3076f22ef01cSRoman Divacky /// won't inline them. Instcombine normally deletes these calls, but it isn't 3077f22ef01cSRoman Divacky /// run at -O0. 3078f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 3079f22ef01cSRoman Divacky llvm::Function *NewFn) { 3080f22ef01cSRoman Divacky // If we're redefining a global as a function, don't transform it. 3081139f7f9bSDimitry Andric if (!isa<llvm::Function>(Old)) return; 3082f22ef01cSRoman Divacky 3083139f7f9bSDimitry Andric replaceUsesOfNonProtoConstant(Old, NewFn); 3084f22ef01cSRoman Divacky } 3085f22ef01cSRoman Divacky 3086dff0c46cSDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 3087e7145dcbSDimitry Andric auto DK = VD->isThisDeclarationADefinition(); 3088e7145dcbSDimitry Andric if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) 3089e7145dcbSDimitry Andric return; 3090e7145dcbSDimitry Andric 3091dff0c46cSDimitry Andric TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 3092dff0c46cSDimitry Andric // If we have a definition, this might be a deferred decl. If the 3093dff0c46cSDimitry Andric // instantiation is explicit, make sure we emit it at the end. 3094dff0c46cSDimitry Andric if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 3095dff0c46cSDimitry Andric GetAddrOfGlobalVar(VD); 3096139f7f9bSDimitry Andric 3097139f7f9bSDimitry Andric EmitTopLevelDecl(VD); 3098dff0c46cSDimitry Andric } 3099f22ef01cSRoman Divacky 310059d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 310159d1ed5bSDimitry Andric llvm::GlobalValue *GV) { 310259d1ed5bSDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 31033b0f4066SDimitry Andric 31043b0f4066SDimitry Andric // Compute the function info and LLVM type. 3105dff0c46cSDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 3106dff0c46cSDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 31073b0f4066SDimitry Andric 3108f22ef01cSRoman Divacky // Get or create the prototype for the function. 31090623d748SDimitry Andric if (!GV || (GV->getType()->getElementType() != Ty)) 31100623d748SDimitry Andric GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 31110623d748SDimitry Andric /*DontDefer=*/true, 311244290647SDimitry Andric ForDefinition)); 3113f22ef01cSRoman Divacky 31140623d748SDimitry Andric // Already emitted. 31150623d748SDimitry Andric if (!GV->isDeclaration()) 3116f785676fSDimitry Andric return; 3117f22ef01cSRoman Divacky 31182754fe60SDimitry Andric // We need to set linkage and visibility on the function before 31192754fe60SDimitry Andric // generating code for it because various parts of IR generation 31202754fe60SDimitry Andric // want to propagate this information down (e.g. to local static 31212754fe60SDimitry Andric // declarations). 312259d1ed5bSDimitry Andric auto *Fn = cast<llvm::Function>(GV); 3123f785676fSDimitry Andric setFunctionLinkage(GD, Fn); 312497bc6c73SDimitry Andric setFunctionDLLStorageClass(GD, Fn); 3125f22ef01cSRoman Divacky 312659d1ed5bSDimitry Andric // FIXME: this is redundant with part of setFunctionDefinitionAttributes 31272754fe60SDimitry Andric setGlobalVisibility(Fn, D); 31282754fe60SDimitry Andric 3129284c1978SDimitry Andric MaybeHandleStaticInExternC(D, Fn); 3130284c1978SDimitry Andric 313133956c43SDimitry Andric maybeSetTrivialComdat(*D, *Fn); 313233956c43SDimitry Andric 31333b0f4066SDimitry Andric CodeGenFunction(*this).GenerateCode(D, Fn, FI); 3134f22ef01cSRoman Divacky 313559d1ed5bSDimitry Andric setFunctionDefinitionAttributes(D, Fn); 3136f22ef01cSRoman Divacky SetLLVMFunctionAttributesForDefinition(D, Fn); 3137f22ef01cSRoman Divacky 3138f22ef01cSRoman Divacky if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 3139f22ef01cSRoman Divacky AddGlobalCtor(Fn, CA->getPriority()); 3140f22ef01cSRoman Divacky if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 3141f22ef01cSRoman Divacky AddGlobalDtor(Fn, DA->getPriority()); 31426122f3e6SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 31436122f3e6SDimitry Andric AddGlobalAnnotations(D, Fn); 3144f22ef01cSRoman Divacky } 3145f22ef01cSRoman Divacky 3146f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 314759d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 3148f22ef01cSRoman Divacky const AliasAttr *AA = D->getAttr<AliasAttr>(); 3149f22ef01cSRoman Divacky assert(AA && "Not an alias?"); 3150f22ef01cSRoman Divacky 31516122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 3152f22ef01cSRoman Divacky 31539a4b3118SDimitry Andric if (AA->getAliasee() == MangledName) { 3154e7145dcbSDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 31559a4b3118SDimitry Andric return; 31569a4b3118SDimitry Andric } 31579a4b3118SDimitry Andric 3158f22ef01cSRoman Divacky // If there is a definition in the module, then it wins over the alias. 3159f22ef01cSRoman Divacky // This is dubious, but allow it to be safe. Just ignore the alias. 3160f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3161f22ef01cSRoman Divacky if (Entry && !Entry->isDeclaration()) 3162f22ef01cSRoman Divacky return; 3163f22ef01cSRoman Divacky 3164f785676fSDimitry Andric Aliases.push_back(GD); 3165f785676fSDimitry Andric 31666122f3e6SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 3167f22ef01cSRoman Divacky 3168f22ef01cSRoman Divacky // Create a reference to the named value. This ensures that it is emitted 3169f22ef01cSRoman Divacky // if a deferred decl. 3170f22ef01cSRoman Divacky llvm::Constant *Aliasee; 3171f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(DeclTy)) 31723861d79fSDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 31732754fe60SDimitry Andric /*ForVTable=*/false); 3174f22ef01cSRoman Divacky else 3175f22ef01cSRoman Divacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 317659d1ed5bSDimitry Andric llvm::PointerType::getUnqual(DeclTy), 317739d628a0SDimitry Andric /*D=*/nullptr); 3178f22ef01cSRoman Divacky 3179f22ef01cSRoman Divacky // Create the new alias itself, but don't set a name yet. 318059d1ed5bSDimitry Andric auto *GA = llvm::GlobalAlias::create( 31810623d748SDimitry Andric DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule()); 3182f22ef01cSRoman Divacky 3183f22ef01cSRoman Divacky if (Entry) { 318459d1ed5bSDimitry Andric if (GA->getAliasee() == Entry) { 3185e7145dcbSDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 318659d1ed5bSDimitry Andric return; 318759d1ed5bSDimitry Andric } 318859d1ed5bSDimitry Andric 3189f22ef01cSRoman Divacky assert(Entry->isDeclaration()); 3190f22ef01cSRoman Divacky 3191f22ef01cSRoman Divacky // If there is a declaration in the module, then we had an extern followed 3192f22ef01cSRoman Divacky // by the alias, as in: 3193f22ef01cSRoman Divacky // extern int test6(); 3194f22ef01cSRoman Divacky // ... 3195f22ef01cSRoman Divacky // int test6() __attribute__((alias("test7"))); 3196f22ef01cSRoman Divacky // 3197f22ef01cSRoman Divacky // Remove it and replace uses of it with the alias. 3198f22ef01cSRoman Divacky GA->takeName(Entry); 3199f22ef01cSRoman Divacky 3200f22ef01cSRoman Divacky Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 3201f22ef01cSRoman Divacky Entry->getType())); 3202f22ef01cSRoman Divacky Entry->eraseFromParent(); 3203f22ef01cSRoman Divacky } else { 3204ffd1746dSEd Schouten GA->setName(MangledName); 3205f22ef01cSRoman Divacky } 3206f22ef01cSRoman Divacky 3207f22ef01cSRoman Divacky // Set attributes which are particular to an alias; this is a 3208f22ef01cSRoman Divacky // specialization of the attributes which may be set on a global 3209f22ef01cSRoman Divacky // variable/function. 321039d628a0SDimitry Andric if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 32113b0f4066SDimitry Andric D->isWeakImported()) { 3212f22ef01cSRoman Divacky GA->setLinkage(llvm::Function::WeakAnyLinkage); 3213f22ef01cSRoman Divacky } 3214f22ef01cSRoman Divacky 321539d628a0SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 321639d628a0SDimitry Andric if (VD->getTLSKind()) 321739d628a0SDimitry Andric setTLSMode(GA, *VD); 321839d628a0SDimitry Andric 321939d628a0SDimitry Andric setAliasAttributes(D, GA); 3220f22ef01cSRoman Divacky } 3221f22ef01cSRoman Divacky 3222e7145dcbSDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 3223e7145dcbSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 3224e7145dcbSDimitry Andric const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 3225e7145dcbSDimitry Andric assert(IFA && "Not an ifunc?"); 3226e7145dcbSDimitry Andric 3227e7145dcbSDimitry Andric StringRef MangledName = getMangledName(GD); 3228e7145dcbSDimitry Andric 3229e7145dcbSDimitry Andric if (IFA->getResolver() == MangledName) { 3230e7145dcbSDimitry Andric Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 3231e7145dcbSDimitry Andric return; 3232e7145dcbSDimitry Andric } 3233e7145dcbSDimitry Andric 3234e7145dcbSDimitry Andric // Report an error if some definition overrides ifunc. 3235e7145dcbSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3236e7145dcbSDimitry Andric if (Entry && !Entry->isDeclaration()) { 3237e7145dcbSDimitry Andric GlobalDecl OtherGD; 3238e7145dcbSDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 3239e7145dcbSDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 3240e7145dcbSDimitry Andric Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name); 3241e7145dcbSDimitry Andric Diags.Report(OtherGD.getDecl()->getLocation(), 3242e7145dcbSDimitry Andric diag::note_previous_definition); 3243e7145dcbSDimitry Andric } 3244e7145dcbSDimitry Andric return; 3245e7145dcbSDimitry Andric } 3246e7145dcbSDimitry Andric 3247e7145dcbSDimitry Andric Aliases.push_back(GD); 3248e7145dcbSDimitry Andric 3249e7145dcbSDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 3250e7145dcbSDimitry Andric llvm::Constant *Resolver = 3251e7145dcbSDimitry Andric GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD, 3252e7145dcbSDimitry Andric /*ForVTable=*/false); 3253e7145dcbSDimitry Andric llvm::GlobalIFunc *GIF = 3254e7145dcbSDimitry Andric llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 3255e7145dcbSDimitry Andric "", Resolver, &getModule()); 3256e7145dcbSDimitry Andric if (Entry) { 3257e7145dcbSDimitry Andric if (GIF->getResolver() == Entry) { 3258e7145dcbSDimitry Andric Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 3259e7145dcbSDimitry Andric return; 3260e7145dcbSDimitry Andric } 3261e7145dcbSDimitry Andric assert(Entry->isDeclaration()); 3262e7145dcbSDimitry Andric 3263e7145dcbSDimitry Andric // If there is a declaration in the module, then we had an extern followed 3264e7145dcbSDimitry Andric // by the ifunc, as in: 3265e7145dcbSDimitry Andric // extern int test(); 3266e7145dcbSDimitry Andric // ... 3267e7145dcbSDimitry Andric // int test() __attribute__((ifunc("resolver"))); 3268e7145dcbSDimitry Andric // 3269e7145dcbSDimitry Andric // Remove it and replace uses of it with the ifunc. 3270e7145dcbSDimitry Andric GIF->takeName(Entry); 3271e7145dcbSDimitry Andric 3272e7145dcbSDimitry Andric Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF, 3273e7145dcbSDimitry Andric Entry->getType())); 3274e7145dcbSDimitry Andric Entry->eraseFromParent(); 3275e7145dcbSDimitry Andric } else 3276e7145dcbSDimitry Andric GIF->setName(MangledName); 3277e7145dcbSDimitry Andric 3278e7145dcbSDimitry Andric SetCommonAttributes(D, GIF); 3279e7145dcbSDimitry Andric } 3280e7145dcbSDimitry Andric 328117a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 32826122f3e6SDimitry Andric ArrayRef<llvm::Type*> Tys) { 328317a519f9SDimitry Andric return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 328417a519f9SDimitry Andric Tys); 3285f22ef01cSRoman Divacky } 3286f22ef01cSRoman Divacky 328733956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> & 328833956c43SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 328933956c43SDimitry Andric const StringLiteral *Literal, bool TargetIsLSB, 329033956c43SDimitry Andric bool &IsUTF16, unsigned &StringLength) { 32916122f3e6SDimitry Andric StringRef String = Literal->getString(); 3292e580952dSDimitry Andric unsigned NumBytes = String.size(); 3293f22ef01cSRoman Divacky 3294f22ef01cSRoman Divacky // Check for simple case. 3295f22ef01cSRoman Divacky if (!Literal->containsNonAsciiOrNull()) { 3296f22ef01cSRoman Divacky StringLength = NumBytes; 329739d628a0SDimitry Andric return *Map.insert(std::make_pair(String, nullptr)).first; 3298f22ef01cSRoman Divacky } 3299f22ef01cSRoman Divacky 3300dff0c46cSDimitry Andric // Otherwise, convert the UTF8 literals into a string of shorts. 3301dff0c46cSDimitry Andric IsUTF16 = true; 3302dff0c46cSDimitry Andric 330344290647SDimitry Andric SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 330444290647SDimitry Andric const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 330544290647SDimitry Andric llvm::UTF16 *ToPtr = &ToBuf[0]; 3306f22ef01cSRoman Divacky 330744290647SDimitry Andric (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 330844290647SDimitry Andric ToPtr + NumBytes, llvm::strictConversion); 3309f22ef01cSRoman Divacky 3310f22ef01cSRoman Divacky // ConvertUTF8toUTF16 returns the length in ToPtr. 3311f22ef01cSRoman Divacky StringLength = ToPtr - &ToBuf[0]; 3312f22ef01cSRoman Divacky 3313dff0c46cSDimitry Andric // Add an explicit null. 3314dff0c46cSDimitry Andric *ToPtr = 0; 331539d628a0SDimitry Andric return *Map.insert(std::make_pair( 331639d628a0SDimitry Andric StringRef(reinterpret_cast<const char *>(ToBuf.data()), 331739d628a0SDimitry Andric (StringLength + 1) * 2), 331839d628a0SDimitry Andric nullptr)).first; 3319f22ef01cSRoman Divacky } 3320f22ef01cSRoman Divacky 33210623d748SDimitry Andric ConstantAddress 3322f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 3323f22ef01cSRoman Divacky unsigned StringLength = 0; 3324f22ef01cSRoman Divacky bool isUTF16 = false; 332533956c43SDimitry Andric llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 3326f22ef01cSRoman Divacky GetConstantCFStringEntry(CFConstantStringMap, Literal, 332733956c43SDimitry Andric getDataLayout().isLittleEndian(), isUTF16, 332833956c43SDimitry Andric StringLength); 3329f22ef01cSRoman Divacky 333039d628a0SDimitry Andric if (auto *C = Entry.second) 33310623d748SDimitry Andric return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 3332f22ef01cSRoman Divacky 3333dff0c46cSDimitry Andric llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 3334f22ef01cSRoman Divacky llvm::Constant *Zeros[] = { Zero, Zero }; 3335f22ef01cSRoman Divacky 3336f22ef01cSRoman Divacky // If we don't already have it, get __CFConstantStringClassReference. 3337f22ef01cSRoman Divacky if (!CFConstantStringClassRef) { 33386122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 3339f22ef01cSRoman Divacky Ty = llvm::ArrayType::get(Ty, 0); 3340e7145dcbSDimitry Andric llvm::Constant *GV = 3341e7145dcbSDimitry Andric CreateRuntimeVariable(Ty, "__CFConstantStringClassReference"); 3342e7145dcbSDimitry Andric 334344290647SDimitry Andric if (getTriple().isOSBinFormatCOFF()) { 3344e7145dcbSDimitry Andric IdentifierInfo &II = getContext().Idents.get(GV->getName()); 3345e7145dcbSDimitry Andric TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl(); 3346e7145dcbSDimitry Andric DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 3347e7145dcbSDimitry Andric llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV); 3348e7145dcbSDimitry Andric 3349e7145dcbSDimitry Andric const VarDecl *VD = nullptr; 3350e7145dcbSDimitry Andric for (const auto &Result : DC->lookup(&II)) 3351e7145dcbSDimitry Andric if ((VD = dyn_cast<VarDecl>(Result))) 3352e7145dcbSDimitry Andric break; 3353e7145dcbSDimitry Andric 3354e7145dcbSDimitry Andric if (!VD || !VD->hasAttr<DLLExportAttr>()) { 3355e7145dcbSDimitry Andric CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 3356e7145dcbSDimitry Andric CGV->setLinkage(llvm::GlobalValue::ExternalLinkage); 3357e7145dcbSDimitry Andric } else { 3358e7145dcbSDimitry Andric CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 3359e7145dcbSDimitry Andric CGV->setLinkage(llvm::GlobalValue::ExternalLinkage); 3360e7145dcbSDimitry Andric } 3361e7145dcbSDimitry Andric } 3362e7145dcbSDimitry Andric 3363f22ef01cSRoman Divacky // Decay array -> ptr 336444290647SDimitry Andric CFConstantStringClassRef = 336544290647SDimitry Andric llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros); 3366e7145dcbSDimitry Andric } 3367f22ef01cSRoman Divacky 3368f22ef01cSRoman Divacky QualType CFTy = getContext().getCFConstantStringType(); 3369f22ef01cSRoman Divacky 337059d1ed5bSDimitry Andric auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 3371f22ef01cSRoman Divacky 337244290647SDimitry Andric ConstantInitBuilder Builder(*this); 337344290647SDimitry Andric auto Fields = Builder.beginStruct(STy); 3374f22ef01cSRoman Divacky 3375f22ef01cSRoman Divacky // Class pointer. 337644290647SDimitry Andric Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef)); 3377f22ef01cSRoman Divacky 3378f22ef01cSRoman Divacky // Flags. 337944290647SDimitry Andric Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); 3380f22ef01cSRoman Divacky 3381f22ef01cSRoman Divacky // String pointer. 338259d1ed5bSDimitry Andric llvm::Constant *C = nullptr; 3383dff0c46cSDimitry Andric if (isUTF16) { 33840623d748SDimitry Andric auto Arr = llvm::makeArrayRef( 338539d628a0SDimitry Andric reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 338639d628a0SDimitry Andric Entry.first().size() / 2); 3387dff0c46cSDimitry Andric C = llvm::ConstantDataArray::get(VMContext, Arr); 3388dff0c46cSDimitry Andric } else { 338939d628a0SDimitry Andric C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 3390dff0c46cSDimitry Andric } 3391f22ef01cSRoman Divacky 3392dff0c46cSDimitry Andric // Note: -fwritable-strings doesn't make the backing store strings of 3393dff0c46cSDimitry Andric // CFStrings writable. (See <rdar://problem/10657500>) 339459d1ed5bSDimitry Andric auto *GV = 3395dff0c46cSDimitry Andric new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 339659d1ed5bSDimitry Andric llvm::GlobalValue::PrivateLinkage, C, ".str"); 3397e7145dcbSDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3398284c1978SDimitry Andric // Don't enforce the target's minimum global alignment, since the only use 3399284c1978SDimitry Andric // of the string is via this class initializer. 3400e7145dcbSDimitry Andric CharUnits Align = isUTF16 3401e7145dcbSDimitry Andric ? getContext().getTypeAlignInChars(getContext().ShortTy) 3402e7145dcbSDimitry Andric : getContext().getTypeAlignInChars(getContext().CharTy); 3403f22ef01cSRoman Divacky GV->setAlignment(Align.getQuantity()); 3404e7145dcbSDimitry Andric 3405e7145dcbSDimitry Andric // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 3406e7145dcbSDimitry Andric // Without it LLVM can merge the string with a non unnamed_addr one during 3407e7145dcbSDimitry Andric // LTO. Doing that changes the section it ends in, which surprises ld64. 340844290647SDimitry Andric if (getTriple().isOSBinFormatMachO()) 3409e7145dcbSDimitry Andric GV->setSection(isUTF16 ? "__TEXT,__ustring" 3410e7145dcbSDimitry Andric : "__TEXT,__cstring,cstring_literals"); 3411dff0c46cSDimitry Andric 3412dff0c46cSDimitry Andric // String. 341344290647SDimitry Andric llvm::Constant *Str = 341433956c43SDimitry Andric llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 3415f22ef01cSRoman Divacky 3416dff0c46cSDimitry Andric if (isUTF16) 3417dff0c46cSDimitry Andric // Cast the UTF16 string to the correct type. 341844290647SDimitry Andric Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy); 341944290647SDimitry Andric Fields.add(Str); 3420dff0c46cSDimitry Andric 3421f22ef01cSRoman Divacky // String length. 342244290647SDimitry Andric auto Ty = getTypes().ConvertType(getContext().LongTy); 342344290647SDimitry Andric Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength); 3424f22ef01cSRoman Divacky 34250623d748SDimitry Andric CharUnits Alignment = getPointerAlign(); 34260623d748SDimitry Andric 3427f22ef01cSRoman Divacky // The struct. 342844290647SDimitry Andric GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, 342944290647SDimitry Andric /*isConstant=*/false, 343044290647SDimitry Andric llvm::GlobalVariable::PrivateLinkage); 343144290647SDimitry Andric switch (getTriple().getObjectFormat()) { 3432e7145dcbSDimitry Andric case llvm::Triple::UnknownObjectFormat: 3433e7145dcbSDimitry Andric llvm_unreachable("unknown file format"); 3434e7145dcbSDimitry Andric case llvm::Triple::COFF: 3435e7145dcbSDimitry Andric case llvm::Triple::ELF: 343620e90f04SDimitry Andric case llvm::Triple::Wasm: 3437e7145dcbSDimitry Andric GV->setSection("cfstring"); 3438e7145dcbSDimitry Andric break; 3439e7145dcbSDimitry Andric case llvm::Triple::MachO: 3440e7145dcbSDimitry Andric GV->setSection("__DATA,__cfstring"); 3441e7145dcbSDimitry Andric break; 3442e7145dcbSDimitry Andric } 344339d628a0SDimitry Andric Entry.second = GV; 3444f22ef01cSRoman Divacky 34450623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3446f22ef01cSRoman Divacky } 3447f22ef01cSRoman Divacky 34486122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() { 34496122f3e6SDimitry Andric if (ObjCFastEnumerationStateType.isNull()) { 345059d1ed5bSDimitry Andric RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 34516122f3e6SDimitry Andric D->startDefinition(); 34526122f3e6SDimitry Andric 34536122f3e6SDimitry Andric QualType FieldTypes[] = { 34546122f3e6SDimitry Andric Context.UnsignedLongTy, 34556122f3e6SDimitry Andric Context.getPointerType(Context.getObjCIdType()), 34566122f3e6SDimitry Andric Context.getPointerType(Context.UnsignedLongTy), 34576122f3e6SDimitry Andric Context.getConstantArrayType(Context.UnsignedLongTy, 34586122f3e6SDimitry Andric llvm::APInt(32, 5), ArrayType::Normal, 0) 34596122f3e6SDimitry Andric }; 34606122f3e6SDimitry Andric 34616122f3e6SDimitry Andric for (size_t i = 0; i < 4; ++i) { 34626122f3e6SDimitry Andric FieldDecl *Field = FieldDecl::Create(Context, 34636122f3e6SDimitry Andric D, 34646122f3e6SDimitry Andric SourceLocation(), 346559d1ed5bSDimitry Andric SourceLocation(), nullptr, 346659d1ed5bSDimitry Andric FieldTypes[i], /*TInfo=*/nullptr, 346759d1ed5bSDimitry Andric /*BitWidth=*/nullptr, 34686122f3e6SDimitry Andric /*Mutable=*/false, 34697ae0e2c9SDimitry Andric ICIS_NoInit); 34706122f3e6SDimitry Andric Field->setAccess(AS_public); 34716122f3e6SDimitry Andric D->addDecl(Field); 34726122f3e6SDimitry Andric } 34736122f3e6SDimitry Andric 34746122f3e6SDimitry Andric D->completeDefinition(); 34756122f3e6SDimitry Andric ObjCFastEnumerationStateType = Context.getTagDeclType(D); 34766122f3e6SDimitry Andric } 34776122f3e6SDimitry Andric 34786122f3e6SDimitry Andric return ObjCFastEnumerationStateType; 34796122f3e6SDimitry Andric } 34806122f3e6SDimitry Andric 3481dff0c46cSDimitry Andric llvm::Constant * 3482dff0c46cSDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 3483dff0c46cSDimitry Andric assert(!E->getType()->isPointerType() && "Strings are always arrays"); 3484f22ef01cSRoman Divacky 3485dff0c46cSDimitry Andric // Don't emit it as the address of the string, emit the string data itself 3486dff0c46cSDimitry Andric // as an inline array. 3487dff0c46cSDimitry Andric if (E->getCharByteWidth() == 1) { 3488dff0c46cSDimitry Andric SmallString<64> Str(E->getString()); 3489f22ef01cSRoman Divacky 3490dff0c46cSDimitry Andric // Resize the string to the right size, which is indicated by its type. 3491dff0c46cSDimitry Andric const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 3492dff0c46cSDimitry Andric Str.resize(CAT->getSize().getZExtValue()); 3493dff0c46cSDimitry Andric return llvm::ConstantDataArray::getString(VMContext, Str, false); 34946122f3e6SDimitry Andric } 3495f22ef01cSRoman Divacky 349659d1ed5bSDimitry Andric auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 3497dff0c46cSDimitry Andric llvm::Type *ElemTy = AType->getElementType(); 3498dff0c46cSDimitry Andric unsigned NumElements = AType->getNumElements(); 3499f22ef01cSRoman Divacky 3500dff0c46cSDimitry Andric // Wide strings have either 2-byte or 4-byte elements. 3501dff0c46cSDimitry Andric if (ElemTy->getPrimitiveSizeInBits() == 16) { 3502dff0c46cSDimitry Andric SmallVector<uint16_t, 32> Elements; 3503dff0c46cSDimitry Andric Elements.reserve(NumElements); 3504dff0c46cSDimitry Andric 3505dff0c46cSDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 3506dff0c46cSDimitry Andric Elements.push_back(E->getCodeUnit(i)); 3507dff0c46cSDimitry Andric Elements.resize(NumElements); 3508dff0c46cSDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 3509dff0c46cSDimitry Andric } 3510dff0c46cSDimitry Andric 3511dff0c46cSDimitry Andric assert(ElemTy->getPrimitiveSizeInBits() == 32); 3512dff0c46cSDimitry Andric SmallVector<uint32_t, 32> Elements; 3513dff0c46cSDimitry Andric Elements.reserve(NumElements); 3514dff0c46cSDimitry Andric 3515dff0c46cSDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 3516dff0c46cSDimitry Andric Elements.push_back(E->getCodeUnit(i)); 3517dff0c46cSDimitry Andric Elements.resize(NumElements); 3518dff0c46cSDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 3519f22ef01cSRoman Divacky } 3520f22ef01cSRoman Divacky 352159d1ed5bSDimitry Andric static llvm::GlobalVariable * 352259d1ed5bSDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 352359d1ed5bSDimitry Andric CodeGenModule &CGM, StringRef GlobalName, 35240623d748SDimitry Andric CharUnits Alignment) { 352559d1ed5bSDimitry Andric // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 352659d1ed5bSDimitry Andric unsigned AddrSpace = 0; 352759d1ed5bSDimitry Andric if (CGM.getLangOpts().OpenCL) 352859d1ed5bSDimitry Andric AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant); 3529dff0c46cSDimitry Andric 353033956c43SDimitry Andric llvm::Module &M = CGM.getModule(); 353159d1ed5bSDimitry Andric // Create a global variable for this string 353259d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 353333956c43SDimitry Andric M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 353433956c43SDimitry Andric nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 35350623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 3536e7145dcbSDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 353733956c43SDimitry Andric if (GV->isWeakForLinker()) { 353833956c43SDimitry Andric assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 353933956c43SDimitry Andric GV->setComdat(M.getOrInsertComdat(GV->getName())); 354033956c43SDimitry Andric } 354133956c43SDimitry Andric 354259d1ed5bSDimitry Andric return GV; 3543f22ef01cSRoman Divacky } 3544dff0c46cSDimitry Andric 354559d1ed5bSDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 354659d1ed5bSDimitry Andric /// constant array for the given string literal. 35470623d748SDimitry Andric ConstantAddress 354839d628a0SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 354939d628a0SDimitry Andric StringRef Name) { 35500623d748SDimitry Andric CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 3551dff0c46cSDimitry Andric 355259d1ed5bSDimitry Andric llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 355359d1ed5bSDimitry Andric llvm::GlobalVariable **Entry = nullptr; 355459d1ed5bSDimitry Andric if (!LangOpts.WritableStrings) { 355559d1ed5bSDimitry Andric Entry = &ConstantStringMap[C]; 355659d1ed5bSDimitry Andric if (auto GV = *Entry) { 35570623d748SDimitry Andric if (Alignment.getQuantity() > GV->getAlignment()) 35580623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 35590623d748SDimitry Andric return ConstantAddress(GV, Alignment); 356059d1ed5bSDimitry Andric } 356159d1ed5bSDimitry Andric } 356259d1ed5bSDimitry Andric 356359d1ed5bSDimitry Andric SmallString<256> MangledNameBuffer; 356459d1ed5bSDimitry Andric StringRef GlobalVariableName; 356559d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes LT; 356659d1ed5bSDimitry Andric 356759d1ed5bSDimitry Andric // Mangle the string literal if the ABI allows for it. However, we cannot 356859d1ed5bSDimitry Andric // do this if we are compiling with ASan or -fwritable-strings because they 356959d1ed5bSDimitry Andric // rely on strings having normal linkage. 357039d628a0SDimitry Andric if (!LangOpts.WritableStrings && 357139d628a0SDimitry Andric !LangOpts.Sanitize.has(SanitizerKind::Address) && 357259d1ed5bSDimitry Andric getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) { 357359d1ed5bSDimitry Andric llvm::raw_svector_ostream Out(MangledNameBuffer); 357459d1ed5bSDimitry Andric getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 357559d1ed5bSDimitry Andric 357659d1ed5bSDimitry Andric LT = llvm::GlobalValue::LinkOnceODRLinkage; 357759d1ed5bSDimitry Andric GlobalVariableName = MangledNameBuffer; 357859d1ed5bSDimitry Andric } else { 357959d1ed5bSDimitry Andric LT = llvm::GlobalValue::PrivateLinkage; 358039d628a0SDimitry Andric GlobalVariableName = Name; 358159d1ed5bSDimitry Andric } 358259d1ed5bSDimitry Andric 358359d1ed5bSDimitry Andric auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 358459d1ed5bSDimitry Andric if (Entry) 358559d1ed5bSDimitry Andric *Entry = GV; 358659d1ed5bSDimitry Andric 358739d628a0SDimitry Andric SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>", 358839d628a0SDimitry Andric QualType()); 35890623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3590f22ef01cSRoman Divacky } 3591f22ef01cSRoman Divacky 3592f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 3593f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node. 35940623d748SDimitry Andric ConstantAddress 3595f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 3596f22ef01cSRoman Divacky std::string Str; 3597f22ef01cSRoman Divacky getContext().getObjCEncodingForType(E->getEncodedType(), Str); 3598f22ef01cSRoman Divacky 3599f22ef01cSRoman Divacky return GetAddrOfConstantCString(Str); 3600f22ef01cSRoman Divacky } 3601f22ef01cSRoman Divacky 360259d1ed5bSDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing 360359d1ed5bSDimitry Andric /// the literal and a terminating '\0' character. 360459d1ed5bSDimitry Andric /// The result has pointer to array type. 36050623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString( 36060623d748SDimitry Andric const std::string &Str, const char *GlobalName) { 360759d1ed5bSDimitry Andric StringRef StrWithNull(Str.c_str(), Str.size() + 1); 36080623d748SDimitry Andric CharUnits Alignment = 36090623d748SDimitry Andric getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 3610f22ef01cSRoman Divacky 361159d1ed5bSDimitry Andric llvm::Constant *C = 361259d1ed5bSDimitry Andric llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 361359d1ed5bSDimitry Andric 361459d1ed5bSDimitry Andric // Don't share any string literals if strings aren't constant. 361559d1ed5bSDimitry Andric llvm::GlobalVariable **Entry = nullptr; 361659d1ed5bSDimitry Andric if (!LangOpts.WritableStrings) { 361759d1ed5bSDimitry Andric Entry = &ConstantStringMap[C]; 361859d1ed5bSDimitry Andric if (auto GV = *Entry) { 36190623d748SDimitry Andric if (Alignment.getQuantity() > GV->getAlignment()) 36200623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 36210623d748SDimitry Andric return ConstantAddress(GV, Alignment); 362259d1ed5bSDimitry Andric } 362359d1ed5bSDimitry Andric } 362459d1ed5bSDimitry Andric 3625f22ef01cSRoman Divacky // Get the default prefix if a name wasn't specified. 3626f22ef01cSRoman Divacky if (!GlobalName) 3627f22ef01cSRoman Divacky GlobalName = ".str"; 3628f22ef01cSRoman Divacky // Create a global variable for this. 362959d1ed5bSDimitry Andric auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 363059d1ed5bSDimitry Andric GlobalName, Alignment); 363159d1ed5bSDimitry Andric if (Entry) 363259d1ed5bSDimitry Andric *Entry = GV; 36330623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3634f22ef01cSRoman Divacky } 3635f22ef01cSRoman Divacky 36360623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 3637f785676fSDimitry Andric const MaterializeTemporaryExpr *E, const Expr *Init) { 3638f785676fSDimitry Andric assert((E->getStorageDuration() == SD_Static || 3639f785676fSDimitry Andric E->getStorageDuration() == SD_Thread) && "not a global temporary"); 364059d1ed5bSDimitry Andric const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 3641f785676fSDimitry Andric 3642f785676fSDimitry Andric // If we're not materializing a subobject of the temporary, keep the 3643f785676fSDimitry Andric // cv-qualifiers from the type of the MaterializeTemporaryExpr. 3644f785676fSDimitry Andric QualType MaterializedType = Init->getType(); 3645f785676fSDimitry Andric if (Init == E->GetTemporaryExpr()) 3646f785676fSDimitry Andric MaterializedType = E->getType(); 3647f785676fSDimitry Andric 36480623d748SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 36490623d748SDimitry Andric 36500623d748SDimitry Andric if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E]) 36510623d748SDimitry Andric return ConstantAddress(Slot, Align); 3652f785676fSDimitry Andric 3653f785676fSDimitry Andric // FIXME: If an externally-visible declaration extends multiple temporaries, 3654f785676fSDimitry Andric // we need to give each temporary the same name in every translation unit (and 3655f785676fSDimitry Andric // we also need to make the temporaries externally-visible). 3656f785676fSDimitry Andric SmallString<256> Name; 3657f785676fSDimitry Andric llvm::raw_svector_ostream Out(Name); 365859d1ed5bSDimitry Andric getCXXABI().getMangleContext().mangleReferenceTemporary( 365959d1ed5bSDimitry Andric VD, E->getManglingNumber(), Out); 3660f785676fSDimitry Andric 366159d1ed5bSDimitry Andric APValue *Value = nullptr; 3662f785676fSDimitry Andric if (E->getStorageDuration() == SD_Static) { 3663f785676fSDimitry Andric // We might have a cached constant initializer for this temporary. Note 3664f785676fSDimitry Andric // that this might have a different value from the value computed by 3665f785676fSDimitry Andric // evaluating the initializer if the surrounding constant expression 3666f785676fSDimitry Andric // modifies the temporary. 3667f785676fSDimitry Andric Value = getContext().getMaterializedTemporaryValue(E, false); 3668f785676fSDimitry Andric if (Value && Value->isUninit()) 366959d1ed5bSDimitry Andric Value = nullptr; 3670f785676fSDimitry Andric } 3671f785676fSDimitry Andric 3672f785676fSDimitry Andric // Try evaluating it now, it might have a constant initializer. 3673f785676fSDimitry Andric Expr::EvalResult EvalResult; 3674f785676fSDimitry Andric if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 3675f785676fSDimitry Andric !EvalResult.hasSideEffects()) 3676f785676fSDimitry Andric Value = &EvalResult.Val; 3677f785676fSDimitry Andric 367859d1ed5bSDimitry Andric llvm::Constant *InitialValue = nullptr; 3679f785676fSDimitry Andric bool Constant = false; 3680f785676fSDimitry Andric llvm::Type *Type; 3681f785676fSDimitry Andric if (Value) { 3682f785676fSDimitry Andric // The temporary has a constant initializer, use it. 368359d1ed5bSDimitry Andric InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr); 3684f785676fSDimitry Andric Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 3685f785676fSDimitry Andric Type = InitialValue->getType(); 3686f785676fSDimitry Andric } else { 3687f785676fSDimitry Andric // No initializer, the initialization will be provided when we 3688f785676fSDimitry Andric // initialize the declaration which performed lifetime extension. 3689f785676fSDimitry Andric Type = getTypes().ConvertTypeForMem(MaterializedType); 3690f785676fSDimitry Andric } 3691f785676fSDimitry Andric 3692f785676fSDimitry Andric // Create a global variable for this lifetime-extended temporary. 369359d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 369459d1ed5bSDimitry Andric getLLVMLinkageVarDefinition(VD, Constant); 369533956c43SDimitry Andric if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 369633956c43SDimitry Andric const VarDecl *InitVD; 369733956c43SDimitry Andric if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 369833956c43SDimitry Andric isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 369933956c43SDimitry Andric // Temporaries defined inside a class get linkonce_odr linkage because the 370033956c43SDimitry Andric // class can be defined in multipe translation units. 370133956c43SDimitry Andric Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 370233956c43SDimitry Andric } else { 370333956c43SDimitry Andric // There is no need for this temporary to have external linkage if the 370433956c43SDimitry Andric // VarDecl has external linkage. 370533956c43SDimitry Andric Linkage = llvm::GlobalVariable::InternalLinkage; 370633956c43SDimitry Andric } 370733956c43SDimitry Andric } 370859d1ed5bSDimitry Andric unsigned AddrSpace = GetGlobalVarAddressSpace( 370959d1ed5bSDimitry Andric VD, getContext().getTargetAddressSpace(MaterializedType)); 371059d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 371159d1ed5bSDimitry Andric getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 371259d1ed5bSDimitry Andric /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, 371359d1ed5bSDimitry Andric AddrSpace); 371459d1ed5bSDimitry Andric setGlobalVisibility(GV, VD); 37150623d748SDimitry Andric GV->setAlignment(Align.getQuantity()); 371633956c43SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker()) 371733956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3718f785676fSDimitry Andric if (VD->getTLSKind()) 3719f785676fSDimitry Andric setTLSMode(GV, *VD); 37200623d748SDimitry Andric MaterializedGlobalTemporaryMap[E] = GV; 37210623d748SDimitry Andric return ConstantAddress(GV, Align); 3722f785676fSDimitry Andric } 3723f785676fSDimitry Andric 3724f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized 3725f22ef01cSRoman Divacky /// properties for an implementation. 3726f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const 3727f22ef01cSRoman Divacky ObjCImplementationDecl *D) { 372859d1ed5bSDimitry Andric for (const auto *PID : D->property_impls()) { 3729f22ef01cSRoman Divacky // Dynamic is just for type-checking. 3730f22ef01cSRoman Divacky if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 3731f22ef01cSRoman Divacky ObjCPropertyDecl *PD = PID->getPropertyDecl(); 3732f22ef01cSRoman Divacky 3733f22ef01cSRoman Divacky // Determine which methods need to be implemented, some may have 37343861d79fSDimitry Andric // been overridden. Note that ::isPropertyAccessor is not the method 3735f22ef01cSRoman Divacky // we want, that just indicates if the decl came from a 3736f22ef01cSRoman Divacky // property. What we want to know is if the method is defined in 3737f22ef01cSRoman Divacky // this implementation. 3738f22ef01cSRoman Divacky if (!D->getInstanceMethod(PD->getGetterName())) 3739f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCGetter( 3740f22ef01cSRoman Divacky const_cast<ObjCImplementationDecl *>(D), PID); 3741f22ef01cSRoman Divacky if (!PD->isReadOnly() && 3742f22ef01cSRoman Divacky !D->getInstanceMethod(PD->getSetterName())) 3743f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCSetter( 3744f22ef01cSRoman Divacky const_cast<ObjCImplementationDecl *>(D), PID); 3745f22ef01cSRoman Divacky } 3746f22ef01cSRoman Divacky } 3747f22ef01cSRoman Divacky } 3748f22ef01cSRoman Divacky 37493b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) { 37506122f3e6SDimitry Andric const ObjCInterfaceDecl *iface = impl->getClassInterface(); 37516122f3e6SDimitry Andric for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 37523b0f4066SDimitry Andric ivar; ivar = ivar->getNextIvar()) 37533b0f4066SDimitry Andric if (ivar->getType().isDestructedType()) 37543b0f4066SDimitry Andric return true; 37553b0f4066SDimitry Andric 37563b0f4066SDimitry Andric return false; 37573b0f4066SDimitry Andric } 37583b0f4066SDimitry Andric 375939d628a0SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM, 376039d628a0SDimitry Andric ObjCImplementationDecl *D) { 376139d628a0SDimitry Andric CodeGenFunction CGF(CGM); 376239d628a0SDimitry Andric for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 376339d628a0SDimitry Andric E = D->init_end(); B != E; ++B) { 376439d628a0SDimitry Andric CXXCtorInitializer *CtorInitExp = *B; 376539d628a0SDimitry Andric Expr *Init = CtorInitExp->getInit(); 376639d628a0SDimitry Andric if (!CGF.isTrivialInitializer(Init)) 376739d628a0SDimitry Andric return false; 376839d628a0SDimitry Andric } 376939d628a0SDimitry Andric return true; 377039d628a0SDimitry Andric } 377139d628a0SDimitry Andric 3772f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization 3773f22ef01cSRoman Divacky /// for an implementation. 3774f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 37753b0f4066SDimitry Andric // We might need a .cxx_destruct even if we don't have any ivar initializers. 37763b0f4066SDimitry Andric if (needsDestructMethod(D)) { 3777f22ef01cSRoman Divacky IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 3778f22ef01cSRoman Divacky Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 37793b0f4066SDimitry Andric ObjCMethodDecl *DTORMethod = 37803b0f4066SDimitry Andric ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 378159d1ed5bSDimitry Andric cxxSelector, getContext().VoidTy, nullptr, D, 37826122f3e6SDimitry Andric /*isInstance=*/true, /*isVariadic=*/false, 37833861d79fSDimitry Andric /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 37846122f3e6SDimitry Andric /*isDefined=*/false, ObjCMethodDecl::Required); 3785f22ef01cSRoman Divacky D->addInstanceMethod(DTORMethod); 3786f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 37873861d79fSDimitry Andric D->setHasDestructors(true); 37883b0f4066SDimitry Andric } 3789f22ef01cSRoman Divacky 37903b0f4066SDimitry Andric // If the implementation doesn't have any ivar initializers, we don't need 37913b0f4066SDimitry Andric // a .cxx_construct. 379239d628a0SDimitry Andric if (D->getNumIvarInitializers() == 0 || 379339d628a0SDimitry Andric AllTrivialInitializers(*this, D)) 37943b0f4066SDimitry Andric return; 37953b0f4066SDimitry Andric 37963b0f4066SDimitry Andric IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 37973b0f4066SDimitry Andric Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 3798f22ef01cSRoman Divacky // The constructor returns 'self'. 3799f22ef01cSRoman Divacky ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 3800f22ef01cSRoman Divacky D->getLocation(), 38016122f3e6SDimitry Andric D->getLocation(), 38026122f3e6SDimitry Andric cxxSelector, 380359d1ed5bSDimitry Andric getContext().getObjCIdType(), 380459d1ed5bSDimitry Andric nullptr, D, /*isInstance=*/true, 38056122f3e6SDimitry Andric /*isVariadic=*/false, 38063861d79fSDimitry Andric /*isPropertyAccessor=*/true, 38076122f3e6SDimitry Andric /*isImplicitlyDeclared=*/true, 38086122f3e6SDimitry Andric /*isDefined=*/false, 3809f22ef01cSRoman Divacky ObjCMethodDecl::Required); 3810f22ef01cSRoman Divacky D->addInstanceMethod(CTORMethod); 3811f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 38123861d79fSDimitry Andric D->setHasNonZeroConstructors(true); 3813f22ef01cSRoman Divacky } 3814f22ef01cSRoman Divacky 3815f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec. 3816f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 3817f22ef01cSRoman Divacky if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 3818f22ef01cSRoman Divacky LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 3819f22ef01cSRoman Divacky ErrorUnsupported(LSD, "linkage spec"); 3820f22ef01cSRoman Divacky return; 3821f22ef01cSRoman Divacky } 3822f22ef01cSRoman Divacky 382344290647SDimitry Andric EmitDeclContext(LSD); 382444290647SDimitry Andric } 382544290647SDimitry Andric 382644290647SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) { 382744290647SDimitry Andric for (auto *I : DC->decls()) { 382844290647SDimitry Andric // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope 382944290647SDimitry Andric // are themselves considered "top-level", so EmitTopLevelDecl on an 383044290647SDimitry Andric // ObjCImplDecl does not recursively visit them. We need to do that in 383144290647SDimitry Andric // case they're nested inside another construct (LinkageSpecDecl / 383244290647SDimitry Andric // ExportDecl) that does stop them from being considered "top-level". 383359d1ed5bSDimitry Andric if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 383459d1ed5bSDimitry Andric for (auto *M : OID->methods()) 383559d1ed5bSDimitry Andric EmitTopLevelDecl(M); 38363861d79fSDimitry Andric } 383744290647SDimitry Andric 383859d1ed5bSDimitry Andric EmitTopLevelDecl(I); 3839f22ef01cSRoman Divacky } 38403861d79fSDimitry Andric } 3841f22ef01cSRoman Divacky 3842f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration. 3843f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) { 3844f22ef01cSRoman Divacky // Ignore dependent declarations. 3845f22ef01cSRoman Divacky if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 3846f22ef01cSRoman Divacky return; 3847f22ef01cSRoman Divacky 3848f22ef01cSRoman Divacky switch (D->getKind()) { 3849f22ef01cSRoman Divacky case Decl::CXXConversion: 3850f22ef01cSRoman Divacky case Decl::CXXMethod: 3851f22ef01cSRoman Divacky case Decl::Function: 3852f22ef01cSRoman Divacky // Skip function templates 38533b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 38543b0f4066SDimitry Andric cast<FunctionDecl>(D)->isLateTemplateParsed()) 3855f22ef01cSRoman Divacky return; 3856f22ef01cSRoman Divacky 3857f22ef01cSRoman Divacky EmitGlobal(cast<FunctionDecl>(D)); 385839d628a0SDimitry Andric // Always provide some coverage mapping 385939d628a0SDimitry Andric // even for the functions that aren't emitted. 386039d628a0SDimitry Andric AddDeferredUnusedCoverageMapping(D); 3861f22ef01cSRoman Divacky break; 3862f22ef01cSRoman Divacky 38636bc11b14SDimitry Andric case Decl::CXXDeductionGuide: 38646bc11b14SDimitry Andric // Function-like, but does not result in code emission. 38656bc11b14SDimitry Andric break; 38666bc11b14SDimitry Andric 3867f22ef01cSRoman Divacky case Decl::Var: 386844290647SDimitry Andric case Decl::Decomposition: 3869f785676fSDimitry Andric // Skip variable templates 3870f785676fSDimitry Andric if (cast<VarDecl>(D)->getDescribedVarTemplate()) 3871f785676fSDimitry Andric return; 38726d97bb29SDimitry Andric LLVM_FALLTHROUGH; 3873f785676fSDimitry Andric case Decl::VarTemplateSpecialization: 3874f22ef01cSRoman Divacky EmitGlobal(cast<VarDecl>(D)); 387544290647SDimitry Andric if (auto *DD = dyn_cast<DecompositionDecl>(D)) 387644290647SDimitry Andric for (auto *B : DD->bindings()) 387744290647SDimitry Andric if (auto *HD = B->getHoldingVar()) 387844290647SDimitry Andric EmitGlobal(HD); 3879f22ef01cSRoman Divacky break; 3880f22ef01cSRoman Divacky 38813b0f4066SDimitry Andric // Indirect fields from global anonymous structs and unions can be 38823b0f4066SDimitry Andric // ignored; only the actual variable requires IR gen support. 38833b0f4066SDimitry Andric case Decl::IndirectField: 38843b0f4066SDimitry Andric break; 38853b0f4066SDimitry Andric 3886f22ef01cSRoman Divacky // C++ Decls 3887f22ef01cSRoman Divacky case Decl::Namespace: 388844290647SDimitry Andric EmitDeclContext(cast<NamespaceDecl>(D)); 3889f22ef01cSRoman Divacky break; 3890e7145dcbSDimitry Andric case Decl::CXXRecord: 389120e90f04SDimitry Andric if (DebugInfo) { 389220e90f04SDimitry Andric if (auto *ES = D->getASTContext().getExternalSource()) 389320e90f04SDimitry Andric if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) 389420e90f04SDimitry Andric DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D)); 389520e90f04SDimitry Andric } 3896e7145dcbSDimitry Andric // Emit any static data members, they may be definitions. 3897e7145dcbSDimitry Andric for (auto *I : cast<CXXRecordDecl>(D)->decls()) 3898e7145dcbSDimitry Andric if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) 3899e7145dcbSDimitry Andric EmitTopLevelDecl(I); 3900e7145dcbSDimitry Andric break; 3901f22ef01cSRoman Divacky // No code generation needed. 3902f22ef01cSRoman Divacky case Decl::UsingShadow: 3903f22ef01cSRoman Divacky case Decl::ClassTemplate: 3904f785676fSDimitry Andric case Decl::VarTemplate: 3905f785676fSDimitry Andric case Decl::VarTemplatePartialSpecialization: 3906f22ef01cSRoman Divacky case Decl::FunctionTemplate: 3907bd5abe19SDimitry Andric case Decl::TypeAliasTemplate: 3908bd5abe19SDimitry Andric case Decl::Block: 3909139f7f9bSDimitry Andric case Decl::Empty: 3910f22ef01cSRoman Divacky break; 391159d1ed5bSDimitry Andric case Decl::Using: // using X; [C++] 391259d1ed5bSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 391359d1ed5bSDimitry Andric DI->EmitUsingDecl(cast<UsingDecl>(*D)); 391459d1ed5bSDimitry Andric return; 3915f785676fSDimitry Andric case Decl::NamespaceAlias: 3916f785676fSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3917f785676fSDimitry Andric DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 3918f785676fSDimitry Andric return; 3919284c1978SDimitry Andric case Decl::UsingDirective: // using namespace X; [C++] 3920284c1978SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3921284c1978SDimitry Andric DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 3922284c1978SDimitry Andric return; 3923f22ef01cSRoman Divacky case Decl::CXXConstructor: 3924f22ef01cSRoman Divacky // Skip function templates 39253b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 39263b0f4066SDimitry Andric cast<FunctionDecl>(D)->isLateTemplateParsed()) 3927f22ef01cSRoman Divacky return; 3928f22ef01cSRoman Divacky 3929f785676fSDimitry Andric getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 3930f22ef01cSRoman Divacky break; 3931f22ef01cSRoman Divacky case Decl::CXXDestructor: 39323b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 39333b0f4066SDimitry Andric return; 3934f785676fSDimitry Andric getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 3935f22ef01cSRoman Divacky break; 3936f22ef01cSRoman Divacky 3937f22ef01cSRoman Divacky case Decl::StaticAssert: 3938f22ef01cSRoman Divacky // Nothing to do. 3939f22ef01cSRoman Divacky break; 3940f22ef01cSRoman Divacky 3941f22ef01cSRoman Divacky // Objective-C Decls 3942f22ef01cSRoman Divacky 3943f22ef01cSRoman Divacky // Forward declarations, no (immediate) code generation. 3944f22ef01cSRoman Divacky case Decl::ObjCInterface: 39457ae0e2c9SDimitry Andric case Decl::ObjCCategory: 3946f22ef01cSRoman Divacky break; 3947f22ef01cSRoman Divacky 3948dff0c46cSDimitry Andric case Decl::ObjCProtocol: { 394959d1ed5bSDimitry Andric auto *Proto = cast<ObjCProtocolDecl>(D); 3950dff0c46cSDimitry Andric if (Proto->isThisDeclarationADefinition()) 3951dff0c46cSDimitry Andric ObjCRuntime->GenerateProtocol(Proto); 3952f22ef01cSRoman Divacky break; 3953dff0c46cSDimitry Andric } 3954f22ef01cSRoman Divacky 3955f22ef01cSRoman Divacky case Decl::ObjCCategoryImpl: 3956f22ef01cSRoman Divacky // Categories have properties but don't support synthesize so we 3957f22ef01cSRoman Divacky // can ignore them here. 39586122f3e6SDimitry Andric ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 3959f22ef01cSRoman Divacky break; 3960f22ef01cSRoman Divacky 3961f22ef01cSRoman Divacky case Decl::ObjCImplementation: { 396259d1ed5bSDimitry Andric auto *OMD = cast<ObjCImplementationDecl>(D); 3963f22ef01cSRoman Divacky EmitObjCPropertyImplementations(OMD); 3964f22ef01cSRoman Divacky EmitObjCIvarInitializations(OMD); 39656122f3e6SDimitry Andric ObjCRuntime->GenerateClass(OMD); 3966dff0c46cSDimitry Andric // Emit global variable debug information. 3967dff0c46cSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3968e7145dcbSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) 3969139f7f9bSDimitry Andric DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 3970139f7f9bSDimitry Andric OMD->getClassInterface()), OMD->getLocation()); 3971f22ef01cSRoman Divacky break; 3972f22ef01cSRoman Divacky } 3973f22ef01cSRoman Divacky case Decl::ObjCMethod: { 397459d1ed5bSDimitry Andric auto *OMD = cast<ObjCMethodDecl>(D); 3975f22ef01cSRoman Divacky // If this is not a prototype, emit the body. 3976f22ef01cSRoman Divacky if (OMD->getBody()) 3977f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCMethod(OMD); 3978f22ef01cSRoman Divacky break; 3979f22ef01cSRoman Divacky } 3980f22ef01cSRoman Divacky case Decl::ObjCCompatibleAlias: 3981dff0c46cSDimitry Andric ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 3982f22ef01cSRoman Divacky break; 3983f22ef01cSRoman Divacky 3984e7145dcbSDimitry Andric case Decl::PragmaComment: { 3985e7145dcbSDimitry Andric const auto *PCD = cast<PragmaCommentDecl>(D); 3986e7145dcbSDimitry Andric switch (PCD->getCommentKind()) { 3987e7145dcbSDimitry Andric case PCK_Unknown: 3988e7145dcbSDimitry Andric llvm_unreachable("unexpected pragma comment kind"); 3989e7145dcbSDimitry Andric case PCK_Linker: 3990e7145dcbSDimitry Andric AppendLinkerOptions(PCD->getArg()); 3991e7145dcbSDimitry Andric break; 3992e7145dcbSDimitry Andric case PCK_Lib: 3993e7145dcbSDimitry Andric AddDependentLib(PCD->getArg()); 3994e7145dcbSDimitry Andric break; 3995e7145dcbSDimitry Andric case PCK_Compiler: 3996e7145dcbSDimitry Andric case PCK_ExeStr: 3997e7145dcbSDimitry Andric case PCK_User: 3998e7145dcbSDimitry Andric break; // We ignore all of these. 3999e7145dcbSDimitry Andric } 4000e7145dcbSDimitry Andric break; 4001e7145dcbSDimitry Andric } 4002e7145dcbSDimitry Andric 4003e7145dcbSDimitry Andric case Decl::PragmaDetectMismatch: { 4004e7145dcbSDimitry Andric const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 4005e7145dcbSDimitry Andric AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 4006e7145dcbSDimitry Andric break; 4007e7145dcbSDimitry Andric } 4008e7145dcbSDimitry Andric 4009f22ef01cSRoman Divacky case Decl::LinkageSpec: 4010f22ef01cSRoman Divacky EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 4011f22ef01cSRoman Divacky break; 4012f22ef01cSRoman Divacky 4013f22ef01cSRoman Divacky case Decl::FileScopeAsm: { 401433956c43SDimitry Andric // File-scope asm is ignored during device-side CUDA compilation. 401533956c43SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 401633956c43SDimitry Andric break; 4017ea942507SDimitry Andric // File-scope asm is ignored during device-side OpenMP compilation. 4018ea942507SDimitry Andric if (LangOpts.OpenMPIsDevice) 4019ea942507SDimitry Andric break; 402059d1ed5bSDimitry Andric auto *AD = cast<FileScopeAsmDecl>(D); 402133956c43SDimitry Andric getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 4022f22ef01cSRoman Divacky break; 4023f22ef01cSRoman Divacky } 4024f22ef01cSRoman Divacky 4025139f7f9bSDimitry Andric case Decl::Import: { 402659d1ed5bSDimitry Andric auto *Import = cast<ImportDecl>(D); 4027139f7f9bSDimitry Andric 402844290647SDimitry Andric // If we've already imported this module, we're done. 402944290647SDimitry Andric if (!ImportedModules.insert(Import->getImportedModule())) 4030139f7f9bSDimitry Andric break; 403144290647SDimitry Andric 403244290647SDimitry Andric // Emit debug information for direct imports. 403344290647SDimitry Andric if (!Import->getImportedOwningModule()) { 40343dac3a9bSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 40353dac3a9bSDimitry Andric DI->EmitImportDecl(*Import); 403644290647SDimitry Andric } 4037139f7f9bSDimitry Andric 403844290647SDimitry Andric // Find all of the submodules and emit the module initializers. 403944290647SDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 404044290647SDimitry Andric SmallVector<clang::Module *, 16> Stack; 404144290647SDimitry Andric Visited.insert(Import->getImportedModule()); 404244290647SDimitry Andric Stack.push_back(Import->getImportedModule()); 404344290647SDimitry Andric 404444290647SDimitry Andric while (!Stack.empty()) { 404544290647SDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 404644290647SDimitry Andric if (!EmittedModuleInitializers.insert(Mod).second) 404744290647SDimitry Andric continue; 404844290647SDimitry Andric 404944290647SDimitry Andric for (auto *D : Context.getModuleInitializers(Mod)) 405044290647SDimitry Andric EmitTopLevelDecl(D); 405144290647SDimitry Andric 405244290647SDimitry Andric // Visit the submodules of this module. 405344290647SDimitry Andric for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 405444290647SDimitry Andric SubEnd = Mod->submodule_end(); 405544290647SDimitry Andric Sub != SubEnd; ++Sub) { 405644290647SDimitry Andric // Skip explicit children; they need to be explicitly imported to emit 405744290647SDimitry Andric // the initializers. 405844290647SDimitry Andric if ((*Sub)->IsExplicit) 405944290647SDimitry Andric continue; 406044290647SDimitry Andric 406144290647SDimitry Andric if (Visited.insert(*Sub).second) 406244290647SDimitry Andric Stack.push_back(*Sub); 406344290647SDimitry Andric } 406444290647SDimitry Andric } 4065139f7f9bSDimitry Andric break; 4066139f7f9bSDimitry Andric } 4067139f7f9bSDimitry Andric 406844290647SDimitry Andric case Decl::Export: 406944290647SDimitry Andric EmitDeclContext(cast<ExportDecl>(D)); 407044290647SDimitry Andric break; 407144290647SDimitry Andric 407239d628a0SDimitry Andric case Decl::OMPThreadPrivate: 407339d628a0SDimitry Andric EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 407439d628a0SDimitry Andric break; 407539d628a0SDimitry Andric 407659d1ed5bSDimitry Andric case Decl::ClassTemplateSpecialization: { 407759d1ed5bSDimitry Andric const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 407859d1ed5bSDimitry Andric if (DebugInfo && 407939d628a0SDimitry Andric Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition && 408039d628a0SDimitry Andric Spec->hasDefinition()) 408159d1ed5bSDimitry Andric DebugInfo->completeTemplateDefinition(*Spec); 408239d628a0SDimitry Andric break; 408359d1ed5bSDimitry Andric } 408459d1ed5bSDimitry Andric 4085e7145dcbSDimitry Andric case Decl::OMPDeclareReduction: 4086e7145dcbSDimitry Andric EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 4087e7145dcbSDimitry Andric break; 4088e7145dcbSDimitry Andric 4089f22ef01cSRoman Divacky default: 4090f22ef01cSRoman Divacky // Make sure we handled everything we should, every other kind is a 4091f22ef01cSRoman Divacky // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 4092f22ef01cSRoman Divacky // function. Need to recode Decl::Kind to do that easily. 4093f22ef01cSRoman Divacky assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 409439d628a0SDimitry Andric break; 409539d628a0SDimitry Andric } 409639d628a0SDimitry Andric } 409739d628a0SDimitry Andric 409839d628a0SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 409939d628a0SDimitry Andric // Do we need to generate coverage mapping? 410039d628a0SDimitry Andric if (!CodeGenOpts.CoverageMapping) 410139d628a0SDimitry Andric return; 410239d628a0SDimitry Andric switch (D->getKind()) { 410339d628a0SDimitry Andric case Decl::CXXConversion: 410439d628a0SDimitry Andric case Decl::CXXMethod: 410539d628a0SDimitry Andric case Decl::Function: 410639d628a0SDimitry Andric case Decl::ObjCMethod: 410739d628a0SDimitry Andric case Decl::CXXConstructor: 410839d628a0SDimitry Andric case Decl::CXXDestructor: { 41090623d748SDimitry Andric if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 411039d628a0SDimitry Andric return; 411139d628a0SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 411239d628a0SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 411339d628a0SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = true; 411439d628a0SDimitry Andric break; 411539d628a0SDimitry Andric } 411639d628a0SDimitry Andric default: 411739d628a0SDimitry Andric break; 411839d628a0SDimitry Andric }; 411939d628a0SDimitry Andric } 412039d628a0SDimitry Andric 412139d628a0SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 412239d628a0SDimitry Andric // Do we need to generate coverage mapping? 412339d628a0SDimitry Andric if (!CodeGenOpts.CoverageMapping) 412439d628a0SDimitry Andric return; 412539d628a0SDimitry Andric if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 412639d628a0SDimitry Andric if (Fn->isTemplateInstantiation()) 412739d628a0SDimitry Andric ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 412839d628a0SDimitry Andric } 412939d628a0SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 413039d628a0SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 413139d628a0SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = false; 413239d628a0SDimitry Andric else 413339d628a0SDimitry Andric I->second = false; 413439d628a0SDimitry Andric } 413539d628a0SDimitry Andric 413639d628a0SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 413739d628a0SDimitry Andric std::vector<const Decl *> DeferredDecls; 413833956c43SDimitry Andric for (const auto &I : DeferredEmptyCoverageMappingDecls) { 413939d628a0SDimitry Andric if (!I.second) 414039d628a0SDimitry Andric continue; 414139d628a0SDimitry Andric DeferredDecls.push_back(I.first); 414239d628a0SDimitry Andric } 414339d628a0SDimitry Andric // Sort the declarations by their location to make sure that the tests get a 414439d628a0SDimitry Andric // predictable order for the coverage mapping for the unused declarations. 414539d628a0SDimitry Andric if (CodeGenOpts.DumpCoverageMapping) 414639d628a0SDimitry Andric std::sort(DeferredDecls.begin(), DeferredDecls.end(), 414739d628a0SDimitry Andric [] (const Decl *LHS, const Decl *RHS) { 414839d628a0SDimitry Andric return LHS->getLocStart() < RHS->getLocStart(); 414939d628a0SDimitry Andric }); 415039d628a0SDimitry Andric for (const auto *D : DeferredDecls) { 415139d628a0SDimitry Andric switch (D->getKind()) { 415239d628a0SDimitry Andric case Decl::CXXConversion: 415339d628a0SDimitry Andric case Decl::CXXMethod: 415439d628a0SDimitry Andric case Decl::Function: 415539d628a0SDimitry Andric case Decl::ObjCMethod: { 415639d628a0SDimitry Andric CodeGenPGO PGO(*this); 415739d628a0SDimitry Andric GlobalDecl GD(cast<FunctionDecl>(D)); 415839d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 415939d628a0SDimitry Andric getFunctionLinkage(GD)); 416039d628a0SDimitry Andric break; 416139d628a0SDimitry Andric } 416239d628a0SDimitry Andric case Decl::CXXConstructor: { 416339d628a0SDimitry Andric CodeGenPGO PGO(*this); 416439d628a0SDimitry Andric GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 416539d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 416639d628a0SDimitry Andric getFunctionLinkage(GD)); 416739d628a0SDimitry Andric break; 416839d628a0SDimitry Andric } 416939d628a0SDimitry Andric case Decl::CXXDestructor: { 417039d628a0SDimitry Andric CodeGenPGO PGO(*this); 417139d628a0SDimitry Andric GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 417239d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 417339d628a0SDimitry Andric getFunctionLinkage(GD)); 417439d628a0SDimitry Andric break; 417539d628a0SDimitry Andric } 417639d628a0SDimitry Andric default: 417739d628a0SDimitry Andric break; 417839d628a0SDimitry Andric }; 4179f22ef01cSRoman Divacky } 4180f22ef01cSRoman Divacky } 4181ffd1746dSEd Schouten 4182ffd1746dSEd Schouten /// Turns the given pointer into a constant. 4183ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 4184ffd1746dSEd Schouten const void *Ptr) { 4185ffd1746dSEd Schouten uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 41866122f3e6SDimitry Andric llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 4187ffd1746dSEd Schouten return llvm::ConstantInt::get(i64, PtrInt); 4188ffd1746dSEd Schouten } 4189ffd1746dSEd Schouten 4190ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 4191ffd1746dSEd Schouten llvm::NamedMDNode *&GlobalMetadata, 4192ffd1746dSEd Schouten GlobalDecl D, 4193ffd1746dSEd Schouten llvm::GlobalValue *Addr) { 4194ffd1746dSEd Schouten if (!GlobalMetadata) 4195ffd1746dSEd Schouten GlobalMetadata = 4196ffd1746dSEd Schouten CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 4197ffd1746dSEd Schouten 4198ffd1746dSEd Schouten // TODO: should we report variant information for ctors/dtors? 419939d628a0SDimitry Andric llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 420039d628a0SDimitry Andric llvm::ConstantAsMetadata::get(GetPointerConstant( 420139d628a0SDimitry Andric CGM.getLLVMContext(), D.getDecl()))}; 42023b0f4066SDimitry Andric GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 4203ffd1746dSEd Schouten } 4204ffd1746dSEd Schouten 4205284c1978SDimitry Andric /// For each function which is declared within an extern "C" region and marked 4206284c1978SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled 4207284c1978SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer 4208284c1978SDimitry Andric /// to such functions with an unmangled name from inline assembly within the 4209284c1978SDimitry Andric /// same translation unit. 4210284c1978SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() { 4211e7145dcbSDimitry Andric // Don't do anything if we're generating CUDA device code -- the NVPTX 4212e7145dcbSDimitry Andric // assembly target doesn't support aliases. 4213e7145dcbSDimitry Andric if (Context.getTargetInfo().getTriple().isNVPTX()) 4214e7145dcbSDimitry Andric return; 42158f0fd8f6SDimitry Andric for (auto &I : StaticExternCValues) { 42168f0fd8f6SDimitry Andric IdentifierInfo *Name = I.first; 42178f0fd8f6SDimitry Andric llvm::GlobalValue *Val = I.second; 4218284c1978SDimitry Andric if (Val && !getModule().getNamedValue(Name->getName())) 421959d1ed5bSDimitry Andric addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 4220284c1978SDimitry Andric } 4221284c1978SDimitry Andric } 4222284c1978SDimitry Andric 422359d1ed5bSDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 422459d1ed5bSDimitry Andric GlobalDecl &Result) const { 422559d1ed5bSDimitry Andric auto Res = Manglings.find(MangledName); 422659d1ed5bSDimitry Andric if (Res == Manglings.end()) 422759d1ed5bSDimitry Andric return false; 422859d1ed5bSDimitry Andric Result = Res->getValue(); 422959d1ed5bSDimitry Andric return true; 423059d1ed5bSDimitry Andric } 423159d1ed5bSDimitry Andric 4232ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the 4233ffd1746dSEd Schouten /// current module with the Decls they came from. This is useful for 4234ffd1746dSEd Schouten /// projects using IR gen as a subroutine. 4235ffd1746dSEd Schouten /// 4236ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly 4237ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata 4238ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'. 4239ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() { 424059d1ed5bSDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 4241ffd1746dSEd Schouten 424259d1ed5bSDimitry Andric for (auto &I : MangledDeclNames) { 424359d1ed5bSDimitry Andric llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 42440623d748SDimitry Andric // Some mangled names don't necessarily have an associated GlobalValue 42450623d748SDimitry Andric // in this module, e.g. if we mangled it for DebugInfo. 42460623d748SDimitry Andric if (Addr) 424759d1ed5bSDimitry Andric EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 4248ffd1746dSEd Schouten } 4249ffd1746dSEd Schouten } 4250ffd1746dSEd Schouten 4251ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current 4252ffd1746dSEd Schouten /// function. 4253ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() { 4254ffd1746dSEd Schouten if (LocalDeclMap.empty()) return; 4255ffd1746dSEd Schouten 4256ffd1746dSEd Schouten llvm::LLVMContext &Context = getLLVMContext(); 4257ffd1746dSEd Schouten 4258ffd1746dSEd Schouten // Find the unique metadata ID for this name. 4259ffd1746dSEd Schouten unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 4260ffd1746dSEd Schouten 426159d1ed5bSDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 4262ffd1746dSEd Schouten 426359d1ed5bSDimitry Andric for (auto &I : LocalDeclMap) { 426459d1ed5bSDimitry Andric const Decl *D = I.first; 42650623d748SDimitry Andric llvm::Value *Addr = I.second.getPointer(); 426659d1ed5bSDimitry Andric if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 4267ffd1746dSEd Schouten llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 426839d628a0SDimitry Andric Alloca->setMetadata( 426939d628a0SDimitry Andric DeclPtrKind, llvm::MDNode::get( 427039d628a0SDimitry Andric Context, llvm::ValueAsMetadata::getConstant(DAddr))); 427159d1ed5bSDimitry Andric } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 4272ffd1746dSEd Schouten GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 4273ffd1746dSEd Schouten EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 4274ffd1746dSEd Schouten } 4275ffd1746dSEd Schouten } 4276ffd1746dSEd Schouten } 4277e580952dSDimitry Andric 4278f785676fSDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() { 4279f785676fSDimitry Andric llvm::NamedMDNode *IdentMetadata = 4280f785676fSDimitry Andric TheModule.getOrInsertNamedMetadata("llvm.ident"); 4281f785676fSDimitry Andric std::string Version = getClangFullVersion(); 4282f785676fSDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 4283f785676fSDimitry Andric 428439d628a0SDimitry Andric llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 4285f785676fSDimitry Andric IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 4286f785676fSDimitry Andric } 4287f785676fSDimitry Andric 428859d1ed5bSDimitry Andric void CodeGenModule::EmitTargetMetadata() { 428939d628a0SDimitry Andric // Warning, new MangledDeclNames may be appended within this loop. 429039d628a0SDimitry Andric // We rely on MapVector insertions adding new elements to the end 429139d628a0SDimitry Andric // of the container. 429239d628a0SDimitry Andric // FIXME: Move this loop into the one target that needs it, and only 429339d628a0SDimitry Andric // loop over those declarations for which we couldn't emit the target 429439d628a0SDimitry Andric // metadata when we emitted the declaration. 429539d628a0SDimitry Andric for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 429639d628a0SDimitry Andric auto Val = *(MangledDeclNames.begin() + I); 429739d628a0SDimitry Andric const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 429839d628a0SDimitry Andric llvm::GlobalValue *GV = GetGlobalValue(Val.second); 429959d1ed5bSDimitry Andric getTargetCodeGenInfo().emitTargetMD(D, GV, *this); 430059d1ed5bSDimitry Andric } 430159d1ed5bSDimitry Andric } 430259d1ed5bSDimitry Andric 4303bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() { 430444290647SDimitry Andric if (getCodeGenOpts().CoverageDataFile.empty() && 430544290647SDimitry Andric getCodeGenOpts().CoverageNotesFile.empty()) 430644290647SDimitry Andric return; 430744290647SDimitry Andric 430844290647SDimitry Andric llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); 430944290647SDimitry Andric if (!CUNode) 431044290647SDimitry Andric return; 431144290647SDimitry Andric 4312bd5abe19SDimitry Andric llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 4313bd5abe19SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 431444290647SDimitry Andric auto *CoverageDataFile = 431544290647SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); 431644290647SDimitry Andric auto *CoverageNotesFile = 431744290647SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); 4318bd5abe19SDimitry Andric for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 4319bd5abe19SDimitry Andric llvm::MDNode *CU = CUNode->getOperand(i); 432044290647SDimitry Andric llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; 432139d628a0SDimitry Andric GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 4322bd5abe19SDimitry Andric } 4323bd5abe19SDimitry Andric } 43243861d79fSDimitry Andric 432539d628a0SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) { 43263861d79fSDimitry Andric // Sema has checked that all uuid strings are of the form 43273861d79fSDimitry Andric // "12345678-1234-1234-1234-1234567890ab". 43283861d79fSDimitry Andric assert(Uuid.size() == 36); 4329f785676fSDimitry Andric for (unsigned i = 0; i < 36; ++i) { 4330f785676fSDimitry Andric if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-'); 4331f785676fSDimitry Andric else assert(isHexDigit(Uuid[i])); 43323861d79fSDimitry Andric } 43333861d79fSDimitry Andric 433439d628a0SDimitry Andric // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab". 4335f785676fSDimitry Andric const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 43363861d79fSDimitry Andric 4337f785676fSDimitry Andric llvm::Constant *Field3[8]; 4338f785676fSDimitry Andric for (unsigned Idx = 0; Idx < 8; ++Idx) 4339f785676fSDimitry Andric Field3[Idx] = llvm::ConstantInt::get( 4340f785676fSDimitry Andric Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16); 43413861d79fSDimitry Andric 4342f785676fSDimitry Andric llvm::Constant *Fields[4] = { 4343f785676fSDimitry Andric llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16), 4344f785676fSDimitry Andric llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16), 4345f785676fSDimitry Andric llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16), 4346f785676fSDimitry Andric llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3) 4347f785676fSDimitry Andric }; 4348f785676fSDimitry Andric 4349f785676fSDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 43503861d79fSDimitry Andric } 435159d1ed5bSDimitry Andric 435259d1ed5bSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 435359d1ed5bSDimitry Andric bool ForEH) { 435459d1ed5bSDimitry Andric // Return a bogus pointer if RTTI is disabled, unless it's for EH. 435559d1ed5bSDimitry Andric // FIXME: should we even be calling this method if RTTI is disabled 435659d1ed5bSDimitry Andric // and it's not for EH? 435759d1ed5bSDimitry Andric if (!ForEH && !getLangOpts().RTTI) 435859d1ed5bSDimitry Andric return llvm::Constant::getNullValue(Int8PtrTy); 435959d1ed5bSDimitry Andric 436059d1ed5bSDimitry Andric if (ForEH && Ty->isObjCObjectPointerType() && 436159d1ed5bSDimitry Andric LangOpts.ObjCRuntime.isGNUFamily()) 436259d1ed5bSDimitry Andric return ObjCRuntime->GetEHType(Ty); 436359d1ed5bSDimitry Andric 436459d1ed5bSDimitry Andric return getCXXABI().getAddrOfRTTIDescriptor(Ty); 436559d1ed5bSDimitry Andric } 436659d1ed5bSDimitry Andric 436739d628a0SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 436839d628a0SDimitry Andric for (auto RefExpr : D->varlists()) { 436939d628a0SDimitry Andric auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 437039d628a0SDimitry Andric bool PerformInit = 437139d628a0SDimitry Andric VD->getAnyInitializer() && 437239d628a0SDimitry Andric !VD->getAnyInitializer()->isConstantInitializer(getContext(), 437339d628a0SDimitry Andric /*ForRef=*/false); 43740623d748SDimitry Andric 43750623d748SDimitry Andric Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD)); 437633956c43SDimitry Andric if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 43770623d748SDimitry Andric VD, Addr, RefExpr->getLocStart(), PerformInit)) 437839d628a0SDimitry Andric CXXGlobalInits.push_back(InitFunction); 437939d628a0SDimitry Andric } 438039d628a0SDimitry Andric } 43818f0fd8f6SDimitry Andric 43820623d748SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 43830623d748SDimitry Andric llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()]; 43840623d748SDimitry Andric if (InternalId) 43850623d748SDimitry Andric return InternalId; 43860623d748SDimitry Andric 43870623d748SDimitry Andric if (isExternallyVisible(T->getLinkage())) { 43888f0fd8f6SDimitry Andric std::string OutName; 43898f0fd8f6SDimitry Andric llvm::raw_string_ostream Out(OutName); 43900623d748SDimitry Andric getCXXABI().getMangleContext().mangleTypeName(T, Out); 43918f0fd8f6SDimitry Andric 43920623d748SDimitry Andric InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 43930623d748SDimitry Andric } else { 43940623d748SDimitry Andric InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 43950623d748SDimitry Andric llvm::ArrayRef<llvm::Metadata *>()); 43960623d748SDimitry Andric } 43970623d748SDimitry Andric 43980623d748SDimitry Andric return InternalId; 43990623d748SDimitry Andric } 44000623d748SDimitry Andric 4401e7145dcbSDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier. 4402e7145dcbSDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const { 4403e7145dcbSDimitry Andric // Returns true if at least one of vtable-based CFI checkers is enabled and 4404e7145dcbSDimitry Andric // is not in the trapping mode. 4405e7145dcbSDimitry Andric return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 4406e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 4407e7145dcbSDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 4408e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 4409e7145dcbSDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 4410e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 4411e7145dcbSDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 4412e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 4413e7145dcbSDimitry Andric } 4414e7145dcbSDimitry Andric 4415e7145dcbSDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 44160623d748SDimitry Andric CharUnits Offset, 44170623d748SDimitry Andric const CXXRecordDecl *RD) { 44180623d748SDimitry Andric llvm::Metadata *MD = 44190623d748SDimitry Andric CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 4420e7145dcbSDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), MD); 44210623d748SDimitry Andric 4422e7145dcbSDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 4423e7145dcbSDimitry Andric if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 4424e7145dcbSDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), 4425e7145dcbSDimitry Andric llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 4426e7145dcbSDimitry Andric 4427e7145dcbSDimitry Andric if (NeedAllVtablesTypeId()) { 4428e7145dcbSDimitry Andric llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 4429e7145dcbSDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), MD); 44300623d748SDimitry Andric } 44310623d748SDimitry Andric } 44320623d748SDimitry Andric 44330623d748SDimitry Andric // Fills in the supplied string map with the set of target features for the 44340623d748SDimitry Andric // passed in function. 44350623d748SDimitry Andric void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 44360623d748SDimitry Andric const FunctionDecl *FD) { 44370623d748SDimitry Andric StringRef TargetCPU = Target.getTargetOpts().CPU; 44380623d748SDimitry Andric if (const auto *TD = FD->getAttr<TargetAttr>()) { 44390623d748SDimitry Andric // If we have a TargetAttr build up the feature map based on that. 44400623d748SDimitry Andric TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse(); 44410623d748SDimitry Andric 44420623d748SDimitry Andric // Make a copy of the features as passed on the command line into the 44430623d748SDimitry Andric // beginning of the additional features from the function to override. 44440623d748SDimitry Andric ParsedAttr.first.insert(ParsedAttr.first.begin(), 44450623d748SDimitry Andric Target.getTargetOpts().FeaturesAsWritten.begin(), 44460623d748SDimitry Andric Target.getTargetOpts().FeaturesAsWritten.end()); 44470623d748SDimitry Andric 44480623d748SDimitry Andric if (ParsedAttr.second != "") 44490623d748SDimitry Andric TargetCPU = ParsedAttr.second; 44500623d748SDimitry Andric 44510623d748SDimitry Andric // Now populate the feature map, first with the TargetCPU which is either 44520623d748SDimitry Andric // the default or a new one from the target attribute string. Then we'll use 44530623d748SDimitry Andric // the passed in features (FeaturesAsWritten) along with the new ones from 44540623d748SDimitry Andric // the attribute. 44550623d748SDimitry Andric Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first); 44560623d748SDimitry Andric } else { 44570623d748SDimitry Andric Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, 44580623d748SDimitry Andric Target.getTargetOpts().Features); 44590623d748SDimitry Andric } 44608f0fd8f6SDimitry Andric } 4461e7145dcbSDimitry Andric 4462e7145dcbSDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 4463e7145dcbSDimitry Andric if (!SanStats) 4464e7145dcbSDimitry Andric SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule()); 4465e7145dcbSDimitry Andric 4466e7145dcbSDimitry Andric return *SanStats; 4467e7145dcbSDimitry Andric } 446844290647SDimitry Andric llvm::Value * 446944290647SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, 447044290647SDimitry Andric CodeGenFunction &CGF) { 447144290647SDimitry Andric llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF); 447244290647SDimitry Andric auto SamplerT = getOpenCLRuntime().getSamplerType(); 447344290647SDimitry Andric auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); 447444290647SDimitry Andric return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy, 447544290647SDimitry Andric "__translate_sampler_initializer"), 447644290647SDimitry Andric {C}); 447744290647SDimitry Andric } 4478