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" 23139f7f9bSDimitry Andric #include "CodeGenFunction.h" 2459d1ed5bSDimitry Andric #include "CodeGenPGO.h" 25139f7f9bSDimitry Andric #include "CodeGenTBAA.h" 2639d628a0SDimitry Andric #include "CoverageMappingGen.h" 27f22ef01cSRoman Divacky #include "TargetInfo.h" 28f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h" 29f22ef01cSRoman Divacky #include "clang/AST/CharUnits.h" 30f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h" 31139f7f9bSDimitry Andric #include "clang/AST/DeclObjC.h" 32ffd1746dSEd Schouten #include "clang/AST/DeclTemplate.h" 332754fe60SDimitry Andric #include "clang/AST/Mangle.h" 34f22ef01cSRoman Divacky #include "clang/AST/RecordLayout.h" 35f8254f43SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h" 36dff0c46cSDimitry Andric #include "clang/Basic/Builtins.h" 37139f7f9bSDimitry Andric #include "clang/Basic/CharInfo.h" 38f22ef01cSRoman Divacky #include "clang/Basic/Diagnostic.h" 39139f7f9bSDimitry Andric #include "clang/Basic/Module.h" 40f22ef01cSRoman Divacky #include "clang/Basic/SourceManager.h" 41f22ef01cSRoman Divacky #include "clang/Basic/TargetInfo.h" 42f785676fSDimitry Andric #include "clang/Basic/Version.h" 43139f7f9bSDimitry Andric #include "clang/Frontend/CodeGenOptions.h" 44f785676fSDimitry Andric #include "clang/Sema/SemaDiagnostic.h" 45dff0c46cSDimitry Andric #include "llvm/ADT/APSInt.h" 46f22ef01cSRoman Divacky #include "llvm/ADT/Triple.h" 4759d1ed5bSDimitry Andric #include "llvm/IR/CallSite.h" 48139f7f9bSDimitry Andric #include "llvm/IR/CallingConv.h" 49139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h" 50139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h" 51139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h" 52139f7f9bSDimitry Andric #include "llvm/IR/Module.h" 5359d1ed5bSDimitry Andric #include "llvm/ProfileData/InstrProfReader.h" 54139f7f9bSDimitry Andric #include "llvm/Support/ConvertUTF.h" 55f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h" 560623d748SDimitry Andric #include "llvm/Support/MD5.h" 57139f7f9bSDimitry Andric 58f22ef01cSRoman Divacky using namespace clang; 59f22ef01cSRoman Divacky using namespace CodeGen; 60f22ef01cSRoman Divacky 616122f3e6SDimitry Andric static const char AnnotationSection[] = "llvm.metadata"; 626122f3e6SDimitry Andric 6359d1ed5bSDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) { 64284c1978SDimitry Andric switch (CGM.getTarget().getCXXABI().getKind()) { 65139f7f9bSDimitry Andric case TargetCXXABI::GenericAArch64: 66139f7f9bSDimitry Andric case TargetCXXABI::GenericARM: 67139f7f9bSDimitry Andric case TargetCXXABI::iOS: 6859d1ed5bSDimitry Andric case TargetCXXABI::iOS64: 690623d748SDimitry Andric case TargetCXXABI::WatchOS: 70ef6fa9e2SDimitry Andric case TargetCXXABI::GenericMIPS: 71139f7f9bSDimitry Andric case TargetCXXABI::GenericItanium: 720623d748SDimitry Andric case TargetCXXABI::WebAssembly: 7359d1ed5bSDimitry Andric return CreateItaniumCXXABI(CGM); 74139f7f9bSDimitry Andric case TargetCXXABI::Microsoft: 7559d1ed5bSDimitry Andric return CreateMicrosoftCXXABI(CGM); 76e580952dSDimitry Andric } 77e580952dSDimitry Andric 78e580952dSDimitry Andric llvm_unreachable("invalid C++ ABI kind"); 79e580952dSDimitry Andric } 80e580952dSDimitry Andric 813dac3a9bSDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO, 823dac3a9bSDimitry Andric const PreprocessorOptions &PPO, 833dac3a9bSDimitry Andric const CodeGenOptions &CGO, llvm::Module &M, 8439d628a0SDimitry Andric DiagnosticsEngine &diags, 8539d628a0SDimitry Andric CoverageSourceInfo *CoverageInfo) 863dac3a9bSDimitry Andric : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO), 873dac3a9bSDimitry Andric PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags), 880623d748SDimitry Andric Target(C.getTargetInfo()), ABI(createCXXABI(*this)), 893dac3a9bSDimitry Andric VMContext(M.getContext()), TBAA(nullptr), TheTargetCodeGenInfo(nullptr), 903dac3a9bSDimitry Andric Types(*this), VTables(*this), ObjCRuntime(nullptr), 913dac3a9bSDimitry Andric OpenCLRuntime(nullptr), OpenMPRuntime(nullptr), CUDARuntime(nullptr), 920623d748SDimitry Andric DebugInfo(nullptr), ObjCData(nullptr), 930623d748SDimitry Andric NoObjCARCExceptionsMetadata(nullptr), PGOReader(nullptr), 9459d1ed5bSDimitry Andric CFConstantStringClassRef(nullptr), ConstantStringClassRef(nullptr), 9559d1ed5bSDimitry Andric NSConstantStringType(nullptr), NSConcreteGlobalBlock(nullptr), 9659d1ed5bSDimitry Andric NSConcreteStackBlock(nullptr), BlockObjectAssign(nullptr), 9759d1ed5bSDimitry Andric BlockObjectDispose(nullptr), BlockDescriptorType(nullptr), 9859d1ed5bSDimitry Andric GenericBlockLiteralType(nullptr), LifetimeStartFn(nullptr), 9939d628a0SDimitry Andric LifetimeEndFn(nullptr), SanitizerMD(new SanitizerMetadata(*this)) { 100dff0c46cSDimitry Andric 101dff0c46cSDimitry Andric // Initialize the type cache. 102dff0c46cSDimitry Andric llvm::LLVMContext &LLVMContext = M.getContext(); 103dff0c46cSDimitry Andric VoidTy = llvm::Type::getVoidTy(LLVMContext); 104dff0c46cSDimitry Andric Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 105dff0c46cSDimitry Andric Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 106dff0c46cSDimitry Andric Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 107dff0c46cSDimitry Andric Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 108dff0c46cSDimitry Andric FloatTy = llvm::Type::getFloatTy(LLVMContext); 109dff0c46cSDimitry Andric DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 110dff0c46cSDimitry Andric PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 111dff0c46cSDimitry Andric PointerAlignInBytes = 112dff0c46cSDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 1130623d748SDimitry Andric IntAlignInBytes = 1140623d748SDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity(); 115dff0c46cSDimitry Andric IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 116dff0c46cSDimitry Andric IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits); 117dff0c46cSDimitry Andric Int8PtrTy = Int8Ty->getPointerTo(0); 118dff0c46cSDimitry Andric Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 119dff0c46cSDimitry Andric 120139f7f9bSDimitry Andric RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 12139d628a0SDimitry Andric BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC(); 122139f7f9bSDimitry Andric 123dff0c46cSDimitry Andric if (LangOpts.ObjC1) 1243b0f4066SDimitry Andric createObjCRuntime(); 125dff0c46cSDimitry Andric if (LangOpts.OpenCL) 1266122f3e6SDimitry Andric createOpenCLRuntime(); 12759d1ed5bSDimitry Andric if (LangOpts.OpenMP) 12859d1ed5bSDimitry Andric createOpenMPRuntime(); 129dff0c46cSDimitry Andric if (LangOpts.CUDA) 1306122f3e6SDimitry Andric createCUDARuntime(); 131f22ef01cSRoman Divacky 1327ae0e2c9SDimitry Andric // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 13339d628a0SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::Thread) || 1347ae0e2c9SDimitry Andric (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 1357ae0e2c9SDimitry Andric TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(), 13659d1ed5bSDimitry Andric getCXXABI().getMangleContext()); 1372754fe60SDimitry Andric 1383b0f4066SDimitry Andric // If debug info or coverage generation is enabled, create the CGDebugInfo 1393b0f4066SDimitry Andric // object. 1403861d79fSDimitry Andric if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo || 1417ae0e2c9SDimitry Andric CodeGenOpts.EmitGcovArcs || 1423b0f4066SDimitry Andric CodeGenOpts.EmitGcovNotes) 1433b0f4066SDimitry Andric DebugInfo = new CGDebugInfo(*this); 1442754fe60SDimitry Andric 1452754fe60SDimitry Andric Block.GlobalUniqueCount = 0; 1462754fe60SDimitry Andric 1470623d748SDimitry Andric if (C.getLangOpts().ObjC1) 1480623d748SDimitry Andric ObjCData = new ObjCEntrypoints(); 14959d1ed5bSDimitry Andric 15059d1ed5bSDimitry Andric if (!CodeGenOpts.InstrProfileInput.empty()) { 15133956c43SDimitry Andric auto ReaderOrErr = 15233956c43SDimitry Andric llvm::IndexedInstrProfReader::create(CodeGenOpts.InstrProfileInput); 15333956c43SDimitry Andric if (std::error_code EC = ReaderOrErr.getError()) { 15459d1ed5bSDimitry Andric unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 1553dac3a9bSDimitry Andric "Could not read profile %0: %1"); 1563dac3a9bSDimitry Andric getDiags().Report(DiagID) << CodeGenOpts.InstrProfileInput 1573dac3a9bSDimitry Andric << EC.message(); 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 168f22ef01cSRoman Divacky CodeGenModule::~CodeGenModule() { 1696122f3e6SDimitry Andric delete ObjCRuntime; 1706122f3e6SDimitry Andric delete OpenCLRuntime; 17159d1ed5bSDimitry Andric delete OpenMPRuntime; 1726122f3e6SDimitry Andric delete CUDARuntime; 1736122f3e6SDimitry Andric delete TheTargetCodeGenInfo; 1742754fe60SDimitry Andric delete TBAA; 175f22ef01cSRoman Divacky delete DebugInfo; 1760623d748SDimitry Andric delete ObjCData; 177f22ef01cSRoman Divacky } 178f22ef01cSRoman Divacky 179f22ef01cSRoman Divacky void CodeGenModule::createObjCRuntime() { 1807ae0e2c9SDimitry Andric // This is just isGNUFamily(), but we want to force implementors of 1817ae0e2c9SDimitry Andric // new ABIs to decide how best to do this. 1827ae0e2c9SDimitry Andric switch (LangOpts.ObjCRuntime.getKind()) { 1837ae0e2c9SDimitry Andric case ObjCRuntime::GNUstep: 1847ae0e2c9SDimitry Andric case ObjCRuntime::GCC: 1857ae0e2c9SDimitry Andric case ObjCRuntime::ObjFW: 1866122f3e6SDimitry Andric ObjCRuntime = CreateGNUObjCRuntime(*this); 1877ae0e2c9SDimitry Andric return; 1887ae0e2c9SDimitry Andric 1897ae0e2c9SDimitry Andric case ObjCRuntime::FragileMacOSX: 1907ae0e2c9SDimitry Andric case ObjCRuntime::MacOSX: 1917ae0e2c9SDimitry Andric case ObjCRuntime::iOS: 1920623d748SDimitry Andric case ObjCRuntime::WatchOS: 1936122f3e6SDimitry Andric ObjCRuntime = CreateMacObjCRuntime(*this); 1947ae0e2c9SDimitry Andric return; 1957ae0e2c9SDimitry Andric } 1967ae0e2c9SDimitry Andric llvm_unreachable("bad runtime kind"); 1976122f3e6SDimitry Andric } 1986122f3e6SDimitry Andric 1996122f3e6SDimitry Andric void CodeGenModule::createOpenCLRuntime() { 2006122f3e6SDimitry Andric OpenCLRuntime = new CGOpenCLRuntime(*this); 2016122f3e6SDimitry Andric } 2026122f3e6SDimitry Andric 20359d1ed5bSDimitry Andric void CodeGenModule::createOpenMPRuntime() { 20459d1ed5bSDimitry Andric OpenMPRuntime = new CGOpenMPRuntime(*this); 20559d1ed5bSDimitry Andric } 20659d1ed5bSDimitry Andric 2076122f3e6SDimitry Andric void CodeGenModule::createCUDARuntime() { 2086122f3e6SDimitry Andric CUDARuntime = CreateNVCUDARuntime(*this); 209f22ef01cSRoman Divacky } 210f22ef01cSRoman Divacky 21139d628a0SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { 21239d628a0SDimitry Andric Replacements[Name] = C; 21339d628a0SDimitry Andric } 21439d628a0SDimitry Andric 215f785676fSDimitry Andric void CodeGenModule::applyReplacements() { 2168f0fd8f6SDimitry Andric for (auto &I : Replacements) { 2178f0fd8f6SDimitry Andric StringRef MangledName = I.first(); 2188f0fd8f6SDimitry Andric llvm::Constant *Replacement = I.second; 219f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 220f785676fSDimitry Andric if (!Entry) 221f785676fSDimitry Andric continue; 22259d1ed5bSDimitry Andric auto *OldF = cast<llvm::Function>(Entry); 22359d1ed5bSDimitry Andric auto *NewF = dyn_cast<llvm::Function>(Replacement); 224f785676fSDimitry Andric if (!NewF) { 22559d1ed5bSDimitry Andric if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 22659d1ed5bSDimitry Andric NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 22759d1ed5bSDimitry Andric } else { 22859d1ed5bSDimitry Andric auto *CE = cast<llvm::ConstantExpr>(Replacement); 229f785676fSDimitry Andric assert(CE->getOpcode() == llvm::Instruction::BitCast || 230f785676fSDimitry Andric CE->getOpcode() == llvm::Instruction::GetElementPtr); 231f785676fSDimitry Andric NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 232f785676fSDimitry Andric } 23359d1ed5bSDimitry Andric } 234f785676fSDimitry Andric 235f785676fSDimitry Andric // Replace old with new, but keep the old order. 236f785676fSDimitry Andric OldF->replaceAllUsesWith(Replacement); 237f785676fSDimitry Andric if (NewF) { 238f785676fSDimitry Andric NewF->removeFromParent(); 2390623d748SDimitry Andric OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(), 2400623d748SDimitry Andric NewF); 241f785676fSDimitry Andric } 242f785676fSDimitry Andric OldF->eraseFromParent(); 243f785676fSDimitry Andric } 244f785676fSDimitry Andric } 245f785676fSDimitry Andric 2460623d748SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { 2470623d748SDimitry Andric GlobalValReplacements.push_back(std::make_pair(GV, C)); 2480623d748SDimitry Andric } 2490623d748SDimitry Andric 2500623d748SDimitry Andric void CodeGenModule::applyGlobalValReplacements() { 2510623d748SDimitry Andric for (auto &I : GlobalValReplacements) { 2520623d748SDimitry Andric llvm::GlobalValue *GV = I.first; 2530623d748SDimitry Andric llvm::Constant *C = I.second; 2540623d748SDimitry Andric 2550623d748SDimitry Andric GV->replaceAllUsesWith(C); 2560623d748SDimitry Andric GV->eraseFromParent(); 2570623d748SDimitry Andric } 2580623d748SDimitry Andric } 2590623d748SDimitry Andric 26059d1ed5bSDimitry Andric // This is only used in aliases that we created and we know they have a 26159d1ed5bSDimitry Andric // linear structure. 26259d1ed5bSDimitry Andric static const llvm::GlobalObject *getAliasedGlobal(const llvm::GlobalAlias &GA) { 26359d1ed5bSDimitry Andric llvm::SmallPtrSet<const llvm::GlobalAlias*, 4> Visited; 26459d1ed5bSDimitry Andric const llvm::Constant *C = &GA; 26559d1ed5bSDimitry Andric for (;;) { 26659d1ed5bSDimitry Andric C = C->stripPointerCasts(); 26759d1ed5bSDimitry Andric if (auto *GO = dyn_cast<llvm::GlobalObject>(C)) 26859d1ed5bSDimitry Andric return GO; 26959d1ed5bSDimitry Andric // stripPointerCasts will not walk over weak aliases. 27059d1ed5bSDimitry Andric auto *GA2 = dyn_cast<llvm::GlobalAlias>(C); 27159d1ed5bSDimitry Andric if (!GA2) 27259d1ed5bSDimitry Andric return nullptr; 27339d628a0SDimitry Andric if (!Visited.insert(GA2).second) 27459d1ed5bSDimitry Andric return nullptr; 27559d1ed5bSDimitry Andric C = GA2->getAliasee(); 27659d1ed5bSDimitry Andric } 27759d1ed5bSDimitry Andric } 27859d1ed5bSDimitry Andric 279f785676fSDimitry Andric void CodeGenModule::checkAliases() { 28059d1ed5bSDimitry Andric // Check if the constructed aliases are well formed. It is really unfortunate 28159d1ed5bSDimitry Andric // that we have to do this in CodeGen, but we only construct mangled names 28259d1ed5bSDimitry Andric // and aliases during codegen. 283f785676fSDimitry Andric bool Error = false; 28459d1ed5bSDimitry Andric DiagnosticsEngine &Diags = getDiags(); 2858f0fd8f6SDimitry Andric for (const GlobalDecl &GD : Aliases) { 28659d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 287f785676fSDimitry Andric const AliasAttr *AA = D->getAttr<AliasAttr>(); 288f785676fSDimitry Andric StringRef MangledName = getMangledName(GD); 289f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 29059d1ed5bSDimitry Andric auto *Alias = cast<llvm::GlobalAlias>(Entry); 29159d1ed5bSDimitry Andric const llvm::GlobalValue *GV = getAliasedGlobal(*Alias); 29259d1ed5bSDimitry Andric if (!GV) { 293f785676fSDimitry Andric Error = true; 29459d1ed5bSDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias); 29559d1ed5bSDimitry Andric } else if (GV->isDeclaration()) { 296f785676fSDimitry Andric Error = true; 29759d1ed5bSDimitry Andric Diags.Report(AA->getLocation(), diag::err_alias_to_undefined); 29859d1ed5bSDimitry Andric } 29959d1ed5bSDimitry Andric 30059d1ed5bSDimitry Andric llvm::Constant *Aliasee = Alias->getAliasee(); 30159d1ed5bSDimitry Andric llvm::GlobalValue *AliaseeGV; 30259d1ed5bSDimitry Andric if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 30359d1ed5bSDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 30459d1ed5bSDimitry Andric else 30559d1ed5bSDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 30659d1ed5bSDimitry Andric 30759d1ed5bSDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 30859d1ed5bSDimitry Andric StringRef AliasSection = SA->getName(); 30959d1ed5bSDimitry Andric if (AliasSection != AliaseeGV->getSection()) 31059d1ed5bSDimitry Andric Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 31159d1ed5bSDimitry Andric << AliasSection; 31259d1ed5bSDimitry Andric } 31359d1ed5bSDimitry Andric 31459d1ed5bSDimitry Andric // We have to handle alias to weak aliases in here. LLVM itself disallows 31559d1ed5bSDimitry Andric // this since the object semantics would not match the IL one. For 31659d1ed5bSDimitry Andric // compatibility with gcc we implement it by just pointing the alias 31759d1ed5bSDimitry Andric // to its aliasee's aliasee. We also warn, since the user is probably 31859d1ed5bSDimitry Andric // expecting the link to be weak. 31959d1ed5bSDimitry Andric if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) { 32059d1ed5bSDimitry Andric if (GA->mayBeOverridden()) { 32159d1ed5bSDimitry Andric Diags.Report(AA->getLocation(), diag::warn_alias_to_weak_alias) 32259d1ed5bSDimitry Andric << GV->getName() << GA->getName(); 32359d1ed5bSDimitry Andric Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 32459d1ed5bSDimitry Andric GA->getAliasee(), Alias->getType()); 32559d1ed5bSDimitry Andric Alias->setAliasee(Aliasee); 32659d1ed5bSDimitry Andric } 327f785676fSDimitry Andric } 328f785676fSDimitry Andric } 329f785676fSDimitry Andric if (!Error) 330f785676fSDimitry Andric return; 331f785676fSDimitry Andric 3328f0fd8f6SDimitry Andric for (const GlobalDecl &GD : Aliases) { 333f785676fSDimitry Andric StringRef MangledName = getMangledName(GD); 334f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 33559d1ed5bSDimitry Andric auto *Alias = cast<llvm::GlobalAlias>(Entry); 336f785676fSDimitry Andric Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 337f785676fSDimitry Andric Alias->eraseFromParent(); 338f785676fSDimitry Andric } 339f785676fSDimitry Andric } 340f785676fSDimitry Andric 34159d1ed5bSDimitry Andric void CodeGenModule::clear() { 34259d1ed5bSDimitry Andric DeferredDeclsToEmit.clear(); 34333956c43SDimitry Andric if (OpenMPRuntime) 34433956c43SDimitry Andric OpenMPRuntime->clear(); 34559d1ed5bSDimitry Andric } 34659d1ed5bSDimitry Andric 34759d1ed5bSDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 34859d1ed5bSDimitry Andric StringRef MainFile) { 34959d1ed5bSDimitry Andric if (!hasDiagnostics()) 35059d1ed5bSDimitry Andric return; 35159d1ed5bSDimitry Andric if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 35259d1ed5bSDimitry Andric if (MainFile.empty()) 35359d1ed5bSDimitry Andric MainFile = "<stdin>"; 35459d1ed5bSDimitry Andric Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 35559d1ed5bSDimitry Andric } else 35659d1ed5bSDimitry Andric Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing 35759d1ed5bSDimitry Andric << Mismatched; 35859d1ed5bSDimitry Andric } 35959d1ed5bSDimitry Andric 360f22ef01cSRoman Divacky void CodeGenModule::Release() { 361f22ef01cSRoman Divacky EmitDeferred(); 3620623d748SDimitry Andric applyGlobalValReplacements(); 363f785676fSDimitry Andric applyReplacements(); 364f785676fSDimitry Andric checkAliases(); 365f22ef01cSRoman Divacky EmitCXXGlobalInitFunc(); 366f22ef01cSRoman Divacky EmitCXXGlobalDtorFunc(); 367284c1978SDimitry Andric EmitCXXThreadLocalInitFunc(); 3686122f3e6SDimitry Andric if (ObjCRuntime) 3696122f3e6SDimitry Andric if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 370f22ef01cSRoman Divacky AddGlobalCtor(ObjCInitFunction); 37133956c43SDimitry Andric if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice && 37233956c43SDimitry Andric CUDARuntime) { 37333956c43SDimitry Andric if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction()) 37433956c43SDimitry Andric AddGlobalCtor(CudaCtorFunction); 37533956c43SDimitry Andric if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction()) 37633956c43SDimitry Andric AddGlobalDtor(CudaDtorFunction); 37733956c43SDimitry Andric } 378ea942507SDimitry Andric if (OpenMPRuntime) 379ea942507SDimitry Andric if (llvm::Function *OpenMPRegistrationFunction = 380ea942507SDimitry Andric OpenMPRuntime->emitRegistrationFunction()) 381ea942507SDimitry Andric AddGlobalCtor(OpenMPRegistrationFunction, 0); 3820623d748SDimitry Andric if (PGOReader) { 3830623d748SDimitry Andric getModule().setMaximumFunctionCount(PGOReader->getMaximumFunctionCount()); 3840623d748SDimitry Andric if (PGOStats.hasDiagnostics()) 38559d1ed5bSDimitry Andric PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 3860623d748SDimitry Andric } 387f22ef01cSRoman Divacky EmitCtorList(GlobalCtors, "llvm.global_ctors"); 388f22ef01cSRoman Divacky EmitCtorList(GlobalDtors, "llvm.global_dtors"); 3896122f3e6SDimitry Andric EmitGlobalAnnotations(); 390284c1978SDimitry Andric EmitStaticExternCAliases(); 39139d628a0SDimitry Andric EmitDeferredUnusedCoverageMappings(); 39239d628a0SDimitry Andric if (CoverageMapping) 39339d628a0SDimitry Andric CoverageMapping->emit(); 39459d1ed5bSDimitry Andric emitLLVMUsed(); 395ffd1746dSEd Schouten 396f785676fSDimitry Andric if (CodeGenOpts.Autolink && 397f785676fSDimitry Andric (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 398139f7f9bSDimitry Andric EmitModuleLinkOptions(); 399139f7f9bSDimitry Andric } 4000623d748SDimitry Andric if (CodeGenOpts.DwarfVersion) { 401f785676fSDimitry Andric // We actually want the latest version when there are conflicts. 402f785676fSDimitry Andric // We can change from Warning to Latest if such mode is supported. 403f785676fSDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version", 404f785676fSDimitry Andric CodeGenOpts.DwarfVersion); 4050623d748SDimitry Andric } 4060623d748SDimitry Andric if (CodeGenOpts.EmitCodeView) { 4070623d748SDimitry Andric // Indicate that we want CodeView in the metadata. 4080623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); 4090623d748SDimitry Andric } 4100623d748SDimitry Andric if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { 4110623d748SDimitry Andric // We don't support LTO with 2 with different StrictVTablePointers 4120623d748SDimitry Andric // FIXME: we could support it by stripping all the information introduced 4130623d748SDimitry Andric // by StrictVTablePointers. 4140623d748SDimitry Andric 4150623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); 4160623d748SDimitry Andric 4170623d748SDimitry Andric llvm::Metadata *Ops[2] = { 4180623d748SDimitry Andric llvm::MDString::get(VMContext, "StrictVTablePointers"), 4190623d748SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 4200623d748SDimitry Andric llvm::Type::getInt32Ty(VMContext), 1))}; 4210623d748SDimitry Andric 4220623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Require, 4230623d748SDimitry Andric "StrictVTablePointersRequirement", 4240623d748SDimitry Andric llvm::MDNode::get(VMContext, Ops)); 4250623d748SDimitry Andric } 426f785676fSDimitry Andric if (DebugInfo) 42759d1ed5bSDimitry Andric // We support a single version in the linked module. The LLVM 42859d1ed5bSDimitry Andric // parser will drop debug info with a different version number 42959d1ed5bSDimitry Andric // (and warn about it, too). 43059d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 431f785676fSDimitry Andric llvm::DEBUG_METADATA_VERSION); 432139f7f9bSDimitry Andric 43359d1ed5bSDimitry Andric // We need to record the widths of enums and wchar_t, so that we can generate 43459d1ed5bSDimitry Andric // the correct build attributes in the ARM backend. 43559d1ed5bSDimitry Andric llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 43659d1ed5bSDimitry Andric if ( Arch == llvm::Triple::arm 43759d1ed5bSDimitry Andric || Arch == llvm::Triple::armeb 43859d1ed5bSDimitry Andric || Arch == llvm::Triple::thumb 43959d1ed5bSDimitry Andric || Arch == llvm::Triple::thumbeb) { 44059d1ed5bSDimitry Andric // Width of wchar_t in bytes 44159d1ed5bSDimitry Andric uint64_t WCharWidth = 44259d1ed5bSDimitry Andric Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 44359d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 44459d1ed5bSDimitry Andric 44559d1ed5bSDimitry Andric // The minimum width of an enum in bytes 44659d1ed5bSDimitry Andric uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 44759d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 44859d1ed5bSDimitry Andric } 44959d1ed5bSDimitry Andric 4500623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 4510623d748SDimitry Andric // Indicate that we want cross-DSO control flow integrity checks. 4520623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); 4530623d748SDimitry Andric } 4540623d748SDimitry Andric 45539d628a0SDimitry Andric if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 45639d628a0SDimitry Andric llvm::PICLevel::Level PL = llvm::PICLevel::Default; 45739d628a0SDimitry Andric switch (PLevel) { 45839d628a0SDimitry Andric case 0: break; 45939d628a0SDimitry Andric case 1: PL = llvm::PICLevel::Small; break; 46039d628a0SDimitry Andric case 2: PL = llvm::PICLevel::Large; break; 46139d628a0SDimitry Andric default: llvm_unreachable("Invalid PIC Level"); 46239d628a0SDimitry Andric } 46339d628a0SDimitry Andric 46439d628a0SDimitry Andric getModule().setPICLevel(PL); 46539d628a0SDimitry Andric } 46639d628a0SDimitry Andric 4672754fe60SDimitry Andric SimplifyPersonality(); 4682754fe60SDimitry Andric 469ffd1746dSEd Schouten if (getCodeGenOpts().EmitDeclMetadata) 470ffd1746dSEd Schouten EmitDeclMetadata(); 471bd5abe19SDimitry Andric 472bd5abe19SDimitry Andric if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 473bd5abe19SDimitry Andric EmitCoverageFile(); 4746122f3e6SDimitry Andric 4756122f3e6SDimitry Andric if (DebugInfo) 4766122f3e6SDimitry Andric DebugInfo->finalize(); 477f785676fSDimitry Andric 478f785676fSDimitry Andric EmitVersionIdentMetadata(); 47959d1ed5bSDimitry Andric 48059d1ed5bSDimitry Andric EmitTargetMetadata(); 481f22ef01cSRoman Divacky } 482f22ef01cSRoman Divacky 4833b0f4066SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 4843b0f4066SDimitry Andric // Make sure that this type is translated. 4853b0f4066SDimitry Andric Types.UpdateCompletedType(TD); 4863b0f4066SDimitry Andric } 4873b0f4066SDimitry Andric 4882754fe60SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 4892754fe60SDimitry Andric if (!TBAA) 49059d1ed5bSDimitry Andric return nullptr; 4912754fe60SDimitry Andric return TBAA->getTBAAInfo(QTy); 4922754fe60SDimitry Andric } 4932754fe60SDimitry Andric 494dff0c46cSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() { 495dff0c46cSDimitry Andric if (!TBAA) 49659d1ed5bSDimitry Andric return nullptr; 497dff0c46cSDimitry Andric return TBAA->getTBAAInfoForVTablePtr(); 498dff0c46cSDimitry Andric } 499dff0c46cSDimitry Andric 5003861d79fSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 5013861d79fSDimitry Andric if (!TBAA) 50259d1ed5bSDimitry Andric return nullptr; 5033861d79fSDimitry Andric return TBAA->getTBAAStructInfo(QTy); 5043861d79fSDimitry Andric } 5053861d79fSDimitry Andric 506139f7f9bSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy, 507139f7f9bSDimitry Andric llvm::MDNode *AccessN, 508139f7f9bSDimitry Andric uint64_t O) { 509139f7f9bSDimitry Andric if (!TBAA) 51059d1ed5bSDimitry Andric return nullptr; 511139f7f9bSDimitry Andric return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O); 512139f7f9bSDimitry Andric } 513139f7f9bSDimitry Andric 514f785676fSDimitry Andric /// Decorate the instruction with a TBAA tag. For both scalar TBAA 515f785676fSDimitry Andric /// and struct-path aware TBAA, the tag has the same format: 516f785676fSDimitry Andric /// base type, access type and offset. 517284c1978SDimitry Andric /// When ConvertTypeToTag is true, we create a tag based on the scalar type. 5180623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, 519284c1978SDimitry Andric llvm::MDNode *TBAAInfo, 520284c1978SDimitry Andric bool ConvertTypeToTag) { 521f785676fSDimitry Andric if (ConvertTypeToTag && TBAA) 522284c1978SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, 523284c1978SDimitry Andric TBAA->getTBAAScalarTagInfo(TBAAInfo)); 524284c1978SDimitry Andric else 5252754fe60SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 5262754fe60SDimitry Andric } 5272754fe60SDimitry Andric 5280623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup( 5290623d748SDimitry Andric llvm::Instruction *I, const CXXRecordDecl *RD) { 5300623d748SDimitry Andric llvm::Metadata *MD = CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 5310623d748SDimitry Andric auto *MetaDataNode = dyn_cast<llvm::MDNode>(MD); 5320623d748SDimitry Andric // Check if we have to wrap MDString in MDNode. 5330623d748SDimitry Andric if (!MetaDataNode) 5340623d748SDimitry Andric MetaDataNode = llvm::MDNode::get(getLLVMContext(), MD); 5350623d748SDimitry Andric I->setMetadata(llvm::LLVMContext::MD_invariant_group, MetaDataNode); 5360623d748SDimitry Andric } 5370623d748SDimitry Andric 53859d1ed5bSDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) { 53959d1ed5bSDimitry Andric unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 54059d1ed5bSDimitry Andric getDiags().Report(Context.getFullLoc(loc), diagID) << message; 541f22ef01cSRoman Divacky } 542f22ef01cSRoman Divacky 543f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 544f22ef01cSRoman Divacky /// specified stmt yet. 545f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 5466122f3e6SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 547f22ef01cSRoman Divacky "cannot compile this %0 yet"); 548f22ef01cSRoman Divacky std::string Msg = Type; 549f22ef01cSRoman Divacky getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 550f22ef01cSRoman Divacky << Msg << S->getSourceRange(); 551f22ef01cSRoman Divacky } 552f22ef01cSRoman Divacky 553f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 554f22ef01cSRoman Divacky /// specified decl yet. 555f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 5566122f3e6SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 557f22ef01cSRoman Divacky "cannot compile this %0 yet"); 558f22ef01cSRoman Divacky std::string Msg = Type; 559f22ef01cSRoman Divacky getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 560f22ef01cSRoman Divacky } 561f22ef01cSRoman Divacky 56217a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 56317a519f9SDimitry Andric return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 56417a519f9SDimitry Andric } 56517a519f9SDimitry Andric 566f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 5672754fe60SDimitry Andric const NamedDecl *D) const { 568f22ef01cSRoman Divacky // Internal definitions always have default visibility. 569f22ef01cSRoman Divacky if (GV->hasLocalLinkage()) { 570f22ef01cSRoman Divacky GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 571f22ef01cSRoman Divacky return; 572f22ef01cSRoman Divacky } 573f22ef01cSRoman Divacky 5742754fe60SDimitry Andric // Set visibility for definitions. 575139f7f9bSDimitry Andric LinkageInfo LV = D->getLinkageAndVisibility(); 576139f7f9bSDimitry Andric if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 577139f7f9bSDimitry Andric GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 578f22ef01cSRoman Divacky } 579f22ef01cSRoman Divacky 5807ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 5817ae0e2c9SDimitry Andric return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 5827ae0e2c9SDimitry Andric .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 5837ae0e2c9SDimitry Andric .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 5847ae0e2c9SDimitry Andric .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 5857ae0e2c9SDimitry Andric .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 5867ae0e2c9SDimitry Andric } 5877ae0e2c9SDimitry Andric 5887ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel( 5897ae0e2c9SDimitry Andric CodeGenOptions::TLSModel M) { 5907ae0e2c9SDimitry Andric switch (M) { 5917ae0e2c9SDimitry Andric case CodeGenOptions::GeneralDynamicTLSModel: 5927ae0e2c9SDimitry Andric return llvm::GlobalVariable::GeneralDynamicTLSModel; 5937ae0e2c9SDimitry Andric case CodeGenOptions::LocalDynamicTLSModel: 5947ae0e2c9SDimitry Andric return llvm::GlobalVariable::LocalDynamicTLSModel; 5957ae0e2c9SDimitry Andric case CodeGenOptions::InitialExecTLSModel: 5967ae0e2c9SDimitry Andric return llvm::GlobalVariable::InitialExecTLSModel; 5977ae0e2c9SDimitry Andric case CodeGenOptions::LocalExecTLSModel: 5987ae0e2c9SDimitry Andric return llvm::GlobalVariable::LocalExecTLSModel; 5997ae0e2c9SDimitry Andric } 6007ae0e2c9SDimitry Andric llvm_unreachable("Invalid TLS model!"); 6017ae0e2c9SDimitry Andric } 6027ae0e2c9SDimitry Andric 60339d628a0SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 604284c1978SDimitry Andric assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 6057ae0e2c9SDimitry Andric 60639d628a0SDimitry Andric llvm::GlobalValue::ThreadLocalMode TLM; 6073861d79fSDimitry Andric TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel()); 6087ae0e2c9SDimitry Andric 6097ae0e2c9SDimitry Andric // Override the TLS model if it is explicitly specified. 61059d1ed5bSDimitry Andric if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 6117ae0e2c9SDimitry Andric TLM = GetLLVMTLSModel(Attr->getModel()); 6127ae0e2c9SDimitry Andric } 6137ae0e2c9SDimitry Andric 6147ae0e2c9SDimitry Andric GV->setThreadLocalMode(TLM); 6157ae0e2c9SDimitry Andric } 6167ae0e2c9SDimitry Andric 6176122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 618444ed5c5SDimitry Andric GlobalDecl CanonicalGD = GD.getCanonicalDecl(); 619444ed5c5SDimitry Andric 620444ed5c5SDimitry Andric // Some ABIs don't have constructor variants. Make sure that base and 621444ed5c5SDimitry Andric // complete constructors get mangled the same. 622444ed5c5SDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { 623444ed5c5SDimitry Andric if (!getTarget().getCXXABI().hasConstructorVariants()) { 624444ed5c5SDimitry Andric CXXCtorType OrigCtorType = GD.getCtorType(); 625444ed5c5SDimitry Andric assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); 626444ed5c5SDimitry Andric if (OrigCtorType == Ctor_Base) 627444ed5c5SDimitry Andric CanonicalGD = GlobalDecl(CD, Ctor_Complete); 628444ed5c5SDimitry Andric } 629444ed5c5SDimitry Andric } 630444ed5c5SDimitry Andric 631444ed5c5SDimitry Andric StringRef &FoundStr = MangledDeclNames[CanonicalGD]; 63259d1ed5bSDimitry Andric if (!FoundStr.empty()) 63359d1ed5bSDimitry Andric return FoundStr; 634f22ef01cSRoman Divacky 63559d1ed5bSDimitry Andric const auto *ND = cast<NamedDecl>(GD.getDecl()); 636dff0c46cSDimitry Andric SmallString<256> Buffer; 63759d1ed5bSDimitry Andric StringRef Str; 63859d1ed5bSDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 6392754fe60SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 64059d1ed5bSDimitry Andric if (const auto *D = dyn_cast<CXXConstructorDecl>(ND)) 6412754fe60SDimitry Andric getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 64259d1ed5bSDimitry Andric else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND)) 6432754fe60SDimitry Andric getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 644ffd1746dSEd Schouten else 6452754fe60SDimitry Andric getCXXABI().getMangleContext().mangleName(ND, Out); 64659d1ed5bSDimitry Andric Str = Out.str(); 64759d1ed5bSDimitry Andric } else { 64859d1ed5bSDimitry Andric IdentifierInfo *II = ND->getIdentifier(); 64959d1ed5bSDimitry Andric assert(II && "Attempt to mangle unnamed decl."); 65059d1ed5bSDimitry Andric Str = II->getName(); 651ffd1746dSEd Schouten } 652ffd1746dSEd Schouten 65339d628a0SDimitry Andric // Keep the first result in the case of a mangling collision. 65439d628a0SDimitry Andric auto Result = Manglings.insert(std::make_pair(Str, GD)); 65539d628a0SDimitry Andric return FoundStr = Result.first->first(); 65659d1ed5bSDimitry Andric } 65759d1ed5bSDimitry Andric 65859d1ed5bSDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 659ffd1746dSEd Schouten const BlockDecl *BD) { 6602754fe60SDimitry Andric MangleContext &MangleCtx = getCXXABI().getMangleContext(); 6612754fe60SDimitry Andric const Decl *D = GD.getDecl(); 66259d1ed5bSDimitry Andric 66359d1ed5bSDimitry Andric SmallString<256> Buffer; 66459d1ed5bSDimitry Andric llvm::raw_svector_ostream Out(Buffer); 66559d1ed5bSDimitry Andric if (!D) 6667ae0e2c9SDimitry Andric MangleCtx.mangleGlobalBlock(BD, 6677ae0e2c9SDimitry Andric dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 66859d1ed5bSDimitry Andric else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 6692754fe60SDimitry Andric MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 67059d1ed5bSDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 6712754fe60SDimitry Andric MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 6722754fe60SDimitry Andric else 6732754fe60SDimitry Andric MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 67459d1ed5bSDimitry Andric 67539d628a0SDimitry Andric auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 67639d628a0SDimitry Andric return Result.first->first(); 677f22ef01cSRoman Divacky } 678f22ef01cSRoman Divacky 6796122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 680f22ef01cSRoman Divacky return getModule().getNamedValue(Name); 681f22ef01cSRoman Divacky } 682f22ef01cSRoman Divacky 683f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before 684f22ef01cSRoman Divacky /// main() runs. 68559d1ed5bSDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 68659d1ed5bSDimitry Andric llvm::Constant *AssociatedData) { 687f22ef01cSRoman Divacky // FIXME: Type coercion of void()* types. 68859d1ed5bSDimitry Andric GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); 689f22ef01cSRoman Divacky } 690f22ef01cSRoman Divacky 691f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called 692f22ef01cSRoman Divacky /// when the module is unloaded. 693f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) { 694f22ef01cSRoman Divacky // FIXME: Type coercion of void()* types. 69559d1ed5bSDimitry Andric GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); 696f22ef01cSRoman Divacky } 697f22ef01cSRoman Divacky 698f22ef01cSRoman Divacky void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 699f22ef01cSRoman Divacky // Ctor function type is void()*. 700bd5abe19SDimitry Andric llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 701f22ef01cSRoman Divacky llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 702f22ef01cSRoman Divacky 70359d1ed5bSDimitry Andric // Get the type of a ctor entry, { i32, void ()*, i8* }. 70459d1ed5bSDimitry Andric llvm::StructType *CtorStructTy = llvm::StructType::get( 70539d628a0SDimitry Andric Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr); 706f22ef01cSRoman Divacky 707f22ef01cSRoman Divacky // Construct the constructor and destructor arrays. 708dff0c46cSDimitry Andric SmallVector<llvm::Constant *, 8> Ctors; 7098f0fd8f6SDimitry Andric for (const auto &I : Fns) { 710dff0c46cSDimitry Andric llvm::Constant *S[] = { 7118f0fd8f6SDimitry Andric llvm::ConstantInt::get(Int32Ty, I.Priority, false), 7128f0fd8f6SDimitry Andric llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy), 7138f0fd8f6SDimitry Andric (I.AssociatedData 7148f0fd8f6SDimitry Andric ? llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy) 7158f0fd8f6SDimitry Andric : llvm::Constant::getNullValue(VoidPtrTy))}; 716f22ef01cSRoman Divacky Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 717f22ef01cSRoman Divacky } 718f22ef01cSRoman Divacky 719f22ef01cSRoman Divacky if (!Ctors.empty()) { 720f22ef01cSRoman Divacky llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 721f22ef01cSRoman Divacky new llvm::GlobalVariable(TheModule, AT, false, 722f22ef01cSRoman Divacky llvm::GlobalValue::AppendingLinkage, 723f22ef01cSRoman Divacky llvm::ConstantArray::get(AT, Ctors), 724f22ef01cSRoman Divacky GlobalName); 725f22ef01cSRoman Divacky } 726f22ef01cSRoman Divacky } 727f22ef01cSRoman Divacky 728f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes 729f785676fSDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 73059d1ed5bSDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 731f785676fSDimitry Andric 732e580952dSDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 733f22ef01cSRoman Divacky 73459d1ed5bSDimitry Andric if (isa<CXXDestructorDecl>(D) && 73559d1ed5bSDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 73659d1ed5bSDimitry Andric GD.getDtorType())) { 73759d1ed5bSDimitry Andric // Destructor variants in the Microsoft C++ ABI are always internal or 73859d1ed5bSDimitry Andric // linkonce_odr thunks emitted on an as-needed basis. 73959d1ed5bSDimitry Andric return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage 74059d1ed5bSDimitry Andric : llvm::GlobalValue::LinkOnceODRLinkage; 741f22ef01cSRoman Divacky } 742f22ef01cSRoman Divacky 74359d1ed5bSDimitry Andric return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false); 74459d1ed5bSDimitry Andric } 745f22ef01cSRoman Divacky 74697bc6c73SDimitry Andric void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) { 74797bc6c73SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 74897bc6c73SDimitry Andric 74997bc6c73SDimitry Andric if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) { 75097bc6c73SDimitry Andric if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) { 75197bc6c73SDimitry Andric // Don't dllexport/import destructor thunks. 75297bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 75397bc6c73SDimitry Andric return; 75497bc6c73SDimitry Andric } 75597bc6c73SDimitry Andric } 75697bc6c73SDimitry Andric 75797bc6c73SDimitry Andric if (FD->hasAttr<DLLImportAttr>()) 75897bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 75997bc6c73SDimitry Andric else if (FD->hasAttr<DLLExportAttr>()) 76097bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 76197bc6c73SDimitry Andric else 76297bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 76397bc6c73SDimitry Andric } 76497bc6c73SDimitry Andric 7650623d748SDimitry Andric llvm::ConstantInt * 7660623d748SDimitry Andric CodeGenModule::CreateCfiIdForTypeMetadata(llvm::Metadata *MD) { 7670623d748SDimitry Andric llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 7680623d748SDimitry Andric if (!MDS) return nullptr; 7690623d748SDimitry Andric 7700623d748SDimitry Andric llvm::MD5 md5; 7710623d748SDimitry Andric llvm::MD5::MD5Result result; 7720623d748SDimitry Andric md5.update(MDS->getString()); 7730623d748SDimitry Andric md5.final(result); 7740623d748SDimitry Andric uint64_t id = 0; 7750623d748SDimitry Andric for (int i = 0; i < 8; ++i) 7760623d748SDimitry Andric id |= static_cast<uint64_t>(result[i]) << (i * 8); 7770623d748SDimitry Andric return llvm::ConstantInt::get(Int64Ty, id); 7780623d748SDimitry Andric } 7790623d748SDimitry Andric 78059d1ed5bSDimitry Andric void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D, 78159d1ed5bSDimitry Andric llvm::Function *F) { 78259d1ed5bSDimitry Andric setNonAliasAttributes(D, F); 783f22ef01cSRoman Divacky } 784f22ef01cSRoman Divacky 785f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 786f22ef01cSRoman Divacky const CGFunctionInfo &Info, 787f22ef01cSRoman Divacky llvm::Function *F) { 788f22ef01cSRoman Divacky unsigned CallingConv; 789f22ef01cSRoman Divacky AttributeListType AttributeList; 790ea942507SDimitry Andric ConstructAttributeList(F->getName(), Info, D, AttributeList, CallingConv, 791ea942507SDimitry Andric false); 792139f7f9bSDimitry Andric F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList)); 793f22ef01cSRoman Divacky F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 794f22ef01cSRoman Divacky } 795f22ef01cSRoman Divacky 7966122f3e6SDimitry Andric /// Determines whether the language options require us to model 7976122f3e6SDimitry Andric /// unwind exceptions. We treat -fexceptions as mandating this 7986122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions 7996122f3e6SDimitry Andric /// enabled. This means, for example, that C with -fexceptions 8006122f3e6SDimitry Andric /// enables this. 801dff0c46cSDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) { 8026122f3e6SDimitry Andric // If exceptions are completely disabled, obviously this is false. 803dff0c46cSDimitry Andric if (!LangOpts.Exceptions) return false; 8046122f3e6SDimitry Andric 8056122f3e6SDimitry Andric // If C++ exceptions are enabled, this is true. 806dff0c46cSDimitry Andric if (LangOpts.CXXExceptions) return true; 8076122f3e6SDimitry Andric 8086122f3e6SDimitry Andric // If ObjC exceptions are enabled, this depends on the ABI. 809dff0c46cSDimitry Andric if (LangOpts.ObjCExceptions) { 8107ae0e2c9SDimitry Andric return LangOpts.ObjCRuntime.hasUnwindExceptions(); 8116122f3e6SDimitry Andric } 8126122f3e6SDimitry Andric 8136122f3e6SDimitry Andric return true; 8146122f3e6SDimitry Andric } 8156122f3e6SDimitry Andric 816f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 817f22ef01cSRoman Divacky llvm::Function *F) { 818f785676fSDimitry Andric llvm::AttrBuilder B; 819f785676fSDimitry Andric 820bd5abe19SDimitry Andric if (CodeGenOpts.UnwindTables) 821f785676fSDimitry Andric B.addAttribute(llvm::Attribute::UWTable); 822bd5abe19SDimitry Andric 823dff0c46cSDimitry Andric if (!hasUnwindExceptions(LangOpts)) 824f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoUnwind); 825f22ef01cSRoman Divacky 8260623d748SDimitry Andric if (LangOpts.getStackProtector() == LangOptions::SSPOn) 8270623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtect); 8280623d748SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 8290623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectStrong); 8300623d748SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 8310623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectReq); 8320623d748SDimitry Andric 8330623d748SDimitry Andric if (!D) { 8340623d748SDimitry Andric F->addAttributes(llvm::AttributeSet::FunctionIndex, 8350623d748SDimitry Andric llvm::AttributeSet::get( 8360623d748SDimitry Andric F->getContext(), 8370623d748SDimitry Andric llvm::AttributeSet::FunctionIndex, B)); 8380623d748SDimitry Andric return; 8390623d748SDimitry Andric } 8400623d748SDimitry Andric 8416122f3e6SDimitry Andric if (D->hasAttr<NakedAttr>()) { 8426122f3e6SDimitry Andric // Naked implies noinline: we should not be inlining such functions. 843f785676fSDimitry Andric B.addAttribute(llvm::Attribute::Naked); 844f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 84559d1ed5bSDimitry Andric } else if (D->hasAttr<NoDuplicateAttr>()) { 84659d1ed5bSDimitry Andric B.addAttribute(llvm::Attribute::NoDuplicate); 847f785676fSDimitry Andric } else if (D->hasAttr<NoInlineAttr>()) { 848f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 84959d1ed5bSDimitry Andric } else if (D->hasAttr<AlwaysInlineAttr>() && 850f785676fSDimitry Andric !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex, 851f785676fSDimitry Andric llvm::Attribute::NoInline)) { 852f785676fSDimitry Andric // (noinline wins over always_inline, and we can't specify both in IR) 853f785676fSDimitry Andric B.addAttribute(llvm::Attribute::AlwaysInline); 8546122f3e6SDimitry Andric } 8552754fe60SDimitry Andric 856f785676fSDimitry Andric if (D->hasAttr<ColdAttr>()) { 85739d628a0SDimitry Andric if (!D->hasAttr<OptimizeNoneAttr>()) 858f785676fSDimitry Andric B.addAttribute(llvm::Attribute::OptimizeForSize); 859f785676fSDimitry Andric B.addAttribute(llvm::Attribute::Cold); 860f785676fSDimitry Andric } 8613861d79fSDimitry Andric 8623861d79fSDimitry Andric if (D->hasAttr<MinSizeAttr>()) 863f785676fSDimitry Andric B.addAttribute(llvm::Attribute::MinSize); 864f22ef01cSRoman Divacky 865f785676fSDimitry Andric F->addAttributes(llvm::AttributeSet::FunctionIndex, 866f785676fSDimitry Andric llvm::AttributeSet::get( 867f785676fSDimitry Andric F->getContext(), llvm::AttributeSet::FunctionIndex, B)); 868f785676fSDimitry Andric 86939d628a0SDimitry Andric if (D->hasAttr<OptimizeNoneAttr>()) { 87039d628a0SDimitry Andric // OptimizeNone implies noinline; we should not be inlining such functions. 87139d628a0SDimitry Andric F->addFnAttr(llvm::Attribute::OptimizeNone); 87239d628a0SDimitry Andric F->addFnAttr(llvm::Attribute::NoInline); 87339d628a0SDimitry Andric 87439d628a0SDimitry Andric // OptimizeNone wins over OptimizeForSize, MinSize, AlwaysInline. 8750623d748SDimitry Andric F->removeFnAttr(llvm::Attribute::OptimizeForSize); 8760623d748SDimitry Andric F->removeFnAttr(llvm::Attribute::MinSize); 87739d628a0SDimitry Andric assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 87839d628a0SDimitry Andric "OptimizeNone and AlwaysInline on same function!"); 87939d628a0SDimitry Andric 88039d628a0SDimitry Andric // Attribute 'inlinehint' has no effect on 'optnone' functions. 88139d628a0SDimitry Andric // Explicitly remove it from the set of function attributes. 88239d628a0SDimitry Andric F->removeFnAttr(llvm::Attribute::InlineHint); 88339d628a0SDimitry Andric } 88439d628a0SDimitry Andric 885f785676fSDimitry Andric if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 886f785676fSDimitry Andric F->setUnnamedAddr(true); 88759d1ed5bSDimitry Andric else if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) 888f785676fSDimitry Andric if (MD->isVirtual()) 889f785676fSDimitry Andric F->setUnnamedAddr(true); 890f785676fSDimitry Andric 891e580952dSDimitry Andric unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 892e580952dSDimitry Andric if (alignment) 893e580952dSDimitry Andric F->setAlignment(alignment); 894e580952dSDimitry Andric 8950623d748SDimitry Andric // Some C++ ABIs require 2-byte alignment for member functions, in order to 8960623d748SDimitry Andric // reserve a bit for differentiating between virtual and non-virtual member 8970623d748SDimitry Andric // functions. If the current target's C++ ABI requires this and this is a 8980623d748SDimitry Andric // member function, set its alignment accordingly. 8990623d748SDimitry Andric if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 900f22ef01cSRoman Divacky if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 901f22ef01cSRoman Divacky F->setAlignment(2); 902f22ef01cSRoman Divacky } 9030623d748SDimitry Andric } 904f22ef01cSRoman Divacky 905f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D, 906f22ef01cSRoman Divacky llvm::GlobalValue *GV) { 9070623d748SDimitry Andric if (const auto *ND = dyn_cast_or_null<NamedDecl>(D)) 9082754fe60SDimitry Andric setGlobalVisibility(GV, ND); 9092754fe60SDimitry Andric else 9102754fe60SDimitry Andric GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 911f22ef01cSRoman Divacky 9120623d748SDimitry Andric if (D && D->hasAttr<UsedAttr>()) 91359d1ed5bSDimitry Andric addUsedGlobal(GV); 91459d1ed5bSDimitry Andric } 91559d1ed5bSDimitry Andric 91639d628a0SDimitry Andric void CodeGenModule::setAliasAttributes(const Decl *D, 91739d628a0SDimitry Andric llvm::GlobalValue *GV) { 91839d628a0SDimitry Andric SetCommonAttributes(D, GV); 91939d628a0SDimitry Andric 92039d628a0SDimitry Andric // Process the dllexport attribute based on whether the original definition 92139d628a0SDimitry Andric // (not necessarily the aliasee) was exported. 92239d628a0SDimitry Andric if (D->hasAttr<DLLExportAttr>()) 92339d628a0SDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 92439d628a0SDimitry Andric } 92539d628a0SDimitry Andric 92659d1ed5bSDimitry Andric void CodeGenModule::setNonAliasAttributes(const Decl *D, 92759d1ed5bSDimitry Andric llvm::GlobalObject *GO) { 92859d1ed5bSDimitry Andric SetCommonAttributes(D, GO); 929f22ef01cSRoman Divacky 9300623d748SDimitry Andric if (D) 931f22ef01cSRoman Divacky if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 93259d1ed5bSDimitry Andric GO->setSection(SA->getName()); 933f22ef01cSRoman Divacky 93497bc6c73SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 935f22ef01cSRoman Divacky } 936f22ef01cSRoman Divacky 937f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 938f22ef01cSRoman Divacky llvm::Function *F, 939f22ef01cSRoman Divacky const CGFunctionInfo &FI) { 940f22ef01cSRoman Divacky SetLLVMFunctionAttributes(D, FI, F); 941f22ef01cSRoman Divacky SetLLVMFunctionAttributesForDefinition(D, F); 942f22ef01cSRoman Divacky 943f22ef01cSRoman Divacky F->setLinkage(llvm::Function::InternalLinkage); 944f22ef01cSRoman Divacky 94559d1ed5bSDimitry Andric setNonAliasAttributes(D, F); 94659d1ed5bSDimitry Andric } 94759d1ed5bSDimitry Andric 94859d1ed5bSDimitry Andric static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV, 94959d1ed5bSDimitry Andric const NamedDecl *ND) { 95059d1ed5bSDimitry Andric // Set linkage and visibility in case we never see a definition. 95159d1ed5bSDimitry Andric LinkageInfo LV = ND->getLinkageAndVisibility(); 95259d1ed5bSDimitry Andric if (LV.getLinkage() != ExternalLinkage) { 95359d1ed5bSDimitry Andric // Don't set internal linkage on declarations. 95459d1ed5bSDimitry Andric } else { 95559d1ed5bSDimitry Andric if (ND->hasAttr<DLLImportAttr>()) { 95659d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 95759d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 95859d1ed5bSDimitry Andric } else if (ND->hasAttr<DLLExportAttr>()) { 95959d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 96059d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 96159d1ed5bSDimitry Andric } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) { 96259d1ed5bSDimitry Andric // "extern_weak" is overloaded in LLVM; we probably should have 96359d1ed5bSDimitry Andric // separate linkage types for this. 96459d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 96559d1ed5bSDimitry Andric } 96659d1ed5bSDimitry Andric 96759d1ed5bSDimitry Andric // Set visibility on a declaration only if it's explicit. 96859d1ed5bSDimitry Andric if (LV.isVisibilityExplicit()) 96959d1ed5bSDimitry Andric GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility())); 97059d1ed5bSDimitry Andric } 971f22ef01cSRoman Divacky } 972f22ef01cSRoman Divacky 9730623d748SDimitry Andric void CodeGenModule::CreateFunctionBitSetEntry(const FunctionDecl *FD, 9740623d748SDimitry Andric llvm::Function *F) { 9750623d748SDimitry Andric // Only if we are checking indirect calls. 9760623d748SDimitry Andric if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 9770623d748SDimitry Andric return; 9780623d748SDimitry Andric 9790623d748SDimitry Andric // Non-static class methods are handled via vtable pointer checks elsewhere. 9800623d748SDimitry Andric if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 9810623d748SDimitry Andric return; 9820623d748SDimitry Andric 9830623d748SDimitry Andric // Additionally, if building with cross-DSO support... 9840623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 9850623d748SDimitry Andric // Don't emit entries for function declarations. In cross-DSO mode these are 9860623d748SDimitry Andric // handled with better precision at run time. 9870623d748SDimitry Andric if (!FD->hasBody()) 9880623d748SDimitry Andric return; 9890623d748SDimitry Andric // Skip available_externally functions. They won't be codegen'ed in the 9900623d748SDimitry Andric // current module anyway. 9910623d748SDimitry Andric if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally) 9920623d748SDimitry Andric return; 9930623d748SDimitry Andric } 9940623d748SDimitry Andric 9950623d748SDimitry Andric llvm::NamedMDNode *BitsetsMD = 9960623d748SDimitry Andric getModule().getOrInsertNamedMetadata("llvm.bitsets"); 9970623d748SDimitry Andric 9980623d748SDimitry Andric llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 9990623d748SDimitry Andric llvm::Metadata *BitsetOps[] = { 10000623d748SDimitry Andric MD, llvm::ConstantAsMetadata::get(F), 10010623d748SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int64Ty, 0))}; 10020623d748SDimitry Andric BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps)); 10030623d748SDimitry Andric 10040623d748SDimitry Andric // Emit a hash-based bit set entry for cross-DSO calls. 10050623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 10060623d748SDimitry Andric if (auto TypeId = CreateCfiIdForTypeMetadata(MD)) { 10070623d748SDimitry Andric llvm::Metadata *BitsetOps2[] = { 10080623d748SDimitry Andric llvm::ConstantAsMetadata::get(TypeId), 10090623d748SDimitry Andric llvm::ConstantAsMetadata::get(F), 10100623d748SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int64Ty, 0))}; 10110623d748SDimitry Andric BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps2)); 10120623d748SDimitry Andric } 10130623d748SDimitry Andric } 10140623d748SDimitry Andric } 10150623d748SDimitry Andric 101639d628a0SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 101739d628a0SDimitry Andric bool IsIncompleteFunction, 101839d628a0SDimitry Andric bool IsThunk) { 101933956c43SDimitry Andric if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 10203b0f4066SDimitry Andric // If this is an intrinsic function, set the function's attributes 10213b0f4066SDimitry Andric // to the intrinsic's attributes. 102233956c43SDimitry Andric F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 10233b0f4066SDimitry Andric return; 10243b0f4066SDimitry Andric } 10253b0f4066SDimitry Andric 102659d1ed5bSDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 1027f22ef01cSRoman Divacky 1028f22ef01cSRoman Divacky if (!IsIncompleteFunction) 1029dff0c46cSDimitry Andric SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); 1030f22ef01cSRoman Divacky 103159d1ed5bSDimitry Andric // Add the Returned attribute for "this", except for iOS 5 and earlier 103259d1ed5bSDimitry Andric // where substantial code, including the libstdc++ dylib, was compiled with 103359d1ed5bSDimitry Andric // GCC and does not actually return "this". 103439d628a0SDimitry Andric if (!IsThunk && getCXXABI().HasThisReturn(GD) && 103559d1ed5bSDimitry Andric !(getTarget().getTriple().isiOS() && 103659d1ed5bSDimitry Andric getTarget().getTriple().isOSVersionLT(6))) { 1037f785676fSDimitry Andric assert(!F->arg_empty() && 1038f785676fSDimitry Andric F->arg_begin()->getType() 1039f785676fSDimitry Andric ->canLosslesslyBitCastTo(F->getReturnType()) && 1040f785676fSDimitry Andric "unexpected this return"); 1041f785676fSDimitry Andric F->addAttribute(1, llvm::Attribute::Returned); 1042f785676fSDimitry Andric } 1043f785676fSDimitry Andric 1044f22ef01cSRoman Divacky // Only a few attributes are set on declarations; these may later be 1045f22ef01cSRoman Divacky // overridden by a definition. 1046f22ef01cSRoman Divacky 104759d1ed5bSDimitry Andric setLinkageAndVisibilityForGV(F, FD); 10482754fe60SDimitry Andric 1049f22ef01cSRoman Divacky if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 1050f22ef01cSRoman Divacky F->setSection(SA->getName()); 1051f785676fSDimitry Andric 1052f785676fSDimitry Andric // A replaceable global allocation function does not act like a builtin by 1053f785676fSDimitry Andric // default, only if it is invoked by a new-expression or delete-expression. 1054f785676fSDimitry Andric if (FD->isReplaceableGlobalAllocationFunction()) 1055f785676fSDimitry Andric F->addAttribute(llvm::AttributeSet::FunctionIndex, 1056f785676fSDimitry Andric llvm::Attribute::NoBuiltin); 10570623d748SDimitry Andric 10580623d748SDimitry Andric CreateFunctionBitSetEntry(FD, F); 1059f22ef01cSRoman Divacky } 1060f22ef01cSRoman Divacky 106159d1ed5bSDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 1062f22ef01cSRoman Divacky assert(!GV->isDeclaration() && 1063f22ef01cSRoman Divacky "Only globals with definition can force usage."); 106497bc6c73SDimitry Andric LLVMUsed.emplace_back(GV); 1065f22ef01cSRoman Divacky } 1066f22ef01cSRoman Divacky 106759d1ed5bSDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 106859d1ed5bSDimitry Andric assert(!GV->isDeclaration() && 106959d1ed5bSDimitry Andric "Only globals with definition can force usage."); 107097bc6c73SDimitry Andric LLVMCompilerUsed.emplace_back(GV); 107159d1ed5bSDimitry Andric } 107259d1ed5bSDimitry Andric 107359d1ed5bSDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name, 107459d1ed5bSDimitry Andric std::vector<llvm::WeakVH> &List) { 1075f22ef01cSRoman Divacky // Don't create llvm.used if there is no need. 107659d1ed5bSDimitry Andric if (List.empty()) 1077f22ef01cSRoman Divacky return; 1078f22ef01cSRoman Divacky 107959d1ed5bSDimitry Andric // Convert List to what ConstantArray needs. 1080dff0c46cSDimitry Andric SmallVector<llvm::Constant*, 8> UsedArray; 108159d1ed5bSDimitry Andric UsedArray.resize(List.size()); 108259d1ed5bSDimitry Andric for (unsigned i = 0, e = List.size(); i != e; ++i) { 1083f22ef01cSRoman Divacky UsedArray[i] = 108444f7b0dcSDimitry Andric llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 108544f7b0dcSDimitry Andric cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 1086f22ef01cSRoman Divacky } 1087f22ef01cSRoman Divacky 1088f22ef01cSRoman Divacky if (UsedArray.empty()) 1089f22ef01cSRoman Divacky return; 109059d1ed5bSDimitry Andric llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 1091f22ef01cSRoman Divacky 109259d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 109359d1ed5bSDimitry Andric CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 109459d1ed5bSDimitry Andric llvm::ConstantArray::get(ATy, UsedArray), Name); 1095f22ef01cSRoman Divacky 1096f22ef01cSRoman Divacky GV->setSection("llvm.metadata"); 1097f22ef01cSRoman Divacky } 1098f22ef01cSRoman Divacky 109959d1ed5bSDimitry Andric void CodeGenModule::emitLLVMUsed() { 110059d1ed5bSDimitry Andric emitUsed(*this, "llvm.used", LLVMUsed); 110159d1ed5bSDimitry Andric emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 110259d1ed5bSDimitry Andric } 110359d1ed5bSDimitry Andric 1104f785676fSDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 110539d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 1106f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1107f785676fSDimitry Andric } 1108f785676fSDimitry Andric 1109f785676fSDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 1110f785676fSDimitry Andric llvm::SmallString<32> Opt; 1111f785676fSDimitry Andric getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 111239d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1113f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1114f785676fSDimitry Andric } 1115f785676fSDimitry Andric 1116f785676fSDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) { 1117f785676fSDimitry Andric llvm::SmallString<24> Opt; 1118f785676fSDimitry Andric getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 111939d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1120f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1121f785676fSDimitry Andric } 1122f785676fSDimitry Andric 1123139f7f9bSDimitry Andric /// \brief Add link options implied by the given module, including modules 1124139f7f9bSDimitry Andric /// it depends on, using a postorder walk. 112539d628a0SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 112639d628a0SDimitry Andric SmallVectorImpl<llvm::Metadata *> &Metadata, 1127139f7f9bSDimitry Andric llvm::SmallPtrSet<Module *, 16> &Visited) { 1128139f7f9bSDimitry Andric // Import this module's parent. 112939d628a0SDimitry Andric if (Mod->Parent && Visited.insert(Mod->Parent).second) { 1130f785676fSDimitry Andric addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 1131139f7f9bSDimitry Andric } 1132139f7f9bSDimitry Andric 1133139f7f9bSDimitry Andric // Import this module's dependencies. 1134139f7f9bSDimitry Andric for (unsigned I = Mod->Imports.size(); I > 0; --I) { 113539d628a0SDimitry Andric if (Visited.insert(Mod->Imports[I - 1]).second) 1136f785676fSDimitry Andric addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 1137139f7f9bSDimitry Andric } 1138139f7f9bSDimitry Andric 1139139f7f9bSDimitry Andric // Add linker options to link against the libraries/frameworks 1140139f7f9bSDimitry Andric // described by this module. 1141f785676fSDimitry Andric llvm::LLVMContext &Context = CGM.getLLVMContext(); 1142139f7f9bSDimitry Andric for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 1143f785676fSDimitry Andric // Link against a framework. Frameworks are currently Darwin only, so we 1144f785676fSDimitry Andric // don't to ask TargetCodeGenInfo for the spelling of the linker option. 1145139f7f9bSDimitry Andric if (Mod->LinkLibraries[I-1].IsFramework) { 114639d628a0SDimitry Andric llvm::Metadata *Args[2] = { 1147139f7f9bSDimitry Andric llvm::MDString::get(Context, "-framework"), 114839d628a0SDimitry Andric llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)}; 1149139f7f9bSDimitry Andric 1150139f7f9bSDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, Args)); 1151139f7f9bSDimitry Andric continue; 1152139f7f9bSDimitry Andric } 1153139f7f9bSDimitry Andric 1154139f7f9bSDimitry Andric // Link against a library. 1155f785676fSDimitry Andric llvm::SmallString<24> Opt; 1156f785676fSDimitry Andric CGM.getTargetCodeGenInfo().getDependentLibraryOption( 1157f785676fSDimitry Andric Mod->LinkLibraries[I-1].Library, Opt); 115839d628a0SDimitry Andric auto *OptString = llvm::MDString::get(Context, Opt); 1159139f7f9bSDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, OptString)); 1160139f7f9bSDimitry Andric } 1161139f7f9bSDimitry Andric } 1162139f7f9bSDimitry Andric 1163139f7f9bSDimitry Andric void CodeGenModule::EmitModuleLinkOptions() { 1164139f7f9bSDimitry Andric // Collect the set of all of the modules we want to visit to emit link 1165139f7f9bSDimitry Andric // options, which is essentially the imported modules and all of their 1166139f7f9bSDimitry Andric // non-explicit child modules. 1167139f7f9bSDimitry Andric llvm::SetVector<clang::Module *> LinkModules; 1168139f7f9bSDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 1169139f7f9bSDimitry Andric SmallVector<clang::Module *, 16> Stack; 1170139f7f9bSDimitry Andric 1171139f7f9bSDimitry Andric // Seed the stack with imported modules. 11728f0fd8f6SDimitry Andric for (Module *M : ImportedModules) 11738f0fd8f6SDimitry Andric if (Visited.insert(M).second) 11748f0fd8f6SDimitry Andric Stack.push_back(M); 1175139f7f9bSDimitry Andric 1176139f7f9bSDimitry Andric // Find all of the modules to import, making a little effort to prune 1177139f7f9bSDimitry Andric // non-leaf modules. 1178139f7f9bSDimitry Andric while (!Stack.empty()) { 1179f785676fSDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 1180139f7f9bSDimitry Andric 1181139f7f9bSDimitry Andric bool AnyChildren = false; 1182139f7f9bSDimitry Andric 1183139f7f9bSDimitry Andric // Visit the submodules of this module. 1184139f7f9bSDimitry Andric for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 1185139f7f9bSDimitry Andric SubEnd = Mod->submodule_end(); 1186139f7f9bSDimitry Andric Sub != SubEnd; ++Sub) { 1187139f7f9bSDimitry Andric // Skip explicit children; they need to be explicitly imported to be 1188139f7f9bSDimitry Andric // linked against. 1189139f7f9bSDimitry Andric if ((*Sub)->IsExplicit) 1190139f7f9bSDimitry Andric continue; 1191139f7f9bSDimitry Andric 119239d628a0SDimitry Andric if (Visited.insert(*Sub).second) { 1193139f7f9bSDimitry Andric Stack.push_back(*Sub); 1194139f7f9bSDimitry Andric AnyChildren = true; 1195139f7f9bSDimitry Andric } 1196139f7f9bSDimitry Andric } 1197139f7f9bSDimitry Andric 1198139f7f9bSDimitry Andric // We didn't find any children, so add this module to the list of 1199139f7f9bSDimitry Andric // modules to link against. 1200139f7f9bSDimitry Andric if (!AnyChildren) { 1201139f7f9bSDimitry Andric LinkModules.insert(Mod); 1202139f7f9bSDimitry Andric } 1203139f7f9bSDimitry Andric } 1204139f7f9bSDimitry Andric 1205139f7f9bSDimitry Andric // Add link options for all of the imported modules in reverse topological 1206f785676fSDimitry Andric // order. We don't do anything to try to order import link flags with respect 1207f785676fSDimitry Andric // to linker options inserted by things like #pragma comment(). 120839d628a0SDimitry Andric SmallVector<llvm::Metadata *, 16> MetadataArgs; 1209139f7f9bSDimitry Andric Visited.clear(); 12108f0fd8f6SDimitry Andric for (Module *M : LinkModules) 12118f0fd8f6SDimitry Andric if (Visited.insert(M).second) 12128f0fd8f6SDimitry Andric addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 1213139f7f9bSDimitry Andric std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 1214f785676fSDimitry Andric LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 1215139f7f9bSDimitry Andric 1216139f7f9bSDimitry Andric // Add the linker options metadata flag. 1217139f7f9bSDimitry Andric getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options", 1218f785676fSDimitry Andric llvm::MDNode::get(getLLVMContext(), 1219f785676fSDimitry Andric LinkerOptionsMetadata)); 1220139f7f9bSDimitry Andric } 1221139f7f9bSDimitry Andric 1222f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() { 1223f22ef01cSRoman Divacky // Emit code for any potentially referenced deferred decls. Since a 1224f22ef01cSRoman Divacky // previously unused static decl may become used during the generation of code 1225f22ef01cSRoman Divacky // for a static function, iterate until no changes are made. 1226f22ef01cSRoman Divacky 1227f22ef01cSRoman Divacky if (!DeferredVTables.empty()) { 1228139f7f9bSDimitry Andric EmitDeferredVTables(); 1229139f7f9bSDimitry Andric 1230139f7f9bSDimitry Andric // Emitting a v-table doesn't directly cause more v-tables to 1231139f7f9bSDimitry Andric // become deferred, although it can cause functions to be 1232139f7f9bSDimitry Andric // emitted that then need those v-tables. 1233139f7f9bSDimitry Andric assert(DeferredVTables.empty()); 1234f22ef01cSRoman Divacky } 1235f22ef01cSRoman Divacky 1236139f7f9bSDimitry Andric // Stop if we're out of both deferred v-tables and deferred declarations. 123733956c43SDimitry Andric if (DeferredDeclsToEmit.empty()) 123833956c43SDimitry Andric return; 1239139f7f9bSDimitry Andric 124033956c43SDimitry Andric // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 124133956c43SDimitry Andric // work, it will not interfere with this. 124233956c43SDimitry Andric std::vector<DeferredGlobal> CurDeclsToEmit; 124333956c43SDimitry Andric CurDeclsToEmit.swap(DeferredDeclsToEmit); 124433956c43SDimitry Andric 124533956c43SDimitry Andric for (DeferredGlobal &G : CurDeclsToEmit) { 124659d1ed5bSDimitry Andric GlobalDecl D = G.GD; 124759d1ed5bSDimitry Andric llvm::GlobalValue *GV = G.GV; 124833956c43SDimitry Andric G.GV = nullptr; 1249f22ef01cSRoman Divacky 12500623d748SDimitry Andric // We should call GetAddrOfGlobal with IsForDefinition set to true in order 12510623d748SDimitry Andric // to get GlobalValue with exactly the type we need, not something that 12520623d748SDimitry Andric // might had been created for another decl with the same mangled name but 12530623d748SDimitry Andric // different type. 12540623d748SDimitry Andric // FIXME: Support for variables is not implemented yet. 12550623d748SDimitry Andric if (isa<FunctionDecl>(D.getDecl())) 12560623d748SDimitry Andric GV = cast<llvm::GlobalValue>(GetAddrOfGlobal(D, /*IsForDefinition=*/true)); 12570623d748SDimitry Andric else 125839d628a0SDimitry Andric if (!GV) 125939d628a0SDimitry Andric GV = GetGlobalValue(getMangledName(D)); 126039d628a0SDimitry Andric 1261f22ef01cSRoman Divacky // Check to see if we've already emitted this. This is necessary 1262f22ef01cSRoman Divacky // for a couple of reasons: first, decls can end up in the 1263f22ef01cSRoman Divacky // deferred-decls queue multiple times, and second, decls can end 1264f22ef01cSRoman Divacky // up with definitions in unusual ways (e.g. by an extern inline 1265f22ef01cSRoman Divacky // function acquiring a strong function redefinition). Just 1266f22ef01cSRoman Divacky // ignore these cases. 126739d628a0SDimitry Andric if (GV && !GV->isDeclaration()) 1268f22ef01cSRoman Divacky continue; 1269f22ef01cSRoman Divacky 1270f22ef01cSRoman Divacky // Otherwise, emit the definition and move on to the next one. 127159d1ed5bSDimitry Andric EmitGlobalDefinition(D, GV); 127233956c43SDimitry Andric 127333956c43SDimitry Andric // If we found out that we need to emit more decls, do that recursively. 127433956c43SDimitry Andric // This has the advantage that the decls are emitted in a DFS and related 127533956c43SDimitry Andric // ones are close together, which is convenient for testing. 127633956c43SDimitry Andric if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 127733956c43SDimitry Andric EmitDeferred(); 127833956c43SDimitry Andric assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 127933956c43SDimitry Andric } 1280f22ef01cSRoman Divacky } 1281f22ef01cSRoman Divacky } 1282f22ef01cSRoman Divacky 12836122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() { 12846122f3e6SDimitry Andric if (Annotations.empty()) 12856122f3e6SDimitry Andric return; 12866122f3e6SDimitry Andric 12876122f3e6SDimitry Andric // Create a new global variable for the ConstantStruct in the Module. 12886122f3e6SDimitry Andric llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 12896122f3e6SDimitry Andric Annotations[0]->getType(), Annotations.size()), Annotations); 129059d1ed5bSDimitry Andric auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 129159d1ed5bSDimitry Andric llvm::GlobalValue::AppendingLinkage, 129259d1ed5bSDimitry Andric Array, "llvm.global.annotations"); 12936122f3e6SDimitry Andric gv->setSection(AnnotationSection); 12946122f3e6SDimitry Andric } 12956122f3e6SDimitry Andric 1296139f7f9bSDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 1297f785676fSDimitry Andric llvm::Constant *&AStr = AnnotationStrings[Str]; 1298f785676fSDimitry Andric if (AStr) 1299f785676fSDimitry Andric return AStr; 13006122f3e6SDimitry Andric 13016122f3e6SDimitry Andric // Not found yet, create a new global. 1302dff0c46cSDimitry Andric llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 130359d1ed5bSDimitry Andric auto *gv = 130459d1ed5bSDimitry Andric new llvm::GlobalVariable(getModule(), s->getType(), true, 130559d1ed5bSDimitry Andric llvm::GlobalValue::PrivateLinkage, s, ".str"); 13066122f3e6SDimitry Andric gv->setSection(AnnotationSection); 13076122f3e6SDimitry Andric gv->setUnnamedAddr(true); 1308f785676fSDimitry Andric AStr = gv; 13096122f3e6SDimitry Andric return gv; 13106122f3e6SDimitry Andric } 13116122f3e6SDimitry Andric 13126122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 13136122f3e6SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 13146122f3e6SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(Loc); 13156122f3e6SDimitry Andric if (PLoc.isValid()) 13166122f3e6SDimitry Andric return EmitAnnotationString(PLoc.getFilename()); 13176122f3e6SDimitry Andric return EmitAnnotationString(SM.getBufferName(Loc)); 13186122f3e6SDimitry Andric } 13196122f3e6SDimitry Andric 13206122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 13216122f3e6SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 13226122f3e6SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(L); 13236122f3e6SDimitry Andric unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 13246122f3e6SDimitry Andric SM.getExpansionLineNumber(L); 13256122f3e6SDimitry Andric return llvm::ConstantInt::get(Int32Ty, LineNo); 13266122f3e6SDimitry Andric } 13276122f3e6SDimitry Andric 1328f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 1329f22ef01cSRoman Divacky const AnnotateAttr *AA, 13306122f3e6SDimitry Andric SourceLocation L) { 13316122f3e6SDimitry Andric // Get the globals for file name, annotation, and the line number. 13326122f3e6SDimitry Andric llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 13336122f3e6SDimitry Andric *UnitGV = EmitAnnotationUnit(L), 13346122f3e6SDimitry Andric *LineNoCst = EmitAnnotationLineNo(L); 1335f22ef01cSRoman Divacky 1336f22ef01cSRoman Divacky // Create the ConstantStruct for the global annotation. 1337f22ef01cSRoman Divacky llvm::Constant *Fields[4] = { 13386122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 13396122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 13406122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 13416122f3e6SDimitry Andric LineNoCst 1342f22ef01cSRoman Divacky }; 134317a519f9SDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 1344f22ef01cSRoman Divacky } 1345f22ef01cSRoman Divacky 13466122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 13476122f3e6SDimitry Andric llvm::GlobalValue *GV) { 13486122f3e6SDimitry Andric assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 13496122f3e6SDimitry Andric // Get the struct elements for these annotations. 135059d1ed5bSDimitry Andric for (const auto *I : D->specific_attrs<AnnotateAttr>()) 135159d1ed5bSDimitry Andric Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 13526122f3e6SDimitry Andric } 13536122f3e6SDimitry Andric 135439d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn, 135539d628a0SDimitry Andric SourceLocation Loc) const { 135639d628a0SDimitry Andric const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 135739d628a0SDimitry Andric // Blacklist by function name. 135839d628a0SDimitry Andric if (SanitizerBL.isBlacklistedFunction(Fn->getName())) 135939d628a0SDimitry Andric return true; 136039d628a0SDimitry Andric // Blacklist by location. 13610623d748SDimitry Andric if (Loc.isValid()) 136239d628a0SDimitry Andric return SanitizerBL.isBlacklistedLocation(Loc); 136339d628a0SDimitry Andric // If location is unknown, this may be a compiler-generated function. Assume 136439d628a0SDimitry Andric // it's located in the main file. 136539d628a0SDimitry Andric auto &SM = Context.getSourceManager(); 136639d628a0SDimitry Andric if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 136739d628a0SDimitry Andric return SanitizerBL.isBlacklistedFile(MainFile->getName()); 136839d628a0SDimitry Andric } 136939d628a0SDimitry Andric return false; 137039d628a0SDimitry Andric } 137139d628a0SDimitry Andric 137239d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV, 137339d628a0SDimitry Andric SourceLocation Loc, QualType Ty, 137439d628a0SDimitry Andric StringRef Category) const { 13758f0fd8f6SDimitry Andric // For now globals can be blacklisted only in ASan and KASan. 13768f0fd8f6SDimitry Andric if (!LangOpts.Sanitize.hasOneOf( 13778f0fd8f6SDimitry Andric SanitizerKind::Address | SanitizerKind::KernelAddress)) 137839d628a0SDimitry Andric return false; 137939d628a0SDimitry Andric const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 138039d628a0SDimitry Andric if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category)) 138139d628a0SDimitry Andric return true; 138239d628a0SDimitry Andric if (SanitizerBL.isBlacklistedLocation(Loc, Category)) 138339d628a0SDimitry Andric return true; 138439d628a0SDimitry Andric // Check global type. 138539d628a0SDimitry Andric if (!Ty.isNull()) { 138639d628a0SDimitry Andric // Drill down the array types: if global variable of a fixed type is 138739d628a0SDimitry Andric // blacklisted, we also don't instrument arrays of them. 138839d628a0SDimitry Andric while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 138939d628a0SDimitry Andric Ty = AT->getElementType(); 139039d628a0SDimitry Andric Ty = Ty.getCanonicalType().getUnqualifiedType(); 139139d628a0SDimitry Andric // We allow to blacklist only record types (classes, structs etc.) 139239d628a0SDimitry Andric if (Ty->isRecordType()) { 139339d628a0SDimitry Andric std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 139439d628a0SDimitry Andric if (SanitizerBL.isBlacklistedType(TypeStr, Category)) 139539d628a0SDimitry Andric return true; 139639d628a0SDimitry Andric } 139739d628a0SDimitry Andric } 139839d628a0SDimitry Andric return false; 139939d628a0SDimitry Andric } 140039d628a0SDimitry Andric 140139d628a0SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 1402e580952dSDimitry Andric // Never defer when EmitAllDecls is specified. 1403dff0c46cSDimitry Andric if (LangOpts.EmitAllDecls) 140439d628a0SDimitry Andric return true; 140539d628a0SDimitry Andric 140639d628a0SDimitry Andric return getContext().DeclMustBeEmitted(Global); 140739d628a0SDimitry Andric } 140839d628a0SDimitry Andric 140939d628a0SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 141039d628a0SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) 141139d628a0SDimitry Andric if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 141239d628a0SDimitry Andric // Implicit template instantiations may change linkage if they are later 141339d628a0SDimitry Andric // explicitly instantiated, so they should not be emitted eagerly. 1414f22ef01cSRoman Divacky return false; 1415875ed548SDimitry Andric // If OpenMP is enabled and threadprivates must be generated like TLS, delay 1416875ed548SDimitry Andric // codegen for global variables, because they may be marked as threadprivate. 1417875ed548SDimitry Andric if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 1418875ed548SDimitry Andric getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global)) 1419875ed548SDimitry Andric return false; 1420f22ef01cSRoman Divacky 142139d628a0SDimitry Andric return true; 1422f22ef01cSRoman Divacky } 1423f22ef01cSRoman Divacky 14240623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor( 14253861d79fSDimitry Andric const CXXUuidofExpr* E) { 14263861d79fSDimitry Andric // Sema has verified that IIDSource has a __declspec(uuid()), and that its 14273861d79fSDimitry Andric // well-formed. 1428f785676fSDimitry Andric StringRef Uuid = E->getUuidAsStringRef(Context); 1429f785676fSDimitry Andric std::string Name = "_GUID_" + Uuid.lower(); 1430f785676fSDimitry Andric std::replace(Name.begin(), Name.end(), '-', '_'); 14313861d79fSDimitry Andric 14320623d748SDimitry Andric // Contains a 32-bit field. 14330623d748SDimitry Andric CharUnits Alignment = CharUnits::fromQuantity(4); 14340623d748SDimitry Andric 14353861d79fSDimitry Andric // Look for an existing global. 14363861d79fSDimitry Andric if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 14370623d748SDimitry Andric return ConstantAddress(GV, Alignment); 14383861d79fSDimitry Andric 143939d628a0SDimitry Andric llvm::Constant *Init = EmitUuidofInitializer(Uuid); 14403861d79fSDimitry Andric assert(Init && "failed to initialize as constant"); 14413861d79fSDimitry Andric 144259d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 1443f785676fSDimitry Andric getModule(), Init->getType(), 1444f785676fSDimitry Andric /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 144533956c43SDimitry Andric if (supportsCOMDAT()) 144633956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 14470623d748SDimitry Andric return ConstantAddress(GV, Alignment); 14483861d79fSDimitry Andric } 14493861d79fSDimitry Andric 14500623d748SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 1451f22ef01cSRoman Divacky const AliasAttr *AA = VD->getAttr<AliasAttr>(); 1452f22ef01cSRoman Divacky assert(AA && "No alias?"); 1453f22ef01cSRoman Divacky 14540623d748SDimitry Andric CharUnits Alignment = getContext().getDeclAlign(VD); 14556122f3e6SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 1456f22ef01cSRoman Divacky 1457f22ef01cSRoman Divacky // See if there is already something with the target's name in the module. 1458f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 14593861d79fSDimitry Andric if (Entry) { 14603861d79fSDimitry Andric unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 14610623d748SDimitry Andric auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 14620623d748SDimitry Andric return ConstantAddress(Ptr, Alignment); 14633861d79fSDimitry Andric } 1464f22ef01cSRoman Divacky 1465f22ef01cSRoman Divacky llvm::Constant *Aliasee; 1466f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(DeclTy)) 14673861d79fSDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 14683861d79fSDimitry Andric GlobalDecl(cast<FunctionDecl>(VD)), 14692754fe60SDimitry Andric /*ForVTable=*/false); 1470f22ef01cSRoman Divacky else 1471f22ef01cSRoman Divacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 147259d1ed5bSDimitry Andric llvm::PointerType::getUnqual(DeclTy), 147359d1ed5bSDimitry Andric nullptr); 14743861d79fSDimitry Andric 147559d1ed5bSDimitry Andric auto *F = cast<llvm::GlobalValue>(Aliasee); 1476f22ef01cSRoman Divacky F->setLinkage(llvm::Function::ExternalWeakLinkage); 1477f22ef01cSRoman Divacky WeakRefReferences.insert(F); 1478f22ef01cSRoman Divacky 14790623d748SDimitry Andric return ConstantAddress(Aliasee, Alignment); 1480f22ef01cSRoman Divacky } 1481f22ef01cSRoman Divacky 1482f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) { 148359d1ed5bSDimitry Andric const auto *Global = cast<ValueDecl>(GD.getDecl()); 1484f22ef01cSRoman Divacky 1485f22ef01cSRoman Divacky // Weak references don't produce any output by themselves. 1486f22ef01cSRoman Divacky if (Global->hasAttr<WeakRefAttr>()) 1487f22ef01cSRoman Divacky return; 1488f22ef01cSRoman Divacky 1489f22ef01cSRoman Divacky // If this is an alias definition (which otherwise looks like a declaration) 1490f22ef01cSRoman Divacky // emit it now. 1491f22ef01cSRoman Divacky if (Global->hasAttr<AliasAttr>()) 1492f22ef01cSRoman Divacky return EmitAliasDefinition(GD); 1493f22ef01cSRoman Divacky 14946122f3e6SDimitry Andric // If this is CUDA, be selective about which declarations we emit. 1495dff0c46cSDimitry Andric if (LangOpts.CUDA) { 149633956c43SDimitry Andric if (LangOpts.CUDAIsDevice) { 14976122f3e6SDimitry Andric if (!Global->hasAttr<CUDADeviceAttr>() && 14986122f3e6SDimitry Andric !Global->hasAttr<CUDAGlobalAttr>() && 14996122f3e6SDimitry Andric !Global->hasAttr<CUDAConstantAttr>() && 15006122f3e6SDimitry Andric !Global->hasAttr<CUDASharedAttr>()) 15016122f3e6SDimitry Andric return; 15026122f3e6SDimitry Andric } else { 15036122f3e6SDimitry Andric if (!Global->hasAttr<CUDAHostAttr>() && ( 15046122f3e6SDimitry Andric Global->hasAttr<CUDADeviceAttr>() || 15056122f3e6SDimitry Andric Global->hasAttr<CUDAConstantAttr>() || 15066122f3e6SDimitry Andric Global->hasAttr<CUDASharedAttr>())) 15076122f3e6SDimitry Andric return; 1508e580952dSDimitry Andric } 1509e580952dSDimitry Andric } 1510e580952dSDimitry Andric 1511ea942507SDimitry Andric // If this is OpenMP device, check if it is legal to emit this global 1512ea942507SDimitry Andric // normally. 1513ea942507SDimitry Andric if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 1514ea942507SDimitry Andric return; 1515ea942507SDimitry Andric 15166122f3e6SDimitry Andric // Ignore declarations, they will be emitted on their first use. 151759d1ed5bSDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 1518f22ef01cSRoman Divacky // Forward declarations are emitted lazily on first use. 15196122f3e6SDimitry Andric if (!FD->doesThisDeclarationHaveABody()) { 15206122f3e6SDimitry Andric if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 1521f22ef01cSRoman Divacky return; 15226122f3e6SDimitry Andric 15236122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 152459d1ed5bSDimitry Andric 152559d1ed5bSDimitry Andric // Compute the function info and LLVM type. 152659d1ed5bSDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 152759d1ed5bSDimitry Andric llvm::Type *Ty = getTypes().GetFunctionType(FI); 152859d1ed5bSDimitry Andric 152959d1ed5bSDimitry Andric GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 153059d1ed5bSDimitry Andric /*DontDefer=*/false); 15316122f3e6SDimitry Andric return; 15326122f3e6SDimitry Andric } 1533f22ef01cSRoman Divacky } else { 153459d1ed5bSDimitry Andric const auto *VD = cast<VarDecl>(Global); 1535f22ef01cSRoman Divacky assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 1536f22ef01cSRoman Divacky 153759d1ed5bSDimitry Andric if (VD->isThisDeclarationADefinition() != VarDecl::Definition && 153859d1ed5bSDimitry Andric !Context.isMSStaticDataMemberInlineDefinition(VD)) 1539f22ef01cSRoman Divacky return; 1540f22ef01cSRoman Divacky } 1541f22ef01cSRoman Divacky 154239d628a0SDimitry Andric // Defer code generation to first use when possible, e.g. if this is an inline 154339d628a0SDimitry Andric // function. If the global must always be emitted, do it eagerly if possible 154439d628a0SDimitry Andric // to benefit from cache locality. 154539d628a0SDimitry Andric if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 1546f22ef01cSRoman Divacky // Emit the definition if it can't be deferred. 1547f22ef01cSRoman Divacky EmitGlobalDefinition(GD); 1548f22ef01cSRoman Divacky return; 1549f22ef01cSRoman Divacky } 1550f22ef01cSRoman Divacky 1551e580952dSDimitry Andric // If we're deferring emission of a C++ variable with an 1552e580952dSDimitry Andric // initializer, remember the order in which it appeared in the file. 1553dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 1554e580952dSDimitry Andric cast<VarDecl>(Global)->hasInit()) { 1555e580952dSDimitry Andric DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 155659d1ed5bSDimitry Andric CXXGlobalInits.push_back(nullptr); 1557e580952dSDimitry Andric } 1558e580952dSDimitry Andric 15596122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 156039d628a0SDimitry Andric if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) { 156139d628a0SDimitry Andric // The value has already been used and should therefore be emitted. 156259d1ed5bSDimitry Andric addDeferredDeclToEmit(GV, GD); 156339d628a0SDimitry Andric } else if (MustBeEmitted(Global)) { 156439d628a0SDimitry Andric // The value must be emitted, but cannot be emitted eagerly. 156539d628a0SDimitry Andric assert(!MayBeEmittedEagerly(Global)); 156639d628a0SDimitry Andric addDeferredDeclToEmit(/*GV=*/nullptr, GD); 156739d628a0SDimitry Andric } else { 1568f22ef01cSRoman Divacky // Otherwise, remember that we saw a deferred decl with this name. The 1569f22ef01cSRoman Divacky // first use of the mangled name will cause it to move into 1570f22ef01cSRoman Divacky // DeferredDeclsToEmit. 1571f22ef01cSRoman Divacky DeferredDecls[MangledName] = GD; 1572f22ef01cSRoman Divacky } 1573f22ef01cSRoman Divacky } 1574f22ef01cSRoman Divacky 1575f8254f43SDimitry Andric namespace { 1576f8254f43SDimitry Andric struct FunctionIsDirectlyRecursive : 1577f8254f43SDimitry Andric public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 1578f8254f43SDimitry Andric const StringRef Name; 1579dff0c46cSDimitry Andric const Builtin::Context &BI; 1580f8254f43SDimitry Andric bool Result; 1581dff0c46cSDimitry Andric FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 1582dff0c46cSDimitry Andric Name(N), BI(C), Result(false) { 1583f8254f43SDimitry Andric } 1584f8254f43SDimitry Andric typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 1585f8254f43SDimitry Andric 1586f8254f43SDimitry Andric bool TraverseCallExpr(CallExpr *E) { 1587dff0c46cSDimitry Andric const FunctionDecl *FD = E->getDirectCallee(); 1588dff0c46cSDimitry Andric if (!FD) 1589f8254f43SDimitry Andric return true; 1590dff0c46cSDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1591dff0c46cSDimitry Andric if (Attr && Name == Attr->getLabel()) { 1592dff0c46cSDimitry Andric Result = true; 1593dff0c46cSDimitry Andric return false; 1594dff0c46cSDimitry Andric } 1595dff0c46cSDimitry Andric unsigned BuiltinID = FD->getBuiltinID(); 15963dac3a9bSDimitry Andric if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 1597f8254f43SDimitry Andric return true; 15980623d748SDimitry Andric StringRef BuiltinName = BI.getName(BuiltinID); 1599dff0c46cSDimitry Andric if (BuiltinName.startswith("__builtin_") && 1600dff0c46cSDimitry Andric Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 1601f8254f43SDimitry Andric Result = true; 1602f8254f43SDimitry Andric return false; 1603f8254f43SDimitry Andric } 1604f8254f43SDimitry Andric return true; 1605f8254f43SDimitry Andric } 1606f8254f43SDimitry Andric }; 16070623d748SDimitry Andric 16080623d748SDimitry Andric struct DLLImportFunctionVisitor 16090623d748SDimitry Andric : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 16100623d748SDimitry Andric bool SafeToInline = true; 16110623d748SDimitry Andric 16120623d748SDimitry Andric bool VisitVarDecl(VarDecl *VD) { 16130623d748SDimitry Andric // A thread-local variable cannot be imported. 16140623d748SDimitry Andric SafeToInline = !VD->getTLSKind(); 16150623d748SDimitry Andric return SafeToInline; 16160623d748SDimitry Andric } 16170623d748SDimitry Andric 16180623d748SDimitry Andric // Make sure we're not referencing non-imported vars or functions. 16190623d748SDimitry Andric bool VisitDeclRefExpr(DeclRefExpr *E) { 16200623d748SDimitry Andric ValueDecl *VD = E->getDecl(); 16210623d748SDimitry Andric if (isa<FunctionDecl>(VD)) 16220623d748SDimitry Andric SafeToInline = VD->hasAttr<DLLImportAttr>(); 16230623d748SDimitry Andric else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 16240623d748SDimitry Andric SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 16250623d748SDimitry Andric return SafeToInline; 16260623d748SDimitry Andric } 16270623d748SDimitry Andric bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 16280623d748SDimitry Andric SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 16290623d748SDimitry Andric return SafeToInline; 16300623d748SDimitry Andric } 16310623d748SDimitry Andric bool VisitCXXNewExpr(CXXNewExpr *E) { 16320623d748SDimitry Andric SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 16330623d748SDimitry Andric return SafeToInline; 16340623d748SDimitry Andric } 16350623d748SDimitry Andric }; 1636f8254f43SDimitry Andric } 1637f8254f43SDimitry Andric 1638dff0c46cSDimitry Andric // isTriviallyRecursive - Check if this function calls another 1639dff0c46cSDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin, 1640dff0c46cSDimitry Andric // ends up pointing to itself. 1641f8254f43SDimitry Andric bool 1642dff0c46cSDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 1643dff0c46cSDimitry Andric StringRef Name; 1644dff0c46cSDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 1645dff0c46cSDimitry Andric // asm labels are a special kind of mangling we have to support. 1646dff0c46cSDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1647dff0c46cSDimitry Andric if (!Attr) 1648f8254f43SDimitry Andric return false; 1649dff0c46cSDimitry Andric Name = Attr->getLabel(); 1650dff0c46cSDimitry Andric } else { 1651dff0c46cSDimitry Andric Name = FD->getName(); 1652dff0c46cSDimitry Andric } 1653f8254f43SDimitry Andric 1654dff0c46cSDimitry Andric FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 1655dff0c46cSDimitry Andric Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 1656f8254f43SDimitry Andric return Walker.Result; 1657f8254f43SDimitry Andric } 1658f8254f43SDimitry Andric 1659f8254f43SDimitry Andric bool 1660f785676fSDimitry Andric CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 1661f785676fSDimitry Andric if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 1662f8254f43SDimitry Andric return true; 166359d1ed5bSDimitry Andric const auto *F = cast<FunctionDecl>(GD.getDecl()); 166459d1ed5bSDimitry Andric if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 1665f8254f43SDimitry Andric return false; 16660623d748SDimitry Andric 16670623d748SDimitry Andric if (F->hasAttr<DLLImportAttr>()) { 16680623d748SDimitry Andric // Check whether it would be safe to inline this dllimport function. 16690623d748SDimitry Andric DLLImportFunctionVisitor Visitor; 16700623d748SDimitry Andric Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 16710623d748SDimitry Andric if (!Visitor.SafeToInline) 16720623d748SDimitry Andric return false; 16730623d748SDimitry Andric } 16740623d748SDimitry Andric 1675f8254f43SDimitry Andric // PR9614. Avoid cases where the source code is lying to us. An available 1676f8254f43SDimitry Andric // externally function should have an equivalent function somewhere else, 1677f8254f43SDimitry Andric // but a function that calls itself is clearly not equivalent to the real 1678f8254f43SDimitry Andric // implementation. 1679f8254f43SDimitry Andric // This happens in glibc's btowc and in some configure checks. 1680dff0c46cSDimitry Andric return !isTriviallyRecursive(F); 1681f8254f43SDimitry Andric } 1682f8254f43SDimitry Andric 1683f785676fSDimitry Andric /// If the type for the method's class was generated by 1684f785676fSDimitry Andric /// CGDebugInfo::createContextChain(), the cache contains only a 1685f785676fSDimitry Andric /// limited DIType without any declarations. Since EmitFunctionStart() 1686f785676fSDimitry Andric /// needs to find the canonical declaration for each method, we need 1687f785676fSDimitry Andric /// to construct the complete type prior to emitting the method. 1688f785676fSDimitry Andric void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) { 1689f785676fSDimitry Andric if (!D->isInstance()) 1690f785676fSDimitry Andric return; 1691f785676fSDimitry Andric 1692f785676fSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 1693f785676fSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) { 169459d1ed5bSDimitry Andric const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext())); 1695f785676fSDimitry Andric DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation()); 1696f785676fSDimitry Andric } 1697f785676fSDimitry Andric } 1698f785676fSDimitry Andric 169959d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 170059d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 1701f22ef01cSRoman Divacky 1702f22ef01cSRoman Divacky PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 1703f22ef01cSRoman Divacky Context.getSourceManager(), 1704f22ef01cSRoman Divacky "Generating code for declaration"); 1705f22ef01cSRoman Divacky 1706f785676fSDimitry Andric if (isa<FunctionDecl>(D)) { 1707ffd1746dSEd Schouten // At -O0, don't generate IR for functions with available_externally 1708ffd1746dSEd Schouten // linkage. 1709f785676fSDimitry Andric if (!shouldEmitFunction(GD)) 1710ffd1746dSEd Schouten return; 1711ffd1746dSEd Schouten 171259d1ed5bSDimitry Andric if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 1713f785676fSDimitry Andric CompleteDIClassType(Method); 1714bd5abe19SDimitry Andric // Make sure to emit the definition(s) before we emit the thunks. 1715bd5abe19SDimitry Andric // This is necessary for the generation of certain thunks. 171659d1ed5bSDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method)) 171739d628a0SDimitry Andric ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType())); 171859d1ed5bSDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method)) 171939d628a0SDimitry Andric ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType())); 1720bd5abe19SDimitry Andric else 172159d1ed5bSDimitry Andric EmitGlobalFunctionDefinition(GD, GV); 1722bd5abe19SDimitry Andric 1723f22ef01cSRoman Divacky if (Method->isVirtual()) 1724f22ef01cSRoman Divacky getVTables().EmitThunks(GD); 1725f22ef01cSRoman Divacky 1726bd5abe19SDimitry Andric return; 1727ffd1746dSEd Schouten } 1728f22ef01cSRoman Divacky 172959d1ed5bSDimitry Andric return EmitGlobalFunctionDefinition(GD, GV); 1730ffd1746dSEd Schouten } 1731f22ef01cSRoman Divacky 173259d1ed5bSDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 1733f22ef01cSRoman Divacky return EmitGlobalVarDefinition(VD); 1734f22ef01cSRoman Divacky 17356122f3e6SDimitry Andric llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 1736f22ef01cSRoman Divacky } 1737f22ef01cSRoman Divacky 17380623d748SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 17390623d748SDimitry Andric llvm::Function *NewFn); 17400623d748SDimitry Andric 1741f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 1742f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there 1743f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially 1744f22ef01cSRoman Divacky /// bitcasted to the right type. 1745f22ef01cSRoman Divacky /// 1746f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this. This is used 1747f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created. 1748f22ef01cSRoman Divacky llvm::Constant * 17496122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName, 17506122f3e6SDimitry Andric llvm::Type *Ty, 1751f785676fSDimitry Andric GlobalDecl GD, bool ForVTable, 175239d628a0SDimitry Andric bool DontDefer, bool IsThunk, 17530623d748SDimitry Andric llvm::AttributeSet ExtraAttrs, 17540623d748SDimitry Andric bool IsForDefinition) { 1755f785676fSDimitry Andric const Decl *D = GD.getDecl(); 1756f785676fSDimitry Andric 1757f22ef01cSRoman Divacky // Lookup the entry, lazily creating it if necessary. 1758f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1759f22ef01cSRoman Divacky if (Entry) { 17603861d79fSDimitry Andric if (WeakRefReferences.erase(Entry)) { 1761f785676fSDimitry Andric const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 1762f22ef01cSRoman Divacky if (FD && !FD->hasAttr<WeakAttr>()) 1763f22ef01cSRoman Divacky Entry->setLinkage(llvm::Function::ExternalLinkage); 1764f22ef01cSRoman Divacky } 1765f22ef01cSRoman Divacky 176639d628a0SDimitry Andric // Handle dropped DLL attributes. 176739d628a0SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 176839d628a0SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 176939d628a0SDimitry Andric 17700623d748SDimitry Andric // If there are two attempts to define the same mangled name, issue an 17710623d748SDimitry Andric // error. 17720623d748SDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 17730623d748SDimitry Andric GlobalDecl OtherGD; 17740623d748SDimitry Andric // Check that GD is not yet in ExplicitDefinitions is required to make 17750623d748SDimitry Andric // sure that we issue an error only once. 17760623d748SDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 17770623d748SDimitry Andric (GD.getCanonicalDecl().getDecl() != 17780623d748SDimitry Andric OtherGD.getCanonicalDecl().getDecl()) && 17790623d748SDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 17800623d748SDimitry Andric getDiags().Report(D->getLocation(), 17810623d748SDimitry Andric diag::err_duplicate_mangled_name); 17820623d748SDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 17830623d748SDimitry Andric diag::note_previous_definition); 17840623d748SDimitry Andric } 17850623d748SDimitry Andric } 17860623d748SDimitry Andric 17870623d748SDimitry Andric if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 17880623d748SDimitry Andric (Entry->getType()->getElementType() == Ty)) { 1789f22ef01cSRoman Divacky return Entry; 17900623d748SDimitry Andric } 1791f22ef01cSRoman Divacky 1792f22ef01cSRoman Divacky // Make sure the result is of the correct type. 17930623d748SDimitry Andric // (If function is requested for a definition, we always need to create a new 17940623d748SDimitry Andric // function, not just return a bitcast.) 17950623d748SDimitry Andric if (!IsForDefinition) 179617a519f9SDimitry Andric return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 1797f22ef01cSRoman Divacky } 1798f22ef01cSRoman Divacky 1799f22ef01cSRoman Divacky // This function doesn't have a complete type (for example, the return 1800f22ef01cSRoman Divacky // type is an incomplete struct). Use a fake type instead, and make 1801f22ef01cSRoman Divacky // sure not to try to set attributes. 1802f22ef01cSRoman Divacky bool IsIncompleteFunction = false; 1803f22ef01cSRoman Divacky 18046122f3e6SDimitry Andric llvm::FunctionType *FTy; 1805f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(Ty)) { 1806f22ef01cSRoman Divacky FTy = cast<llvm::FunctionType>(Ty); 1807f22ef01cSRoman Divacky } else { 1808bd5abe19SDimitry Andric FTy = llvm::FunctionType::get(VoidTy, false); 1809f22ef01cSRoman Divacky IsIncompleteFunction = true; 1810f22ef01cSRoman Divacky } 1811ffd1746dSEd Schouten 18120623d748SDimitry Andric llvm::Function *F = 18130623d748SDimitry Andric llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 18140623d748SDimitry Andric Entry ? StringRef() : MangledName, &getModule()); 18150623d748SDimitry Andric 18160623d748SDimitry Andric // If we already created a function with the same mangled name (but different 18170623d748SDimitry Andric // type) before, take its name and add it to the list of functions to be 18180623d748SDimitry Andric // replaced with F at the end of CodeGen. 18190623d748SDimitry Andric // 18200623d748SDimitry Andric // This happens if there is a prototype for a function (e.g. "int f()") and 18210623d748SDimitry Andric // then a definition of a different type (e.g. "int f(int x)"). 18220623d748SDimitry Andric if (Entry) { 18230623d748SDimitry Andric F->takeName(Entry); 18240623d748SDimitry Andric 18250623d748SDimitry Andric // This might be an implementation of a function without a prototype, in 18260623d748SDimitry Andric // which case, try to do special replacement of calls which match the new 18270623d748SDimitry Andric // prototype. The really key thing here is that we also potentially drop 18280623d748SDimitry Andric // arguments from the call site so as to make a direct call, which makes the 18290623d748SDimitry Andric // inliner happier and suppresses a number of optimizer warnings (!) about 18300623d748SDimitry Andric // dropping arguments. 18310623d748SDimitry Andric if (!Entry->use_empty()) { 18320623d748SDimitry Andric ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 18330623d748SDimitry Andric Entry->removeDeadConstantUsers(); 18340623d748SDimitry Andric } 18350623d748SDimitry Andric 18360623d748SDimitry Andric llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 18370623d748SDimitry Andric F, Entry->getType()->getElementType()->getPointerTo()); 18380623d748SDimitry Andric addGlobalValReplacement(Entry, BC); 18390623d748SDimitry Andric } 18400623d748SDimitry Andric 1841f22ef01cSRoman Divacky assert(F->getName() == MangledName && "name was uniqued!"); 1842f785676fSDimitry Andric if (D) 184339d628a0SDimitry Andric SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 1844139f7f9bSDimitry Andric if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) { 1845139f7f9bSDimitry Andric llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex); 1846139f7f9bSDimitry Andric F->addAttributes(llvm::AttributeSet::FunctionIndex, 1847139f7f9bSDimitry Andric llvm::AttributeSet::get(VMContext, 1848139f7f9bSDimitry Andric llvm::AttributeSet::FunctionIndex, 1849139f7f9bSDimitry Andric B)); 1850139f7f9bSDimitry Andric } 1851f22ef01cSRoman Divacky 185259d1ed5bSDimitry Andric if (!DontDefer) { 185359d1ed5bSDimitry Andric // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 185459d1ed5bSDimitry Andric // each other bottoming out with the base dtor. Therefore we emit non-base 185559d1ed5bSDimitry Andric // dtors on usage, even if there is no dtor definition in the TU. 185659d1ed5bSDimitry Andric if (D && isa<CXXDestructorDecl>(D) && 185759d1ed5bSDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 185859d1ed5bSDimitry Andric GD.getDtorType())) 185959d1ed5bSDimitry Andric addDeferredDeclToEmit(F, GD); 186059d1ed5bSDimitry Andric 1861f22ef01cSRoman Divacky // This is the first use or definition of a mangled name. If there is a 1862f22ef01cSRoman Divacky // deferred decl with this name, remember that we need to emit it at the end 1863f22ef01cSRoman Divacky // of the file. 186459d1ed5bSDimitry Andric auto DDI = DeferredDecls.find(MangledName); 1865f22ef01cSRoman Divacky if (DDI != DeferredDecls.end()) { 186659d1ed5bSDimitry Andric // Move the potentially referenced deferred decl to the 186759d1ed5bSDimitry Andric // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 186859d1ed5bSDimitry Andric // don't need it anymore). 186959d1ed5bSDimitry Andric addDeferredDeclToEmit(F, DDI->second); 1870f22ef01cSRoman Divacky DeferredDecls.erase(DDI); 18712754fe60SDimitry Andric 18722754fe60SDimitry Andric // Otherwise, there are cases we have to worry about where we're 18732754fe60SDimitry Andric // using a declaration for which we must emit a definition but where 18742754fe60SDimitry Andric // we might not find a top-level definition: 18752754fe60SDimitry Andric // - member functions defined inline in their classes 18762754fe60SDimitry Andric // - friend functions defined inline in some class 18772754fe60SDimitry Andric // - special member functions with implicit definitions 18782754fe60SDimitry Andric // If we ever change our AST traversal to walk into class methods, 18792754fe60SDimitry Andric // this will be unnecessary. 18802754fe60SDimitry Andric // 188159d1ed5bSDimitry Andric // We also don't emit a definition for a function if it's going to be an 188239d628a0SDimitry Andric // entry in a vtable, unless it's already marked as used. 1883f785676fSDimitry Andric } else if (getLangOpts().CPlusPlus && D) { 18842754fe60SDimitry Andric // Look for a declaration that's lexically in a record. 188539d628a0SDimitry Andric for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 188639d628a0SDimitry Andric FD = FD->getPreviousDecl()) { 18872754fe60SDimitry Andric if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 188839d628a0SDimitry Andric if (FD->doesThisDeclarationHaveABody()) { 188959d1ed5bSDimitry Andric addDeferredDeclToEmit(F, GD.getWithDecl(FD)); 18902754fe60SDimitry Andric break; 1891f22ef01cSRoman Divacky } 1892f22ef01cSRoman Divacky } 189339d628a0SDimitry Andric } 1894f22ef01cSRoman Divacky } 189559d1ed5bSDimitry Andric } 1896f22ef01cSRoman Divacky 1897f22ef01cSRoman Divacky // Make sure the result is of the requested type. 1898f22ef01cSRoman Divacky if (!IsIncompleteFunction) { 1899f22ef01cSRoman Divacky assert(F->getType()->getElementType() == Ty); 1900f22ef01cSRoman Divacky return F; 1901f22ef01cSRoman Divacky } 1902f22ef01cSRoman Divacky 190317a519f9SDimitry Andric llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 1904f22ef01cSRoman Divacky return llvm::ConstantExpr::getBitCast(F, PTy); 1905f22ef01cSRoman Divacky } 1906f22ef01cSRoman Divacky 1907f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function. If Ty is 1908f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to 1909f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function). 1910f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 19116122f3e6SDimitry Andric llvm::Type *Ty, 191259d1ed5bSDimitry Andric bool ForVTable, 19130623d748SDimitry Andric bool DontDefer, 19140623d748SDimitry Andric bool IsForDefinition) { 1915f22ef01cSRoman Divacky // If there was no specific requested type, just convert it now. 19160623d748SDimitry Andric if (!Ty) { 19170623d748SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 19180623d748SDimitry Andric auto CanonTy = Context.getCanonicalType(FD->getType()); 19190623d748SDimitry Andric Ty = getTypes().ConvertFunctionType(CanonTy, FD); 19200623d748SDimitry Andric } 1921ffd1746dSEd Schouten 19226122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 19230623d748SDimitry Andric return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 19240623d748SDimitry Andric /*IsThunk=*/false, llvm::AttributeSet(), 19250623d748SDimitry Andric IsForDefinition); 1926f22ef01cSRoman Divacky } 1927f22ef01cSRoman Divacky 1928f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified 1929f22ef01cSRoman Divacky /// type and name. 1930f22ef01cSRoman Divacky llvm::Constant * 19316122f3e6SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, 19326122f3e6SDimitry Andric StringRef Name, 1933139f7f9bSDimitry Andric llvm::AttributeSet ExtraAttrs) { 193459d1ed5bSDimitry Andric llvm::Constant *C = 193559d1ed5bSDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 193639d628a0SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); 193759d1ed5bSDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) 1938139f7f9bSDimitry Andric if (F->empty()) 1939139f7f9bSDimitry Andric F->setCallingConv(getRuntimeCC()); 1940139f7f9bSDimitry Andric return C; 1941f22ef01cSRoman Divacky } 1942f22ef01cSRoman Divacky 194339d628a0SDimitry Andric /// CreateBuiltinFunction - Create a new builtin function with the specified 194439d628a0SDimitry Andric /// type and name. 194539d628a0SDimitry Andric llvm::Constant * 194639d628a0SDimitry Andric CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, 194739d628a0SDimitry Andric StringRef Name, 194839d628a0SDimitry Andric llvm::AttributeSet ExtraAttrs) { 194939d628a0SDimitry Andric llvm::Constant *C = 195039d628a0SDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 195139d628a0SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); 195239d628a0SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) 195339d628a0SDimitry Andric if (F->empty()) 195439d628a0SDimitry Andric F->setCallingConv(getBuiltinCC()); 195539d628a0SDimitry Andric return C; 195639d628a0SDimitry Andric } 195739d628a0SDimitry Andric 1958dff0c46cSDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted 1959dff0c46cSDimitry Andric /// as a constant. 1960dff0c46cSDimitry Andric /// 1961dff0c46cSDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs 1962dff0c46cSDimitry Andric /// will not be considered. The caller will need to verify that the object is 1963dff0c46cSDimitry Andric /// not written to during its construction. 1964dff0c46cSDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 1965dff0c46cSDimitry Andric if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 1966f22ef01cSRoman Divacky return false; 1967bd5abe19SDimitry Andric 1968dff0c46cSDimitry Andric if (Context.getLangOpts().CPlusPlus) { 1969dff0c46cSDimitry Andric if (const CXXRecordDecl *Record 1970dff0c46cSDimitry Andric = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 1971dff0c46cSDimitry Andric return ExcludeCtor && !Record->hasMutableFields() && 1972dff0c46cSDimitry Andric Record->hasTrivialDestructor(); 1973f22ef01cSRoman Divacky } 1974bd5abe19SDimitry Andric 1975f22ef01cSRoman Divacky return true; 1976f22ef01cSRoman Divacky } 1977f22ef01cSRoman Divacky 1978f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 1979f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type. If there 1980f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially 1981f22ef01cSRoman Divacky /// bitcasted to the right type. 1982f22ef01cSRoman Divacky /// 1983f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this. This is used 1984f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created. 1985f22ef01cSRoman Divacky llvm::Constant * 19866122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 19876122f3e6SDimitry Andric llvm::PointerType *Ty, 198859d1ed5bSDimitry Andric const VarDecl *D) { 1989f22ef01cSRoman Divacky // Lookup the entry, lazily creating it if necessary. 1990f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1991f22ef01cSRoman Divacky if (Entry) { 19923861d79fSDimitry Andric if (WeakRefReferences.erase(Entry)) { 1993f22ef01cSRoman Divacky if (D && !D->hasAttr<WeakAttr>()) 1994f22ef01cSRoman Divacky Entry->setLinkage(llvm::Function::ExternalLinkage); 1995f22ef01cSRoman Divacky } 1996f22ef01cSRoman Divacky 199739d628a0SDimitry Andric // Handle dropped DLL attributes. 199839d628a0SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 199939d628a0SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 200039d628a0SDimitry Andric 2001f22ef01cSRoman Divacky if (Entry->getType() == Ty) 2002f22ef01cSRoman Divacky return Entry; 2003f22ef01cSRoman Divacky 2004f22ef01cSRoman Divacky // Make sure the result is of the correct type. 2005f785676fSDimitry Andric if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) 2006f785676fSDimitry Andric return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); 2007f785676fSDimitry Andric 2008f22ef01cSRoman Divacky return llvm::ConstantExpr::getBitCast(Entry, Ty); 2009f22ef01cSRoman Divacky } 2010f22ef01cSRoman Divacky 201159d1ed5bSDimitry Andric unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace()); 201259d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 201359d1ed5bSDimitry Andric getModule(), Ty->getElementType(), false, 201459d1ed5bSDimitry Andric llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr, 201559d1ed5bSDimitry Andric llvm::GlobalVariable::NotThreadLocal, AddrSpace); 201659d1ed5bSDimitry Andric 2017f22ef01cSRoman Divacky // This is the first use or definition of a mangled name. If there is a 2018f22ef01cSRoman Divacky // deferred decl with this name, remember that we need to emit it at the end 2019f22ef01cSRoman Divacky // of the file. 202059d1ed5bSDimitry Andric auto DDI = DeferredDecls.find(MangledName); 2021f22ef01cSRoman Divacky if (DDI != DeferredDecls.end()) { 2022f22ef01cSRoman Divacky // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 2023f22ef01cSRoman Divacky // list, and remove it from DeferredDecls (since we don't need it anymore). 202459d1ed5bSDimitry Andric addDeferredDeclToEmit(GV, DDI->second); 2025f22ef01cSRoman Divacky DeferredDecls.erase(DDI); 2026f22ef01cSRoman Divacky } 2027f22ef01cSRoman Divacky 2028f22ef01cSRoman Divacky // Handle things which are present even on external declarations. 2029f22ef01cSRoman Divacky if (D) { 2030f22ef01cSRoman Divacky // FIXME: This code is overly simple and should be merged with other global 2031f22ef01cSRoman Divacky // handling. 2032dff0c46cSDimitry Andric GV->setConstant(isTypeConstant(D->getType(), false)); 2033f22ef01cSRoman Divacky 203433956c43SDimitry Andric GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 203533956c43SDimitry Andric 203659d1ed5bSDimitry Andric setLinkageAndVisibilityForGV(GV, D); 20372754fe60SDimitry Andric 2038284c1978SDimitry Andric if (D->getTLSKind()) { 2039284c1978SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 20400623d748SDimitry Andric CXXThreadLocals.push_back(D); 20417ae0e2c9SDimitry Andric setTLSMode(GV, *D); 2042f22ef01cSRoman Divacky } 2043f785676fSDimitry Andric 2044f785676fSDimitry Andric // If required by the ABI, treat declarations of static data members with 2045f785676fSDimitry Andric // inline initializers as definitions. 204659d1ed5bSDimitry Andric if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 2047f785676fSDimitry Andric EmitGlobalVarDefinition(D); 2048284c1978SDimitry Andric } 2049f22ef01cSRoman Divacky 205059d1ed5bSDimitry Andric // Handle XCore specific ABI requirements. 205159d1ed5bSDimitry Andric if (getTarget().getTriple().getArch() == llvm::Triple::xcore && 205259d1ed5bSDimitry Andric D->getLanguageLinkage() == CLanguageLinkage && 205359d1ed5bSDimitry Andric D->getType().isConstant(Context) && 205459d1ed5bSDimitry Andric isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 205559d1ed5bSDimitry Andric GV->setSection(".cp.rodata"); 205659d1ed5bSDimitry Andric } 205759d1ed5bSDimitry Andric 20587ae0e2c9SDimitry Andric if (AddrSpace != Ty->getAddressSpace()) 2059f785676fSDimitry Andric return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty); 2060f785676fSDimitry Andric 2061f22ef01cSRoman Divacky return GV; 2062f22ef01cSRoman Divacky } 2063f22ef01cSRoman Divacky 20640623d748SDimitry Andric llvm::Constant * 20650623d748SDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, 20660623d748SDimitry Andric bool IsForDefinition) { 20670623d748SDimitry Andric if (isa<CXXConstructorDecl>(GD.getDecl())) 20680623d748SDimitry Andric return getAddrOfCXXStructor(cast<CXXConstructorDecl>(GD.getDecl()), 20690623d748SDimitry Andric getFromCtorType(GD.getCtorType()), 20700623d748SDimitry Andric /*FnInfo=*/nullptr, /*FnType=*/nullptr, 20710623d748SDimitry Andric /*DontDefer=*/false, IsForDefinition); 20720623d748SDimitry Andric else if (isa<CXXDestructorDecl>(GD.getDecl())) 20730623d748SDimitry Andric return getAddrOfCXXStructor(cast<CXXDestructorDecl>(GD.getDecl()), 20740623d748SDimitry Andric getFromDtorType(GD.getDtorType()), 20750623d748SDimitry Andric /*FnInfo=*/nullptr, /*FnType=*/nullptr, 20760623d748SDimitry Andric /*DontDefer=*/false, IsForDefinition); 20770623d748SDimitry Andric else if (isa<CXXMethodDecl>(GD.getDecl())) { 20780623d748SDimitry Andric auto FInfo = &getTypes().arrangeCXXMethodDeclaration( 20790623d748SDimitry Andric cast<CXXMethodDecl>(GD.getDecl())); 20800623d748SDimitry Andric auto Ty = getTypes().GetFunctionType(*FInfo); 20810623d748SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 20820623d748SDimitry Andric IsForDefinition); 20830623d748SDimitry Andric } else if (isa<FunctionDecl>(GD.getDecl())) { 20840623d748SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 20850623d748SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 20860623d748SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 20870623d748SDimitry Andric IsForDefinition); 20880623d748SDimitry Andric } else 20890623d748SDimitry Andric return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl())); 20900623d748SDimitry Andric } 2091f22ef01cSRoman Divacky 20922754fe60SDimitry Andric llvm::GlobalVariable * 20936122f3e6SDimitry Andric CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 20946122f3e6SDimitry Andric llvm::Type *Ty, 20952754fe60SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage) { 20962754fe60SDimitry Andric llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 209759d1ed5bSDimitry Andric llvm::GlobalVariable *OldGV = nullptr; 20982754fe60SDimitry Andric 20992754fe60SDimitry Andric if (GV) { 21002754fe60SDimitry Andric // Check if the variable has the right type. 21012754fe60SDimitry Andric if (GV->getType()->getElementType() == Ty) 21022754fe60SDimitry Andric return GV; 21032754fe60SDimitry Andric 21042754fe60SDimitry Andric // Because C++ name mangling, the only way we can end up with an already 21052754fe60SDimitry Andric // existing global with the same name is if it has been declared extern "C". 21062754fe60SDimitry Andric assert(GV->isDeclaration() && "Declaration has wrong type!"); 21072754fe60SDimitry Andric OldGV = GV; 21082754fe60SDimitry Andric } 21092754fe60SDimitry Andric 21102754fe60SDimitry Andric // Create a new variable. 21112754fe60SDimitry Andric GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 211259d1ed5bSDimitry Andric Linkage, nullptr, Name); 21132754fe60SDimitry Andric 21142754fe60SDimitry Andric if (OldGV) { 21152754fe60SDimitry Andric // Replace occurrences of the old variable if needed. 21162754fe60SDimitry Andric GV->takeName(OldGV); 21172754fe60SDimitry Andric 21182754fe60SDimitry Andric if (!OldGV->use_empty()) { 21192754fe60SDimitry Andric llvm::Constant *NewPtrForOldDecl = 21202754fe60SDimitry Andric llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 21212754fe60SDimitry Andric OldGV->replaceAllUsesWith(NewPtrForOldDecl); 21222754fe60SDimitry Andric } 21232754fe60SDimitry Andric 21242754fe60SDimitry Andric OldGV->eraseFromParent(); 21252754fe60SDimitry Andric } 21262754fe60SDimitry Andric 212733956c43SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker() && 212833956c43SDimitry Andric !GV->hasAvailableExternallyLinkage()) 212933956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 213033956c43SDimitry Andric 21312754fe60SDimitry Andric return GV; 21322754fe60SDimitry Andric } 21332754fe60SDimitry Andric 2134f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 2135f22ef01cSRoman Divacky /// given global variable. If Ty is non-null and if the global doesn't exist, 2136cb4dff85SDimitry Andric /// then it will be created with the specified type instead of whatever the 2137f22ef01cSRoman Divacky /// normal requested type would be. 2138f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 21396122f3e6SDimitry Andric llvm::Type *Ty) { 2140f22ef01cSRoman Divacky assert(D->hasGlobalStorage() && "Not a global variable"); 2141f22ef01cSRoman Divacky QualType ASTTy = D->getType(); 214259d1ed5bSDimitry Andric if (!Ty) 2143f22ef01cSRoman Divacky Ty = getTypes().ConvertTypeForMem(ASTTy); 2144f22ef01cSRoman Divacky 21456122f3e6SDimitry Andric llvm::PointerType *PTy = 21463b0f4066SDimitry Andric llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 2147f22ef01cSRoman Divacky 21486122f3e6SDimitry Andric StringRef MangledName = getMangledName(D); 2149f22ef01cSRoman Divacky return GetOrCreateLLVMGlobal(MangledName, PTy, D); 2150f22ef01cSRoman Divacky } 2151f22ef01cSRoman Divacky 2152f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the 2153f22ef01cSRoman Divacky /// specified type and name. 2154f22ef01cSRoman Divacky llvm::Constant * 21556122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 21566122f3e6SDimitry Andric StringRef Name) { 215759d1ed5bSDimitry Andric return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr); 2158f22ef01cSRoman Divacky } 2159f22ef01cSRoman Divacky 2160f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 2161f22ef01cSRoman Divacky assert(!D->getInit() && "Cannot emit definite definitions here!"); 2162f22ef01cSRoman Divacky 216339d628a0SDimitry Andric if (!MustBeEmitted(D)) { 2164f22ef01cSRoman Divacky // If we have not seen a reference to this variable yet, place it 2165f22ef01cSRoman Divacky // into the deferred declarations table to be emitted if needed 2166f22ef01cSRoman Divacky // later. 21676122f3e6SDimitry Andric StringRef MangledName = getMangledName(D); 2168f22ef01cSRoman Divacky if (!GetGlobalValue(MangledName)) { 2169f22ef01cSRoman Divacky DeferredDecls[MangledName] = D; 2170f22ef01cSRoman Divacky return; 2171f22ef01cSRoman Divacky } 2172f22ef01cSRoman Divacky } 2173f22ef01cSRoman Divacky 2174f22ef01cSRoman Divacky // The tentative definition is the only definition. 2175f22ef01cSRoman Divacky EmitGlobalVarDefinition(D); 2176f22ef01cSRoman Divacky } 2177f22ef01cSRoman Divacky 21786122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 21792754fe60SDimitry Andric return Context.toCharUnitsFromBits( 21800623d748SDimitry Andric getDataLayout().getTypeStoreSizeInBits(Ty)); 2181f22ef01cSRoman Divacky } 2182f22ef01cSRoman Divacky 21837ae0e2c9SDimitry Andric unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D, 21847ae0e2c9SDimitry Andric unsigned AddrSpace) { 218533956c43SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { 21867ae0e2c9SDimitry Andric if (D->hasAttr<CUDAConstantAttr>()) 21877ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant); 21887ae0e2c9SDimitry Andric else if (D->hasAttr<CUDASharedAttr>()) 21897ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared); 21907ae0e2c9SDimitry Andric else 21917ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device); 21927ae0e2c9SDimitry Andric } 21937ae0e2c9SDimitry Andric 21947ae0e2c9SDimitry Andric return AddrSpace; 21957ae0e2c9SDimitry Andric } 21967ae0e2c9SDimitry Andric 2197284c1978SDimitry Andric template<typename SomeDecl> 2198284c1978SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 2199284c1978SDimitry Andric llvm::GlobalValue *GV) { 2200284c1978SDimitry Andric if (!getLangOpts().CPlusPlus) 2201284c1978SDimitry Andric return; 2202284c1978SDimitry Andric 2203284c1978SDimitry Andric // Must have 'used' attribute, or else inline assembly can't rely on 2204284c1978SDimitry Andric // the name existing. 2205284c1978SDimitry Andric if (!D->template hasAttr<UsedAttr>()) 2206284c1978SDimitry Andric return; 2207284c1978SDimitry Andric 2208284c1978SDimitry Andric // Must have internal linkage and an ordinary name. 2209f785676fSDimitry Andric if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 2210284c1978SDimitry Andric return; 2211284c1978SDimitry Andric 2212284c1978SDimitry Andric // Must be in an extern "C" context. Entities declared directly within 2213284c1978SDimitry Andric // a record are not extern "C" even if the record is in such a context. 2214f785676fSDimitry Andric const SomeDecl *First = D->getFirstDecl(); 2215284c1978SDimitry Andric if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 2216284c1978SDimitry Andric return; 2217284c1978SDimitry Andric 2218284c1978SDimitry Andric // OK, this is an internal linkage entity inside an extern "C" linkage 2219284c1978SDimitry Andric // specification. Make a note of that so we can give it the "expected" 2220284c1978SDimitry Andric // mangled name if nothing else is using that name. 2221284c1978SDimitry Andric std::pair<StaticExternCMap::iterator, bool> R = 2222284c1978SDimitry Andric StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 2223284c1978SDimitry Andric 2224284c1978SDimitry Andric // If we have multiple internal linkage entities with the same name 2225284c1978SDimitry Andric // in extern "C" regions, none of them gets that name. 2226284c1978SDimitry Andric if (!R.second) 222759d1ed5bSDimitry Andric R.first->second = nullptr; 2228284c1978SDimitry Andric } 2229284c1978SDimitry Andric 223033956c43SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 223133956c43SDimitry Andric if (!CGM.supportsCOMDAT()) 223233956c43SDimitry Andric return false; 223333956c43SDimitry Andric 223433956c43SDimitry Andric if (D.hasAttr<SelectAnyAttr>()) 223533956c43SDimitry Andric return true; 223633956c43SDimitry Andric 223733956c43SDimitry Andric GVALinkage Linkage; 223833956c43SDimitry Andric if (auto *VD = dyn_cast<VarDecl>(&D)) 223933956c43SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 224033956c43SDimitry Andric else 224133956c43SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 224233956c43SDimitry Andric 224333956c43SDimitry Andric switch (Linkage) { 224433956c43SDimitry Andric case GVA_Internal: 224533956c43SDimitry Andric case GVA_AvailableExternally: 224633956c43SDimitry Andric case GVA_StrongExternal: 224733956c43SDimitry Andric return false; 224833956c43SDimitry Andric case GVA_DiscardableODR: 224933956c43SDimitry Andric case GVA_StrongODR: 225033956c43SDimitry Andric return true; 225133956c43SDimitry Andric } 225233956c43SDimitry Andric llvm_unreachable("No such linkage"); 225333956c43SDimitry Andric } 225433956c43SDimitry Andric 225533956c43SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 225633956c43SDimitry Andric llvm::GlobalObject &GO) { 225733956c43SDimitry Andric if (!shouldBeInCOMDAT(*this, D)) 225833956c43SDimitry Andric return; 225933956c43SDimitry Andric GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 226033956c43SDimitry Andric } 226133956c43SDimitry Andric 2262f22ef01cSRoman Divacky void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 226359d1ed5bSDimitry Andric llvm::Constant *Init = nullptr; 2264f22ef01cSRoman Divacky QualType ASTTy = D->getType(); 2265dff0c46cSDimitry Andric CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2266dff0c46cSDimitry Andric bool NeedsGlobalCtor = false; 2267dff0c46cSDimitry Andric bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 2268f22ef01cSRoman Divacky 2269dff0c46cSDimitry Andric const VarDecl *InitDecl; 2270dff0c46cSDimitry Andric const Expr *InitExpr = D->getAnyInitializer(InitDecl); 2271f22ef01cSRoman Divacky 22720623d748SDimitry Andric // CUDA E.2.4.1 "__shared__ variables cannot have an initialization as part 22730623d748SDimitry Andric // of their declaration." 22740623d748SDimitry Andric if (getLangOpts().CPlusPlus && getLangOpts().CUDAIsDevice 22750623d748SDimitry Andric && D->hasAttr<CUDASharedAttr>()) { 22760623d748SDimitry Andric if (InitExpr) { 22770623d748SDimitry Andric const auto *C = dyn_cast<CXXConstructExpr>(InitExpr); 22780623d748SDimitry Andric if (C == nullptr || !C->getConstructor()->hasTrivialBody()) 22790623d748SDimitry Andric Error(D->getLocation(), 22800623d748SDimitry Andric "__shared__ variable cannot have an initialization."); 22810623d748SDimitry Andric } 22820623d748SDimitry Andric Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy)); 22830623d748SDimitry Andric } else if (!InitExpr) { 2284f22ef01cSRoman Divacky // This is a tentative definition; tentative definitions are 2285f22ef01cSRoman Divacky // implicitly initialized with { 0 }. 2286f22ef01cSRoman Divacky // 2287f22ef01cSRoman Divacky // Note that tentative definitions are only emitted at the end of 2288f22ef01cSRoman Divacky // a translation unit, so they should never have incomplete 2289f22ef01cSRoman Divacky // type. In addition, EmitTentativeDefinition makes sure that we 2290f22ef01cSRoman Divacky // never attempt to emit a tentative definition if a real one 2291f22ef01cSRoman Divacky // exists. A use may still exists, however, so we still may need 2292f22ef01cSRoman Divacky // to do a RAUW. 2293f22ef01cSRoman Divacky assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 2294f22ef01cSRoman Divacky Init = EmitNullConstant(D->getType()); 2295f22ef01cSRoman Divacky } else { 22967ae0e2c9SDimitry Andric initializedGlobalDecl = GlobalDecl(D); 2297dff0c46cSDimitry Andric Init = EmitConstantInit(*InitDecl); 2298f785676fSDimitry Andric 2299f22ef01cSRoman Divacky if (!Init) { 2300f22ef01cSRoman Divacky QualType T = InitExpr->getType(); 2301f22ef01cSRoman Divacky if (D->getType()->isReferenceType()) 2302f22ef01cSRoman Divacky T = D->getType(); 2303f22ef01cSRoman Divacky 2304dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus) { 2305f22ef01cSRoman Divacky Init = EmitNullConstant(T); 2306dff0c46cSDimitry Andric NeedsGlobalCtor = true; 2307f22ef01cSRoman Divacky } else { 2308f22ef01cSRoman Divacky ErrorUnsupported(D, "static initializer"); 2309f22ef01cSRoman Divacky Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 2310f22ef01cSRoman Divacky } 2311e580952dSDimitry Andric } else { 2312e580952dSDimitry Andric // We don't need an initializer, so remove the entry for the delayed 2313dff0c46cSDimitry Andric // initializer position (just in case this entry was delayed) if we 2314dff0c46cSDimitry Andric // also don't need to register a destructor. 2315dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 2316e580952dSDimitry Andric DelayedCXXInitPosition.erase(D); 2317f22ef01cSRoman Divacky } 2318f22ef01cSRoman Divacky } 2319f22ef01cSRoman Divacky 23206122f3e6SDimitry Andric llvm::Type* InitType = Init->getType(); 2321f22ef01cSRoman Divacky llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 2322f22ef01cSRoman Divacky 2323f22ef01cSRoman Divacky // Strip off a bitcast if we got one back. 232459d1ed5bSDimitry Andric if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 2325f22ef01cSRoman Divacky assert(CE->getOpcode() == llvm::Instruction::BitCast || 2326f785676fSDimitry Andric CE->getOpcode() == llvm::Instruction::AddrSpaceCast || 2327f785676fSDimitry Andric // All zero index gep. 2328f22ef01cSRoman Divacky CE->getOpcode() == llvm::Instruction::GetElementPtr); 2329f22ef01cSRoman Divacky Entry = CE->getOperand(0); 2330f22ef01cSRoman Divacky } 2331f22ef01cSRoman Divacky 2332f22ef01cSRoman Divacky // Entry is now either a Function or GlobalVariable. 233359d1ed5bSDimitry Andric auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 2334f22ef01cSRoman Divacky 2335f22ef01cSRoman Divacky // We have a definition after a declaration with the wrong type. 2336f22ef01cSRoman Divacky // We must make a new GlobalVariable* and update everything that used OldGV 2337f22ef01cSRoman Divacky // (a declaration or tentative definition) with the new GlobalVariable* 2338f22ef01cSRoman Divacky // (which will be a definition). 2339f22ef01cSRoman Divacky // 2340f22ef01cSRoman Divacky // This happens if there is a prototype for a global (e.g. 2341f22ef01cSRoman Divacky // "extern int x[];") and then a definition of a different type (e.g. 2342f22ef01cSRoman Divacky // "int x[10];"). This also happens when an initializer has a different type 2343f22ef01cSRoman Divacky // from the type of the global (this happens with unions). 234459d1ed5bSDimitry Andric if (!GV || 2345f22ef01cSRoman Divacky GV->getType()->getElementType() != InitType || 23463b0f4066SDimitry Andric GV->getType()->getAddressSpace() != 23477ae0e2c9SDimitry Andric GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) { 2348f22ef01cSRoman Divacky 2349f22ef01cSRoman Divacky // Move the old entry aside so that we'll create a new one. 23506122f3e6SDimitry Andric Entry->setName(StringRef()); 2351f22ef01cSRoman Divacky 2352f22ef01cSRoman Divacky // Make a new global with the correct type, this is now guaranteed to work. 2353f22ef01cSRoman Divacky GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 2354f22ef01cSRoman Divacky 2355f22ef01cSRoman Divacky // Replace all uses of the old global with the new global 2356f22ef01cSRoman Divacky llvm::Constant *NewPtrForOldDecl = 2357f22ef01cSRoman Divacky llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 2358f22ef01cSRoman Divacky Entry->replaceAllUsesWith(NewPtrForOldDecl); 2359f22ef01cSRoman Divacky 2360f22ef01cSRoman Divacky // Erase the old global, since it is no longer used. 2361f22ef01cSRoman Divacky cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 2362f22ef01cSRoman Divacky } 2363f22ef01cSRoman Divacky 2364284c1978SDimitry Andric MaybeHandleStaticInExternC(D, GV); 2365284c1978SDimitry Andric 23666122f3e6SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 23676122f3e6SDimitry Andric AddGlobalAnnotations(D, GV); 2368f22ef01cSRoman Divacky 23690623d748SDimitry Andric // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 23700623d748SDimitry Andric // the device. [...]" 23710623d748SDimitry Andric // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 23720623d748SDimitry Andric // __device__, declares a variable that: [...] 23730623d748SDimitry Andric // Is accessible from all the threads within the grid and from the host 23740623d748SDimitry Andric // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 23750623d748SDimitry Andric // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 23760623d748SDimitry Andric if (GV && LangOpts.CUDA && LangOpts.CUDAIsDevice && 23770623d748SDimitry Andric (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>())) { 23780623d748SDimitry Andric GV->setExternallyInitialized(true); 23790623d748SDimitry Andric } 2380f22ef01cSRoman Divacky GV->setInitializer(Init); 2381f22ef01cSRoman Divacky 2382f22ef01cSRoman Divacky // If it is safe to mark the global 'constant', do so now. 2383dff0c46cSDimitry Andric GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 2384dff0c46cSDimitry Andric isTypeConstant(D->getType(), true)); 2385f22ef01cSRoman Divacky 238639d628a0SDimitry Andric // If it is in a read-only section, mark it 'constant'. 238739d628a0SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 238839d628a0SDimitry Andric const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 238939d628a0SDimitry Andric if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 239039d628a0SDimitry Andric GV->setConstant(true); 239139d628a0SDimitry Andric } 239239d628a0SDimitry Andric 2393f22ef01cSRoman Divacky GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 2394f22ef01cSRoman Divacky 2395f22ef01cSRoman Divacky // Set the llvm linkage type as appropriate. 23962754fe60SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 239759d1ed5bSDimitry Andric getLLVMLinkageVarDefinition(D, GV->isConstant()); 2398f785676fSDimitry Andric 23990623d748SDimitry Andric // On Darwin, if the normal linkage of a C++ thread_local variable is 24000623d748SDimitry Andric // LinkOnce or Weak, we keep the normal linkage to prevent multiple 24010623d748SDimitry Andric // copies within a linkage unit; otherwise, the backing variable has 24020623d748SDimitry Andric // internal linkage and all accesses should just be calls to the 240359d1ed5bSDimitry Andric // Itanium-specified entry point, which has the normal linkage of the 24040623d748SDimitry Andric // variable. This is to preserve the ability to change the implementation 24050623d748SDimitry Andric // behind the scenes. 240639d628a0SDimitry Andric if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic && 24070623d748SDimitry Andric Context.getTargetInfo().getTriple().isOSDarwin() && 24080623d748SDimitry Andric !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) && 24090623d748SDimitry Andric !llvm::GlobalVariable::isWeakLinkage(Linkage)) 241059d1ed5bSDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 241159d1ed5bSDimitry Andric 241259d1ed5bSDimitry Andric GV->setLinkage(Linkage); 241359d1ed5bSDimitry Andric if (D->hasAttr<DLLImportAttr>()) 241459d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 241559d1ed5bSDimitry Andric else if (D->hasAttr<DLLExportAttr>()) 241659d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 241739d628a0SDimitry Andric else 241839d628a0SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 2419f785676fSDimitry Andric 24202754fe60SDimitry Andric if (Linkage == llvm::GlobalVariable::CommonLinkage) 2421f22ef01cSRoman Divacky // common vars aren't constant even if declared const. 2422f22ef01cSRoman Divacky GV->setConstant(false); 2423f22ef01cSRoman Divacky 242459d1ed5bSDimitry Andric setNonAliasAttributes(D, GV); 2425f22ef01cSRoman Divacky 242639d628a0SDimitry Andric if (D->getTLSKind() && !GV->isThreadLocal()) { 242739d628a0SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 24280623d748SDimitry Andric CXXThreadLocals.push_back(D); 242939d628a0SDimitry Andric setTLSMode(GV, *D); 243039d628a0SDimitry Andric } 243139d628a0SDimitry Andric 243233956c43SDimitry Andric maybeSetTrivialComdat(*D, *GV); 243333956c43SDimitry Andric 24342754fe60SDimitry Andric // Emit the initializer function if necessary. 2435dff0c46cSDimitry Andric if (NeedsGlobalCtor || NeedsGlobalDtor) 2436dff0c46cSDimitry Andric EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 24372754fe60SDimitry Andric 243839d628a0SDimitry Andric SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); 24393861d79fSDimitry Andric 2440f22ef01cSRoman Divacky // Emit global variable debug information. 24416122f3e6SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 24423861d79fSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 2443f22ef01cSRoman Divacky DI->EmitGlobalVariable(GV, D); 2444f22ef01cSRoman Divacky } 2445f22ef01cSRoman Divacky 244639d628a0SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context, 244733956c43SDimitry Andric CodeGenModule &CGM, const VarDecl *D, 244833956c43SDimitry Andric bool NoCommon) { 244959d1ed5bSDimitry Andric // Don't give variables common linkage if -fno-common was specified unless it 245059d1ed5bSDimitry Andric // was overridden by a NoCommon attribute. 245159d1ed5bSDimitry Andric if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 245259d1ed5bSDimitry Andric return true; 245359d1ed5bSDimitry Andric 245459d1ed5bSDimitry Andric // C11 6.9.2/2: 245559d1ed5bSDimitry Andric // A declaration of an identifier for an object that has file scope without 245659d1ed5bSDimitry Andric // an initializer, and without a storage-class specifier or with the 245759d1ed5bSDimitry Andric // storage-class specifier static, constitutes a tentative definition. 245859d1ed5bSDimitry Andric if (D->getInit() || D->hasExternalStorage()) 245959d1ed5bSDimitry Andric return true; 246059d1ed5bSDimitry Andric 246159d1ed5bSDimitry Andric // A variable cannot be both common and exist in a section. 246259d1ed5bSDimitry Andric if (D->hasAttr<SectionAttr>()) 246359d1ed5bSDimitry Andric return true; 246459d1ed5bSDimitry Andric 246559d1ed5bSDimitry Andric // Thread local vars aren't considered common linkage. 246659d1ed5bSDimitry Andric if (D->getTLSKind()) 246759d1ed5bSDimitry Andric return true; 246859d1ed5bSDimitry Andric 246959d1ed5bSDimitry Andric // Tentative definitions marked with WeakImportAttr are true definitions. 247059d1ed5bSDimitry Andric if (D->hasAttr<WeakImportAttr>()) 247159d1ed5bSDimitry Andric return true; 247259d1ed5bSDimitry Andric 247333956c43SDimitry Andric // A variable cannot be both common and exist in a comdat. 247433956c43SDimitry Andric if (shouldBeInCOMDAT(CGM, *D)) 247533956c43SDimitry Andric return true; 247633956c43SDimitry Andric 247739d628a0SDimitry Andric // Declarations with a required alignment do not have common linakge in MSVC 247839d628a0SDimitry Andric // mode. 24790623d748SDimitry Andric if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 248033956c43SDimitry Andric if (D->hasAttr<AlignedAttr>()) 248139d628a0SDimitry Andric return true; 248233956c43SDimitry Andric QualType VarType = D->getType(); 248333956c43SDimitry Andric if (Context.isAlignmentRequired(VarType)) 248433956c43SDimitry Andric return true; 248533956c43SDimitry Andric 248633956c43SDimitry Andric if (const auto *RT = VarType->getAs<RecordType>()) { 248733956c43SDimitry Andric const RecordDecl *RD = RT->getDecl(); 248833956c43SDimitry Andric for (const FieldDecl *FD : RD->fields()) { 248933956c43SDimitry Andric if (FD->isBitField()) 249033956c43SDimitry Andric continue; 249133956c43SDimitry Andric if (FD->hasAttr<AlignedAttr>()) 249233956c43SDimitry Andric return true; 249333956c43SDimitry Andric if (Context.isAlignmentRequired(FD->getType())) 249433956c43SDimitry Andric return true; 249533956c43SDimitry Andric } 249633956c43SDimitry Andric } 249733956c43SDimitry Andric } 249839d628a0SDimitry Andric 249959d1ed5bSDimitry Andric return false; 250059d1ed5bSDimitry Andric } 250159d1ed5bSDimitry Andric 250259d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 250359d1ed5bSDimitry Andric const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 25042754fe60SDimitry Andric if (Linkage == GVA_Internal) 25052754fe60SDimitry Andric return llvm::Function::InternalLinkage; 250659d1ed5bSDimitry Andric 250759d1ed5bSDimitry Andric if (D->hasAttr<WeakAttr>()) { 250859d1ed5bSDimitry Andric if (IsConstantVariable) 250959d1ed5bSDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 251059d1ed5bSDimitry Andric else 251159d1ed5bSDimitry Andric return llvm::GlobalVariable::WeakAnyLinkage; 251259d1ed5bSDimitry Andric } 251359d1ed5bSDimitry Andric 251459d1ed5bSDimitry Andric // We are guaranteed to have a strong definition somewhere else, 251559d1ed5bSDimitry Andric // so we can use available_externally linkage. 251659d1ed5bSDimitry Andric if (Linkage == GVA_AvailableExternally) 251759d1ed5bSDimitry Andric return llvm::Function::AvailableExternallyLinkage; 251859d1ed5bSDimitry Andric 251959d1ed5bSDimitry Andric // Note that Apple's kernel linker doesn't support symbol 252059d1ed5bSDimitry Andric // coalescing, so we need to avoid linkonce and weak linkages there. 252159d1ed5bSDimitry Andric // Normally, this means we just map to internal, but for explicit 252259d1ed5bSDimitry Andric // instantiations we'll map to external. 252359d1ed5bSDimitry Andric 252459d1ed5bSDimitry Andric // In C++, the compiler has to emit a definition in every translation unit 252559d1ed5bSDimitry Andric // that references the function. We should use linkonce_odr because 252659d1ed5bSDimitry Andric // a) if all references in this translation unit are optimized away, we 252759d1ed5bSDimitry Andric // don't need to codegen it. b) if the function persists, it needs to be 252859d1ed5bSDimitry Andric // merged with other definitions. c) C++ has the ODR, so we know the 252959d1ed5bSDimitry Andric // definition is dependable. 253059d1ed5bSDimitry Andric if (Linkage == GVA_DiscardableODR) 253159d1ed5bSDimitry Andric return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 253259d1ed5bSDimitry Andric : llvm::Function::InternalLinkage; 253359d1ed5bSDimitry Andric 253459d1ed5bSDimitry Andric // An explicit instantiation of a template has weak linkage, since 253559d1ed5bSDimitry Andric // explicit instantiations can occur in multiple translation units 253659d1ed5bSDimitry Andric // and must all be equivalent. However, we are not allowed to 253759d1ed5bSDimitry Andric // throw away these explicit instantiations. 253859d1ed5bSDimitry Andric if (Linkage == GVA_StrongODR) 253959d1ed5bSDimitry Andric return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage 254059d1ed5bSDimitry Andric : llvm::Function::ExternalLinkage; 254159d1ed5bSDimitry Andric 254259d1ed5bSDimitry Andric // C++ doesn't have tentative definitions and thus cannot have common 254359d1ed5bSDimitry Andric // linkage. 254459d1ed5bSDimitry Andric if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 254533956c43SDimitry Andric !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 254639d628a0SDimitry Andric CodeGenOpts.NoCommon)) 254759d1ed5bSDimitry Andric return llvm::GlobalVariable::CommonLinkage; 254859d1ed5bSDimitry Andric 2549f785676fSDimitry Andric // selectany symbols are externally visible, so use weak instead of 2550f785676fSDimitry Andric // linkonce. MSVC optimizes away references to const selectany globals, so 2551f785676fSDimitry Andric // all definitions should be the same and ODR linkage should be used. 2552f785676fSDimitry Andric // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 255359d1ed5bSDimitry Andric if (D->hasAttr<SelectAnyAttr>()) 2554f785676fSDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 255559d1ed5bSDimitry Andric 255659d1ed5bSDimitry Andric // Otherwise, we have strong external linkage. 255759d1ed5bSDimitry Andric assert(Linkage == GVA_StrongExternal); 25582754fe60SDimitry Andric return llvm::GlobalVariable::ExternalLinkage; 25592754fe60SDimitry Andric } 25602754fe60SDimitry Andric 256159d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 256259d1ed5bSDimitry Andric const VarDecl *VD, bool IsConstant) { 256359d1ed5bSDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 256459d1ed5bSDimitry Andric return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 256559d1ed5bSDimitry Andric } 256659d1ed5bSDimitry Andric 2567139f7f9bSDimitry Andric /// Replace the uses of a function that was declared with a non-proto type. 2568139f7f9bSDimitry Andric /// We want to silently drop extra arguments from call sites 2569139f7f9bSDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 2570139f7f9bSDimitry Andric llvm::Function *newFn) { 2571139f7f9bSDimitry Andric // Fast path. 2572139f7f9bSDimitry Andric if (old->use_empty()) return; 2573139f7f9bSDimitry Andric 2574139f7f9bSDimitry Andric llvm::Type *newRetTy = newFn->getReturnType(); 2575139f7f9bSDimitry Andric SmallVector<llvm::Value*, 4> newArgs; 25760623d748SDimitry Andric SmallVector<llvm::OperandBundleDef, 1> newBundles; 2577139f7f9bSDimitry Andric 2578139f7f9bSDimitry Andric for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 2579139f7f9bSDimitry Andric ui != ue; ) { 2580139f7f9bSDimitry Andric llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 258159d1ed5bSDimitry Andric llvm::User *user = use->getUser(); 2582139f7f9bSDimitry Andric 2583139f7f9bSDimitry Andric // Recognize and replace uses of bitcasts. Most calls to 2584139f7f9bSDimitry Andric // unprototyped functions will use bitcasts. 258559d1ed5bSDimitry Andric if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 2586139f7f9bSDimitry Andric if (bitcast->getOpcode() == llvm::Instruction::BitCast) 2587139f7f9bSDimitry Andric replaceUsesOfNonProtoConstant(bitcast, newFn); 2588139f7f9bSDimitry Andric continue; 2589139f7f9bSDimitry Andric } 2590139f7f9bSDimitry Andric 2591139f7f9bSDimitry Andric // Recognize calls to the function. 2592139f7f9bSDimitry Andric llvm::CallSite callSite(user); 2593139f7f9bSDimitry Andric if (!callSite) continue; 259459d1ed5bSDimitry Andric if (!callSite.isCallee(&*use)) continue; 2595139f7f9bSDimitry Andric 2596139f7f9bSDimitry Andric // If the return types don't match exactly, then we can't 2597139f7f9bSDimitry Andric // transform this call unless it's dead. 2598139f7f9bSDimitry Andric if (callSite->getType() != newRetTy && !callSite->use_empty()) 2599139f7f9bSDimitry Andric continue; 2600139f7f9bSDimitry Andric 2601139f7f9bSDimitry Andric // Get the call site's attribute list. 2602139f7f9bSDimitry Andric SmallVector<llvm::AttributeSet, 8> newAttrs; 2603139f7f9bSDimitry Andric llvm::AttributeSet oldAttrs = callSite.getAttributes(); 2604139f7f9bSDimitry Andric 2605139f7f9bSDimitry Andric // Collect any return attributes from the call. 2606139f7f9bSDimitry Andric if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex)) 2607139f7f9bSDimitry Andric newAttrs.push_back( 2608139f7f9bSDimitry Andric llvm::AttributeSet::get(newFn->getContext(), 2609139f7f9bSDimitry Andric oldAttrs.getRetAttributes())); 2610139f7f9bSDimitry Andric 2611139f7f9bSDimitry Andric // If the function was passed too few arguments, don't transform. 2612139f7f9bSDimitry Andric unsigned newNumArgs = newFn->arg_size(); 2613139f7f9bSDimitry Andric if (callSite.arg_size() < newNumArgs) continue; 2614139f7f9bSDimitry Andric 2615139f7f9bSDimitry Andric // If extra arguments were passed, we silently drop them. 2616139f7f9bSDimitry Andric // If any of the types mismatch, we don't transform. 2617139f7f9bSDimitry Andric unsigned argNo = 0; 2618139f7f9bSDimitry Andric bool dontTransform = false; 2619139f7f9bSDimitry Andric for (llvm::Function::arg_iterator ai = newFn->arg_begin(), 2620139f7f9bSDimitry Andric ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) { 2621139f7f9bSDimitry Andric if (callSite.getArgument(argNo)->getType() != ai->getType()) { 2622139f7f9bSDimitry Andric dontTransform = true; 2623139f7f9bSDimitry Andric break; 2624139f7f9bSDimitry Andric } 2625139f7f9bSDimitry Andric 2626139f7f9bSDimitry Andric // Add any parameter attributes. 2627139f7f9bSDimitry Andric if (oldAttrs.hasAttributes(argNo + 1)) 2628139f7f9bSDimitry Andric newAttrs. 2629139f7f9bSDimitry Andric push_back(llvm:: 2630139f7f9bSDimitry Andric AttributeSet::get(newFn->getContext(), 2631139f7f9bSDimitry Andric oldAttrs.getParamAttributes(argNo + 1))); 2632139f7f9bSDimitry Andric } 2633139f7f9bSDimitry Andric if (dontTransform) 2634139f7f9bSDimitry Andric continue; 2635139f7f9bSDimitry Andric 2636139f7f9bSDimitry Andric if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) 2637139f7f9bSDimitry Andric newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(), 2638139f7f9bSDimitry Andric oldAttrs.getFnAttributes())); 2639139f7f9bSDimitry Andric 2640139f7f9bSDimitry Andric // Okay, we can transform this. Create the new call instruction and copy 2641139f7f9bSDimitry Andric // over the required information. 2642139f7f9bSDimitry Andric newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo); 2643139f7f9bSDimitry Andric 26440623d748SDimitry Andric // Copy over any operand bundles. 26450623d748SDimitry Andric callSite.getOperandBundlesAsDefs(newBundles); 26460623d748SDimitry Andric 2647139f7f9bSDimitry Andric llvm::CallSite newCall; 2648139f7f9bSDimitry Andric if (callSite.isCall()) { 26490623d748SDimitry Andric newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "", 2650139f7f9bSDimitry Andric callSite.getInstruction()); 2651139f7f9bSDimitry Andric } else { 265259d1ed5bSDimitry Andric auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction()); 2653139f7f9bSDimitry Andric newCall = llvm::InvokeInst::Create(newFn, 2654139f7f9bSDimitry Andric oldInvoke->getNormalDest(), 2655139f7f9bSDimitry Andric oldInvoke->getUnwindDest(), 26560623d748SDimitry Andric newArgs, newBundles, "", 2657139f7f9bSDimitry Andric callSite.getInstruction()); 2658139f7f9bSDimitry Andric } 2659139f7f9bSDimitry Andric newArgs.clear(); // for the next iteration 2660139f7f9bSDimitry Andric 2661139f7f9bSDimitry Andric if (!newCall->getType()->isVoidTy()) 2662139f7f9bSDimitry Andric newCall->takeName(callSite.getInstruction()); 2663139f7f9bSDimitry Andric newCall.setAttributes( 2664139f7f9bSDimitry Andric llvm::AttributeSet::get(newFn->getContext(), newAttrs)); 2665139f7f9bSDimitry Andric newCall.setCallingConv(callSite.getCallingConv()); 2666139f7f9bSDimitry Andric 2667139f7f9bSDimitry Andric // Finally, remove the old call, replacing any uses with the new one. 2668139f7f9bSDimitry Andric if (!callSite->use_empty()) 2669139f7f9bSDimitry Andric callSite->replaceAllUsesWith(newCall.getInstruction()); 2670139f7f9bSDimitry Andric 2671139f7f9bSDimitry Andric // Copy debug location attached to CI. 267233956c43SDimitry Andric if (callSite->getDebugLoc()) 2673139f7f9bSDimitry Andric newCall->setDebugLoc(callSite->getDebugLoc()); 26740623d748SDimitry Andric 2675139f7f9bSDimitry Andric callSite->eraseFromParent(); 2676139f7f9bSDimitry Andric } 2677139f7f9bSDimitry Andric } 2678139f7f9bSDimitry Andric 2679f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 2680f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}". If there are 2681f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to 2682f22ef01cSRoman Divacky /// call the new function directly. 2683f22ef01cSRoman Divacky /// 2684f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to 2685f22ef01cSRoman Divacky /// functions to be able to inline them. If there is a bitcast in the way, it 2686f22ef01cSRoman Divacky /// won't inline them. Instcombine normally deletes these calls, but it isn't 2687f22ef01cSRoman Divacky /// run at -O0. 2688f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 2689f22ef01cSRoman Divacky llvm::Function *NewFn) { 2690f22ef01cSRoman Divacky // If we're redefining a global as a function, don't transform it. 2691139f7f9bSDimitry Andric if (!isa<llvm::Function>(Old)) return; 2692f22ef01cSRoman Divacky 2693139f7f9bSDimitry Andric replaceUsesOfNonProtoConstant(Old, NewFn); 2694f22ef01cSRoman Divacky } 2695f22ef01cSRoman Divacky 2696dff0c46cSDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 2697dff0c46cSDimitry Andric TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 2698dff0c46cSDimitry Andric // If we have a definition, this might be a deferred decl. If the 2699dff0c46cSDimitry Andric // instantiation is explicit, make sure we emit it at the end. 2700dff0c46cSDimitry Andric if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 2701dff0c46cSDimitry Andric GetAddrOfGlobalVar(VD); 2702139f7f9bSDimitry Andric 2703139f7f9bSDimitry Andric EmitTopLevelDecl(VD); 2704dff0c46cSDimitry Andric } 2705f22ef01cSRoman Divacky 270659d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 270759d1ed5bSDimitry Andric llvm::GlobalValue *GV) { 270859d1ed5bSDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 27093b0f4066SDimitry Andric 27103b0f4066SDimitry Andric // Compute the function info and LLVM type. 2711dff0c46cSDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2712dff0c46cSDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 27133b0f4066SDimitry Andric 2714f22ef01cSRoman Divacky // Get or create the prototype for the function. 27150623d748SDimitry Andric if (!GV || (GV->getType()->getElementType() != Ty)) 27160623d748SDimitry Andric GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 27170623d748SDimitry Andric /*DontDefer=*/true, 27180623d748SDimitry Andric /*IsForDefinition=*/true)); 2719f22ef01cSRoman Divacky 27200623d748SDimitry Andric // Already emitted. 27210623d748SDimitry Andric if (!GV->isDeclaration()) 2722f785676fSDimitry Andric return; 2723f22ef01cSRoman Divacky 27242754fe60SDimitry Andric // We need to set linkage and visibility on the function before 27252754fe60SDimitry Andric // generating code for it because various parts of IR generation 27262754fe60SDimitry Andric // want to propagate this information down (e.g. to local static 27272754fe60SDimitry Andric // declarations). 272859d1ed5bSDimitry Andric auto *Fn = cast<llvm::Function>(GV); 2729f785676fSDimitry Andric setFunctionLinkage(GD, Fn); 273097bc6c73SDimitry Andric setFunctionDLLStorageClass(GD, Fn); 2731f22ef01cSRoman Divacky 273259d1ed5bSDimitry Andric // FIXME: this is redundant with part of setFunctionDefinitionAttributes 27332754fe60SDimitry Andric setGlobalVisibility(Fn, D); 27342754fe60SDimitry Andric 2735284c1978SDimitry Andric MaybeHandleStaticInExternC(D, Fn); 2736284c1978SDimitry Andric 273733956c43SDimitry Andric maybeSetTrivialComdat(*D, *Fn); 273833956c43SDimitry Andric 27393b0f4066SDimitry Andric CodeGenFunction(*this).GenerateCode(D, Fn, FI); 2740f22ef01cSRoman Divacky 274159d1ed5bSDimitry Andric setFunctionDefinitionAttributes(D, Fn); 2742f22ef01cSRoman Divacky SetLLVMFunctionAttributesForDefinition(D, Fn); 2743f22ef01cSRoman Divacky 2744f22ef01cSRoman Divacky if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 2745f22ef01cSRoman Divacky AddGlobalCtor(Fn, CA->getPriority()); 2746f22ef01cSRoman Divacky if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 2747f22ef01cSRoman Divacky AddGlobalDtor(Fn, DA->getPriority()); 27486122f3e6SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 27496122f3e6SDimitry Andric AddGlobalAnnotations(D, Fn); 2750f22ef01cSRoman Divacky } 2751f22ef01cSRoman Divacky 2752f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 275359d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 2754f22ef01cSRoman Divacky const AliasAttr *AA = D->getAttr<AliasAttr>(); 2755f22ef01cSRoman Divacky assert(AA && "Not an alias?"); 2756f22ef01cSRoman Divacky 27576122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 2758f22ef01cSRoman Divacky 27599a4b3118SDimitry Andric if (AA->getAliasee() == MangledName) { 27609a4b3118SDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias); 27619a4b3118SDimitry Andric return; 27629a4b3118SDimitry Andric } 27639a4b3118SDimitry Andric 2764f22ef01cSRoman Divacky // If there is a definition in the module, then it wins over the alias. 2765f22ef01cSRoman Divacky // This is dubious, but allow it to be safe. Just ignore the alias. 2766f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2767f22ef01cSRoman Divacky if (Entry && !Entry->isDeclaration()) 2768f22ef01cSRoman Divacky return; 2769f22ef01cSRoman Divacky 2770f785676fSDimitry Andric Aliases.push_back(GD); 2771f785676fSDimitry Andric 27726122f3e6SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 2773f22ef01cSRoman Divacky 2774f22ef01cSRoman Divacky // Create a reference to the named value. This ensures that it is emitted 2775f22ef01cSRoman Divacky // if a deferred decl. 2776f22ef01cSRoman Divacky llvm::Constant *Aliasee; 2777f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(DeclTy)) 27783861d79fSDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 27792754fe60SDimitry Andric /*ForVTable=*/false); 2780f22ef01cSRoman Divacky else 2781f22ef01cSRoman Divacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 278259d1ed5bSDimitry Andric llvm::PointerType::getUnqual(DeclTy), 278339d628a0SDimitry Andric /*D=*/nullptr); 2784f22ef01cSRoman Divacky 2785f22ef01cSRoman Divacky // Create the new alias itself, but don't set a name yet. 278659d1ed5bSDimitry Andric auto *GA = llvm::GlobalAlias::create( 27870623d748SDimitry Andric DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule()); 2788f22ef01cSRoman Divacky 2789f22ef01cSRoman Divacky if (Entry) { 279059d1ed5bSDimitry Andric if (GA->getAliasee() == Entry) { 279159d1ed5bSDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias); 279259d1ed5bSDimitry Andric return; 279359d1ed5bSDimitry Andric } 279459d1ed5bSDimitry Andric 2795f22ef01cSRoman Divacky assert(Entry->isDeclaration()); 2796f22ef01cSRoman Divacky 2797f22ef01cSRoman Divacky // If there is a declaration in the module, then we had an extern followed 2798f22ef01cSRoman Divacky // by the alias, as in: 2799f22ef01cSRoman Divacky // extern int test6(); 2800f22ef01cSRoman Divacky // ... 2801f22ef01cSRoman Divacky // int test6() __attribute__((alias("test7"))); 2802f22ef01cSRoman Divacky // 2803f22ef01cSRoman Divacky // Remove it and replace uses of it with the alias. 2804f22ef01cSRoman Divacky GA->takeName(Entry); 2805f22ef01cSRoman Divacky 2806f22ef01cSRoman Divacky Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 2807f22ef01cSRoman Divacky Entry->getType())); 2808f22ef01cSRoman Divacky Entry->eraseFromParent(); 2809f22ef01cSRoman Divacky } else { 2810ffd1746dSEd Schouten GA->setName(MangledName); 2811f22ef01cSRoman Divacky } 2812f22ef01cSRoman Divacky 2813f22ef01cSRoman Divacky // Set attributes which are particular to an alias; this is a 2814f22ef01cSRoman Divacky // specialization of the attributes which may be set on a global 2815f22ef01cSRoman Divacky // variable/function. 281639d628a0SDimitry Andric if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 28173b0f4066SDimitry Andric D->isWeakImported()) { 2818f22ef01cSRoman Divacky GA->setLinkage(llvm::Function::WeakAnyLinkage); 2819f22ef01cSRoman Divacky } 2820f22ef01cSRoman Divacky 282139d628a0SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 282239d628a0SDimitry Andric if (VD->getTLSKind()) 282339d628a0SDimitry Andric setTLSMode(GA, *VD); 282439d628a0SDimitry Andric 282539d628a0SDimitry Andric setAliasAttributes(D, GA); 2826f22ef01cSRoman Divacky } 2827f22ef01cSRoman Divacky 282817a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 28296122f3e6SDimitry Andric ArrayRef<llvm::Type*> Tys) { 283017a519f9SDimitry Andric return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 283117a519f9SDimitry Andric Tys); 2832f22ef01cSRoman Divacky } 2833f22ef01cSRoman Divacky 283433956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> & 283533956c43SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 283633956c43SDimitry Andric const StringLiteral *Literal, bool TargetIsLSB, 283733956c43SDimitry Andric bool &IsUTF16, unsigned &StringLength) { 28386122f3e6SDimitry Andric StringRef String = Literal->getString(); 2839e580952dSDimitry Andric unsigned NumBytes = String.size(); 2840f22ef01cSRoman Divacky 2841f22ef01cSRoman Divacky // Check for simple case. 2842f22ef01cSRoman Divacky if (!Literal->containsNonAsciiOrNull()) { 2843f22ef01cSRoman Divacky StringLength = NumBytes; 284439d628a0SDimitry Andric return *Map.insert(std::make_pair(String, nullptr)).first; 2845f22ef01cSRoman Divacky } 2846f22ef01cSRoman Divacky 2847dff0c46cSDimitry Andric // Otherwise, convert the UTF8 literals into a string of shorts. 2848dff0c46cSDimitry Andric IsUTF16 = true; 2849dff0c46cSDimitry Andric 2850dff0c46cSDimitry Andric SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 28513861d79fSDimitry Andric const UTF8 *FromPtr = (const UTF8 *)String.data(); 2852f22ef01cSRoman Divacky UTF16 *ToPtr = &ToBuf[0]; 2853f22ef01cSRoman Divacky 28542754fe60SDimitry Andric (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 2855f22ef01cSRoman Divacky &ToPtr, ToPtr + NumBytes, 2856f22ef01cSRoman Divacky strictConversion); 2857f22ef01cSRoman Divacky 2858f22ef01cSRoman Divacky // ConvertUTF8toUTF16 returns the length in ToPtr. 2859f22ef01cSRoman Divacky StringLength = ToPtr - &ToBuf[0]; 2860f22ef01cSRoman Divacky 2861dff0c46cSDimitry Andric // Add an explicit null. 2862dff0c46cSDimitry Andric *ToPtr = 0; 286339d628a0SDimitry Andric return *Map.insert(std::make_pair( 286439d628a0SDimitry Andric StringRef(reinterpret_cast<const char *>(ToBuf.data()), 286539d628a0SDimitry Andric (StringLength + 1) * 2), 286639d628a0SDimitry Andric nullptr)).first; 2867f22ef01cSRoman Divacky } 2868f22ef01cSRoman Divacky 286933956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> & 287033956c43SDimitry Andric GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 287133956c43SDimitry Andric const StringLiteral *Literal, unsigned &StringLength) { 28726122f3e6SDimitry Andric StringRef String = Literal->getString(); 2873bd5abe19SDimitry Andric StringLength = String.size(); 287439d628a0SDimitry Andric return *Map.insert(std::make_pair(String, nullptr)).first; 2875bd5abe19SDimitry Andric } 2876bd5abe19SDimitry Andric 28770623d748SDimitry Andric ConstantAddress 2878f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 2879f22ef01cSRoman Divacky unsigned StringLength = 0; 2880f22ef01cSRoman Divacky bool isUTF16 = false; 288133956c43SDimitry Andric llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 2882f22ef01cSRoman Divacky GetConstantCFStringEntry(CFConstantStringMap, Literal, 288333956c43SDimitry Andric getDataLayout().isLittleEndian(), isUTF16, 288433956c43SDimitry Andric StringLength); 2885f22ef01cSRoman Divacky 288639d628a0SDimitry Andric if (auto *C = Entry.second) 28870623d748SDimitry Andric return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 2888f22ef01cSRoman Divacky 2889dff0c46cSDimitry Andric llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2890f22ef01cSRoman Divacky llvm::Constant *Zeros[] = { Zero, Zero }; 2891284c1978SDimitry Andric llvm::Value *V; 2892f22ef01cSRoman Divacky 2893f22ef01cSRoman Divacky // If we don't already have it, get __CFConstantStringClassReference. 2894f22ef01cSRoman Divacky if (!CFConstantStringClassRef) { 28956122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2896f22ef01cSRoman Divacky Ty = llvm::ArrayType::get(Ty, 0); 2897f22ef01cSRoman Divacky llvm::Constant *GV = CreateRuntimeVariable(Ty, 2898f22ef01cSRoman Divacky "__CFConstantStringClassReference"); 2899f22ef01cSRoman Divacky // Decay array -> ptr 290033956c43SDimitry Andric V = llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros); 2901284c1978SDimitry Andric CFConstantStringClassRef = V; 2902f22ef01cSRoman Divacky } 2903284c1978SDimitry Andric else 2904284c1978SDimitry Andric V = CFConstantStringClassRef; 2905f22ef01cSRoman Divacky 2906f22ef01cSRoman Divacky QualType CFTy = getContext().getCFConstantStringType(); 2907f22ef01cSRoman Divacky 290859d1ed5bSDimitry Andric auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 2909f22ef01cSRoman Divacky 2910dff0c46cSDimitry Andric llvm::Constant *Fields[4]; 2911f22ef01cSRoman Divacky 2912f22ef01cSRoman Divacky // Class pointer. 2913284c1978SDimitry Andric Fields[0] = cast<llvm::ConstantExpr>(V); 2914f22ef01cSRoman Divacky 2915f22ef01cSRoman Divacky // Flags. 29166122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2917f22ef01cSRoman Divacky Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 2918f22ef01cSRoman Divacky llvm::ConstantInt::get(Ty, 0x07C8); 2919f22ef01cSRoman Divacky 2920f22ef01cSRoman Divacky // String pointer. 292159d1ed5bSDimitry Andric llvm::Constant *C = nullptr; 2922dff0c46cSDimitry Andric if (isUTF16) { 29230623d748SDimitry Andric auto Arr = llvm::makeArrayRef( 292439d628a0SDimitry Andric reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 292539d628a0SDimitry Andric Entry.first().size() / 2); 2926dff0c46cSDimitry Andric C = llvm::ConstantDataArray::get(VMContext, Arr); 2927dff0c46cSDimitry Andric } else { 292839d628a0SDimitry Andric C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 2929dff0c46cSDimitry Andric } 2930f22ef01cSRoman Divacky 2931dff0c46cSDimitry Andric // Note: -fwritable-strings doesn't make the backing store strings of 2932dff0c46cSDimitry Andric // CFStrings writable. (See <rdar://problem/10657500>) 293359d1ed5bSDimitry Andric auto *GV = 2934dff0c46cSDimitry Andric new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 293559d1ed5bSDimitry Andric llvm::GlobalValue::PrivateLinkage, C, ".str"); 29362754fe60SDimitry Andric GV->setUnnamedAddr(true); 2937284c1978SDimitry Andric // Don't enforce the target's minimum global alignment, since the only use 2938284c1978SDimitry Andric // of the string is via this class initializer. 293959d1ed5bSDimitry Andric // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without 294059d1ed5bSDimitry Andric // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing 294159d1ed5bSDimitry Andric // that changes the section it ends in, which surprises ld64. 2942f22ef01cSRoman Divacky if (isUTF16) { 2943f22ef01cSRoman Divacky CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 2944f22ef01cSRoman Divacky GV->setAlignment(Align.getQuantity()); 294559d1ed5bSDimitry Andric GV->setSection("__TEXT,__ustring"); 29463b0f4066SDimitry Andric } else { 29473b0f4066SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 29483b0f4066SDimitry Andric GV->setAlignment(Align.getQuantity()); 294959d1ed5bSDimitry Andric GV->setSection("__TEXT,__cstring,cstring_literals"); 2950f22ef01cSRoman Divacky } 2951dff0c46cSDimitry Andric 2952dff0c46cSDimitry Andric // String. 295333956c43SDimitry Andric Fields[2] = 295433956c43SDimitry Andric llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 2955f22ef01cSRoman Divacky 2956dff0c46cSDimitry Andric if (isUTF16) 2957dff0c46cSDimitry Andric // Cast the UTF16 string to the correct type. 2958dff0c46cSDimitry Andric Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy); 2959dff0c46cSDimitry Andric 2960f22ef01cSRoman Divacky // String length. 2961f22ef01cSRoman Divacky Ty = getTypes().ConvertType(getContext().LongTy); 2962f22ef01cSRoman Divacky Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 2963f22ef01cSRoman Divacky 29640623d748SDimitry Andric CharUnits Alignment = getPointerAlign(); 29650623d748SDimitry Andric 2966f22ef01cSRoman Divacky // The struct. 2967f22ef01cSRoman Divacky C = llvm::ConstantStruct::get(STy, Fields); 2968f22ef01cSRoman Divacky GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2969f22ef01cSRoman Divacky llvm::GlobalVariable::PrivateLinkage, C, 2970f22ef01cSRoman Divacky "_unnamed_cfstring_"); 297159d1ed5bSDimitry Andric GV->setSection("__DATA,__cfstring"); 29720623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 297339d628a0SDimitry Andric Entry.second = GV; 2974f22ef01cSRoman Divacky 29750623d748SDimitry Andric return ConstantAddress(GV, Alignment); 2976f22ef01cSRoman Divacky } 2977f22ef01cSRoman Divacky 29780623d748SDimitry Andric ConstantAddress 29792754fe60SDimitry Andric CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 2980f22ef01cSRoman Divacky unsigned StringLength = 0; 298133956c43SDimitry Andric llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 2982bd5abe19SDimitry Andric GetConstantStringEntry(CFConstantStringMap, Literal, StringLength); 2983f22ef01cSRoman Divacky 298439d628a0SDimitry Andric if (auto *C = Entry.second) 29850623d748SDimitry Andric return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 2986f22ef01cSRoman Divacky 2987dff0c46cSDimitry Andric llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2988f22ef01cSRoman Divacky llvm::Constant *Zeros[] = { Zero, Zero }; 2989284c1978SDimitry Andric llvm::Value *V; 2990f22ef01cSRoman Divacky // If we don't already have it, get _NSConstantStringClassReference. 29912754fe60SDimitry Andric if (!ConstantStringClassRef) { 2992dff0c46cSDimitry Andric std::string StringClass(getLangOpts().ObjCConstantStringClass); 29936122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 29942754fe60SDimitry Andric llvm::Constant *GV; 29957ae0e2c9SDimitry Andric if (LangOpts.ObjCRuntime.isNonFragile()) { 2996bd5abe19SDimitry Andric std::string str = 2997bd5abe19SDimitry Andric StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 2998bd5abe19SDimitry Andric : "OBJC_CLASS_$_" + StringClass; 2999bd5abe19SDimitry Andric GV = getObjCRuntime().GetClassGlobal(str); 3000bd5abe19SDimitry Andric // Make sure the result is of the correct type. 30016122f3e6SDimitry Andric llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 3002284c1978SDimitry Andric V = llvm::ConstantExpr::getBitCast(GV, PTy); 3003284c1978SDimitry Andric ConstantStringClassRef = V; 3004bd5abe19SDimitry Andric } else { 3005bd5abe19SDimitry Andric std::string str = 3006bd5abe19SDimitry Andric StringClass.empty() ? "_NSConstantStringClassReference" 3007bd5abe19SDimitry Andric : "_" + StringClass + "ClassReference"; 30086122f3e6SDimitry Andric llvm::Type *PTy = llvm::ArrayType::get(Ty, 0); 3009bd5abe19SDimitry Andric GV = CreateRuntimeVariable(PTy, str); 3010f22ef01cSRoman Divacky // Decay array -> ptr 301133956c43SDimitry Andric V = llvm::ConstantExpr::getGetElementPtr(PTy, GV, Zeros); 3012284c1978SDimitry Andric ConstantStringClassRef = V; 3013f22ef01cSRoman Divacky } 301433956c43SDimitry Andric } else 3015284c1978SDimitry Andric V = ConstantStringClassRef; 3016f22ef01cSRoman Divacky 30176122f3e6SDimitry Andric if (!NSConstantStringType) { 30186122f3e6SDimitry Andric // Construct the type for a constant NSString. 301959d1ed5bSDimitry Andric RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString"); 30206122f3e6SDimitry Andric D->startDefinition(); 3021f22ef01cSRoman Divacky 30226122f3e6SDimitry Andric QualType FieldTypes[3]; 30236122f3e6SDimitry Andric 30246122f3e6SDimitry Andric // const int *isa; 30256122f3e6SDimitry Andric FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst()); 30266122f3e6SDimitry Andric // const char *str; 30276122f3e6SDimitry Andric FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst()); 30286122f3e6SDimitry Andric // unsigned int length; 30296122f3e6SDimitry Andric FieldTypes[2] = Context.UnsignedIntTy; 30306122f3e6SDimitry Andric 30316122f3e6SDimitry Andric // Create fields 30326122f3e6SDimitry Andric for (unsigned i = 0; i < 3; ++i) { 30336122f3e6SDimitry Andric FieldDecl *Field = FieldDecl::Create(Context, D, 30346122f3e6SDimitry Andric SourceLocation(), 303559d1ed5bSDimitry Andric SourceLocation(), nullptr, 303659d1ed5bSDimitry Andric FieldTypes[i], /*TInfo=*/nullptr, 303759d1ed5bSDimitry Andric /*BitWidth=*/nullptr, 30386122f3e6SDimitry Andric /*Mutable=*/false, 30397ae0e2c9SDimitry Andric ICIS_NoInit); 30406122f3e6SDimitry Andric Field->setAccess(AS_public); 30416122f3e6SDimitry Andric D->addDecl(Field); 30426122f3e6SDimitry Andric } 30436122f3e6SDimitry Andric 30446122f3e6SDimitry Andric D->completeDefinition(); 30456122f3e6SDimitry Andric QualType NSTy = Context.getTagDeclType(D); 30466122f3e6SDimitry Andric NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 30476122f3e6SDimitry Andric } 3048f22ef01cSRoman Divacky 3049dff0c46cSDimitry Andric llvm::Constant *Fields[3]; 3050f22ef01cSRoman Divacky 3051f22ef01cSRoman Divacky // Class pointer. 3052284c1978SDimitry Andric Fields[0] = cast<llvm::ConstantExpr>(V); 3053f22ef01cSRoman Divacky 3054f22ef01cSRoman Divacky // String pointer. 3055dff0c46cSDimitry Andric llvm::Constant *C = 305639d628a0SDimitry Andric llvm::ConstantDataArray::getString(VMContext, Entry.first()); 3057f22ef01cSRoman Divacky 3058f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes Linkage; 3059f22ef01cSRoman Divacky bool isConstant; 3060f22ef01cSRoman Divacky Linkage = llvm::GlobalValue::PrivateLinkage; 3061dff0c46cSDimitry Andric isConstant = !LangOpts.WritableStrings; 3062f22ef01cSRoman Divacky 306359d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant, 306459d1ed5bSDimitry Andric Linkage, C, ".str"); 30652754fe60SDimitry Andric GV->setUnnamedAddr(true); 3066284c1978SDimitry Andric // Don't enforce the target's minimum global alignment, since the only use 3067284c1978SDimitry Andric // of the string is via this class initializer. 30683b0f4066SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 30693b0f4066SDimitry Andric GV->setAlignment(Align.getQuantity()); 307033956c43SDimitry Andric Fields[1] = 307133956c43SDimitry Andric llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 3072f22ef01cSRoman Divacky 3073f22ef01cSRoman Divacky // String length. 30746122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 3075f22ef01cSRoman Divacky Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 3076f22ef01cSRoman Divacky 3077f22ef01cSRoman Divacky // The struct. 30780623d748SDimitry Andric CharUnits Alignment = getPointerAlign(); 30796122f3e6SDimitry Andric C = llvm::ConstantStruct::get(NSConstantStringType, Fields); 3080f22ef01cSRoman Divacky GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 3081f22ef01cSRoman Divacky llvm::GlobalVariable::PrivateLinkage, C, 3082f22ef01cSRoman Divacky "_unnamed_nsstring_"); 30830623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 308459d1ed5bSDimitry Andric const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip"; 308559d1ed5bSDimitry Andric const char *NSStringNonFragileABISection = 308659d1ed5bSDimitry Andric "__DATA,__objc_stringobj,regular,no_dead_strip"; 3087f22ef01cSRoman Divacky // FIXME. Fix section. 308859d1ed5bSDimitry Andric GV->setSection(LangOpts.ObjCRuntime.isNonFragile() 308959d1ed5bSDimitry Andric ? NSStringNonFragileABISection 309059d1ed5bSDimitry Andric : NSStringSection); 309139d628a0SDimitry Andric Entry.second = GV; 3092f22ef01cSRoman Divacky 30930623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3094f22ef01cSRoman Divacky } 3095f22ef01cSRoman Divacky 30966122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() { 30976122f3e6SDimitry Andric if (ObjCFastEnumerationStateType.isNull()) { 309859d1ed5bSDimitry Andric RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 30996122f3e6SDimitry Andric D->startDefinition(); 31006122f3e6SDimitry Andric 31016122f3e6SDimitry Andric QualType FieldTypes[] = { 31026122f3e6SDimitry Andric Context.UnsignedLongTy, 31036122f3e6SDimitry Andric Context.getPointerType(Context.getObjCIdType()), 31046122f3e6SDimitry Andric Context.getPointerType(Context.UnsignedLongTy), 31056122f3e6SDimitry Andric Context.getConstantArrayType(Context.UnsignedLongTy, 31066122f3e6SDimitry Andric llvm::APInt(32, 5), ArrayType::Normal, 0) 31076122f3e6SDimitry Andric }; 31086122f3e6SDimitry Andric 31096122f3e6SDimitry Andric for (size_t i = 0; i < 4; ++i) { 31106122f3e6SDimitry Andric FieldDecl *Field = FieldDecl::Create(Context, 31116122f3e6SDimitry Andric D, 31126122f3e6SDimitry Andric SourceLocation(), 311359d1ed5bSDimitry Andric SourceLocation(), nullptr, 311459d1ed5bSDimitry Andric FieldTypes[i], /*TInfo=*/nullptr, 311559d1ed5bSDimitry Andric /*BitWidth=*/nullptr, 31166122f3e6SDimitry Andric /*Mutable=*/false, 31177ae0e2c9SDimitry Andric ICIS_NoInit); 31186122f3e6SDimitry Andric Field->setAccess(AS_public); 31196122f3e6SDimitry Andric D->addDecl(Field); 31206122f3e6SDimitry Andric } 31216122f3e6SDimitry Andric 31226122f3e6SDimitry Andric D->completeDefinition(); 31236122f3e6SDimitry Andric ObjCFastEnumerationStateType = Context.getTagDeclType(D); 31246122f3e6SDimitry Andric } 31256122f3e6SDimitry Andric 31266122f3e6SDimitry Andric return ObjCFastEnumerationStateType; 31276122f3e6SDimitry Andric } 31286122f3e6SDimitry Andric 3129dff0c46cSDimitry Andric llvm::Constant * 3130dff0c46cSDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 3131dff0c46cSDimitry Andric assert(!E->getType()->isPointerType() && "Strings are always arrays"); 3132f22ef01cSRoman Divacky 3133dff0c46cSDimitry Andric // Don't emit it as the address of the string, emit the string data itself 3134dff0c46cSDimitry Andric // as an inline array. 3135dff0c46cSDimitry Andric if (E->getCharByteWidth() == 1) { 3136dff0c46cSDimitry Andric SmallString<64> Str(E->getString()); 3137f22ef01cSRoman Divacky 3138dff0c46cSDimitry Andric // Resize the string to the right size, which is indicated by its type. 3139dff0c46cSDimitry Andric const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 3140dff0c46cSDimitry Andric Str.resize(CAT->getSize().getZExtValue()); 3141dff0c46cSDimitry Andric return llvm::ConstantDataArray::getString(VMContext, Str, false); 31426122f3e6SDimitry Andric } 3143f22ef01cSRoman Divacky 314459d1ed5bSDimitry Andric auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 3145dff0c46cSDimitry Andric llvm::Type *ElemTy = AType->getElementType(); 3146dff0c46cSDimitry Andric unsigned NumElements = AType->getNumElements(); 3147f22ef01cSRoman Divacky 3148dff0c46cSDimitry Andric // Wide strings have either 2-byte or 4-byte elements. 3149dff0c46cSDimitry Andric if (ElemTy->getPrimitiveSizeInBits() == 16) { 3150dff0c46cSDimitry Andric SmallVector<uint16_t, 32> Elements; 3151dff0c46cSDimitry Andric Elements.reserve(NumElements); 3152dff0c46cSDimitry Andric 3153dff0c46cSDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 3154dff0c46cSDimitry Andric Elements.push_back(E->getCodeUnit(i)); 3155dff0c46cSDimitry Andric Elements.resize(NumElements); 3156dff0c46cSDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 3157dff0c46cSDimitry Andric } 3158dff0c46cSDimitry Andric 3159dff0c46cSDimitry Andric assert(ElemTy->getPrimitiveSizeInBits() == 32); 3160dff0c46cSDimitry Andric SmallVector<uint32_t, 32> Elements; 3161dff0c46cSDimitry Andric Elements.reserve(NumElements); 3162dff0c46cSDimitry Andric 3163dff0c46cSDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 3164dff0c46cSDimitry Andric Elements.push_back(E->getCodeUnit(i)); 3165dff0c46cSDimitry Andric Elements.resize(NumElements); 3166dff0c46cSDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 3167f22ef01cSRoman Divacky } 3168f22ef01cSRoman Divacky 316959d1ed5bSDimitry Andric static llvm::GlobalVariable * 317059d1ed5bSDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 317159d1ed5bSDimitry Andric CodeGenModule &CGM, StringRef GlobalName, 31720623d748SDimitry Andric CharUnits Alignment) { 317359d1ed5bSDimitry Andric // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 317459d1ed5bSDimitry Andric unsigned AddrSpace = 0; 317559d1ed5bSDimitry Andric if (CGM.getLangOpts().OpenCL) 317659d1ed5bSDimitry Andric AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant); 3177dff0c46cSDimitry Andric 317833956c43SDimitry Andric llvm::Module &M = CGM.getModule(); 317959d1ed5bSDimitry Andric // Create a global variable for this string 318059d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 318133956c43SDimitry Andric M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 318233956c43SDimitry Andric nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 31830623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 318459d1ed5bSDimitry Andric GV->setUnnamedAddr(true); 318533956c43SDimitry Andric if (GV->isWeakForLinker()) { 318633956c43SDimitry Andric assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 318733956c43SDimitry Andric GV->setComdat(M.getOrInsertComdat(GV->getName())); 318833956c43SDimitry Andric } 318933956c43SDimitry Andric 319059d1ed5bSDimitry Andric return GV; 3191f22ef01cSRoman Divacky } 3192dff0c46cSDimitry Andric 319359d1ed5bSDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 319459d1ed5bSDimitry Andric /// constant array for the given string literal. 31950623d748SDimitry Andric ConstantAddress 319639d628a0SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 319739d628a0SDimitry Andric StringRef Name) { 31980623d748SDimitry Andric CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 3199dff0c46cSDimitry Andric 320059d1ed5bSDimitry Andric llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 320159d1ed5bSDimitry Andric llvm::GlobalVariable **Entry = nullptr; 320259d1ed5bSDimitry Andric if (!LangOpts.WritableStrings) { 320359d1ed5bSDimitry Andric Entry = &ConstantStringMap[C]; 320459d1ed5bSDimitry Andric if (auto GV = *Entry) { 32050623d748SDimitry Andric if (Alignment.getQuantity() > GV->getAlignment()) 32060623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 32070623d748SDimitry Andric return ConstantAddress(GV, Alignment); 320859d1ed5bSDimitry Andric } 320959d1ed5bSDimitry Andric } 321059d1ed5bSDimitry Andric 321159d1ed5bSDimitry Andric SmallString<256> MangledNameBuffer; 321259d1ed5bSDimitry Andric StringRef GlobalVariableName; 321359d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes LT; 321459d1ed5bSDimitry Andric 321559d1ed5bSDimitry Andric // Mangle the string literal if the ABI allows for it. However, we cannot 321659d1ed5bSDimitry Andric // do this if we are compiling with ASan or -fwritable-strings because they 321759d1ed5bSDimitry Andric // rely on strings having normal linkage. 321839d628a0SDimitry Andric if (!LangOpts.WritableStrings && 321939d628a0SDimitry Andric !LangOpts.Sanitize.has(SanitizerKind::Address) && 322059d1ed5bSDimitry Andric getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) { 322159d1ed5bSDimitry Andric llvm::raw_svector_ostream Out(MangledNameBuffer); 322259d1ed5bSDimitry Andric getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 322359d1ed5bSDimitry Andric 322459d1ed5bSDimitry Andric LT = llvm::GlobalValue::LinkOnceODRLinkage; 322559d1ed5bSDimitry Andric GlobalVariableName = MangledNameBuffer; 322659d1ed5bSDimitry Andric } else { 322759d1ed5bSDimitry Andric LT = llvm::GlobalValue::PrivateLinkage; 322839d628a0SDimitry Andric GlobalVariableName = Name; 322959d1ed5bSDimitry Andric } 323059d1ed5bSDimitry Andric 323159d1ed5bSDimitry Andric auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 323259d1ed5bSDimitry Andric if (Entry) 323359d1ed5bSDimitry Andric *Entry = GV; 323459d1ed5bSDimitry Andric 323539d628a0SDimitry Andric SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>", 323639d628a0SDimitry Andric QualType()); 32370623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3238f22ef01cSRoman Divacky } 3239f22ef01cSRoman Divacky 3240f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 3241f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node. 32420623d748SDimitry Andric ConstantAddress 3243f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 3244f22ef01cSRoman Divacky std::string Str; 3245f22ef01cSRoman Divacky getContext().getObjCEncodingForType(E->getEncodedType(), Str); 3246f22ef01cSRoman Divacky 3247f22ef01cSRoman Divacky return GetAddrOfConstantCString(Str); 3248f22ef01cSRoman Divacky } 3249f22ef01cSRoman Divacky 325059d1ed5bSDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing 325159d1ed5bSDimitry Andric /// the literal and a terminating '\0' character. 325259d1ed5bSDimitry Andric /// The result has pointer to array type. 32530623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString( 32540623d748SDimitry Andric const std::string &Str, const char *GlobalName) { 325559d1ed5bSDimitry Andric StringRef StrWithNull(Str.c_str(), Str.size() + 1); 32560623d748SDimitry Andric CharUnits Alignment = 32570623d748SDimitry Andric getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 3258f22ef01cSRoman Divacky 325959d1ed5bSDimitry Andric llvm::Constant *C = 326059d1ed5bSDimitry Andric llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 326159d1ed5bSDimitry Andric 326259d1ed5bSDimitry Andric // Don't share any string literals if strings aren't constant. 326359d1ed5bSDimitry Andric llvm::GlobalVariable **Entry = nullptr; 326459d1ed5bSDimitry Andric if (!LangOpts.WritableStrings) { 326559d1ed5bSDimitry Andric Entry = &ConstantStringMap[C]; 326659d1ed5bSDimitry Andric if (auto GV = *Entry) { 32670623d748SDimitry Andric if (Alignment.getQuantity() > GV->getAlignment()) 32680623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 32690623d748SDimitry Andric return ConstantAddress(GV, Alignment); 327059d1ed5bSDimitry Andric } 327159d1ed5bSDimitry Andric } 327259d1ed5bSDimitry Andric 3273f22ef01cSRoman Divacky // Get the default prefix if a name wasn't specified. 3274f22ef01cSRoman Divacky if (!GlobalName) 3275f22ef01cSRoman Divacky GlobalName = ".str"; 3276f22ef01cSRoman Divacky // Create a global variable for this. 327759d1ed5bSDimitry Andric auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 327859d1ed5bSDimitry Andric GlobalName, Alignment); 327959d1ed5bSDimitry Andric if (Entry) 328059d1ed5bSDimitry Andric *Entry = GV; 32810623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3282f22ef01cSRoman Divacky } 3283f22ef01cSRoman Divacky 32840623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 3285f785676fSDimitry Andric const MaterializeTemporaryExpr *E, const Expr *Init) { 3286f785676fSDimitry Andric assert((E->getStorageDuration() == SD_Static || 3287f785676fSDimitry Andric E->getStorageDuration() == SD_Thread) && "not a global temporary"); 328859d1ed5bSDimitry Andric const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 3289f785676fSDimitry Andric 3290f785676fSDimitry Andric // If we're not materializing a subobject of the temporary, keep the 3291f785676fSDimitry Andric // cv-qualifiers from the type of the MaterializeTemporaryExpr. 3292f785676fSDimitry Andric QualType MaterializedType = Init->getType(); 3293f785676fSDimitry Andric if (Init == E->GetTemporaryExpr()) 3294f785676fSDimitry Andric MaterializedType = E->getType(); 3295f785676fSDimitry Andric 32960623d748SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 32970623d748SDimitry Andric 32980623d748SDimitry Andric if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E]) 32990623d748SDimitry Andric return ConstantAddress(Slot, Align); 3300f785676fSDimitry Andric 3301f785676fSDimitry Andric // FIXME: If an externally-visible declaration extends multiple temporaries, 3302f785676fSDimitry Andric // we need to give each temporary the same name in every translation unit (and 3303f785676fSDimitry Andric // we also need to make the temporaries externally-visible). 3304f785676fSDimitry Andric SmallString<256> Name; 3305f785676fSDimitry Andric llvm::raw_svector_ostream Out(Name); 330659d1ed5bSDimitry Andric getCXXABI().getMangleContext().mangleReferenceTemporary( 330759d1ed5bSDimitry Andric VD, E->getManglingNumber(), Out); 3308f785676fSDimitry Andric 330959d1ed5bSDimitry Andric APValue *Value = nullptr; 3310f785676fSDimitry Andric if (E->getStorageDuration() == SD_Static) { 3311f785676fSDimitry Andric // We might have a cached constant initializer for this temporary. Note 3312f785676fSDimitry Andric // that this might have a different value from the value computed by 3313f785676fSDimitry Andric // evaluating the initializer if the surrounding constant expression 3314f785676fSDimitry Andric // modifies the temporary. 3315f785676fSDimitry Andric Value = getContext().getMaterializedTemporaryValue(E, false); 3316f785676fSDimitry Andric if (Value && Value->isUninit()) 331759d1ed5bSDimitry Andric Value = nullptr; 3318f785676fSDimitry Andric } 3319f785676fSDimitry Andric 3320f785676fSDimitry Andric // Try evaluating it now, it might have a constant initializer. 3321f785676fSDimitry Andric Expr::EvalResult EvalResult; 3322f785676fSDimitry Andric if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 3323f785676fSDimitry Andric !EvalResult.hasSideEffects()) 3324f785676fSDimitry Andric Value = &EvalResult.Val; 3325f785676fSDimitry Andric 332659d1ed5bSDimitry Andric llvm::Constant *InitialValue = nullptr; 3327f785676fSDimitry Andric bool Constant = false; 3328f785676fSDimitry Andric llvm::Type *Type; 3329f785676fSDimitry Andric if (Value) { 3330f785676fSDimitry Andric // The temporary has a constant initializer, use it. 333159d1ed5bSDimitry Andric InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr); 3332f785676fSDimitry Andric Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 3333f785676fSDimitry Andric Type = InitialValue->getType(); 3334f785676fSDimitry Andric } else { 3335f785676fSDimitry Andric // No initializer, the initialization will be provided when we 3336f785676fSDimitry Andric // initialize the declaration which performed lifetime extension. 3337f785676fSDimitry Andric Type = getTypes().ConvertTypeForMem(MaterializedType); 3338f785676fSDimitry Andric } 3339f785676fSDimitry Andric 3340f785676fSDimitry Andric // Create a global variable for this lifetime-extended temporary. 334159d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 334259d1ed5bSDimitry Andric getLLVMLinkageVarDefinition(VD, Constant); 334333956c43SDimitry Andric if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 334433956c43SDimitry Andric const VarDecl *InitVD; 334533956c43SDimitry Andric if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 334633956c43SDimitry Andric isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 334733956c43SDimitry Andric // Temporaries defined inside a class get linkonce_odr linkage because the 334833956c43SDimitry Andric // class can be defined in multipe translation units. 334933956c43SDimitry Andric Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 335033956c43SDimitry Andric } else { 335133956c43SDimitry Andric // There is no need for this temporary to have external linkage if the 335233956c43SDimitry Andric // VarDecl has external linkage. 335333956c43SDimitry Andric Linkage = llvm::GlobalVariable::InternalLinkage; 335433956c43SDimitry Andric } 335533956c43SDimitry Andric } 335659d1ed5bSDimitry Andric unsigned AddrSpace = GetGlobalVarAddressSpace( 335759d1ed5bSDimitry Andric VD, getContext().getTargetAddressSpace(MaterializedType)); 335859d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 335959d1ed5bSDimitry Andric getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 336059d1ed5bSDimitry Andric /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, 336159d1ed5bSDimitry Andric AddrSpace); 336259d1ed5bSDimitry Andric setGlobalVisibility(GV, VD); 33630623d748SDimitry Andric GV->setAlignment(Align.getQuantity()); 336433956c43SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker()) 336533956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3366f785676fSDimitry Andric if (VD->getTLSKind()) 3367f785676fSDimitry Andric setTLSMode(GV, *VD); 33680623d748SDimitry Andric MaterializedGlobalTemporaryMap[E] = GV; 33690623d748SDimitry Andric return ConstantAddress(GV, Align); 3370f785676fSDimitry Andric } 3371f785676fSDimitry Andric 3372f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized 3373f22ef01cSRoman Divacky /// properties for an implementation. 3374f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const 3375f22ef01cSRoman Divacky ObjCImplementationDecl *D) { 337659d1ed5bSDimitry Andric for (const auto *PID : D->property_impls()) { 3377f22ef01cSRoman Divacky // Dynamic is just for type-checking. 3378f22ef01cSRoman Divacky if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 3379f22ef01cSRoman Divacky ObjCPropertyDecl *PD = PID->getPropertyDecl(); 3380f22ef01cSRoman Divacky 3381f22ef01cSRoman Divacky // Determine which methods need to be implemented, some may have 33823861d79fSDimitry Andric // been overridden. Note that ::isPropertyAccessor is not the method 3383f22ef01cSRoman Divacky // we want, that just indicates if the decl came from a 3384f22ef01cSRoman Divacky // property. What we want to know is if the method is defined in 3385f22ef01cSRoman Divacky // this implementation. 3386f22ef01cSRoman Divacky if (!D->getInstanceMethod(PD->getGetterName())) 3387f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCGetter( 3388f22ef01cSRoman Divacky const_cast<ObjCImplementationDecl *>(D), PID); 3389f22ef01cSRoman Divacky if (!PD->isReadOnly() && 3390f22ef01cSRoman Divacky !D->getInstanceMethod(PD->getSetterName())) 3391f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCSetter( 3392f22ef01cSRoman Divacky const_cast<ObjCImplementationDecl *>(D), PID); 3393f22ef01cSRoman Divacky } 3394f22ef01cSRoman Divacky } 3395f22ef01cSRoman Divacky } 3396f22ef01cSRoman Divacky 33973b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) { 33986122f3e6SDimitry Andric const ObjCInterfaceDecl *iface = impl->getClassInterface(); 33996122f3e6SDimitry Andric for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 34003b0f4066SDimitry Andric ivar; ivar = ivar->getNextIvar()) 34013b0f4066SDimitry Andric if (ivar->getType().isDestructedType()) 34023b0f4066SDimitry Andric return true; 34033b0f4066SDimitry Andric 34043b0f4066SDimitry Andric return false; 34053b0f4066SDimitry Andric } 34063b0f4066SDimitry Andric 340739d628a0SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM, 340839d628a0SDimitry Andric ObjCImplementationDecl *D) { 340939d628a0SDimitry Andric CodeGenFunction CGF(CGM); 341039d628a0SDimitry Andric for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 341139d628a0SDimitry Andric E = D->init_end(); B != E; ++B) { 341239d628a0SDimitry Andric CXXCtorInitializer *CtorInitExp = *B; 341339d628a0SDimitry Andric Expr *Init = CtorInitExp->getInit(); 341439d628a0SDimitry Andric if (!CGF.isTrivialInitializer(Init)) 341539d628a0SDimitry Andric return false; 341639d628a0SDimitry Andric } 341739d628a0SDimitry Andric return true; 341839d628a0SDimitry Andric } 341939d628a0SDimitry Andric 3420f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization 3421f22ef01cSRoman Divacky /// for an implementation. 3422f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 34233b0f4066SDimitry Andric // We might need a .cxx_destruct even if we don't have any ivar initializers. 34243b0f4066SDimitry Andric if (needsDestructMethod(D)) { 3425f22ef01cSRoman Divacky IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 3426f22ef01cSRoman Divacky Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 34273b0f4066SDimitry Andric ObjCMethodDecl *DTORMethod = 34283b0f4066SDimitry Andric ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 342959d1ed5bSDimitry Andric cxxSelector, getContext().VoidTy, nullptr, D, 34306122f3e6SDimitry Andric /*isInstance=*/true, /*isVariadic=*/false, 34313861d79fSDimitry Andric /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 34326122f3e6SDimitry Andric /*isDefined=*/false, ObjCMethodDecl::Required); 3433f22ef01cSRoman Divacky D->addInstanceMethod(DTORMethod); 3434f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 34353861d79fSDimitry Andric D->setHasDestructors(true); 34363b0f4066SDimitry Andric } 3437f22ef01cSRoman Divacky 34383b0f4066SDimitry Andric // If the implementation doesn't have any ivar initializers, we don't need 34393b0f4066SDimitry Andric // a .cxx_construct. 344039d628a0SDimitry Andric if (D->getNumIvarInitializers() == 0 || 344139d628a0SDimitry Andric AllTrivialInitializers(*this, D)) 34423b0f4066SDimitry Andric return; 34433b0f4066SDimitry Andric 34443b0f4066SDimitry Andric IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 34453b0f4066SDimitry Andric Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 3446f22ef01cSRoman Divacky // The constructor returns 'self'. 3447f22ef01cSRoman Divacky ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 3448f22ef01cSRoman Divacky D->getLocation(), 34496122f3e6SDimitry Andric D->getLocation(), 34506122f3e6SDimitry Andric cxxSelector, 345159d1ed5bSDimitry Andric getContext().getObjCIdType(), 345259d1ed5bSDimitry Andric nullptr, D, /*isInstance=*/true, 34536122f3e6SDimitry Andric /*isVariadic=*/false, 34543861d79fSDimitry Andric /*isPropertyAccessor=*/true, 34556122f3e6SDimitry Andric /*isImplicitlyDeclared=*/true, 34566122f3e6SDimitry Andric /*isDefined=*/false, 3457f22ef01cSRoman Divacky ObjCMethodDecl::Required); 3458f22ef01cSRoman Divacky D->addInstanceMethod(CTORMethod); 3459f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 34603861d79fSDimitry Andric D->setHasNonZeroConstructors(true); 3461f22ef01cSRoman Divacky } 3462f22ef01cSRoman Divacky 3463f22ef01cSRoman Divacky /// EmitNamespace - Emit all declarations in a namespace. 3464f22ef01cSRoman Divacky void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 346559d1ed5bSDimitry Andric for (auto *I : ND->decls()) { 346659d1ed5bSDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(I)) 3467f785676fSDimitry Andric if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization && 3468f785676fSDimitry Andric VD->getTemplateSpecializationKind() != TSK_Undeclared) 3469f785676fSDimitry Andric continue; 347059d1ed5bSDimitry Andric EmitTopLevelDecl(I); 3471f22ef01cSRoman Divacky } 3472f785676fSDimitry Andric } 3473f22ef01cSRoman Divacky 3474f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec. 3475f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 3476f22ef01cSRoman Divacky if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 3477f22ef01cSRoman Divacky LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 3478f22ef01cSRoman Divacky ErrorUnsupported(LSD, "linkage spec"); 3479f22ef01cSRoman Divacky return; 3480f22ef01cSRoman Divacky } 3481f22ef01cSRoman Divacky 348259d1ed5bSDimitry Andric for (auto *I : LSD->decls()) { 34833861d79fSDimitry Andric // Meta-data for ObjC class includes references to implemented methods. 34843861d79fSDimitry Andric // Generate class's method definitions first. 348559d1ed5bSDimitry Andric if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 348659d1ed5bSDimitry Andric for (auto *M : OID->methods()) 348759d1ed5bSDimitry Andric EmitTopLevelDecl(M); 34883861d79fSDimitry Andric } 348959d1ed5bSDimitry Andric EmitTopLevelDecl(I); 3490f22ef01cSRoman Divacky } 34913861d79fSDimitry Andric } 3492f22ef01cSRoman Divacky 3493f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration. 3494f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) { 3495f22ef01cSRoman Divacky // Ignore dependent declarations. 3496f22ef01cSRoman Divacky if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 3497f22ef01cSRoman Divacky return; 3498f22ef01cSRoman Divacky 3499f22ef01cSRoman Divacky switch (D->getKind()) { 3500f22ef01cSRoman Divacky case Decl::CXXConversion: 3501f22ef01cSRoman Divacky case Decl::CXXMethod: 3502f22ef01cSRoman Divacky case Decl::Function: 3503f22ef01cSRoman Divacky // Skip function templates 35043b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 35053b0f4066SDimitry Andric cast<FunctionDecl>(D)->isLateTemplateParsed()) 3506f22ef01cSRoman Divacky return; 3507f22ef01cSRoman Divacky 3508f22ef01cSRoman Divacky EmitGlobal(cast<FunctionDecl>(D)); 350939d628a0SDimitry Andric // Always provide some coverage mapping 351039d628a0SDimitry Andric // even for the functions that aren't emitted. 351139d628a0SDimitry Andric AddDeferredUnusedCoverageMapping(D); 3512f22ef01cSRoman Divacky break; 3513f22ef01cSRoman Divacky 3514f22ef01cSRoman Divacky case Decl::Var: 3515f785676fSDimitry Andric // Skip variable templates 3516f785676fSDimitry Andric if (cast<VarDecl>(D)->getDescribedVarTemplate()) 3517f785676fSDimitry Andric return; 3518f785676fSDimitry Andric case Decl::VarTemplateSpecialization: 3519f22ef01cSRoman Divacky EmitGlobal(cast<VarDecl>(D)); 3520f22ef01cSRoman Divacky break; 3521f22ef01cSRoman Divacky 35223b0f4066SDimitry Andric // Indirect fields from global anonymous structs and unions can be 35233b0f4066SDimitry Andric // ignored; only the actual variable requires IR gen support. 35243b0f4066SDimitry Andric case Decl::IndirectField: 35253b0f4066SDimitry Andric break; 35263b0f4066SDimitry Andric 3527f22ef01cSRoman Divacky // C++ Decls 3528f22ef01cSRoman Divacky case Decl::Namespace: 3529f22ef01cSRoman Divacky EmitNamespace(cast<NamespaceDecl>(D)); 3530f22ef01cSRoman Divacky break; 3531f22ef01cSRoman Divacky // No code generation needed. 3532f22ef01cSRoman Divacky case Decl::UsingShadow: 3533f22ef01cSRoman Divacky case Decl::ClassTemplate: 3534f785676fSDimitry Andric case Decl::VarTemplate: 3535f785676fSDimitry Andric case Decl::VarTemplatePartialSpecialization: 3536f22ef01cSRoman Divacky case Decl::FunctionTemplate: 3537bd5abe19SDimitry Andric case Decl::TypeAliasTemplate: 3538bd5abe19SDimitry Andric case Decl::Block: 3539139f7f9bSDimitry Andric case Decl::Empty: 3540f22ef01cSRoman Divacky break; 354159d1ed5bSDimitry Andric case Decl::Using: // using X; [C++] 354259d1ed5bSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 354359d1ed5bSDimitry Andric DI->EmitUsingDecl(cast<UsingDecl>(*D)); 354459d1ed5bSDimitry Andric return; 3545f785676fSDimitry Andric case Decl::NamespaceAlias: 3546f785676fSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3547f785676fSDimitry Andric DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 3548f785676fSDimitry Andric return; 3549284c1978SDimitry Andric case Decl::UsingDirective: // using namespace X; [C++] 3550284c1978SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3551284c1978SDimitry Andric DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 3552284c1978SDimitry Andric return; 3553f22ef01cSRoman Divacky case Decl::CXXConstructor: 3554f22ef01cSRoman Divacky // Skip function templates 35553b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 35563b0f4066SDimitry Andric cast<FunctionDecl>(D)->isLateTemplateParsed()) 3557f22ef01cSRoman Divacky return; 3558f22ef01cSRoman Divacky 3559f785676fSDimitry Andric getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 3560f22ef01cSRoman Divacky break; 3561f22ef01cSRoman Divacky case Decl::CXXDestructor: 35623b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 35633b0f4066SDimitry Andric return; 3564f785676fSDimitry Andric getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 3565f22ef01cSRoman Divacky break; 3566f22ef01cSRoman Divacky 3567f22ef01cSRoman Divacky case Decl::StaticAssert: 3568f22ef01cSRoman Divacky // Nothing to do. 3569f22ef01cSRoman Divacky break; 3570f22ef01cSRoman Divacky 3571f22ef01cSRoman Divacky // Objective-C Decls 3572f22ef01cSRoman Divacky 3573f22ef01cSRoman Divacky // Forward declarations, no (immediate) code generation. 3574f22ef01cSRoman Divacky case Decl::ObjCInterface: 35757ae0e2c9SDimitry Andric case Decl::ObjCCategory: 3576f22ef01cSRoman Divacky break; 3577f22ef01cSRoman Divacky 3578dff0c46cSDimitry Andric case Decl::ObjCProtocol: { 357959d1ed5bSDimitry Andric auto *Proto = cast<ObjCProtocolDecl>(D); 3580dff0c46cSDimitry Andric if (Proto->isThisDeclarationADefinition()) 3581dff0c46cSDimitry Andric ObjCRuntime->GenerateProtocol(Proto); 3582f22ef01cSRoman Divacky break; 3583dff0c46cSDimitry Andric } 3584f22ef01cSRoman Divacky 3585f22ef01cSRoman Divacky case Decl::ObjCCategoryImpl: 3586f22ef01cSRoman Divacky // Categories have properties but don't support synthesize so we 3587f22ef01cSRoman Divacky // can ignore them here. 35886122f3e6SDimitry Andric ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 3589f22ef01cSRoman Divacky break; 3590f22ef01cSRoman Divacky 3591f22ef01cSRoman Divacky case Decl::ObjCImplementation: { 359259d1ed5bSDimitry Andric auto *OMD = cast<ObjCImplementationDecl>(D); 3593f22ef01cSRoman Divacky EmitObjCPropertyImplementations(OMD); 3594f22ef01cSRoman Divacky EmitObjCIvarInitializations(OMD); 35956122f3e6SDimitry Andric ObjCRuntime->GenerateClass(OMD); 3596dff0c46cSDimitry Andric // Emit global variable debug information. 3597dff0c46cSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3598139f7f9bSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 3599139f7f9bSDimitry Andric DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 3600139f7f9bSDimitry Andric OMD->getClassInterface()), OMD->getLocation()); 3601f22ef01cSRoman Divacky break; 3602f22ef01cSRoman Divacky } 3603f22ef01cSRoman Divacky case Decl::ObjCMethod: { 360459d1ed5bSDimitry Andric auto *OMD = cast<ObjCMethodDecl>(D); 3605f22ef01cSRoman Divacky // If this is not a prototype, emit the body. 3606f22ef01cSRoman Divacky if (OMD->getBody()) 3607f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCMethod(OMD); 3608f22ef01cSRoman Divacky break; 3609f22ef01cSRoman Divacky } 3610f22ef01cSRoman Divacky case Decl::ObjCCompatibleAlias: 3611dff0c46cSDimitry Andric ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 3612f22ef01cSRoman Divacky break; 3613f22ef01cSRoman Divacky 3614f22ef01cSRoman Divacky case Decl::LinkageSpec: 3615f22ef01cSRoman Divacky EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 3616f22ef01cSRoman Divacky break; 3617f22ef01cSRoman Divacky 3618f22ef01cSRoman Divacky case Decl::FileScopeAsm: { 361933956c43SDimitry Andric // File-scope asm is ignored during device-side CUDA compilation. 362033956c43SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 362133956c43SDimitry Andric break; 3622ea942507SDimitry Andric // File-scope asm is ignored during device-side OpenMP compilation. 3623ea942507SDimitry Andric if (LangOpts.OpenMPIsDevice) 3624ea942507SDimitry Andric break; 362559d1ed5bSDimitry Andric auto *AD = cast<FileScopeAsmDecl>(D); 362633956c43SDimitry Andric getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 3627f22ef01cSRoman Divacky break; 3628f22ef01cSRoman Divacky } 3629f22ef01cSRoman Divacky 3630139f7f9bSDimitry Andric case Decl::Import: { 363159d1ed5bSDimitry Andric auto *Import = cast<ImportDecl>(D); 3632139f7f9bSDimitry Andric 3633139f7f9bSDimitry Andric // Ignore import declarations that come from imported modules. 36340623d748SDimitry Andric if (Import->getImportedOwningModule()) 3635139f7f9bSDimitry Andric break; 36363dac3a9bSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 36373dac3a9bSDimitry Andric DI->EmitImportDecl(*Import); 3638139f7f9bSDimitry Andric 3639139f7f9bSDimitry Andric ImportedModules.insert(Import->getImportedModule()); 3640139f7f9bSDimitry Andric break; 3641139f7f9bSDimitry Andric } 3642139f7f9bSDimitry Andric 364339d628a0SDimitry Andric case Decl::OMPThreadPrivate: 364439d628a0SDimitry Andric EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 364539d628a0SDimitry Andric break; 364639d628a0SDimitry Andric 364759d1ed5bSDimitry Andric case Decl::ClassTemplateSpecialization: { 364859d1ed5bSDimitry Andric const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 364959d1ed5bSDimitry Andric if (DebugInfo && 365039d628a0SDimitry Andric Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition && 365139d628a0SDimitry Andric Spec->hasDefinition()) 365259d1ed5bSDimitry Andric DebugInfo->completeTemplateDefinition(*Spec); 365339d628a0SDimitry Andric break; 365459d1ed5bSDimitry Andric } 365559d1ed5bSDimitry Andric 3656f22ef01cSRoman Divacky default: 3657f22ef01cSRoman Divacky // Make sure we handled everything we should, every other kind is a 3658f22ef01cSRoman Divacky // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 3659f22ef01cSRoman Divacky // function. Need to recode Decl::Kind to do that easily. 3660f22ef01cSRoman Divacky assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 366139d628a0SDimitry Andric break; 366239d628a0SDimitry Andric } 366339d628a0SDimitry Andric } 366439d628a0SDimitry Andric 366539d628a0SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 366639d628a0SDimitry Andric // Do we need to generate coverage mapping? 366739d628a0SDimitry Andric if (!CodeGenOpts.CoverageMapping) 366839d628a0SDimitry Andric return; 366939d628a0SDimitry Andric switch (D->getKind()) { 367039d628a0SDimitry Andric case Decl::CXXConversion: 367139d628a0SDimitry Andric case Decl::CXXMethod: 367239d628a0SDimitry Andric case Decl::Function: 367339d628a0SDimitry Andric case Decl::ObjCMethod: 367439d628a0SDimitry Andric case Decl::CXXConstructor: 367539d628a0SDimitry Andric case Decl::CXXDestructor: { 36760623d748SDimitry Andric if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 367739d628a0SDimitry Andric return; 367839d628a0SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 367939d628a0SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 368039d628a0SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = true; 368139d628a0SDimitry Andric break; 368239d628a0SDimitry Andric } 368339d628a0SDimitry Andric default: 368439d628a0SDimitry Andric break; 368539d628a0SDimitry Andric }; 368639d628a0SDimitry Andric } 368739d628a0SDimitry Andric 368839d628a0SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 368939d628a0SDimitry Andric // Do we need to generate coverage mapping? 369039d628a0SDimitry Andric if (!CodeGenOpts.CoverageMapping) 369139d628a0SDimitry Andric return; 369239d628a0SDimitry Andric if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 369339d628a0SDimitry Andric if (Fn->isTemplateInstantiation()) 369439d628a0SDimitry Andric ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 369539d628a0SDimitry Andric } 369639d628a0SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 369739d628a0SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 369839d628a0SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = false; 369939d628a0SDimitry Andric else 370039d628a0SDimitry Andric I->second = false; 370139d628a0SDimitry Andric } 370239d628a0SDimitry Andric 370339d628a0SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 370439d628a0SDimitry Andric std::vector<const Decl *> DeferredDecls; 370533956c43SDimitry Andric for (const auto &I : DeferredEmptyCoverageMappingDecls) { 370639d628a0SDimitry Andric if (!I.second) 370739d628a0SDimitry Andric continue; 370839d628a0SDimitry Andric DeferredDecls.push_back(I.first); 370939d628a0SDimitry Andric } 371039d628a0SDimitry Andric // Sort the declarations by their location to make sure that the tests get a 371139d628a0SDimitry Andric // predictable order for the coverage mapping for the unused declarations. 371239d628a0SDimitry Andric if (CodeGenOpts.DumpCoverageMapping) 371339d628a0SDimitry Andric std::sort(DeferredDecls.begin(), DeferredDecls.end(), 371439d628a0SDimitry Andric [] (const Decl *LHS, const Decl *RHS) { 371539d628a0SDimitry Andric return LHS->getLocStart() < RHS->getLocStart(); 371639d628a0SDimitry Andric }); 371739d628a0SDimitry Andric for (const auto *D : DeferredDecls) { 371839d628a0SDimitry Andric switch (D->getKind()) { 371939d628a0SDimitry Andric case Decl::CXXConversion: 372039d628a0SDimitry Andric case Decl::CXXMethod: 372139d628a0SDimitry Andric case Decl::Function: 372239d628a0SDimitry Andric case Decl::ObjCMethod: { 372339d628a0SDimitry Andric CodeGenPGO PGO(*this); 372439d628a0SDimitry Andric GlobalDecl GD(cast<FunctionDecl>(D)); 372539d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 372639d628a0SDimitry Andric getFunctionLinkage(GD)); 372739d628a0SDimitry Andric break; 372839d628a0SDimitry Andric } 372939d628a0SDimitry Andric case Decl::CXXConstructor: { 373039d628a0SDimitry Andric CodeGenPGO PGO(*this); 373139d628a0SDimitry Andric GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 373239d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 373339d628a0SDimitry Andric getFunctionLinkage(GD)); 373439d628a0SDimitry Andric break; 373539d628a0SDimitry Andric } 373639d628a0SDimitry Andric case Decl::CXXDestructor: { 373739d628a0SDimitry Andric CodeGenPGO PGO(*this); 373839d628a0SDimitry Andric GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 373939d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 374039d628a0SDimitry Andric getFunctionLinkage(GD)); 374139d628a0SDimitry Andric break; 374239d628a0SDimitry Andric } 374339d628a0SDimitry Andric default: 374439d628a0SDimitry Andric break; 374539d628a0SDimitry Andric }; 3746f22ef01cSRoman Divacky } 3747f22ef01cSRoman Divacky } 3748ffd1746dSEd Schouten 3749ffd1746dSEd Schouten /// Turns the given pointer into a constant. 3750ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 3751ffd1746dSEd Schouten const void *Ptr) { 3752ffd1746dSEd Schouten uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 37536122f3e6SDimitry Andric llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 3754ffd1746dSEd Schouten return llvm::ConstantInt::get(i64, PtrInt); 3755ffd1746dSEd Schouten } 3756ffd1746dSEd Schouten 3757ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 3758ffd1746dSEd Schouten llvm::NamedMDNode *&GlobalMetadata, 3759ffd1746dSEd Schouten GlobalDecl D, 3760ffd1746dSEd Schouten llvm::GlobalValue *Addr) { 3761ffd1746dSEd Schouten if (!GlobalMetadata) 3762ffd1746dSEd Schouten GlobalMetadata = 3763ffd1746dSEd Schouten CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 3764ffd1746dSEd Schouten 3765ffd1746dSEd Schouten // TODO: should we report variant information for ctors/dtors? 376639d628a0SDimitry Andric llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 376739d628a0SDimitry Andric llvm::ConstantAsMetadata::get(GetPointerConstant( 376839d628a0SDimitry Andric CGM.getLLVMContext(), D.getDecl()))}; 37693b0f4066SDimitry Andric GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 3770ffd1746dSEd Schouten } 3771ffd1746dSEd Schouten 3772284c1978SDimitry Andric /// For each function which is declared within an extern "C" region and marked 3773284c1978SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled 3774284c1978SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer 3775284c1978SDimitry Andric /// to such functions with an unmangled name from inline assembly within the 3776284c1978SDimitry Andric /// same translation unit. 3777284c1978SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() { 37788f0fd8f6SDimitry Andric for (auto &I : StaticExternCValues) { 37798f0fd8f6SDimitry Andric IdentifierInfo *Name = I.first; 37808f0fd8f6SDimitry Andric llvm::GlobalValue *Val = I.second; 3781284c1978SDimitry Andric if (Val && !getModule().getNamedValue(Name->getName())) 378259d1ed5bSDimitry Andric addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 3783284c1978SDimitry Andric } 3784284c1978SDimitry Andric } 3785284c1978SDimitry Andric 378659d1ed5bSDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 378759d1ed5bSDimitry Andric GlobalDecl &Result) const { 378859d1ed5bSDimitry Andric auto Res = Manglings.find(MangledName); 378959d1ed5bSDimitry Andric if (Res == Manglings.end()) 379059d1ed5bSDimitry Andric return false; 379159d1ed5bSDimitry Andric Result = Res->getValue(); 379259d1ed5bSDimitry Andric return true; 379359d1ed5bSDimitry Andric } 379459d1ed5bSDimitry Andric 3795ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the 3796ffd1746dSEd Schouten /// current module with the Decls they came from. This is useful for 3797ffd1746dSEd Schouten /// projects using IR gen as a subroutine. 3798ffd1746dSEd Schouten /// 3799ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly 3800ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata 3801ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'. 3802ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() { 380359d1ed5bSDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 3804ffd1746dSEd Schouten 380559d1ed5bSDimitry Andric for (auto &I : MangledDeclNames) { 380659d1ed5bSDimitry Andric llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 38070623d748SDimitry Andric // Some mangled names don't necessarily have an associated GlobalValue 38080623d748SDimitry Andric // in this module, e.g. if we mangled it for DebugInfo. 38090623d748SDimitry Andric if (Addr) 381059d1ed5bSDimitry Andric EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 3811ffd1746dSEd Schouten } 3812ffd1746dSEd Schouten } 3813ffd1746dSEd Schouten 3814ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current 3815ffd1746dSEd Schouten /// function. 3816ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() { 3817ffd1746dSEd Schouten if (LocalDeclMap.empty()) return; 3818ffd1746dSEd Schouten 3819ffd1746dSEd Schouten llvm::LLVMContext &Context = getLLVMContext(); 3820ffd1746dSEd Schouten 3821ffd1746dSEd Schouten // Find the unique metadata ID for this name. 3822ffd1746dSEd Schouten unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 3823ffd1746dSEd Schouten 382459d1ed5bSDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 3825ffd1746dSEd Schouten 382659d1ed5bSDimitry Andric for (auto &I : LocalDeclMap) { 382759d1ed5bSDimitry Andric const Decl *D = I.first; 38280623d748SDimitry Andric llvm::Value *Addr = I.second.getPointer(); 382959d1ed5bSDimitry Andric if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 3830ffd1746dSEd Schouten llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 383139d628a0SDimitry Andric Alloca->setMetadata( 383239d628a0SDimitry Andric DeclPtrKind, llvm::MDNode::get( 383339d628a0SDimitry Andric Context, llvm::ValueAsMetadata::getConstant(DAddr))); 383459d1ed5bSDimitry Andric } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 3835ffd1746dSEd Schouten GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 3836ffd1746dSEd Schouten EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 3837ffd1746dSEd Schouten } 3838ffd1746dSEd Schouten } 3839ffd1746dSEd Schouten } 3840e580952dSDimitry Andric 3841f785676fSDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() { 3842f785676fSDimitry Andric llvm::NamedMDNode *IdentMetadata = 3843f785676fSDimitry Andric TheModule.getOrInsertNamedMetadata("llvm.ident"); 3844f785676fSDimitry Andric std::string Version = getClangFullVersion(); 3845f785676fSDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 3846f785676fSDimitry Andric 384739d628a0SDimitry Andric llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 3848f785676fSDimitry Andric IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 3849f785676fSDimitry Andric } 3850f785676fSDimitry Andric 385159d1ed5bSDimitry Andric void CodeGenModule::EmitTargetMetadata() { 385239d628a0SDimitry Andric // Warning, new MangledDeclNames may be appended within this loop. 385339d628a0SDimitry Andric // We rely on MapVector insertions adding new elements to the end 385439d628a0SDimitry Andric // of the container. 385539d628a0SDimitry Andric // FIXME: Move this loop into the one target that needs it, and only 385639d628a0SDimitry Andric // loop over those declarations for which we couldn't emit the target 385739d628a0SDimitry Andric // metadata when we emitted the declaration. 385839d628a0SDimitry Andric for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 385939d628a0SDimitry Andric auto Val = *(MangledDeclNames.begin() + I); 386039d628a0SDimitry Andric const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 386139d628a0SDimitry Andric llvm::GlobalValue *GV = GetGlobalValue(Val.second); 386259d1ed5bSDimitry Andric getTargetCodeGenInfo().emitTargetMD(D, GV, *this); 386359d1ed5bSDimitry Andric } 386459d1ed5bSDimitry Andric } 386559d1ed5bSDimitry Andric 3866bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() { 3867bd5abe19SDimitry Andric if (!getCodeGenOpts().CoverageFile.empty()) { 3868bd5abe19SDimitry Andric if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) { 3869bd5abe19SDimitry Andric llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 3870bd5abe19SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 3871bd5abe19SDimitry Andric llvm::MDString *CoverageFile = 3872bd5abe19SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile); 3873bd5abe19SDimitry Andric for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 3874bd5abe19SDimitry Andric llvm::MDNode *CU = CUNode->getOperand(i); 387539d628a0SDimitry Andric llvm::Metadata *Elts[] = {CoverageFile, CU}; 387639d628a0SDimitry Andric GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 3877bd5abe19SDimitry Andric } 3878bd5abe19SDimitry Andric } 3879bd5abe19SDimitry Andric } 3880bd5abe19SDimitry Andric } 38813861d79fSDimitry Andric 388239d628a0SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) { 38833861d79fSDimitry Andric // Sema has checked that all uuid strings are of the form 38843861d79fSDimitry Andric // "12345678-1234-1234-1234-1234567890ab". 38853861d79fSDimitry Andric assert(Uuid.size() == 36); 3886f785676fSDimitry Andric for (unsigned i = 0; i < 36; ++i) { 3887f785676fSDimitry Andric if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-'); 3888f785676fSDimitry Andric else assert(isHexDigit(Uuid[i])); 38893861d79fSDimitry Andric } 38903861d79fSDimitry Andric 389139d628a0SDimitry Andric // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab". 3892f785676fSDimitry Andric const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 38933861d79fSDimitry Andric 3894f785676fSDimitry Andric llvm::Constant *Field3[8]; 3895f785676fSDimitry Andric for (unsigned Idx = 0; Idx < 8; ++Idx) 3896f785676fSDimitry Andric Field3[Idx] = llvm::ConstantInt::get( 3897f785676fSDimitry Andric Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16); 38983861d79fSDimitry Andric 3899f785676fSDimitry Andric llvm::Constant *Fields[4] = { 3900f785676fSDimitry Andric llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16), 3901f785676fSDimitry Andric llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16), 3902f785676fSDimitry Andric llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16), 3903f785676fSDimitry Andric llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3) 3904f785676fSDimitry Andric }; 3905f785676fSDimitry Andric 3906f785676fSDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 39073861d79fSDimitry Andric } 390859d1ed5bSDimitry Andric 390959d1ed5bSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 391059d1ed5bSDimitry Andric bool ForEH) { 391159d1ed5bSDimitry Andric // Return a bogus pointer if RTTI is disabled, unless it's for EH. 391259d1ed5bSDimitry Andric // FIXME: should we even be calling this method if RTTI is disabled 391359d1ed5bSDimitry Andric // and it's not for EH? 391459d1ed5bSDimitry Andric if (!ForEH && !getLangOpts().RTTI) 391559d1ed5bSDimitry Andric return llvm::Constant::getNullValue(Int8PtrTy); 391659d1ed5bSDimitry Andric 391759d1ed5bSDimitry Andric if (ForEH && Ty->isObjCObjectPointerType() && 391859d1ed5bSDimitry Andric LangOpts.ObjCRuntime.isGNUFamily()) 391959d1ed5bSDimitry Andric return ObjCRuntime->GetEHType(Ty); 392059d1ed5bSDimitry Andric 392159d1ed5bSDimitry Andric return getCXXABI().getAddrOfRTTIDescriptor(Ty); 392259d1ed5bSDimitry Andric } 392359d1ed5bSDimitry Andric 392439d628a0SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 392539d628a0SDimitry Andric for (auto RefExpr : D->varlists()) { 392639d628a0SDimitry Andric auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 392739d628a0SDimitry Andric bool PerformInit = 392839d628a0SDimitry Andric VD->getAnyInitializer() && 392939d628a0SDimitry Andric !VD->getAnyInitializer()->isConstantInitializer(getContext(), 393039d628a0SDimitry Andric /*ForRef=*/false); 39310623d748SDimitry Andric 39320623d748SDimitry Andric Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD)); 393333956c43SDimitry Andric if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 39340623d748SDimitry Andric VD, Addr, RefExpr->getLocStart(), PerformInit)) 393539d628a0SDimitry Andric CXXGlobalInits.push_back(InitFunction); 393639d628a0SDimitry Andric } 393739d628a0SDimitry Andric } 39388f0fd8f6SDimitry Andric 39390623d748SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 39400623d748SDimitry Andric llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()]; 39410623d748SDimitry Andric if (InternalId) 39420623d748SDimitry Andric return InternalId; 39430623d748SDimitry Andric 39440623d748SDimitry Andric if (isExternallyVisible(T->getLinkage())) { 39458f0fd8f6SDimitry Andric std::string OutName; 39468f0fd8f6SDimitry Andric llvm::raw_string_ostream Out(OutName); 39470623d748SDimitry Andric getCXXABI().getMangleContext().mangleTypeName(T, Out); 39488f0fd8f6SDimitry Andric 39490623d748SDimitry Andric InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 39500623d748SDimitry Andric } else { 39510623d748SDimitry Andric InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 39520623d748SDimitry Andric llvm::ArrayRef<llvm::Metadata *>()); 39530623d748SDimitry Andric } 39540623d748SDimitry Andric 39550623d748SDimitry Andric return InternalId; 39560623d748SDimitry Andric } 39570623d748SDimitry Andric 39580623d748SDimitry Andric void CodeGenModule::CreateVTableBitSetEntry(llvm::NamedMDNode *BitsetsMD, 39590623d748SDimitry Andric llvm::GlobalVariable *VTable, 39600623d748SDimitry Andric CharUnits Offset, 39610623d748SDimitry Andric const CXXRecordDecl *RD) { 39620623d748SDimitry Andric llvm::Metadata *MD = 39630623d748SDimitry Andric CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 39648f0fd8f6SDimitry Andric llvm::Metadata *BitsetOps[] = { 39650623d748SDimitry Andric MD, llvm::ConstantAsMetadata::get(VTable), 39660623d748SDimitry Andric llvm::ConstantAsMetadata::get( 39670623d748SDimitry Andric llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))}; 39680623d748SDimitry Andric BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps)); 39690623d748SDimitry Andric 39700623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 39710623d748SDimitry Andric if (auto TypeId = CreateCfiIdForTypeMetadata(MD)) { 39720623d748SDimitry Andric llvm::Metadata *BitsetOps2[] = { 39730623d748SDimitry Andric llvm::ConstantAsMetadata::get(TypeId), 39748f0fd8f6SDimitry Andric llvm::ConstantAsMetadata::get(VTable), 39758f0fd8f6SDimitry Andric llvm::ConstantAsMetadata::get( 39768f0fd8f6SDimitry Andric llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))}; 39770623d748SDimitry Andric BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps2)); 39780623d748SDimitry Andric } 39790623d748SDimitry Andric } 39800623d748SDimitry Andric } 39810623d748SDimitry Andric 39820623d748SDimitry Andric // Fills in the supplied string map with the set of target features for the 39830623d748SDimitry Andric // passed in function. 39840623d748SDimitry Andric void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 39850623d748SDimitry Andric const FunctionDecl *FD) { 39860623d748SDimitry Andric StringRef TargetCPU = Target.getTargetOpts().CPU; 39870623d748SDimitry Andric if (const auto *TD = FD->getAttr<TargetAttr>()) { 39880623d748SDimitry Andric // If we have a TargetAttr build up the feature map based on that. 39890623d748SDimitry Andric TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse(); 39900623d748SDimitry Andric 39910623d748SDimitry Andric // Make a copy of the features as passed on the command line into the 39920623d748SDimitry Andric // beginning of the additional features from the function to override. 39930623d748SDimitry Andric ParsedAttr.first.insert(ParsedAttr.first.begin(), 39940623d748SDimitry Andric Target.getTargetOpts().FeaturesAsWritten.begin(), 39950623d748SDimitry Andric Target.getTargetOpts().FeaturesAsWritten.end()); 39960623d748SDimitry Andric 39970623d748SDimitry Andric if (ParsedAttr.second != "") 39980623d748SDimitry Andric TargetCPU = ParsedAttr.second; 39990623d748SDimitry Andric 40000623d748SDimitry Andric // Now populate the feature map, first with the TargetCPU which is either 40010623d748SDimitry Andric // the default or a new one from the target attribute string. Then we'll use 40020623d748SDimitry Andric // the passed in features (FeaturesAsWritten) along with the new ones from 40030623d748SDimitry Andric // the attribute. 40040623d748SDimitry Andric Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first); 40050623d748SDimitry Andric } else { 40060623d748SDimitry Andric Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, 40070623d748SDimitry Andric Target.getTargetOpts().Features); 40080623d748SDimitry Andric } 40098f0fd8f6SDimitry Andric } 4010