xref: /freebsd/contrib/llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 13138422bc354a1ec35f53a27c4efeccdffc5639)
10b57cec5SDimitry Andric //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This coordinates the per-module state used while generating code.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "CodeGenModule.h"
140b57cec5SDimitry Andric #include "CGBlocks.h"
150b57cec5SDimitry Andric #include "CGCUDARuntime.h"
160b57cec5SDimitry Andric #include "CGCXXABI.h"
170b57cec5SDimitry Andric #include "CGCall.h"
180b57cec5SDimitry Andric #include "CGDebugInfo.h"
190b57cec5SDimitry Andric #include "CGObjCRuntime.h"
200b57cec5SDimitry Andric #include "CGOpenCLRuntime.h"
210b57cec5SDimitry Andric #include "CGOpenMPRuntime.h"
220b57cec5SDimitry Andric #include "CGOpenMPRuntimeNVPTX.h"
230b57cec5SDimitry Andric #include "CodeGenFunction.h"
240b57cec5SDimitry Andric #include "CodeGenPGO.h"
250b57cec5SDimitry Andric #include "ConstantEmitter.h"
260b57cec5SDimitry Andric #include "CoverageMappingGen.h"
270b57cec5SDimitry Andric #include "TargetInfo.h"
280b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
290b57cec5SDimitry Andric #include "clang/AST/CharUnits.h"
300b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h"
310b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h"
320b57cec5SDimitry Andric #include "clang/AST/DeclTemplate.h"
330b57cec5SDimitry Andric #include "clang/AST/Mangle.h"
340b57cec5SDimitry Andric #include "clang/AST/RecordLayout.h"
350b57cec5SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
360b57cec5SDimitry Andric #include "clang/AST/StmtVisitor.h"
370b57cec5SDimitry Andric #include "clang/Basic/Builtins.h"
380b57cec5SDimitry Andric #include "clang/Basic/CharInfo.h"
390b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
400b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h"
410b57cec5SDimitry Andric #include "clang/Basic/Module.h"
420b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h"
430b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h"
440b57cec5SDimitry Andric #include "clang/Basic/Version.h"
450b57cec5SDimitry Andric #include "clang/CodeGen/ConstantInitBuilder.h"
460b57cec5SDimitry Andric #include "clang/Frontend/FrontendDiagnostic.h"
470b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h"
480b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
490b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
50480093f4SDimitry Andric #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
510b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h"
520b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
530b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
540b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
550b57cec5SDimitry Andric #include "llvm/IR/Module.h"
560b57cec5SDimitry Andric #include "llvm/IR/ProfileSummary.h"
570b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfReader.h"
580b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h"
59480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
600b57cec5SDimitry Andric #include "llvm/Support/ConvertUTF.h"
610b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
620b57cec5SDimitry Andric #include "llvm/Support/MD5.h"
630b57cec5SDimitry Andric #include "llvm/Support/TimeProfiler.h"
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric using namespace clang;
660b57cec5SDimitry Andric using namespace CodeGen;
670b57cec5SDimitry Andric 
680b57cec5SDimitry Andric static llvm::cl::opt<bool> LimitedCoverage(
690b57cec5SDimitry Andric     "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
700b57cec5SDimitry Andric     llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
710b57cec5SDimitry Andric     llvm::cl::init(false));
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric static const char AnnotationSection[] = "llvm.metadata";
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
760b57cec5SDimitry Andric   switch (CGM.getTarget().getCXXABI().getKind()) {
77480093f4SDimitry Andric   case TargetCXXABI::Fuchsia:
780b57cec5SDimitry Andric   case TargetCXXABI::GenericAArch64:
790b57cec5SDimitry Andric   case TargetCXXABI::GenericARM:
800b57cec5SDimitry Andric   case TargetCXXABI::iOS:
810b57cec5SDimitry Andric   case TargetCXXABI::iOS64:
820b57cec5SDimitry Andric   case TargetCXXABI::WatchOS:
830b57cec5SDimitry Andric   case TargetCXXABI::GenericMIPS:
840b57cec5SDimitry Andric   case TargetCXXABI::GenericItanium:
850b57cec5SDimitry Andric   case TargetCXXABI::WebAssembly:
860b57cec5SDimitry Andric     return CreateItaniumCXXABI(CGM);
870b57cec5SDimitry Andric   case TargetCXXABI::Microsoft:
880b57cec5SDimitry Andric     return CreateMicrosoftCXXABI(CGM);
890b57cec5SDimitry Andric   }
900b57cec5SDimitry Andric 
910b57cec5SDimitry Andric   llvm_unreachable("invalid C++ ABI kind");
920b57cec5SDimitry Andric }
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
950b57cec5SDimitry Andric                              const PreprocessorOptions &PPO,
960b57cec5SDimitry Andric                              const CodeGenOptions &CGO, llvm::Module &M,
970b57cec5SDimitry Andric                              DiagnosticsEngine &diags,
980b57cec5SDimitry Andric                              CoverageSourceInfo *CoverageInfo)
990b57cec5SDimitry Andric     : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
1000b57cec5SDimitry Andric       PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
1010b57cec5SDimitry Andric       Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
1020b57cec5SDimitry Andric       VMContext(M.getContext()), Types(*this), VTables(*this),
1030b57cec5SDimitry Andric       SanitizerMD(new SanitizerMetadata(*this)) {
1040b57cec5SDimitry Andric 
1050b57cec5SDimitry Andric   // Initialize the type cache.
1060b57cec5SDimitry Andric   llvm::LLVMContext &LLVMContext = M.getContext();
1070b57cec5SDimitry Andric   VoidTy = llvm::Type::getVoidTy(LLVMContext);
1080b57cec5SDimitry Andric   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
1090b57cec5SDimitry Andric   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
1100b57cec5SDimitry Andric   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
1110b57cec5SDimitry Andric   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
1120b57cec5SDimitry Andric   HalfTy = llvm::Type::getHalfTy(LLVMContext);
1130b57cec5SDimitry Andric   FloatTy = llvm::Type::getFloatTy(LLVMContext);
1140b57cec5SDimitry Andric   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
1150b57cec5SDimitry Andric   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
1160b57cec5SDimitry Andric   PointerAlignInBytes =
1170b57cec5SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
1180b57cec5SDimitry Andric   SizeSizeInBytes =
1190b57cec5SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
1200b57cec5SDimitry Andric   IntAlignInBytes =
1210b57cec5SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
1220b57cec5SDimitry Andric   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
1230b57cec5SDimitry Andric   IntPtrTy = llvm::IntegerType::get(LLVMContext,
1240b57cec5SDimitry Andric     C.getTargetInfo().getMaxPointerWidth());
1250b57cec5SDimitry Andric   Int8PtrTy = Int8Ty->getPointerTo(0);
1260b57cec5SDimitry Andric   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
1270b57cec5SDimitry Andric   AllocaInt8PtrTy = Int8Ty->getPointerTo(
1280b57cec5SDimitry Andric       M.getDataLayout().getAllocaAddrSpace());
1290b57cec5SDimitry Andric   ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
1300b57cec5SDimitry Andric 
1310b57cec5SDimitry Andric   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric   if (LangOpts.ObjC)
1340b57cec5SDimitry Andric     createObjCRuntime();
1350b57cec5SDimitry Andric   if (LangOpts.OpenCL)
1360b57cec5SDimitry Andric     createOpenCLRuntime();
1370b57cec5SDimitry Andric   if (LangOpts.OpenMP)
1380b57cec5SDimitry Andric     createOpenMPRuntime();
1390b57cec5SDimitry Andric   if (LangOpts.CUDA)
1400b57cec5SDimitry Andric     createCUDARuntime();
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
1430b57cec5SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
1440b57cec5SDimitry Andric       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
1450b57cec5SDimitry Andric     TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
1460b57cec5SDimitry Andric                                getCXXABI().getMangleContext()));
1470b57cec5SDimitry Andric 
1480b57cec5SDimitry Andric   // If debug info or coverage generation is enabled, create the CGDebugInfo
1490b57cec5SDimitry Andric   // object.
1500b57cec5SDimitry Andric   if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
1510b57cec5SDimitry Andric       CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
1520b57cec5SDimitry Andric     DebugInfo.reset(new CGDebugInfo(*this));
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric   Block.GlobalUniqueCount = 0;
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric   if (C.getLangOpts().ObjC)
1570b57cec5SDimitry Andric     ObjCData.reset(new ObjCEntrypoints());
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric   if (CodeGenOpts.hasProfileClangUse()) {
1600b57cec5SDimitry Andric     auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
1610b57cec5SDimitry Andric         CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile);
1620b57cec5SDimitry Andric     if (auto E = ReaderOrErr.takeError()) {
1630b57cec5SDimitry Andric       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1640b57cec5SDimitry Andric                                               "Could not read profile %0: %1");
1650b57cec5SDimitry Andric       llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
1660b57cec5SDimitry Andric         getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
1670b57cec5SDimitry Andric                                   << EI.message();
1680b57cec5SDimitry Andric       });
1690b57cec5SDimitry Andric     } else
1700b57cec5SDimitry Andric       PGOReader = std::move(ReaderOrErr.get());
1710b57cec5SDimitry Andric   }
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric   // If coverage mapping generation is enabled, create the
1740b57cec5SDimitry Andric   // CoverageMappingModuleGen object.
1750b57cec5SDimitry Andric   if (CodeGenOpts.CoverageMapping)
1760b57cec5SDimitry Andric     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
1770b57cec5SDimitry Andric }
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric CodeGenModule::~CodeGenModule() {}
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric void CodeGenModule::createObjCRuntime() {
1820b57cec5SDimitry Andric   // This is just isGNUFamily(), but we want to force implementors of
1830b57cec5SDimitry Andric   // new ABIs to decide how best to do this.
1840b57cec5SDimitry Andric   switch (LangOpts.ObjCRuntime.getKind()) {
1850b57cec5SDimitry Andric   case ObjCRuntime::GNUstep:
1860b57cec5SDimitry Andric   case ObjCRuntime::GCC:
1870b57cec5SDimitry Andric   case ObjCRuntime::ObjFW:
1880b57cec5SDimitry Andric     ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
1890b57cec5SDimitry Andric     return;
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric   case ObjCRuntime::FragileMacOSX:
1920b57cec5SDimitry Andric   case ObjCRuntime::MacOSX:
1930b57cec5SDimitry Andric   case ObjCRuntime::iOS:
1940b57cec5SDimitry Andric   case ObjCRuntime::WatchOS:
1950b57cec5SDimitry Andric     ObjCRuntime.reset(CreateMacObjCRuntime(*this));
1960b57cec5SDimitry Andric     return;
1970b57cec5SDimitry Andric   }
1980b57cec5SDimitry Andric   llvm_unreachable("bad runtime kind");
1990b57cec5SDimitry Andric }
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric void CodeGenModule::createOpenCLRuntime() {
2020b57cec5SDimitry Andric   OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
2030b57cec5SDimitry Andric }
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric void CodeGenModule::createOpenMPRuntime() {
2060b57cec5SDimitry Andric   // Select a specialized code generation class based on the target, if any.
2070b57cec5SDimitry Andric   // If it does not exist use the default implementation.
2080b57cec5SDimitry Andric   switch (getTriple().getArch()) {
2090b57cec5SDimitry Andric   case llvm::Triple::nvptx:
2100b57cec5SDimitry Andric   case llvm::Triple::nvptx64:
2110b57cec5SDimitry Andric     assert(getLangOpts().OpenMPIsDevice &&
2120b57cec5SDimitry Andric            "OpenMP NVPTX is only prepared to deal with device code.");
2130b57cec5SDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
2140b57cec5SDimitry Andric     break;
2150b57cec5SDimitry Andric   default:
2160b57cec5SDimitry Andric     if (LangOpts.OpenMPSimd)
2170b57cec5SDimitry Andric       OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
2180b57cec5SDimitry Andric     else
2190b57cec5SDimitry Andric       OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
2200b57cec5SDimitry Andric     break;
2210b57cec5SDimitry Andric   }
222480093f4SDimitry Andric 
223480093f4SDimitry Andric   // The OpenMP-IR-Builder should eventually replace the above runtime codegens
224480093f4SDimitry Andric   // but we are not there yet so they both reside in CGModule for now and the
225480093f4SDimitry Andric   // OpenMP-IR-Builder is opt-in only.
226480093f4SDimitry Andric   if (LangOpts.OpenMPIRBuilder) {
227480093f4SDimitry Andric     OMPBuilder.reset(new llvm::OpenMPIRBuilder(TheModule));
228480093f4SDimitry Andric     OMPBuilder->initialize();
229480093f4SDimitry Andric   }
2300b57cec5SDimitry Andric }
2310b57cec5SDimitry Andric 
2320b57cec5SDimitry Andric void CodeGenModule::createCUDARuntime() {
2330b57cec5SDimitry Andric   CUDARuntime.reset(CreateNVCUDARuntime(*this));
2340b57cec5SDimitry Andric }
2350b57cec5SDimitry Andric 
2360b57cec5SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
2370b57cec5SDimitry Andric   Replacements[Name] = C;
2380b57cec5SDimitry Andric }
2390b57cec5SDimitry Andric 
2400b57cec5SDimitry Andric void CodeGenModule::applyReplacements() {
2410b57cec5SDimitry Andric   for (auto &I : Replacements) {
2420b57cec5SDimitry Andric     StringRef MangledName = I.first();
2430b57cec5SDimitry Andric     llvm::Constant *Replacement = I.second;
2440b57cec5SDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2450b57cec5SDimitry Andric     if (!Entry)
2460b57cec5SDimitry Andric       continue;
2470b57cec5SDimitry Andric     auto *OldF = cast<llvm::Function>(Entry);
2480b57cec5SDimitry Andric     auto *NewF = dyn_cast<llvm::Function>(Replacement);
2490b57cec5SDimitry Andric     if (!NewF) {
2500b57cec5SDimitry Andric       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
2510b57cec5SDimitry Andric         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
2520b57cec5SDimitry Andric       } else {
2530b57cec5SDimitry Andric         auto *CE = cast<llvm::ConstantExpr>(Replacement);
2540b57cec5SDimitry Andric         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2550b57cec5SDimitry Andric                CE->getOpcode() == llvm::Instruction::GetElementPtr);
2560b57cec5SDimitry Andric         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
2570b57cec5SDimitry Andric       }
2580b57cec5SDimitry Andric     }
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric     // Replace old with new, but keep the old order.
2610b57cec5SDimitry Andric     OldF->replaceAllUsesWith(Replacement);
2620b57cec5SDimitry Andric     if (NewF) {
2630b57cec5SDimitry Andric       NewF->removeFromParent();
2640b57cec5SDimitry Andric       OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
2650b57cec5SDimitry Andric                                                        NewF);
2660b57cec5SDimitry Andric     }
2670b57cec5SDimitry Andric     OldF->eraseFromParent();
2680b57cec5SDimitry Andric   }
2690b57cec5SDimitry Andric }
2700b57cec5SDimitry Andric 
2710b57cec5SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
2720b57cec5SDimitry Andric   GlobalValReplacements.push_back(std::make_pair(GV, C));
2730b57cec5SDimitry Andric }
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric void CodeGenModule::applyGlobalValReplacements() {
2760b57cec5SDimitry Andric   for (auto &I : GlobalValReplacements) {
2770b57cec5SDimitry Andric     llvm::GlobalValue *GV = I.first;
2780b57cec5SDimitry Andric     llvm::Constant *C = I.second;
2790b57cec5SDimitry Andric 
2800b57cec5SDimitry Andric     GV->replaceAllUsesWith(C);
2810b57cec5SDimitry Andric     GV->eraseFromParent();
2820b57cec5SDimitry Andric   }
2830b57cec5SDimitry Andric }
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric // This is only used in aliases that we created and we know they have a
2860b57cec5SDimitry Andric // linear structure.
2870b57cec5SDimitry Andric static const llvm::GlobalObject *getAliasedGlobal(
2880b57cec5SDimitry Andric     const llvm::GlobalIndirectSymbol &GIS) {
2890b57cec5SDimitry Andric   llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
2900b57cec5SDimitry Andric   const llvm::Constant *C = &GIS;
2910b57cec5SDimitry Andric   for (;;) {
2920b57cec5SDimitry Andric     C = C->stripPointerCasts();
2930b57cec5SDimitry Andric     if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
2940b57cec5SDimitry Andric       return GO;
2950b57cec5SDimitry Andric     // stripPointerCasts will not walk over weak aliases.
2960b57cec5SDimitry Andric     auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
2970b57cec5SDimitry Andric     if (!GIS2)
2980b57cec5SDimitry Andric       return nullptr;
2990b57cec5SDimitry Andric     if (!Visited.insert(GIS2).second)
3000b57cec5SDimitry Andric       return nullptr;
3010b57cec5SDimitry Andric     C = GIS2->getIndirectSymbol();
3020b57cec5SDimitry Andric   }
3030b57cec5SDimitry Andric }
3040b57cec5SDimitry Andric 
3050b57cec5SDimitry Andric void CodeGenModule::checkAliases() {
3060b57cec5SDimitry Andric   // Check if the constructed aliases are well formed. It is really unfortunate
3070b57cec5SDimitry Andric   // that we have to do this in CodeGen, but we only construct mangled names
3080b57cec5SDimitry Andric   // and aliases during codegen.
3090b57cec5SDimitry Andric   bool Error = false;
3100b57cec5SDimitry Andric   DiagnosticsEngine &Diags = getDiags();
3110b57cec5SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
3120b57cec5SDimitry Andric     const auto *D = cast<ValueDecl>(GD.getDecl());
3130b57cec5SDimitry Andric     SourceLocation Location;
3140b57cec5SDimitry Andric     bool IsIFunc = D->hasAttr<IFuncAttr>();
3150b57cec5SDimitry Andric     if (const Attr *A = D->getDefiningAttr())
3160b57cec5SDimitry Andric       Location = A->getLocation();
3170b57cec5SDimitry Andric     else
3180b57cec5SDimitry Andric       llvm_unreachable("Not an alias or ifunc?");
3190b57cec5SDimitry Andric     StringRef MangledName = getMangledName(GD);
3200b57cec5SDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3210b57cec5SDimitry Andric     auto *Alias  = cast<llvm::GlobalIndirectSymbol>(Entry);
3220b57cec5SDimitry Andric     const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
3230b57cec5SDimitry Andric     if (!GV) {
3240b57cec5SDimitry Andric       Error = true;
3250b57cec5SDimitry Andric       Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
3260b57cec5SDimitry Andric     } else if (GV->isDeclaration()) {
3270b57cec5SDimitry Andric       Error = true;
3280b57cec5SDimitry Andric       Diags.Report(Location, diag::err_alias_to_undefined)
3290b57cec5SDimitry Andric           << IsIFunc << IsIFunc;
3300b57cec5SDimitry Andric     } else if (IsIFunc) {
3310b57cec5SDimitry Andric       // Check resolver function type.
3320b57cec5SDimitry Andric       llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
3330b57cec5SDimitry Andric           GV->getType()->getPointerElementType());
3340b57cec5SDimitry Andric       assert(FTy);
3350b57cec5SDimitry Andric       if (!FTy->getReturnType()->isPointerTy())
3360b57cec5SDimitry Andric         Diags.Report(Location, diag::err_ifunc_resolver_return);
3370b57cec5SDimitry Andric     }
3380b57cec5SDimitry Andric 
3390b57cec5SDimitry Andric     llvm::Constant *Aliasee = Alias->getIndirectSymbol();
3400b57cec5SDimitry Andric     llvm::GlobalValue *AliaseeGV;
3410b57cec5SDimitry Andric     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
3420b57cec5SDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
3430b57cec5SDimitry Andric     else
3440b57cec5SDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
3470b57cec5SDimitry Andric       StringRef AliasSection = SA->getName();
3480b57cec5SDimitry Andric       if (AliasSection != AliaseeGV->getSection())
3490b57cec5SDimitry Andric         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
3500b57cec5SDimitry Andric             << AliasSection << IsIFunc << IsIFunc;
3510b57cec5SDimitry Andric     }
3520b57cec5SDimitry Andric 
3530b57cec5SDimitry Andric     // We have to handle alias to weak aliases in here. LLVM itself disallows
3540b57cec5SDimitry Andric     // this since the object semantics would not match the IL one. For
3550b57cec5SDimitry Andric     // compatibility with gcc we implement it by just pointing the alias
3560b57cec5SDimitry Andric     // to its aliasee's aliasee. We also warn, since the user is probably
3570b57cec5SDimitry Andric     // expecting the link to be weak.
3580b57cec5SDimitry Andric     if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
3590b57cec5SDimitry Andric       if (GA->isInterposable()) {
3600b57cec5SDimitry Andric         Diags.Report(Location, diag::warn_alias_to_weak_alias)
3610b57cec5SDimitry Andric             << GV->getName() << GA->getName() << IsIFunc;
3620b57cec5SDimitry Andric         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3630b57cec5SDimitry Andric             GA->getIndirectSymbol(), Alias->getType());
3640b57cec5SDimitry Andric         Alias->setIndirectSymbol(Aliasee);
3650b57cec5SDimitry Andric       }
3660b57cec5SDimitry Andric     }
3670b57cec5SDimitry Andric   }
3680b57cec5SDimitry Andric   if (!Error)
3690b57cec5SDimitry Andric     return;
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
3720b57cec5SDimitry Andric     StringRef MangledName = getMangledName(GD);
3730b57cec5SDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3740b57cec5SDimitry Andric     auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
3750b57cec5SDimitry Andric     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
3760b57cec5SDimitry Andric     Alias->eraseFromParent();
3770b57cec5SDimitry Andric   }
3780b57cec5SDimitry Andric }
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric void CodeGenModule::clear() {
3810b57cec5SDimitry Andric   DeferredDeclsToEmit.clear();
3820b57cec5SDimitry Andric   if (OpenMPRuntime)
3830b57cec5SDimitry Andric     OpenMPRuntime->clear();
3840b57cec5SDimitry Andric }
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
3870b57cec5SDimitry Andric                                        StringRef MainFile) {
3880b57cec5SDimitry Andric   if (!hasDiagnostics())
3890b57cec5SDimitry Andric     return;
3900b57cec5SDimitry Andric   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
3910b57cec5SDimitry Andric     if (MainFile.empty())
3920b57cec5SDimitry Andric       MainFile = "<stdin>";
3930b57cec5SDimitry Andric     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
3940b57cec5SDimitry Andric   } else {
3950b57cec5SDimitry Andric     if (Mismatched > 0)
3960b57cec5SDimitry Andric       Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
3970b57cec5SDimitry Andric 
3980b57cec5SDimitry Andric     if (Missing > 0)
3990b57cec5SDimitry Andric       Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
4000b57cec5SDimitry Andric   }
4010b57cec5SDimitry Andric }
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric void CodeGenModule::Release() {
4040b57cec5SDimitry Andric   EmitDeferred();
4050b57cec5SDimitry Andric   EmitVTablesOpportunistically();
4060b57cec5SDimitry Andric   applyGlobalValReplacements();
4070b57cec5SDimitry Andric   applyReplacements();
4080b57cec5SDimitry Andric   checkAliases();
4090b57cec5SDimitry Andric   emitMultiVersionFunctions();
4100b57cec5SDimitry Andric   EmitCXXGlobalInitFunc();
4110b57cec5SDimitry Andric   EmitCXXGlobalDtorFunc();
4120b57cec5SDimitry Andric   registerGlobalDtorsWithAtExit();
4130b57cec5SDimitry Andric   EmitCXXThreadLocalInitFunc();
4140b57cec5SDimitry Andric   if (ObjCRuntime)
4150b57cec5SDimitry Andric     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
4160b57cec5SDimitry Andric       AddGlobalCtor(ObjCInitFunction);
4170b57cec5SDimitry Andric   if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
4180b57cec5SDimitry Andric       CUDARuntime) {
4190b57cec5SDimitry Andric     if (llvm::Function *CudaCtorFunction =
4200b57cec5SDimitry Andric             CUDARuntime->makeModuleCtorFunction())
4210b57cec5SDimitry Andric       AddGlobalCtor(CudaCtorFunction);
4220b57cec5SDimitry Andric   }
4230b57cec5SDimitry Andric   if (OpenMPRuntime) {
4240b57cec5SDimitry Andric     if (llvm::Function *OpenMPRequiresDirectiveRegFun =
4250b57cec5SDimitry Andric             OpenMPRuntime->emitRequiresDirectiveRegFun()) {
4260b57cec5SDimitry Andric       AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
4270b57cec5SDimitry Andric     }
428a7dea167SDimitry Andric     OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
4290b57cec5SDimitry Andric     OpenMPRuntime->clear();
4300b57cec5SDimitry Andric   }
4310b57cec5SDimitry Andric   if (PGOReader) {
4320b57cec5SDimitry Andric     getModule().setProfileSummary(
4330b57cec5SDimitry Andric         PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
4340b57cec5SDimitry Andric         llvm::ProfileSummary::PSK_Instr);
4350b57cec5SDimitry Andric     if (PGOStats.hasDiagnostics())
4360b57cec5SDimitry Andric       PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
4370b57cec5SDimitry Andric   }
4380b57cec5SDimitry Andric   EmitCtorList(GlobalCtors, "llvm.global_ctors");
4390b57cec5SDimitry Andric   EmitCtorList(GlobalDtors, "llvm.global_dtors");
4400b57cec5SDimitry Andric   EmitGlobalAnnotations();
4410b57cec5SDimitry Andric   EmitStaticExternCAliases();
4420b57cec5SDimitry Andric   EmitDeferredUnusedCoverageMappings();
4430b57cec5SDimitry Andric   if (CoverageMapping)
4440b57cec5SDimitry Andric     CoverageMapping->emit();
4450b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
4460b57cec5SDimitry Andric     CodeGenFunction(*this).EmitCfiCheckFail();
4470b57cec5SDimitry Andric     CodeGenFunction(*this).EmitCfiCheckStub();
4480b57cec5SDimitry Andric   }
4490b57cec5SDimitry Andric   emitAtAvailableLinkGuard();
4500b57cec5SDimitry Andric   emitLLVMUsed();
4510b57cec5SDimitry Andric   if (SanStats)
4520b57cec5SDimitry Andric     SanStats->finish();
4530b57cec5SDimitry Andric 
4540b57cec5SDimitry Andric   if (CodeGenOpts.Autolink &&
4550b57cec5SDimitry Andric       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
4560b57cec5SDimitry Andric     EmitModuleLinkOptions();
4570b57cec5SDimitry Andric   }
4580b57cec5SDimitry Andric 
4590b57cec5SDimitry Andric   // On ELF we pass the dependent library specifiers directly to the linker
4600b57cec5SDimitry Andric   // without manipulating them. This is in contrast to other platforms where
4610b57cec5SDimitry Andric   // they are mapped to a specific linker option by the compiler. This
4620b57cec5SDimitry Andric   // difference is a result of the greater variety of ELF linkers and the fact
4630b57cec5SDimitry Andric   // that ELF linkers tend to handle libraries in a more complicated fashion
4640b57cec5SDimitry Andric   // than on other platforms. This forces us to defer handling the dependent
4650b57cec5SDimitry Andric   // libs to the linker.
4660b57cec5SDimitry Andric   //
4670b57cec5SDimitry Andric   // CUDA/HIP device and host libraries are different. Currently there is no
4680b57cec5SDimitry Andric   // way to differentiate dependent libraries for host or device. Existing
4690b57cec5SDimitry Andric   // usage of #pragma comment(lib, *) is intended for host libraries on
4700b57cec5SDimitry Andric   // Windows. Therefore emit llvm.dependent-libraries only for host.
4710b57cec5SDimitry Andric   if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
4720b57cec5SDimitry Andric     auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
4730b57cec5SDimitry Andric     for (auto *MD : ELFDependentLibraries)
4740b57cec5SDimitry Andric       NMD->addOperand(MD);
4750b57cec5SDimitry Andric   }
4760b57cec5SDimitry Andric 
4770b57cec5SDimitry Andric   // Record mregparm value now so it is visible through rest of codegen.
4780b57cec5SDimitry Andric   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
4790b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
4800b57cec5SDimitry Andric                               CodeGenOpts.NumRegisterParameters);
4810b57cec5SDimitry Andric 
4820b57cec5SDimitry Andric   if (CodeGenOpts.DwarfVersion) {
483480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
4840b57cec5SDimitry Andric                               CodeGenOpts.DwarfVersion);
4850b57cec5SDimitry Andric   }
4860b57cec5SDimitry Andric   if (CodeGenOpts.EmitCodeView) {
4870b57cec5SDimitry Andric     // Indicate that we want CodeView in the metadata.
4880b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
4890b57cec5SDimitry Andric   }
4900b57cec5SDimitry Andric   if (CodeGenOpts.CodeViewGHash) {
4910b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
4920b57cec5SDimitry Andric   }
4930b57cec5SDimitry Andric   if (CodeGenOpts.ControlFlowGuard) {
494480093f4SDimitry Andric     // Function ID tables and checks for Control Flow Guard (cfguard=2).
495480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2);
496480093f4SDimitry Andric   } else if (CodeGenOpts.ControlFlowGuardNoChecks) {
497480093f4SDimitry Andric     // Function ID tables for Control Flow Guard (cfguard=1).
498480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
4990b57cec5SDimitry Andric   }
5000b57cec5SDimitry Andric   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
5010b57cec5SDimitry Andric     // We don't support LTO with 2 with different StrictVTablePointers
5020b57cec5SDimitry Andric     // FIXME: we could support it by stripping all the information introduced
5030b57cec5SDimitry Andric     // by StrictVTablePointers.
5040b57cec5SDimitry Andric 
5050b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric     llvm::Metadata *Ops[2] = {
5080b57cec5SDimitry Andric               llvm::MDString::get(VMContext, "StrictVTablePointers"),
5090b57cec5SDimitry Andric               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
5100b57cec5SDimitry Andric                   llvm::Type::getInt32Ty(VMContext), 1))};
5110b57cec5SDimitry Andric 
5120b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Require,
5130b57cec5SDimitry Andric                               "StrictVTablePointersRequirement",
5140b57cec5SDimitry Andric                               llvm::MDNode::get(VMContext, Ops));
5150b57cec5SDimitry Andric   }
5160b57cec5SDimitry Andric   if (DebugInfo)
5170b57cec5SDimitry Andric     // We support a single version in the linked module. The LLVM
5180b57cec5SDimitry Andric     // parser will drop debug info with a different version number
5190b57cec5SDimitry Andric     // (and warn about it, too).
5200b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
5210b57cec5SDimitry Andric                               llvm::DEBUG_METADATA_VERSION);
5220b57cec5SDimitry Andric 
5230b57cec5SDimitry Andric   // We need to record the widths of enums and wchar_t, so that we can generate
5240b57cec5SDimitry Andric   // the correct build attributes in the ARM backend. wchar_size is also used by
5250b57cec5SDimitry Andric   // TargetLibraryInfo.
5260b57cec5SDimitry Andric   uint64_t WCharWidth =
5270b57cec5SDimitry Andric       Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
5280b57cec5SDimitry Andric   getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
5290b57cec5SDimitry Andric 
5300b57cec5SDimitry Andric   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
5310b57cec5SDimitry Andric   if (   Arch == llvm::Triple::arm
5320b57cec5SDimitry Andric       || Arch == llvm::Triple::armeb
5330b57cec5SDimitry Andric       || Arch == llvm::Triple::thumb
5340b57cec5SDimitry Andric       || Arch == llvm::Triple::thumbeb) {
5350b57cec5SDimitry Andric     // The minimum width of an enum in bytes
5360b57cec5SDimitry Andric     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
5370b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
5380b57cec5SDimitry Andric   }
5390b57cec5SDimitry Andric 
540*13138422SDimitry Andric   if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) {
541*13138422SDimitry Andric     StringRef ABIStr = Target.getABI();
542*13138422SDimitry Andric     llvm::LLVMContext &Ctx = TheModule.getContext();
543*13138422SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "target-abi",
544*13138422SDimitry Andric                               llvm::MDString::get(Ctx, ABIStr));
545*13138422SDimitry Andric   }
546*13138422SDimitry Andric 
5470b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
5480b57cec5SDimitry Andric     // Indicate that we want cross-DSO control flow integrity checks.
5490b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
5500b57cec5SDimitry Andric   }
5510b57cec5SDimitry Andric 
552a7dea167SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
553a7dea167SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override,
554a7dea167SDimitry Andric                               "CFI Canonical Jump Tables",
555a7dea167SDimitry Andric                               CodeGenOpts.SanitizeCfiCanonicalJumpTables);
556a7dea167SDimitry Andric   }
557a7dea167SDimitry Andric 
5580b57cec5SDimitry Andric   if (CodeGenOpts.CFProtectionReturn &&
5590b57cec5SDimitry Andric       Target.checkCFProtectionReturnSupported(getDiags())) {
5600b57cec5SDimitry Andric     // Indicate that we want to instrument return control flow protection.
5610b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
5620b57cec5SDimitry Andric                               1);
5630b57cec5SDimitry Andric   }
5640b57cec5SDimitry Andric 
5650b57cec5SDimitry Andric   if (CodeGenOpts.CFProtectionBranch &&
5660b57cec5SDimitry Andric       Target.checkCFProtectionBranchSupported(getDiags())) {
5670b57cec5SDimitry Andric     // Indicate that we want to instrument branch control flow protection.
5680b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
5690b57cec5SDimitry Andric                               1);
5700b57cec5SDimitry Andric   }
5710b57cec5SDimitry Andric 
5720b57cec5SDimitry Andric   if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
5730b57cec5SDimitry Andric     // Indicate whether __nvvm_reflect should be configured to flush denormal
5740b57cec5SDimitry Andric     // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
5750b57cec5SDimitry Andric     // property.)
5760b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
5770b57cec5SDimitry Andric                               CodeGenOpts.FlushDenorm ? 1 : 0);
5780b57cec5SDimitry Andric   }
5790b57cec5SDimitry Andric 
5800b57cec5SDimitry Andric   // Emit OpenCL specific module metadata: OpenCL/SPIR version.
5810b57cec5SDimitry Andric   if (LangOpts.OpenCL) {
5820b57cec5SDimitry Andric     EmitOpenCLMetadata();
5830b57cec5SDimitry Andric     // Emit SPIR version.
5840b57cec5SDimitry Andric     if (getTriple().isSPIR()) {
5850b57cec5SDimitry Andric       // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
5860b57cec5SDimitry Andric       // opencl.spir.version named metadata.
5870b57cec5SDimitry Andric       // C++ is backwards compatible with OpenCL v2.0.
5880b57cec5SDimitry Andric       auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
5890b57cec5SDimitry Andric       llvm::Metadata *SPIRVerElts[] = {
5900b57cec5SDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
5910b57cec5SDimitry Andric               Int32Ty, Version / 100)),
5920b57cec5SDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
5930b57cec5SDimitry Andric               Int32Ty, (Version / 100 > 1) ? 0 : 2))};
5940b57cec5SDimitry Andric       llvm::NamedMDNode *SPIRVerMD =
5950b57cec5SDimitry Andric           TheModule.getOrInsertNamedMetadata("opencl.spir.version");
5960b57cec5SDimitry Andric       llvm::LLVMContext &Ctx = TheModule.getContext();
5970b57cec5SDimitry Andric       SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
5980b57cec5SDimitry Andric     }
5990b57cec5SDimitry Andric   }
6000b57cec5SDimitry Andric 
6010b57cec5SDimitry Andric   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
6020b57cec5SDimitry Andric     assert(PLevel < 3 && "Invalid PIC Level");
6030b57cec5SDimitry Andric     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
6040b57cec5SDimitry Andric     if (Context.getLangOpts().PIE)
6050b57cec5SDimitry Andric       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
6060b57cec5SDimitry Andric   }
6070b57cec5SDimitry Andric 
6080b57cec5SDimitry Andric   if (getCodeGenOpts().CodeModel.size() > 0) {
6090b57cec5SDimitry Andric     unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
6100b57cec5SDimitry Andric                   .Case("tiny", llvm::CodeModel::Tiny)
6110b57cec5SDimitry Andric                   .Case("small", llvm::CodeModel::Small)
6120b57cec5SDimitry Andric                   .Case("kernel", llvm::CodeModel::Kernel)
6130b57cec5SDimitry Andric                   .Case("medium", llvm::CodeModel::Medium)
6140b57cec5SDimitry Andric                   .Case("large", llvm::CodeModel::Large)
6150b57cec5SDimitry Andric                   .Default(~0u);
6160b57cec5SDimitry Andric     if (CM != ~0u) {
6170b57cec5SDimitry Andric       llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
6180b57cec5SDimitry Andric       getModule().setCodeModel(codeModel);
6190b57cec5SDimitry Andric     }
6200b57cec5SDimitry Andric   }
6210b57cec5SDimitry Andric 
6220b57cec5SDimitry Andric   if (CodeGenOpts.NoPLT)
6230b57cec5SDimitry Andric     getModule().setRtLibUseGOT();
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric   SimplifyPersonality();
6260b57cec5SDimitry Andric 
6270b57cec5SDimitry Andric   if (getCodeGenOpts().EmitDeclMetadata)
6280b57cec5SDimitry Andric     EmitDeclMetadata();
6290b57cec5SDimitry Andric 
6300b57cec5SDimitry Andric   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
6310b57cec5SDimitry Andric     EmitCoverageFile();
6320b57cec5SDimitry Andric 
6330b57cec5SDimitry Andric   if (DebugInfo)
6340b57cec5SDimitry Andric     DebugInfo->finalize();
6350b57cec5SDimitry Andric 
6360b57cec5SDimitry Andric   if (getCodeGenOpts().EmitVersionIdentMetadata)
6370b57cec5SDimitry Andric     EmitVersionIdentMetadata();
6380b57cec5SDimitry Andric 
6390b57cec5SDimitry Andric   if (!getCodeGenOpts().RecordCommandLine.empty())
6400b57cec5SDimitry Andric     EmitCommandLineMetadata();
6410b57cec5SDimitry Andric 
6420b57cec5SDimitry Andric   EmitTargetMetadata();
6430b57cec5SDimitry Andric }
6440b57cec5SDimitry Andric 
6450b57cec5SDimitry Andric void CodeGenModule::EmitOpenCLMetadata() {
6460b57cec5SDimitry Andric   // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
6470b57cec5SDimitry Andric   // opencl.ocl.version named metadata node.
6480b57cec5SDimitry Andric   // C++ is backwards compatible with OpenCL v2.0.
6490b57cec5SDimitry Andric   // FIXME: We might need to add CXX version at some point too?
6500b57cec5SDimitry Andric   auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
6510b57cec5SDimitry Andric   llvm::Metadata *OCLVerElts[] = {
6520b57cec5SDimitry Andric       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
6530b57cec5SDimitry Andric           Int32Ty, Version / 100)),
6540b57cec5SDimitry Andric       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
6550b57cec5SDimitry Andric           Int32Ty, (Version % 100) / 10))};
6560b57cec5SDimitry Andric   llvm::NamedMDNode *OCLVerMD =
6570b57cec5SDimitry Andric       TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
6580b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
6590b57cec5SDimitry Andric   OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
6600b57cec5SDimitry Andric }
6610b57cec5SDimitry Andric 
6620b57cec5SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
6630b57cec5SDimitry Andric   // Make sure that this type is translated.
6640b57cec5SDimitry Andric   Types.UpdateCompletedType(TD);
6650b57cec5SDimitry Andric }
6660b57cec5SDimitry Andric 
6670b57cec5SDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
6680b57cec5SDimitry Andric   // Make sure that this type is translated.
6690b57cec5SDimitry Andric   Types.RefreshTypeCacheForClass(RD);
6700b57cec5SDimitry Andric }
6710b57cec5SDimitry Andric 
6720b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
6730b57cec5SDimitry Andric   if (!TBAA)
6740b57cec5SDimitry Andric     return nullptr;
6750b57cec5SDimitry Andric   return TBAA->getTypeInfo(QTy);
6760b57cec5SDimitry Andric }
6770b57cec5SDimitry Andric 
6780b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
6790b57cec5SDimitry Andric   if (!TBAA)
6800b57cec5SDimitry Andric     return TBAAAccessInfo();
6810b57cec5SDimitry Andric   return TBAA->getAccessInfo(AccessType);
6820b57cec5SDimitry Andric }
6830b57cec5SDimitry Andric 
6840b57cec5SDimitry Andric TBAAAccessInfo
6850b57cec5SDimitry Andric CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
6860b57cec5SDimitry Andric   if (!TBAA)
6870b57cec5SDimitry Andric     return TBAAAccessInfo();
6880b57cec5SDimitry Andric   return TBAA->getVTablePtrAccessInfo(VTablePtrType);
6890b57cec5SDimitry Andric }
6900b57cec5SDimitry Andric 
6910b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
6920b57cec5SDimitry Andric   if (!TBAA)
6930b57cec5SDimitry Andric     return nullptr;
6940b57cec5SDimitry Andric   return TBAA->getTBAAStructInfo(QTy);
6950b57cec5SDimitry Andric }
6960b57cec5SDimitry Andric 
6970b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
6980b57cec5SDimitry Andric   if (!TBAA)
6990b57cec5SDimitry Andric     return nullptr;
7000b57cec5SDimitry Andric   return TBAA->getBaseTypeInfo(QTy);
7010b57cec5SDimitry Andric }
7020b57cec5SDimitry Andric 
7030b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
7040b57cec5SDimitry Andric   if (!TBAA)
7050b57cec5SDimitry Andric     return nullptr;
7060b57cec5SDimitry Andric   return TBAA->getAccessTagInfo(Info);
7070b57cec5SDimitry Andric }
7080b57cec5SDimitry Andric 
7090b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
7100b57cec5SDimitry Andric                                                    TBAAAccessInfo TargetInfo) {
7110b57cec5SDimitry Andric   if (!TBAA)
7120b57cec5SDimitry Andric     return TBAAAccessInfo();
7130b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
7140b57cec5SDimitry Andric }
7150b57cec5SDimitry Andric 
7160b57cec5SDimitry Andric TBAAAccessInfo
7170b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
7180b57cec5SDimitry Andric                                                    TBAAAccessInfo InfoB) {
7190b57cec5SDimitry Andric   if (!TBAA)
7200b57cec5SDimitry Andric     return TBAAAccessInfo();
7210b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
7220b57cec5SDimitry Andric }
7230b57cec5SDimitry Andric 
7240b57cec5SDimitry Andric TBAAAccessInfo
7250b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
7260b57cec5SDimitry Andric                                               TBAAAccessInfo SrcInfo) {
7270b57cec5SDimitry Andric   if (!TBAA)
7280b57cec5SDimitry Andric     return TBAAAccessInfo();
7290b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
7300b57cec5SDimitry Andric }
7310b57cec5SDimitry Andric 
7320b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
7330b57cec5SDimitry Andric                                                 TBAAAccessInfo TBAAInfo) {
7340b57cec5SDimitry Andric   if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
7350b57cec5SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
7360b57cec5SDimitry Andric }
7370b57cec5SDimitry Andric 
7380b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup(
7390b57cec5SDimitry Andric     llvm::Instruction *I, const CXXRecordDecl *RD) {
7400b57cec5SDimitry Andric   I->setMetadata(llvm::LLVMContext::MD_invariant_group,
7410b57cec5SDimitry Andric                  llvm::MDNode::get(getLLVMContext(), {}));
7420b57cec5SDimitry Andric }
7430b57cec5SDimitry Andric 
7440b57cec5SDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) {
7450b57cec5SDimitry Andric   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
7460b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
7470b57cec5SDimitry Andric }
7480b57cec5SDimitry Andric 
7490b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the
7500b57cec5SDimitry Andric /// specified stmt yet.
7510b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
7520b57cec5SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
7530b57cec5SDimitry Andric                                                "cannot compile this %0 yet");
7540b57cec5SDimitry Andric   std::string Msg = Type;
7550b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
7560b57cec5SDimitry Andric       << Msg << S->getSourceRange();
7570b57cec5SDimitry Andric }
7580b57cec5SDimitry Andric 
7590b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the
7600b57cec5SDimitry Andric /// specified decl yet.
7610b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
7620b57cec5SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
7630b57cec5SDimitry Andric                                                "cannot compile this %0 yet");
7640b57cec5SDimitry Andric   std::string Msg = Type;
7650b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
7660b57cec5SDimitry Andric }
7670b57cec5SDimitry Andric 
7680b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
7690b57cec5SDimitry Andric   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
7700b57cec5SDimitry Andric }
7710b57cec5SDimitry Andric 
7720b57cec5SDimitry Andric void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
7730b57cec5SDimitry Andric                                         const NamedDecl *D) const {
7740b57cec5SDimitry Andric   if (GV->hasDLLImportStorageClass())
7750b57cec5SDimitry Andric     return;
7760b57cec5SDimitry Andric   // Internal definitions always have default visibility.
7770b57cec5SDimitry Andric   if (GV->hasLocalLinkage()) {
7780b57cec5SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
7790b57cec5SDimitry Andric     return;
7800b57cec5SDimitry Andric   }
7810b57cec5SDimitry Andric   if (!D)
7820b57cec5SDimitry Andric     return;
7830b57cec5SDimitry Andric   // Set visibility for definitions, and for declarations if requested globally
7840b57cec5SDimitry Andric   // or set explicitly.
7850b57cec5SDimitry Andric   LinkageInfo LV = D->getLinkageAndVisibility();
7860b57cec5SDimitry Andric   if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
7870b57cec5SDimitry Andric       !GV->isDeclarationForLinker())
7880b57cec5SDimitry Andric     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
7890b57cec5SDimitry Andric }
7900b57cec5SDimitry Andric 
7910b57cec5SDimitry Andric static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
7920b57cec5SDimitry Andric                                  llvm::GlobalValue *GV) {
7930b57cec5SDimitry Andric   if (GV->hasLocalLinkage())
7940b57cec5SDimitry Andric     return true;
7950b57cec5SDimitry Andric 
7960b57cec5SDimitry Andric   if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
7970b57cec5SDimitry Andric     return true;
7980b57cec5SDimitry Andric 
7990b57cec5SDimitry Andric   // DLLImport explicitly marks the GV as external.
8000b57cec5SDimitry Andric   if (GV->hasDLLImportStorageClass())
8010b57cec5SDimitry Andric     return false;
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric   const llvm::Triple &TT = CGM.getTriple();
8040b57cec5SDimitry Andric   if (TT.isWindowsGNUEnvironment()) {
8050b57cec5SDimitry Andric     // In MinGW, variables without DLLImport can still be automatically
8060b57cec5SDimitry Andric     // imported from a DLL by the linker; don't mark variables that
8070b57cec5SDimitry Andric     // potentially could come from another DLL as DSO local.
8080b57cec5SDimitry Andric     if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
8090b57cec5SDimitry Andric         !GV->isThreadLocal())
8100b57cec5SDimitry Andric       return false;
8110b57cec5SDimitry Andric   }
8120b57cec5SDimitry Andric 
8130b57cec5SDimitry Andric   // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
8140b57cec5SDimitry Andric   // remain unresolved in the link, they can be resolved to zero, which is
8150b57cec5SDimitry Andric   // outside the current DSO.
8160b57cec5SDimitry Andric   if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
8170b57cec5SDimitry Andric     return false;
8180b57cec5SDimitry Andric 
8190b57cec5SDimitry Andric   // Every other GV is local on COFF.
8200b57cec5SDimitry Andric   // Make an exception for windows OS in the triple: Some firmware builds use
8210b57cec5SDimitry Andric   // *-win32-macho triples. This (accidentally?) produced windows relocations
8220b57cec5SDimitry Andric   // without GOT tables in older clang versions; Keep this behaviour.
8230b57cec5SDimitry Andric   // FIXME: even thread local variables?
8240b57cec5SDimitry Andric   if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
8250b57cec5SDimitry Andric     return true;
8260b57cec5SDimitry Andric 
8270b57cec5SDimitry Andric   // Only handle COFF and ELF for now.
8280b57cec5SDimitry Andric   if (!TT.isOSBinFormatELF())
8290b57cec5SDimitry Andric     return false;
8300b57cec5SDimitry Andric 
8310b57cec5SDimitry Andric   // If this is not an executable, don't assume anything is local.
8320b57cec5SDimitry Andric   const auto &CGOpts = CGM.getCodeGenOpts();
8330b57cec5SDimitry Andric   llvm::Reloc::Model RM = CGOpts.RelocationModel;
8340b57cec5SDimitry Andric   const auto &LOpts = CGM.getLangOpts();
835480093f4SDimitry Andric   if (RM != llvm::Reloc::Static && !LOpts.PIE)
8360b57cec5SDimitry Andric     return false;
8370b57cec5SDimitry Andric 
8380b57cec5SDimitry Andric   // A definition cannot be preempted from an executable.
8390b57cec5SDimitry Andric   if (!GV->isDeclarationForLinker())
8400b57cec5SDimitry Andric     return true;
8410b57cec5SDimitry Andric 
8420b57cec5SDimitry Andric   // Most PIC code sequences that assume that a symbol is local cannot produce a
8430b57cec5SDimitry Andric   // 0 if it turns out the symbol is undefined. While this is ABI and relocation
8440b57cec5SDimitry Andric   // depended, it seems worth it to handle it here.
8450b57cec5SDimitry Andric   if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
8460b57cec5SDimitry Andric     return false;
8470b57cec5SDimitry Andric 
8480b57cec5SDimitry Andric   // PPC has no copy relocations and cannot use a plt entry as a symbol address.
8490b57cec5SDimitry Andric   llvm::Triple::ArchType Arch = TT.getArch();
8500b57cec5SDimitry Andric   if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
8510b57cec5SDimitry Andric       Arch == llvm::Triple::ppc64le)
8520b57cec5SDimitry Andric     return false;
8530b57cec5SDimitry Andric 
8540b57cec5SDimitry Andric   // If we can use copy relocations we can assume it is local.
8550b57cec5SDimitry Andric   if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
8560b57cec5SDimitry Andric     if (!Var->isThreadLocal() &&
8570b57cec5SDimitry Andric         (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
8580b57cec5SDimitry Andric       return true;
8590b57cec5SDimitry Andric 
8600b57cec5SDimitry Andric   // If we can use a plt entry as the symbol address we can assume it
8610b57cec5SDimitry Andric   // is local.
8620b57cec5SDimitry Andric   // FIXME: This should work for PIE, but the gold linker doesn't support it.
8630b57cec5SDimitry Andric   if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
8640b57cec5SDimitry Andric     return true;
8650b57cec5SDimitry Andric 
8660b57cec5SDimitry Andric   // Otherwise don't assue it is local.
8670b57cec5SDimitry Andric   return false;
8680b57cec5SDimitry Andric }
8690b57cec5SDimitry Andric 
8700b57cec5SDimitry Andric void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
8710b57cec5SDimitry Andric   GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
8720b57cec5SDimitry Andric }
8730b57cec5SDimitry Andric 
8740b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
8750b57cec5SDimitry Andric                                           GlobalDecl GD) const {
8760b57cec5SDimitry Andric   const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
8770b57cec5SDimitry Andric   // C++ destructors have a few C++ ABI specific special cases.
8780b57cec5SDimitry Andric   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
8790b57cec5SDimitry Andric     getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
8800b57cec5SDimitry Andric     return;
8810b57cec5SDimitry Andric   }
8820b57cec5SDimitry Andric   setDLLImportDLLExport(GV, D);
8830b57cec5SDimitry Andric }
8840b57cec5SDimitry Andric 
8850b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
8860b57cec5SDimitry Andric                                           const NamedDecl *D) const {
8870b57cec5SDimitry Andric   if (D && D->isExternallyVisible()) {
8880b57cec5SDimitry Andric     if (D->hasAttr<DLLImportAttr>())
8890b57cec5SDimitry Andric       GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
8900b57cec5SDimitry Andric     else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
8910b57cec5SDimitry Andric       GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
8920b57cec5SDimitry Andric   }
8930b57cec5SDimitry Andric }
8940b57cec5SDimitry Andric 
8950b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
8960b57cec5SDimitry Andric                                     GlobalDecl GD) const {
8970b57cec5SDimitry Andric   setDLLImportDLLExport(GV, GD);
8980b57cec5SDimitry Andric   setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
8990b57cec5SDimitry Andric }
9000b57cec5SDimitry Andric 
9010b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
9020b57cec5SDimitry Andric                                     const NamedDecl *D) const {
9030b57cec5SDimitry Andric   setDLLImportDLLExport(GV, D);
9040b57cec5SDimitry Andric   setGVPropertiesAux(GV, D);
9050b57cec5SDimitry Andric }
9060b57cec5SDimitry Andric 
9070b57cec5SDimitry Andric void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
9080b57cec5SDimitry Andric                                        const NamedDecl *D) const {
9090b57cec5SDimitry Andric   setGlobalVisibility(GV, D);
9100b57cec5SDimitry Andric   setDSOLocal(GV);
9110b57cec5SDimitry Andric   GV->setPartition(CodeGenOpts.SymbolPartition);
9120b57cec5SDimitry Andric }
9130b57cec5SDimitry Andric 
9140b57cec5SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
9150b57cec5SDimitry Andric   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
9160b57cec5SDimitry Andric       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
9170b57cec5SDimitry Andric       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
9180b57cec5SDimitry Andric       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
9190b57cec5SDimitry Andric       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
9200b57cec5SDimitry Andric }
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
9230b57cec5SDimitry Andric     CodeGenOptions::TLSModel M) {
9240b57cec5SDimitry Andric   switch (M) {
9250b57cec5SDimitry Andric   case CodeGenOptions::GeneralDynamicTLSModel:
9260b57cec5SDimitry Andric     return llvm::GlobalVariable::GeneralDynamicTLSModel;
9270b57cec5SDimitry Andric   case CodeGenOptions::LocalDynamicTLSModel:
9280b57cec5SDimitry Andric     return llvm::GlobalVariable::LocalDynamicTLSModel;
9290b57cec5SDimitry Andric   case CodeGenOptions::InitialExecTLSModel:
9300b57cec5SDimitry Andric     return llvm::GlobalVariable::InitialExecTLSModel;
9310b57cec5SDimitry Andric   case CodeGenOptions::LocalExecTLSModel:
9320b57cec5SDimitry Andric     return llvm::GlobalVariable::LocalExecTLSModel;
9330b57cec5SDimitry Andric   }
9340b57cec5SDimitry Andric   llvm_unreachable("Invalid TLS model!");
9350b57cec5SDimitry Andric }
9360b57cec5SDimitry Andric 
9370b57cec5SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
9380b57cec5SDimitry Andric   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
9390b57cec5SDimitry Andric 
9400b57cec5SDimitry Andric   llvm::GlobalValue::ThreadLocalMode TLM;
9410b57cec5SDimitry Andric   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
9420b57cec5SDimitry Andric 
9430b57cec5SDimitry Andric   // Override the TLS model if it is explicitly specified.
9440b57cec5SDimitry Andric   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
9450b57cec5SDimitry Andric     TLM = GetLLVMTLSModel(Attr->getModel());
9460b57cec5SDimitry Andric   }
9470b57cec5SDimitry Andric 
9480b57cec5SDimitry Andric   GV->setThreadLocalMode(TLM);
9490b57cec5SDimitry Andric }
9500b57cec5SDimitry Andric 
9510b57cec5SDimitry Andric static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
9520b57cec5SDimitry Andric                                           StringRef Name) {
9530b57cec5SDimitry Andric   const TargetInfo &Target = CGM.getTarget();
9540b57cec5SDimitry Andric   return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
9550b57cec5SDimitry Andric }
9560b57cec5SDimitry Andric 
9570b57cec5SDimitry Andric static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
9580b57cec5SDimitry Andric                                                  const CPUSpecificAttr *Attr,
9590b57cec5SDimitry Andric                                                  unsigned CPUIndex,
9600b57cec5SDimitry Andric                                                  raw_ostream &Out) {
9610b57cec5SDimitry Andric   // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
9620b57cec5SDimitry Andric   // supported.
9630b57cec5SDimitry Andric   if (Attr)
9640b57cec5SDimitry Andric     Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
9650b57cec5SDimitry Andric   else if (CGM.getTarget().supportsIFunc())
9660b57cec5SDimitry Andric     Out << ".resolver";
9670b57cec5SDimitry Andric }
9680b57cec5SDimitry Andric 
9690b57cec5SDimitry Andric static void AppendTargetMangling(const CodeGenModule &CGM,
9700b57cec5SDimitry Andric                                  const TargetAttr *Attr, raw_ostream &Out) {
9710b57cec5SDimitry Andric   if (Attr->isDefaultVersion())
9720b57cec5SDimitry Andric     return;
9730b57cec5SDimitry Andric 
9740b57cec5SDimitry Andric   Out << '.';
9750b57cec5SDimitry Andric   const TargetInfo &Target = CGM.getTarget();
976480093f4SDimitry Andric   ParsedTargetAttr Info =
9770b57cec5SDimitry Andric       Attr->parse([&Target](StringRef LHS, StringRef RHS) {
9780b57cec5SDimitry Andric         // Multiversioning doesn't allow "no-${feature}", so we can
9790b57cec5SDimitry Andric         // only have "+" prefixes here.
9800b57cec5SDimitry Andric         assert(LHS.startswith("+") && RHS.startswith("+") &&
9810b57cec5SDimitry Andric                "Features should always have a prefix.");
9820b57cec5SDimitry Andric         return Target.multiVersionSortPriority(LHS.substr(1)) >
9830b57cec5SDimitry Andric                Target.multiVersionSortPriority(RHS.substr(1));
9840b57cec5SDimitry Andric       });
9850b57cec5SDimitry Andric 
9860b57cec5SDimitry Andric   bool IsFirst = true;
9870b57cec5SDimitry Andric 
9880b57cec5SDimitry Andric   if (!Info.Architecture.empty()) {
9890b57cec5SDimitry Andric     IsFirst = false;
9900b57cec5SDimitry Andric     Out << "arch_" << Info.Architecture;
9910b57cec5SDimitry Andric   }
9920b57cec5SDimitry Andric 
9930b57cec5SDimitry Andric   for (StringRef Feat : Info.Features) {
9940b57cec5SDimitry Andric     if (!IsFirst)
9950b57cec5SDimitry Andric       Out << '_';
9960b57cec5SDimitry Andric     IsFirst = false;
9970b57cec5SDimitry Andric     Out << Feat.substr(1);
9980b57cec5SDimitry Andric   }
9990b57cec5SDimitry Andric }
10000b57cec5SDimitry Andric 
10010b57cec5SDimitry Andric static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
10020b57cec5SDimitry Andric                                       const NamedDecl *ND,
10030b57cec5SDimitry Andric                                       bool OmitMultiVersionMangling = false) {
10040b57cec5SDimitry Andric   SmallString<256> Buffer;
10050b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
10060b57cec5SDimitry Andric   MangleContext &MC = CGM.getCXXABI().getMangleContext();
10070b57cec5SDimitry Andric   if (MC.shouldMangleDeclName(ND)) {
10080b57cec5SDimitry Andric     llvm::raw_svector_ostream Out(Buffer);
10090b57cec5SDimitry Andric     if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
10100b57cec5SDimitry Andric       MC.mangleCXXCtor(D, GD.getCtorType(), Out);
10110b57cec5SDimitry Andric     else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
10120b57cec5SDimitry Andric       MC.mangleCXXDtor(D, GD.getDtorType(), Out);
10130b57cec5SDimitry Andric     else
10140b57cec5SDimitry Andric       MC.mangleName(ND, Out);
10150b57cec5SDimitry Andric   } else {
10160b57cec5SDimitry Andric     IdentifierInfo *II = ND->getIdentifier();
10170b57cec5SDimitry Andric     assert(II && "Attempt to mangle unnamed decl.");
10180b57cec5SDimitry Andric     const auto *FD = dyn_cast<FunctionDecl>(ND);
10190b57cec5SDimitry Andric 
10200b57cec5SDimitry Andric     if (FD &&
10210b57cec5SDimitry Andric         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
10220b57cec5SDimitry Andric       llvm::raw_svector_ostream Out(Buffer);
10230b57cec5SDimitry Andric       Out << "__regcall3__" << II->getName();
10240b57cec5SDimitry Andric     } else {
10250b57cec5SDimitry Andric       Out << II->getName();
10260b57cec5SDimitry Andric     }
10270b57cec5SDimitry Andric   }
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
10300b57cec5SDimitry Andric     if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
10310b57cec5SDimitry Andric       switch (FD->getMultiVersionKind()) {
10320b57cec5SDimitry Andric       case MultiVersionKind::CPUDispatch:
10330b57cec5SDimitry Andric       case MultiVersionKind::CPUSpecific:
10340b57cec5SDimitry Andric         AppendCPUSpecificCPUDispatchMangling(CGM,
10350b57cec5SDimitry Andric                                              FD->getAttr<CPUSpecificAttr>(),
10360b57cec5SDimitry Andric                                              GD.getMultiVersionIndex(), Out);
10370b57cec5SDimitry Andric         break;
10380b57cec5SDimitry Andric       case MultiVersionKind::Target:
10390b57cec5SDimitry Andric         AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
10400b57cec5SDimitry Andric         break;
10410b57cec5SDimitry Andric       case MultiVersionKind::None:
10420b57cec5SDimitry Andric         llvm_unreachable("None multiversion type isn't valid here");
10430b57cec5SDimitry Andric       }
10440b57cec5SDimitry Andric     }
10450b57cec5SDimitry Andric 
10460b57cec5SDimitry Andric   return Out.str();
10470b57cec5SDimitry Andric }
10480b57cec5SDimitry Andric 
10490b57cec5SDimitry Andric void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
10500b57cec5SDimitry Andric                                             const FunctionDecl *FD) {
10510b57cec5SDimitry Andric   if (!FD->isMultiVersion())
10520b57cec5SDimitry Andric     return;
10530b57cec5SDimitry Andric 
10540b57cec5SDimitry Andric   // Get the name of what this would be without the 'target' attribute.  This
10550b57cec5SDimitry Andric   // allows us to lookup the version that was emitted when this wasn't a
10560b57cec5SDimitry Andric   // multiversion function.
10570b57cec5SDimitry Andric   std::string NonTargetName =
10580b57cec5SDimitry Andric       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
10590b57cec5SDimitry Andric   GlobalDecl OtherGD;
10600b57cec5SDimitry Andric   if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
10610b57cec5SDimitry Andric     assert(OtherGD.getCanonicalDecl()
10620b57cec5SDimitry Andric                .getDecl()
10630b57cec5SDimitry Andric                ->getAsFunction()
10640b57cec5SDimitry Andric                ->isMultiVersion() &&
10650b57cec5SDimitry Andric            "Other GD should now be a multiversioned function");
10660b57cec5SDimitry Andric     // OtherFD is the version of this function that was mangled BEFORE
10670b57cec5SDimitry Andric     // becoming a MultiVersion function.  It potentially needs to be updated.
10680b57cec5SDimitry Andric     const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
10690b57cec5SDimitry Andric                                       .getDecl()
10700b57cec5SDimitry Andric                                       ->getAsFunction()
10710b57cec5SDimitry Andric                                       ->getMostRecentDecl();
10720b57cec5SDimitry Andric     std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
10730b57cec5SDimitry Andric     // This is so that if the initial version was already the 'default'
10740b57cec5SDimitry Andric     // version, we don't try to update it.
10750b57cec5SDimitry Andric     if (OtherName != NonTargetName) {
10760b57cec5SDimitry Andric       // Remove instead of erase, since others may have stored the StringRef
10770b57cec5SDimitry Andric       // to this.
10780b57cec5SDimitry Andric       const auto ExistingRecord = Manglings.find(NonTargetName);
10790b57cec5SDimitry Andric       if (ExistingRecord != std::end(Manglings))
10800b57cec5SDimitry Andric         Manglings.remove(&(*ExistingRecord));
10810b57cec5SDimitry Andric       auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
10820b57cec5SDimitry Andric       MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
10830b57cec5SDimitry Andric       if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
10840b57cec5SDimitry Andric         Entry->setName(OtherName);
10850b57cec5SDimitry Andric     }
10860b57cec5SDimitry Andric   }
10870b57cec5SDimitry Andric }
10880b57cec5SDimitry Andric 
10890b57cec5SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
10900b57cec5SDimitry Andric   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
10910b57cec5SDimitry Andric 
10920b57cec5SDimitry Andric   // Some ABIs don't have constructor variants.  Make sure that base and
10930b57cec5SDimitry Andric   // complete constructors get mangled the same.
10940b57cec5SDimitry Andric   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
10950b57cec5SDimitry Andric     if (!getTarget().getCXXABI().hasConstructorVariants()) {
10960b57cec5SDimitry Andric       CXXCtorType OrigCtorType = GD.getCtorType();
10970b57cec5SDimitry Andric       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
10980b57cec5SDimitry Andric       if (OrigCtorType == Ctor_Base)
10990b57cec5SDimitry Andric         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
11000b57cec5SDimitry Andric     }
11010b57cec5SDimitry Andric   }
11020b57cec5SDimitry Andric 
11030b57cec5SDimitry Andric   auto FoundName = MangledDeclNames.find(CanonicalGD);
11040b57cec5SDimitry Andric   if (FoundName != MangledDeclNames.end())
11050b57cec5SDimitry Andric     return FoundName->second;
11060b57cec5SDimitry Andric 
11070b57cec5SDimitry Andric   // Keep the first result in the case of a mangling collision.
11080b57cec5SDimitry Andric   const auto *ND = cast<NamedDecl>(GD.getDecl());
11090b57cec5SDimitry Andric   std::string MangledName = getMangledNameImpl(*this, GD, ND);
11100b57cec5SDimitry Andric 
11110b57cec5SDimitry Andric   // Adjust kernel stub mangling as we may need to be able to differentiate
11120b57cec5SDimitry Andric   // them from the kernel itself (e.g., for HIP).
11130b57cec5SDimitry Andric   if (auto *FD = dyn_cast<FunctionDecl>(GD.getDecl()))
11140b57cec5SDimitry Andric     if (!getLangOpts().CUDAIsDevice && FD->hasAttr<CUDAGlobalAttr>())
11150b57cec5SDimitry Andric       MangledName = getCUDARuntime().getDeviceStubName(MangledName);
11160b57cec5SDimitry Andric 
11170b57cec5SDimitry Andric   auto Result = Manglings.insert(std::make_pair(MangledName, GD));
11180b57cec5SDimitry Andric   return MangledDeclNames[CanonicalGD] = Result.first->first();
11190b57cec5SDimitry Andric }
11200b57cec5SDimitry Andric 
11210b57cec5SDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
11220b57cec5SDimitry Andric                                              const BlockDecl *BD) {
11230b57cec5SDimitry Andric   MangleContext &MangleCtx = getCXXABI().getMangleContext();
11240b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
11250b57cec5SDimitry Andric 
11260b57cec5SDimitry Andric   SmallString<256> Buffer;
11270b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
11280b57cec5SDimitry Andric   if (!D)
11290b57cec5SDimitry Andric     MangleCtx.mangleGlobalBlock(BD,
11300b57cec5SDimitry Andric       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
11310b57cec5SDimitry Andric   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
11320b57cec5SDimitry Andric     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
11330b57cec5SDimitry Andric   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
11340b57cec5SDimitry Andric     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
11350b57cec5SDimitry Andric   else
11360b57cec5SDimitry Andric     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
11370b57cec5SDimitry Andric 
11380b57cec5SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
11390b57cec5SDimitry Andric   return Result.first->first();
11400b57cec5SDimitry Andric }
11410b57cec5SDimitry Andric 
11420b57cec5SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
11430b57cec5SDimitry Andric   return getModule().getNamedValue(Name);
11440b57cec5SDimitry Andric }
11450b57cec5SDimitry Andric 
11460b57cec5SDimitry Andric /// AddGlobalCtor - Add a function to the list that will be called before
11470b57cec5SDimitry Andric /// main() runs.
11480b57cec5SDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
11490b57cec5SDimitry Andric                                   llvm::Constant *AssociatedData) {
11500b57cec5SDimitry Andric   // FIXME: Type coercion of void()* types.
11510b57cec5SDimitry Andric   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
11520b57cec5SDimitry Andric }
11530b57cec5SDimitry Andric 
11540b57cec5SDimitry Andric /// AddGlobalDtor - Add a function to the list that will be called
11550b57cec5SDimitry Andric /// when the module is unloaded.
11560b57cec5SDimitry Andric void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
11570b57cec5SDimitry Andric   if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
11580b57cec5SDimitry Andric     DtorsUsingAtExit[Priority].push_back(Dtor);
11590b57cec5SDimitry Andric     return;
11600b57cec5SDimitry Andric   }
11610b57cec5SDimitry Andric 
11620b57cec5SDimitry Andric   // FIXME: Type coercion of void()* types.
11630b57cec5SDimitry Andric   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
11640b57cec5SDimitry Andric }
11650b57cec5SDimitry Andric 
11660b57cec5SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
11670b57cec5SDimitry Andric   if (Fns.empty()) return;
11680b57cec5SDimitry Andric 
11690b57cec5SDimitry Andric   // Ctor function type is void()*.
11700b57cec5SDimitry Andric   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
11710b57cec5SDimitry Andric   llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
11720b57cec5SDimitry Andric       TheModule.getDataLayout().getProgramAddressSpace());
11730b57cec5SDimitry Andric 
11740b57cec5SDimitry Andric   // Get the type of a ctor entry, { i32, void ()*, i8* }.
11750b57cec5SDimitry Andric   llvm::StructType *CtorStructTy = llvm::StructType::get(
11760b57cec5SDimitry Andric       Int32Ty, CtorPFTy, VoidPtrTy);
11770b57cec5SDimitry Andric 
11780b57cec5SDimitry Andric   // Construct the constructor and destructor arrays.
11790b57cec5SDimitry Andric   ConstantInitBuilder builder(*this);
11800b57cec5SDimitry Andric   auto ctors = builder.beginArray(CtorStructTy);
11810b57cec5SDimitry Andric   for (const auto &I : Fns) {
11820b57cec5SDimitry Andric     auto ctor = ctors.beginStruct(CtorStructTy);
11830b57cec5SDimitry Andric     ctor.addInt(Int32Ty, I.Priority);
11840b57cec5SDimitry Andric     ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
11850b57cec5SDimitry Andric     if (I.AssociatedData)
11860b57cec5SDimitry Andric       ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
11870b57cec5SDimitry Andric     else
11880b57cec5SDimitry Andric       ctor.addNullPointer(VoidPtrTy);
11890b57cec5SDimitry Andric     ctor.finishAndAddTo(ctors);
11900b57cec5SDimitry Andric   }
11910b57cec5SDimitry Andric 
11920b57cec5SDimitry Andric   auto list =
11930b57cec5SDimitry Andric     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
11940b57cec5SDimitry Andric                                 /*constant*/ false,
11950b57cec5SDimitry Andric                                 llvm::GlobalValue::AppendingLinkage);
11960b57cec5SDimitry Andric 
11970b57cec5SDimitry Andric   // The LTO linker doesn't seem to like it when we set an alignment
11980b57cec5SDimitry Andric   // on appending variables.  Take it off as a workaround.
1199a7dea167SDimitry Andric   list->setAlignment(llvm::None);
12000b57cec5SDimitry Andric 
12010b57cec5SDimitry Andric   Fns.clear();
12020b57cec5SDimitry Andric }
12030b57cec5SDimitry Andric 
12040b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes
12050b57cec5SDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
12060b57cec5SDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
12070b57cec5SDimitry Andric 
12080b57cec5SDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
12090b57cec5SDimitry Andric 
12100b57cec5SDimitry Andric   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
12110b57cec5SDimitry Andric     return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
12120b57cec5SDimitry Andric 
12130b57cec5SDimitry Andric   if (isa<CXXConstructorDecl>(D) &&
12140b57cec5SDimitry Andric       cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
12150b57cec5SDimitry Andric       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12160b57cec5SDimitry Andric     // Our approach to inheriting constructors is fundamentally different from
12170b57cec5SDimitry Andric     // that used by the MS ABI, so keep our inheriting constructor thunks
12180b57cec5SDimitry Andric     // internal rather than trying to pick an unambiguous mangling for them.
12190b57cec5SDimitry Andric     return llvm::GlobalValue::InternalLinkage;
12200b57cec5SDimitry Andric   }
12210b57cec5SDimitry Andric 
12220b57cec5SDimitry Andric   return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false);
12230b57cec5SDimitry Andric }
12240b57cec5SDimitry Andric 
12250b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
12260b57cec5SDimitry Andric   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
12270b57cec5SDimitry Andric   if (!MDS) return nullptr;
12280b57cec5SDimitry Andric 
12290b57cec5SDimitry Andric   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
12300b57cec5SDimitry Andric }
12310b57cec5SDimitry Andric 
12320b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
12330b57cec5SDimitry Andric                                               const CGFunctionInfo &Info,
12340b57cec5SDimitry Andric                                               llvm::Function *F) {
12350b57cec5SDimitry Andric   unsigned CallingConv;
12360b57cec5SDimitry Andric   llvm::AttributeList PAL;
12370b57cec5SDimitry Andric   ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, false);
12380b57cec5SDimitry Andric   F->setAttributes(PAL);
12390b57cec5SDimitry Andric   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
12400b57cec5SDimitry Andric }
12410b57cec5SDimitry Andric 
12420b57cec5SDimitry Andric static void removeImageAccessQualifier(std::string& TyName) {
12430b57cec5SDimitry Andric   std::string ReadOnlyQual("__read_only");
12440b57cec5SDimitry Andric   std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
12450b57cec5SDimitry Andric   if (ReadOnlyPos != std::string::npos)
12460b57cec5SDimitry Andric     // "+ 1" for the space after access qualifier.
12470b57cec5SDimitry Andric     TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
12480b57cec5SDimitry Andric   else {
12490b57cec5SDimitry Andric     std::string WriteOnlyQual("__write_only");
12500b57cec5SDimitry Andric     std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
12510b57cec5SDimitry Andric     if (WriteOnlyPos != std::string::npos)
12520b57cec5SDimitry Andric       TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
12530b57cec5SDimitry Andric     else {
12540b57cec5SDimitry Andric       std::string ReadWriteQual("__read_write");
12550b57cec5SDimitry Andric       std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
12560b57cec5SDimitry Andric       if (ReadWritePos != std::string::npos)
12570b57cec5SDimitry Andric         TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
12580b57cec5SDimitry Andric     }
12590b57cec5SDimitry Andric   }
12600b57cec5SDimitry Andric }
12610b57cec5SDimitry Andric 
12620b57cec5SDimitry Andric // Returns the address space id that should be produced to the
12630b57cec5SDimitry Andric // kernel_arg_addr_space metadata. This is always fixed to the ids
12640b57cec5SDimitry Andric // as specified in the SPIR 2.0 specification in order to differentiate
12650b57cec5SDimitry Andric // for example in clGetKernelArgInfo() implementation between the address
12660b57cec5SDimitry Andric // spaces with targets without unique mapping to the OpenCL address spaces
12670b57cec5SDimitry Andric // (basically all single AS CPUs).
12680b57cec5SDimitry Andric static unsigned ArgInfoAddressSpace(LangAS AS) {
12690b57cec5SDimitry Andric   switch (AS) {
12700b57cec5SDimitry Andric   case LangAS::opencl_global:   return 1;
12710b57cec5SDimitry Andric   case LangAS::opencl_constant: return 2;
12720b57cec5SDimitry Andric   case LangAS::opencl_local:    return 3;
12730b57cec5SDimitry Andric   case LangAS::opencl_generic:  return 4; // Not in SPIR 2.0 specs.
12740b57cec5SDimitry Andric   default:
12750b57cec5SDimitry Andric     return 0; // Assume private.
12760b57cec5SDimitry Andric   }
12770b57cec5SDimitry Andric }
12780b57cec5SDimitry Andric 
12790b57cec5SDimitry Andric void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn,
12800b57cec5SDimitry Andric                                          const FunctionDecl *FD,
12810b57cec5SDimitry Andric                                          CodeGenFunction *CGF) {
12820b57cec5SDimitry Andric   assert(((FD && CGF) || (!FD && !CGF)) &&
12830b57cec5SDimitry Andric          "Incorrect use - FD and CGF should either be both null or not!");
12840b57cec5SDimitry Andric   // Create MDNodes that represent the kernel arg metadata.
12850b57cec5SDimitry Andric   // Each MDNode is a list in the form of "key", N number of values which is
12860b57cec5SDimitry Andric   // the same number of values as their are kernel arguments.
12870b57cec5SDimitry Andric 
12880b57cec5SDimitry Andric   const PrintingPolicy &Policy = Context.getPrintingPolicy();
12890b57cec5SDimitry Andric 
12900b57cec5SDimitry Andric   // MDNode for the kernel argument address space qualifiers.
12910b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> addressQuals;
12920b57cec5SDimitry Andric 
12930b57cec5SDimitry Andric   // MDNode for the kernel argument access qualifiers (images only).
12940b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> accessQuals;
12950b57cec5SDimitry Andric 
12960b57cec5SDimitry Andric   // MDNode for the kernel argument type names.
12970b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeNames;
12980b57cec5SDimitry Andric 
12990b57cec5SDimitry Andric   // MDNode for the kernel argument base type names.
13000b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
13010b57cec5SDimitry Andric 
13020b57cec5SDimitry Andric   // MDNode for the kernel argument type qualifiers.
13030b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeQuals;
13040b57cec5SDimitry Andric 
13050b57cec5SDimitry Andric   // MDNode for the kernel argument names.
13060b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argNames;
13070b57cec5SDimitry Andric 
13080b57cec5SDimitry Andric   if (FD && CGF)
13090b57cec5SDimitry Andric     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
13100b57cec5SDimitry Andric       const ParmVarDecl *parm = FD->getParamDecl(i);
13110b57cec5SDimitry Andric       QualType ty = parm->getType();
13120b57cec5SDimitry Andric       std::string typeQuals;
13130b57cec5SDimitry Andric 
13140b57cec5SDimitry Andric       if (ty->isPointerType()) {
13150b57cec5SDimitry Andric         QualType pointeeTy = ty->getPointeeType();
13160b57cec5SDimitry Andric 
13170b57cec5SDimitry Andric         // Get address qualifier.
13180b57cec5SDimitry Andric         addressQuals.push_back(
13190b57cec5SDimitry Andric             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
13200b57cec5SDimitry Andric                 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
13210b57cec5SDimitry Andric 
13220b57cec5SDimitry Andric         // Get argument type name.
13230b57cec5SDimitry Andric         std::string typeName =
13240b57cec5SDimitry Andric             pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
13250b57cec5SDimitry Andric 
13260b57cec5SDimitry Andric         // Turn "unsigned type" to "utype"
13270b57cec5SDimitry Andric         std::string::size_type pos = typeName.find("unsigned");
13280b57cec5SDimitry Andric         if (pointeeTy.isCanonical() && pos != std::string::npos)
13290b57cec5SDimitry Andric           typeName.erase(pos + 1, 8);
13300b57cec5SDimitry Andric 
13310b57cec5SDimitry Andric         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
13320b57cec5SDimitry Andric 
13330b57cec5SDimitry Andric         std::string baseTypeName =
13340b57cec5SDimitry Andric             pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
13350b57cec5SDimitry Andric                 Policy) +
13360b57cec5SDimitry Andric             "*";
13370b57cec5SDimitry Andric 
13380b57cec5SDimitry Andric         // Turn "unsigned type" to "utype"
13390b57cec5SDimitry Andric         pos = baseTypeName.find("unsigned");
13400b57cec5SDimitry Andric         if (pos != std::string::npos)
13410b57cec5SDimitry Andric           baseTypeName.erase(pos + 1, 8);
13420b57cec5SDimitry Andric 
13430b57cec5SDimitry Andric         argBaseTypeNames.push_back(
13440b57cec5SDimitry Andric             llvm::MDString::get(VMContext, baseTypeName));
13450b57cec5SDimitry Andric 
13460b57cec5SDimitry Andric         // Get argument type qualifiers:
13470b57cec5SDimitry Andric         if (ty.isRestrictQualified())
13480b57cec5SDimitry Andric           typeQuals = "restrict";
13490b57cec5SDimitry Andric         if (pointeeTy.isConstQualified() ||
13500b57cec5SDimitry Andric             (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
13510b57cec5SDimitry Andric           typeQuals += typeQuals.empty() ? "const" : " const";
13520b57cec5SDimitry Andric         if (pointeeTy.isVolatileQualified())
13530b57cec5SDimitry Andric           typeQuals += typeQuals.empty() ? "volatile" : " volatile";
13540b57cec5SDimitry Andric       } else {
13550b57cec5SDimitry Andric         uint32_t AddrSpc = 0;
13560b57cec5SDimitry Andric         bool isPipe = ty->isPipeType();
13570b57cec5SDimitry Andric         if (ty->isImageType() || isPipe)
13580b57cec5SDimitry Andric           AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
13590b57cec5SDimitry Andric 
13600b57cec5SDimitry Andric         addressQuals.push_back(
13610b57cec5SDimitry Andric             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
13620b57cec5SDimitry Andric 
13630b57cec5SDimitry Andric         // Get argument type name.
13640b57cec5SDimitry Andric         std::string typeName;
13650b57cec5SDimitry Andric         if (isPipe)
13660b57cec5SDimitry Andric           typeName = ty.getCanonicalType()
13670b57cec5SDimitry Andric                          ->getAs<PipeType>()
13680b57cec5SDimitry Andric                          ->getElementType()
13690b57cec5SDimitry Andric                          .getAsString(Policy);
13700b57cec5SDimitry Andric         else
13710b57cec5SDimitry Andric           typeName = ty.getUnqualifiedType().getAsString(Policy);
13720b57cec5SDimitry Andric 
13730b57cec5SDimitry Andric         // Turn "unsigned type" to "utype"
13740b57cec5SDimitry Andric         std::string::size_type pos = typeName.find("unsigned");
13750b57cec5SDimitry Andric         if (ty.isCanonical() && pos != std::string::npos)
13760b57cec5SDimitry Andric           typeName.erase(pos + 1, 8);
13770b57cec5SDimitry Andric 
13780b57cec5SDimitry Andric         std::string baseTypeName;
13790b57cec5SDimitry Andric         if (isPipe)
13800b57cec5SDimitry Andric           baseTypeName = ty.getCanonicalType()
13810b57cec5SDimitry Andric                              ->getAs<PipeType>()
13820b57cec5SDimitry Andric                              ->getElementType()
13830b57cec5SDimitry Andric                              .getCanonicalType()
13840b57cec5SDimitry Andric                              .getAsString(Policy);
13850b57cec5SDimitry Andric         else
13860b57cec5SDimitry Andric           baseTypeName =
13870b57cec5SDimitry Andric               ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
13880b57cec5SDimitry Andric 
13890b57cec5SDimitry Andric         // Remove access qualifiers on images
13900b57cec5SDimitry Andric         // (as they are inseparable from type in clang implementation,
13910b57cec5SDimitry Andric         // but OpenCL spec provides a special query to get access qualifier
13920b57cec5SDimitry Andric         // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
13930b57cec5SDimitry Andric         if (ty->isImageType()) {
13940b57cec5SDimitry Andric           removeImageAccessQualifier(typeName);
13950b57cec5SDimitry Andric           removeImageAccessQualifier(baseTypeName);
13960b57cec5SDimitry Andric         }
13970b57cec5SDimitry Andric 
13980b57cec5SDimitry Andric         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
13990b57cec5SDimitry Andric 
14000b57cec5SDimitry Andric         // Turn "unsigned type" to "utype"
14010b57cec5SDimitry Andric         pos = baseTypeName.find("unsigned");
14020b57cec5SDimitry Andric         if (pos != std::string::npos)
14030b57cec5SDimitry Andric           baseTypeName.erase(pos + 1, 8);
14040b57cec5SDimitry Andric 
14050b57cec5SDimitry Andric         argBaseTypeNames.push_back(
14060b57cec5SDimitry Andric             llvm::MDString::get(VMContext, baseTypeName));
14070b57cec5SDimitry Andric 
14080b57cec5SDimitry Andric         if (isPipe)
14090b57cec5SDimitry Andric           typeQuals = "pipe";
14100b57cec5SDimitry Andric       }
14110b57cec5SDimitry Andric 
14120b57cec5SDimitry Andric       argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
14130b57cec5SDimitry Andric 
14140b57cec5SDimitry Andric       // Get image and pipe access qualifier:
14150b57cec5SDimitry Andric       if (ty->isImageType() || ty->isPipeType()) {
14160b57cec5SDimitry Andric         const Decl *PDecl = parm;
14170b57cec5SDimitry Andric         if (auto *TD = dyn_cast<TypedefType>(ty))
14180b57cec5SDimitry Andric           PDecl = TD->getDecl();
14190b57cec5SDimitry Andric         const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
14200b57cec5SDimitry Andric         if (A && A->isWriteOnly())
14210b57cec5SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
14220b57cec5SDimitry Andric         else if (A && A->isReadWrite())
14230b57cec5SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
14240b57cec5SDimitry Andric         else
14250b57cec5SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
14260b57cec5SDimitry Andric       } else
14270b57cec5SDimitry Andric         accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
14280b57cec5SDimitry Andric 
14290b57cec5SDimitry Andric       // Get argument name.
14300b57cec5SDimitry Andric       argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
14310b57cec5SDimitry Andric     }
14320b57cec5SDimitry Andric 
14330b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_addr_space",
14340b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, addressQuals));
14350b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_access_qual",
14360b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, accessQuals));
14370b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_type",
14380b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, argTypeNames));
14390b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_base_type",
14400b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, argBaseTypeNames));
14410b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_type_qual",
14420b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, argTypeQuals));
14430b57cec5SDimitry Andric   if (getCodeGenOpts().EmitOpenCLArgMetadata)
14440b57cec5SDimitry Andric     Fn->setMetadata("kernel_arg_name",
14450b57cec5SDimitry Andric                     llvm::MDNode::get(VMContext, argNames));
14460b57cec5SDimitry Andric }
14470b57cec5SDimitry Andric 
14480b57cec5SDimitry Andric /// Determines whether the language options require us to model
14490b57cec5SDimitry Andric /// unwind exceptions.  We treat -fexceptions as mandating this
14500b57cec5SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions
14510b57cec5SDimitry Andric /// enabled.  This means, for example, that C with -fexceptions
14520b57cec5SDimitry Andric /// enables this.
14530b57cec5SDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) {
14540b57cec5SDimitry Andric   // If exceptions are completely disabled, obviously this is false.
14550b57cec5SDimitry Andric   if (!LangOpts.Exceptions) return false;
14560b57cec5SDimitry Andric 
14570b57cec5SDimitry Andric   // If C++ exceptions are enabled, this is true.
14580b57cec5SDimitry Andric   if (LangOpts.CXXExceptions) return true;
14590b57cec5SDimitry Andric 
14600b57cec5SDimitry Andric   // If ObjC exceptions are enabled, this depends on the ABI.
14610b57cec5SDimitry Andric   if (LangOpts.ObjCExceptions) {
14620b57cec5SDimitry Andric     return LangOpts.ObjCRuntime.hasUnwindExceptions();
14630b57cec5SDimitry Andric   }
14640b57cec5SDimitry Andric 
14650b57cec5SDimitry Andric   return true;
14660b57cec5SDimitry Andric }
14670b57cec5SDimitry Andric 
14680b57cec5SDimitry Andric static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
14690b57cec5SDimitry Andric                                                       const CXXMethodDecl *MD) {
14700b57cec5SDimitry Andric   // Check that the type metadata can ever actually be used by a call.
14710b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().LTOUnit ||
14720b57cec5SDimitry Andric       !CGM.HasHiddenLTOVisibility(MD->getParent()))
14730b57cec5SDimitry Andric     return false;
14740b57cec5SDimitry Andric 
14750b57cec5SDimitry Andric   // Only functions whose address can be taken with a member function pointer
14760b57cec5SDimitry Andric   // need this sort of type metadata.
14770b57cec5SDimitry Andric   return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
14780b57cec5SDimitry Andric          !isa<CXXDestructorDecl>(MD);
14790b57cec5SDimitry Andric }
14800b57cec5SDimitry Andric 
14810b57cec5SDimitry Andric std::vector<const CXXRecordDecl *>
14820b57cec5SDimitry Andric CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
14830b57cec5SDimitry Andric   llvm::SetVector<const CXXRecordDecl *> MostBases;
14840b57cec5SDimitry Andric 
14850b57cec5SDimitry Andric   std::function<void (const CXXRecordDecl *)> CollectMostBases;
14860b57cec5SDimitry Andric   CollectMostBases = [&](const CXXRecordDecl *RD) {
14870b57cec5SDimitry Andric     if (RD->getNumBases() == 0)
14880b57cec5SDimitry Andric       MostBases.insert(RD);
14890b57cec5SDimitry Andric     for (const CXXBaseSpecifier &B : RD->bases())
14900b57cec5SDimitry Andric       CollectMostBases(B.getType()->getAsCXXRecordDecl());
14910b57cec5SDimitry Andric   };
14920b57cec5SDimitry Andric   CollectMostBases(RD);
14930b57cec5SDimitry Andric   return MostBases.takeVector();
14940b57cec5SDimitry Andric }
14950b57cec5SDimitry Andric 
14960b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
14970b57cec5SDimitry Andric                                                            llvm::Function *F) {
14980b57cec5SDimitry Andric   llvm::AttrBuilder B;
14990b57cec5SDimitry Andric 
15000b57cec5SDimitry Andric   if (CodeGenOpts.UnwindTables)
15010b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::UWTable);
15020b57cec5SDimitry Andric 
15030b57cec5SDimitry Andric   if (!hasUnwindExceptions(LangOpts))
15040b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoUnwind);
15050b57cec5SDimitry Andric 
15060b57cec5SDimitry Andric   if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
15070b57cec5SDimitry Andric     if (LangOpts.getStackProtector() == LangOptions::SSPOn)
15080b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::StackProtect);
15090b57cec5SDimitry Andric     else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
15100b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::StackProtectStrong);
15110b57cec5SDimitry Andric     else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
15120b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::StackProtectReq);
15130b57cec5SDimitry Andric   }
15140b57cec5SDimitry Andric 
15150b57cec5SDimitry Andric   if (!D) {
15160b57cec5SDimitry Andric     // If we don't have a declaration to control inlining, the function isn't
15170b57cec5SDimitry Andric     // explicitly marked as alwaysinline for semantic reasons, and inlining is
15180b57cec5SDimitry Andric     // disabled, mark the function as noinline.
15190b57cec5SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
15200b57cec5SDimitry Andric         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
15210b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
15220b57cec5SDimitry Andric 
15230b57cec5SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
15240b57cec5SDimitry Andric     return;
15250b57cec5SDimitry Andric   }
15260b57cec5SDimitry Andric 
15270b57cec5SDimitry Andric   // Track whether we need to add the optnone LLVM attribute,
15280b57cec5SDimitry Andric   // starting with the default for this optimization level.
15290b57cec5SDimitry Andric   bool ShouldAddOptNone =
15300b57cec5SDimitry Andric       !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
15310b57cec5SDimitry Andric   // We can't add optnone in the following cases, it won't pass the verifier.
15320b57cec5SDimitry Andric   ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
15330b57cec5SDimitry Andric   ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
15340b57cec5SDimitry Andric 
1535480093f4SDimitry Andric   // Add optnone, but do so only if the function isn't always_inline.
1536480093f4SDimitry Andric   if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
1537480093f4SDimitry Andric       !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
15380b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::OptimizeNone);
15390b57cec5SDimitry Andric 
15400b57cec5SDimitry Andric     // OptimizeNone implies noinline; we should not be inlining such functions.
15410b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
15420b57cec5SDimitry Andric 
15430b57cec5SDimitry Andric     // We still need to handle naked functions even though optnone subsumes
15440b57cec5SDimitry Andric     // much of their semantics.
15450b57cec5SDimitry Andric     if (D->hasAttr<NakedAttr>())
15460b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::Naked);
15470b57cec5SDimitry Andric 
15480b57cec5SDimitry Andric     // OptimizeNone wins over OptimizeForSize and MinSize.
15490b57cec5SDimitry Andric     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
15500b57cec5SDimitry Andric     F->removeFnAttr(llvm::Attribute::MinSize);
15510b57cec5SDimitry Andric   } else if (D->hasAttr<NakedAttr>()) {
15520b57cec5SDimitry Andric     // Naked implies noinline: we should not be inlining such functions.
15530b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::Naked);
15540b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
15550b57cec5SDimitry Andric   } else if (D->hasAttr<NoDuplicateAttr>()) {
15560b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoDuplicate);
1557480093f4SDimitry Andric   } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1558480093f4SDimitry Andric     // Add noinline if the function isn't always_inline.
15590b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
15600b57cec5SDimitry Andric   } else if (D->hasAttr<AlwaysInlineAttr>() &&
15610b57cec5SDimitry Andric              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
15620b57cec5SDimitry Andric     // (noinline wins over always_inline, and we can't specify both in IR)
15630b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::AlwaysInline);
15640b57cec5SDimitry Andric   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
15650b57cec5SDimitry Andric     // If we're not inlining, then force everything that isn't always_inline to
15660b57cec5SDimitry Andric     // carry an explicit noinline attribute.
15670b57cec5SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
15680b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
15690b57cec5SDimitry Andric   } else {
15700b57cec5SDimitry Andric     // Otherwise, propagate the inline hint attribute and potentially use its
15710b57cec5SDimitry Andric     // absence to mark things as noinline.
15720b57cec5SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15730b57cec5SDimitry Andric       // Search function and template pattern redeclarations for inline.
15740b57cec5SDimitry Andric       auto CheckForInline = [](const FunctionDecl *FD) {
15750b57cec5SDimitry Andric         auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
15760b57cec5SDimitry Andric           return Redecl->isInlineSpecified();
15770b57cec5SDimitry Andric         };
15780b57cec5SDimitry Andric         if (any_of(FD->redecls(), CheckRedeclForInline))
15790b57cec5SDimitry Andric           return true;
15800b57cec5SDimitry Andric         const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
15810b57cec5SDimitry Andric         if (!Pattern)
15820b57cec5SDimitry Andric           return false;
15830b57cec5SDimitry Andric         return any_of(Pattern->redecls(), CheckRedeclForInline);
15840b57cec5SDimitry Andric       };
15850b57cec5SDimitry Andric       if (CheckForInline(FD)) {
15860b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::InlineHint);
15870b57cec5SDimitry Andric       } else if (CodeGenOpts.getInlining() ==
15880b57cec5SDimitry Andric                      CodeGenOptions::OnlyHintInlining &&
15890b57cec5SDimitry Andric                  !FD->isInlined() &&
15900b57cec5SDimitry Andric                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
15910b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::NoInline);
15920b57cec5SDimitry Andric       }
15930b57cec5SDimitry Andric     }
15940b57cec5SDimitry Andric   }
15950b57cec5SDimitry Andric 
15960b57cec5SDimitry Andric   // Add other optimization related attributes if we are optimizing this
15970b57cec5SDimitry Andric   // function.
15980b57cec5SDimitry Andric   if (!D->hasAttr<OptimizeNoneAttr>()) {
15990b57cec5SDimitry Andric     if (D->hasAttr<ColdAttr>()) {
16000b57cec5SDimitry Andric       if (!ShouldAddOptNone)
16010b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::OptimizeForSize);
16020b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::Cold);
16030b57cec5SDimitry Andric     }
16040b57cec5SDimitry Andric 
16050b57cec5SDimitry Andric     if (D->hasAttr<MinSizeAttr>())
16060b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::MinSize);
16070b57cec5SDimitry Andric   }
16080b57cec5SDimitry Andric 
16090b57cec5SDimitry Andric   F->addAttributes(llvm::AttributeList::FunctionIndex, B);
16100b57cec5SDimitry Andric 
16110b57cec5SDimitry Andric   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
16120b57cec5SDimitry Andric   if (alignment)
1613a7dea167SDimitry Andric     F->setAlignment(llvm::Align(alignment));
16140b57cec5SDimitry Andric 
16150b57cec5SDimitry Andric   if (!D->hasAttr<AlignedAttr>())
16160b57cec5SDimitry Andric     if (LangOpts.FunctionAlignment)
1617a7dea167SDimitry Andric       F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
16180b57cec5SDimitry Andric 
16190b57cec5SDimitry Andric   // Some C++ ABIs require 2-byte alignment for member functions, in order to
16200b57cec5SDimitry Andric   // reserve a bit for differentiating between virtual and non-virtual member
16210b57cec5SDimitry Andric   // functions. If the current target's C++ ABI requires this and this is a
16220b57cec5SDimitry Andric   // member function, set its alignment accordingly.
16230b57cec5SDimitry Andric   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
16240b57cec5SDimitry Andric     if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1625a7dea167SDimitry Andric       F->setAlignment(llvm::Align(2));
16260b57cec5SDimitry Andric   }
16270b57cec5SDimitry Andric 
1628a7dea167SDimitry Andric   // In the cross-dso CFI mode with canonical jump tables, we want !type
1629a7dea167SDimitry Andric   // attributes on definitions only.
1630a7dea167SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso &&
1631a7dea167SDimitry Andric       CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
1632a7dea167SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1633a7dea167SDimitry Andric       // Skip available_externally functions. They won't be codegen'ed in the
1634a7dea167SDimitry Andric       // current module anyway.
1635a7dea167SDimitry Andric       if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
16360b57cec5SDimitry Andric         CreateFunctionTypeMetadataForIcall(FD, F);
1637a7dea167SDimitry Andric     }
1638a7dea167SDimitry Andric   }
16390b57cec5SDimitry Andric 
16400b57cec5SDimitry Andric   // Emit type metadata on member functions for member function pointer checks.
16410b57cec5SDimitry Andric   // These are only ever necessary on definitions; we're guaranteed that the
16420b57cec5SDimitry Andric   // definition will be present in the LTO unit as a result of LTO visibility.
16430b57cec5SDimitry Andric   auto *MD = dyn_cast<CXXMethodDecl>(D);
16440b57cec5SDimitry Andric   if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
16450b57cec5SDimitry Andric     for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
16460b57cec5SDimitry Andric       llvm::Metadata *Id =
16470b57cec5SDimitry Andric           CreateMetadataIdentifierForType(Context.getMemberPointerType(
16480b57cec5SDimitry Andric               MD->getType(), Context.getRecordType(Base).getTypePtr()));
16490b57cec5SDimitry Andric       F->addTypeMetadata(0, Id);
16500b57cec5SDimitry Andric     }
16510b57cec5SDimitry Andric   }
16520b57cec5SDimitry Andric }
16530b57cec5SDimitry Andric 
16540b57cec5SDimitry Andric void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
16550b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
16560b57cec5SDimitry Andric   if (dyn_cast_or_null<NamedDecl>(D))
16570b57cec5SDimitry Andric     setGVProperties(GV, GD);
16580b57cec5SDimitry Andric   else
16590b57cec5SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
16600b57cec5SDimitry Andric 
16610b57cec5SDimitry Andric   if (D && D->hasAttr<UsedAttr>())
16620b57cec5SDimitry Andric     addUsedGlobal(GV);
16630b57cec5SDimitry Andric 
16640b57cec5SDimitry Andric   if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
16650b57cec5SDimitry Andric     const auto *VD = cast<VarDecl>(D);
16660b57cec5SDimitry Andric     if (VD->getType().isConstQualified() &&
16670b57cec5SDimitry Andric         VD->getStorageDuration() == SD_Static)
16680b57cec5SDimitry Andric       addUsedGlobal(GV);
16690b57cec5SDimitry Andric   }
16700b57cec5SDimitry Andric }
16710b57cec5SDimitry Andric 
16720b57cec5SDimitry Andric bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
16730b57cec5SDimitry Andric                                                 llvm::AttrBuilder &Attrs) {
16740b57cec5SDimitry Andric   // Add target-cpu and target-features attributes to functions. If
16750b57cec5SDimitry Andric   // we have a decl for the function and it has a target attribute then
16760b57cec5SDimitry Andric   // parse that and add it to the feature set.
16770b57cec5SDimitry Andric   StringRef TargetCPU = getTarget().getTargetOpts().CPU;
16780b57cec5SDimitry Andric   std::vector<std::string> Features;
16790b57cec5SDimitry Andric   const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
16800b57cec5SDimitry Andric   FD = FD ? FD->getMostRecentDecl() : FD;
16810b57cec5SDimitry Andric   const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
16820b57cec5SDimitry Andric   const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
16830b57cec5SDimitry Andric   bool AddedAttr = false;
16840b57cec5SDimitry Andric   if (TD || SD) {
16850b57cec5SDimitry Andric     llvm::StringMap<bool> FeatureMap;
1686480093f4SDimitry Andric     getContext().getFunctionFeatureMap(FeatureMap, GD);
16870b57cec5SDimitry Andric 
16880b57cec5SDimitry Andric     // Produce the canonical string for this set of features.
16890b57cec5SDimitry Andric     for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
16900b57cec5SDimitry Andric       Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
16910b57cec5SDimitry Andric 
16920b57cec5SDimitry Andric     // Now add the target-cpu and target-features to the function.
16930b57cec5SDimitry Andric     // While we populated the feature map above, we still need to
16940b57cec5SDimitry Andric     // get and parse the target attribute so we can get the cpu for
16950b57cec5SDimitry Andric     // the function.
16960b57cec5SDimitry Andric     if (TD) {
1697480093f4SDimitry Andric       ParsedTargetAttr ParsedAttr = TD->parse();
16980b57cec5SDimitry Andric       if (ParsedAttr.Architecture != "" &&
16990b57cec5SDimitry Andric           getTarget().isValidCPUName(ParsedAttr.Architecture))
17000b57cec5SDimitry Andric         TargetCPU = ParsedAttr.Architecture;
17010b57cec5SDimitry Andric     }
17020b57cec5SDimitry Andric   } else {
17030b57cec5SDimitry Andric     // Otherwise just add the existing target cpu and target features to the
17040b57cec5SDimitry Andric     // function.
17050b57cec5SDimitry Andric     Features = getTarget().getTargetOpts().Features;
17060b57cec5SDimitry Andric   }
17070b57cec5SDimitry Andric 
17080b57cec5SDimitry Andric   if (TargetCPU != "") {
17090b57cec5SDimitry Andric     Attrs.addAttribute("target-cpu", TargetCPU);
17100b57cec5SDimitry Andric     AddedAttr = true;
17110b57cec5SDimitry Andric   }
17120b57cec5SDimitry Andric   if (!Features.empty()) {
17130b57cec5SDimitry Andric     llvm::sort(Features);
17140b57cec5SDimitry Andric     Attrs.addAttribute("target-features", llvm::join(Features, ","));
17150b57cec5SDimitry Andric     AddedAttr = true;
17160b57cec5SDimitry Andric   }
17170b57cec5SDimitry Andric 
17180b57cec5SDimitry Andric   return AddedAttr;
17190b57cec5SDimitry Andric }
17200b57cec5SDimitry Andric 
17210b57cec5SDimitry Andric void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
17220b57cec5SDimitry Andric                                           llvm::GlobalObject *GO) {
17230b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
17240b57cec5SDimitry Andric   SetCommonAttributes(GD, GO);
17250b57cec5SDimitry Andric 
17260b57cec5SDimitry Andric   if (D) {
17270b57cec5SDimitry Andric     if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
17280b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
17290b57cec5SDimitry Andric         GV->addAttribute("bss-section", SA->getName());
17300b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
17310b57cec5SDimitry Andric         GV->addAttribute("data-section", SA->getName());
17320b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
17330b57cec5SDimitry Andric         GV->addAttribute("rodata-section", SA->getName());
1734a7dea167SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
1735a7dea167SDimitry Andric         GV->addAttribute("relro-section", SA->getName());
17360b57cec5SDimitry Andric     }
17370b57cec5SDimitry Andric 
17380b57cec5SDimitry Andric     if (auto *F = dyn_cast<llvm::Function>(GO)) {
17390b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
17400b57cec5SDimitry Andric         if (!D->getAttr<SectionAttr>())
17410b57cec5SDimitry Andric           F->addFnAttr("implicit-section-name", SA->getName());
17420b57cec5SDimitry Andric 
17430b57cec5SDimitry Andric       llvm::AttrBuilder Attrs;
17440b57cec5SDimitry Andric       if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
17450b57cec5SDimitry Andric         // We know that GetCPUAndFeaturesAttributes will always have the
17460b57cec5SDimitry Andric         // newest set, since it has the newest possible FunctionDecl, so the
17470b57cec5SDimitry Andric         // new ones should replace the old.
17480b57cec5SDimitry Andric         F->removeFnAttr("target-cpu");
17490b57cec5SDimitry Andric         F->removeFnAttr("target-features");
17500b57cec5SDimitry Andric         F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
17510b57cec5SDimitry Andric       }
17520b57cec5SDimitry Andric     }
17530b57cec5SDimitry Andric 
17540b57cec5SDimitry Andric     if (const auto *CSA = D->getAttr<CodeSegAttr>())
17550b57cec5SDimitry Andric       GO->setSection(CSA->getName());
17560b57cec5SDimitry Andric     else if (const auto *SA = D->getAttr<SectionAttr>())
17570b57cec5SDimitry Andric       GO->setSection(SA->getName());
17580b57cec5SDimitry Andric   }
17590b57cec5SDimitry Andric 
17600b57cec5SDimitry Andric   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
17610b57cec5SDimitry Andric }
17620b57cec5SDimitry Andric 
17630b57cec5SDimitry Andric void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
17640b57cec5SDimitry Andric                                                   llvm::Function *F,
17650b57cec5SDimitry Andric                                                   const CGFunctionInfo &FI) {
17660b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
17670b57cec5SDimitry Andric   SetLLVMFunctionAttributes(GD, FI, F);
17680b57cec5SDimitry Andric   SetLLVMFunctionAttributesForDefinition(D, F);
17690b57cec5SDimitry Andric 
17700b57cec5SDimitry Andric   F->setLinkage(llvm::Function::InternalLinkage);
17710b57cec5SDimitry Andric 
17720b57cec5SDimitry Andric   setNonAliasAttributes(GD, F);
17730b57cec5SDimitry Andric }
17740b57cec5SDimitry Andric 
17750b57cec5SDimitry Andric static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
17760b57cec5SDimitry Andric   // Set linkage and visibility in case we never see a definition.
17770b57cec5SDimitry Andric   LinkageInfo LV = ND->getLinkageAndVisibility();
17780b57cec5SDimitry Andric   // Don't set internal linkage on declarations.
17790b57cec5SDimitry Andric   // "extern_weak" is overloaded in LLVM; we probably should have
17800b57cec5SDimitry Andric   // separate linkage types for this.
17810b57cec5SDimitry Andric   if (isExternallyVisible(LV.getLinkage()) &&
17820b57cec5SDimitry Andric       (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
17830b57cec5SDimitry Andric     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
17840b57cec5SDimitry Andric }
17850b57cec5SDimitry Andric 
17860b57cec5SDimitry Andric void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
17870b57cec5SDimitry Andric                                                        llvm::Function *F) {
17880b57cec5SDimitry Andric   // Only if we are checking indirect calls.
17890b57cec5SDimitry Andric   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
17900b57cec5SDimitry Andric     return;
17910b57cec5SDimitry Andric 
17920b57cec5SDimitry Andric   // Non-static class methods are handled via vtable or member function pointer
17930b57cec5SDimitry Andric   // checks elsewhere.
17940b57cec5SDimitry Andric   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
17950b57cec5SDimitry Andric     return;
17960b57cec5SDimitry Andric 
17970b57cec5SDimitry Andric   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
17980b57cec5SDimitry Andric   F->addTypeMetadata(0, MD);
17990b57cec5SDimitry Andric   F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
18000b57cec5SDimitry Andric 
18010b57cec5SDimitry Andric   // Emit a hash-based bit set entry for cross-DSO calls.
18020b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
18030b57cec5SDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
18040b57cec5SDimitry Andric       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
18050b57cec5SDimitry Andric }
18060b57cec5SDimitry Andric 
18070b57cec5SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
18080b57cec5SDimitry Andric                                           bool IsIncompleteFunction,
18090b57cec5SDimitry Andric                                           bool IsThunk) {
18100b57cec5SDimitry Andric 
18110b57cec5SDimitry Andric   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
18120b57cec5SDimitry Andric     // If this is an intrinsic function, set the function's attributes
18130b57cec5SDimitry Andric     // to the intrinsic's attributes.
18140b57cec5SDimitry Andric     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
18150b57cec5SDimitry Andric     return;
18160b57cec5SDimitry Andric   }
18170b57cec5SDimitry Andric 
18180b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
18190b57cec5SDimitry Andric 
18200b57cec5SDimitry Andric   if (!IsIncompleteFunction)
18210b57cec5SDimitry Andric     SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F);
18220b57cec5SDimitry Andric 
18230b57cec5SDimitry Andric   // Add the Returned attribute for "this", except for iOS 5 and earlier
18240b57cec5SDimitry Andric   // where substantial code, including the libstdc++ dylib, was compiled with
18250b57cec5SDimitry Andric   // GCC and does not actually return "this".
18260b57cec5SDimitry Andric   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
18270b57cec5SDimitry Andric       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
18280b57cec5SDimitry Andric     assert(!F->arg_empty() &&
18290b57cec5SDimitry Andric            F->arg_begin()->getType()
18300b57cec5SDimitry Andric              ->canLosslesslyBitCastTo(F->getReturnType()) &&
18310b57cec5SDimitry Andric            "unexpected this return");
18320b57cec5SDimitry Andric     F->addAttribute(1, llvm::Attribute::Returned);
18330b57cec5SDimitry Andric   }
18340b57cec5SDimitry Andric 
18350b57cec5SDimitry Andric   // Only a few attributes are set on declarations; these may later be
18360b57cec5SDimitry Andric   // overridden by a definition.
18370b57cec5SDimitry Andric 
18380b57cec5SDimitry Andric   setLinkageForGV(F, FD);
18390b57cec5SDimitry Andric   setGVProperties(F, FD);
18400b57cec5SDimitry Andric 
18410b57cec5SDimitry Andric   // Setup target-specific attributes.
18420b57cec5SDimitry Andric   if (!IsIncompleteFunction && F->isDeclaration())
18430b57cec5SDimitry Andric     getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
18440b57cec5SDimitry Andric 
18450b57cec5SDimitry Andric   if (const auto *CSA = FD->getAttr<CodeSegAttr>())
18460b57cec5SDimitry Andric     F->setSection(CSA->getName());
18470b57cec5SDimitry Andric   else if (const auto *SA = FD->getAttr<SectionAttr>())
18480b57cec5SDimitry Andric      F->setSection(SA->getName());
18490b57cec5SDimitry Andric 
1850480093f4SDimitry Andric   if (FD->isInlineBuiltinDeclaration()) {
1851480093f4SDimitry Andric     F->addAttribute(llvm::AttributeList::FunctionIndex,
1852480093f4SDimitry Andric                     llvm::Attribute::NoBuiltin);
1853480093f4SDimitry Andric   }
1854480093f4SDimitry Andric 
18550b57cec5SDimitry Andric   if (FD->isReplaceableGlobalAllocationFunction()) {
18560b57cec5SDimitry Andric     // A replaceable global allocation function does not act like a builtin by
18570b57cec5SDimitry Andric     // default, only if it is invoked by a new-expression or delete-expression.
18580b57cec5SDimitry Andric     F->addAttribute(llvm::AttributeList::FunctionIndex,
18590b57cec5SDimitry Andric                     llvm::Attribute::NoBuiltin);
18600b57cec5SDimitry Andric 
18610b57cec5SDimitry Andric     // A sane operator new returns a non-aliasing pointer.
18620b57cec5SDimitry Andric     // FIXME: Also add NonNull attribute to the return value
18630b57cec5SDimitry Andric     // for the non-nothrow forms?
18640b57cec5SDimitry Andric     auto Kind = FD->getDeclName().getCXXOverloadedOperator();
18650b57cec5SDimitry Andric     if (getCodeGenOpts().AssumeSaneOperatorNew &&
18660b57cec5SDimitry Andric         (Kind == OO_New || Kind == OO_Array_New))
18670b57cec5SDimitry Andric       F->addAttribute(llvm::AttributeList::ReturnIndex,
18680b57cec5SDimitry Andric                       llvm::Attribute::NoAlias);
18690b57cec5SDimitry Andric   }
18700b57cec5SDimitry Andric 
18710b57cec5SDimitry Andric   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
18720b57cec5SDimitry Andric     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
18730b57cec5SDimitry Andric   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
18740b57cec5SDimitry Andric     if (MD->isVirtual())
18750b57cec5SDimitry Andric       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
18760b57cec5SDimitry Andric 
18770b57cec5SDimitry Andric   // Don't emit entries for function declarations in the cross-DSO mode. This
1878a7dea167SDimitry Andric   // is handled with better precision by the receiving DSO. But if jump tables
1879a7dea167SDimitry Andric   // are non-canonical then we need type metadata in order to produce the local
1880a7dea167SDimitry Andric   // jump table.
1881a7dea167SDimitry Andric   if (!CodeGenOpts.SanitizeCfiCrossDso ||
1882a7dea167SDimitry Andric       !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
18830b57cec5SDimitry Andric     CreateFunctionTypeMetadataForIcall(FD, F);
18840b57cec5SDimitry Andric 
18850b57cec5SDimitry Andric   if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
18860b57cec5SDimitry Andric     getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
18870b57cec5SDimitry Andric 
18880b57cec5SDimitry Andric   if (const auto *CB = FD->getAttr<CallbackAttr>()) {
18890b57cec5SDimitry Andric     // Annotate the callback behavior as metadata:
18900b57cec5SDimitry Andric     //  - The callback callee (as argument number).
18910b57cec5SDimitry Andric     //  - The callback payloads (as argument numbers).
18920b57cec5SDimitry Andric     llvm::LLVMContext &Ctx = F->getContext();
18930b57cec5SDimitry Andric     llvm::MDBuilder MDB(Ctx);
18940b57cec5SDimitry Andric 
18950b57cec5SDimitry Andric     // The payload indices are all but the first one in the encoding. The first
18960b57cec5SDimitry Andric     // identifies the callback callee.
18970b57cec5SDimitry Andric     int CalleeIdx = *CB->encoding_begin();
18980b57cec5SDimitry Andric     ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
18990b57cec5SDimitry Andric     F->addMetadata(llvm::LLVMContext::MD_callback,
19000b57cec5SDimitry Andric                    *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
19010b57cec5SDimitry Andric                                                CalleeIdx, PayloadIndices,
19020b57cec5SDimitry Andric                                                /* VarArgsArePassed */ false)}));
19030b57cec5SDimitry Andric   }
19040b57cec5SDimitry Andric }
19050b57cec5SDimitry Andric 
19060b57cec5SDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
19070b57cec5SDimitry Andric   assert(!GV->isDeclaration() &&
19080b57cec5SDimitry Andric          "Only globals with definition can force usage.");
19090b57cec5SDimitry Andric   LLVMUsed.emplace_back(GV);
19100b57cec5SDimitry Andric }
19110b57cec5SDimitry Andric 
19120b57cec5SDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
19130b57cec5SDimitry Andric   assert(!GV->isDeclaration() &&
19140b57cec5SDimitry Andric          "Only globals with definition can force usage.");
19150b57cec5SDimitry Andric   LLVMCompilerUsed.emplace_back(GV);
19160b57cec5SDimitry Andric }
19170b57cec5SDimitry Andric 
19180b57cec5SDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name,
19190b57cec5SDimitry Andric                      std::vector<llvm::WeakTrackingVH> &List) {
19200b57cec5SDimitry Andric   // Don't create llvm.used if there is no need.
19210b57cec5SDimitry Andric   if (List.empty())
19220b57cec5SDimitry Andric     return;
19230b57cec5SDimitry Andric 
19240b57cec5SDimitry Andric   // Convert List to what ConstantArray needs.
19250b57cec5SDimitry Andric   SmallVector<llvm::Constant*, 8> UsedArray;
19260b57cec5SDimitry Andric   UsedArray.resize(List.size());
19270b57cec5SDimitry Andric   for (unsigned i = 0, e = List.size(); i != e; ++i) {
19280b57cec5SDimitry Andric     UsedArray[i] =
19290b57cec5SDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
19300b57cec5SDimitry Andric             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
19310b57cec5SDimitry Andric   }
19320b57cec5SDimitry Andric 
19330b57cec5SDimitry Andric   if (UsedArray.empty())
19340b57cec5SDimitry Andric     return;
19350b57cec5SDimitry Andric   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
19360b57cec5SDimitry Andric 
19370b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
19380b57cec5SDimitry Andric       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
19390b57cec5SDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), Name);
19400b57cec5SDimitry Andric 
19410b57cec5SDimitry Andric   GV->setSection("llvm.metadata");
19420b57cec5SDimitry Andric }
19430b57cec5SDimitry Andric 
19440b57cec5SDimitry Andric void CodeGenModule::emitLLVMUsed() {
19450b57cec5SDimitry Andric   emitUsed(*this, "llvm.used", LLVMUsed);
19460b57cec5SDimitry Andric   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
19470b57cec5SDimitry Andric }
19480b57cec5SDimitry Andric 
19490b57cec5SDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
19500b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
19510b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
19520b57cec5SDimitry Andric }
19530b57cec5SDimitry Andric 
19540b57cec5SDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
19550b57cec5SDimitry Andric   llvm::SmallString<32> Opt;
19560b57cec5SDimitry Andric   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
1957480093f4SDimitry Andric   if (Opt.empty())
1958480093f4SDimitry Andric     return;
19590b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
19600b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
19610b57cec5SDimitry Andric }
19620b57cec5SDimitry Andric 
19630b57cec5SDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) {
19640b57cec5SDimitry Andric   auto &C = getLLVMContext();
19650b57cec5SDimitry Andric   if (getTarget().getTriple().isOSBinFormatELF()) {
19660b57cec5SDimitry Andric       ELFDependentLibraries.push_back(
19670b57cec5SDimitry Andric         llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
19680b57cec5SDimitry Andric     return;
19690b57cec5SDimitry Andric   }
19700b57cec5SDimitry Andric 
19710b57cec5SDimitry Andric   llvm::SmallString<24> Opt;
19720b57cec5SDimitry Andric   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
19730b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
19740b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
19750b57cec5SDimitry Andric }
19760b57cec5SDimitry Andric 
19770b57cec5SDimitry Andric /// Add link options implied by the given module, including modules
19780b57cec5SDimitry Andric /// it depends on, using a postorder walk.
19790b57cec5SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
19800b57cec5SDimitry Andric                                     SmallVectorImpl<llvm::MDNode *> &Metadata,
19810b57cec5SDimitry Andric                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
19820b57cec5SDimitry Andric   // Import this module's parent.
19830b57cec5SDimitry Andric   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
19840b57cec5SDimitry Andric     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
19850b57cec5SDimitry Andric   }
19860b57cec5SDimitry Andric 
19870b57cec5SDimitry Andric   // Import this module's dependencies.
19880b57cec5SDimitry Andric   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
19890b57cec5SDimitry Andric     if (Visited.insert(Mod->Imports[I - 1]).second)
19900b57cec5SDimitry Andric       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
19910b57cec5SDimitry Andric   }
19920b57cec5SDimitry Andric 
19930b57cec5SDimitry Andric   // Add linker options to link against the libraries/frameworks
19940b57cec5SDimitry Andric   // described by this module.
19950b57cec5SDimitry Andric   llvm::LLVMContext &Context = CGM.getLLVMContext();
19960b57cec5SDimitry Andric   bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
19970b57cec5SDimitry Andric 
19980b57cec5SDimitry Andric   // For modules that use export_as for linking, use that module
19990b57cec5SDimitry Andric   // name instead.
20000b57cec5SDimitry Andric   if (Mod->UseExportAsModuleLinkName)
20010b57cec5SDimitry Andric     return;
20020b57cec5SDimitry Andric 
20030b57cec5SDimitry Andric   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
20040b57cec5SDimitry Andric     // Link against a framework.  Frameworks are currently Darwin only, so we
20050b57cec5SDimitry Andric     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
20060b57cec5SDimitry Andric     if (Mod->LinkLibraries[I-1].IsFramework) {
20070b57cec5SDimitry Andric       llvm::Metadata *Args[2] = {
20080b57cec5SDimitry Andric           llvm::MDString::get(Context, "-framework"),
20090b57cec5SDimitry Andric           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
20100b57cec5SDimitry Andric 
20110b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
20120b57cec5SDimitry Andric       continue;
20130b57cec5SDimitry Andric     }
20140b57cec5SDimitry Andric 
20150b57cec5SDimitry Andric     // Link against a library.
20160b57cec5SDimitry Andric     if (IsELF) {
20170b57cec5SDimitry Andric       llvm::Metadata *Args[2] = {
20180b57cec5SDimitry Andric           llvm::MDString::get(Context, "lib"),
20190b57cec5SDimitry Andric           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library),
20200b57cec5SDimitry Andric       };
20210b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
20220b57cec5SDimitry Andric     } else {
20230b57cec5SDimitry Andric       llvm::SmallString<24> Opt;
20240b57cec5SDimitry Andric       CGM.getTargetCodeGenInfo().getDependentLibraryOption(
20250b57cec5SDimitry Andric           Mod->LinkLibraries[I - 1].Library, Opt);
20260b57cec5SDimitry Andric       auto *OptString = llvm::MDString::get(Context, Opt);
20270b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, OptString));
20280b57cec5SDimitry Andric     }
20290b57cec5SDimitry Andric   }
20300b57cec5SDimitry Andric }
20310b57cec5SDimitry Andric 
20320b57cec5SDimitry Andric void CodeGenModule::EmitModuleLinkOptions() {
20330b57cec5SDimitry Andric   // Collect the set of all of the modules we want to visit to emit link
20340b57cec5SDimitry Andric   // options, which is essentially the imported modules and all of their
20350b57cec5SDimitry Andric   // non-explicit child modules.
20360b57cec5SDimitry Andric   llvm::SetVector<clang::Module *> LinkModules;
20370b57cec5SDimitry Andric   llvm::SmallPtrSet<clang::Module *, 16> Visited;
20380b57cec5SDimitry Andric   SmallVector<clang::Module *, 16> Stack;
20390b57cec5SDimitry Andric 
20400b57cec5SDimitry Andric   // Seed the stack with imported modules.
20410b57cec5SDimitry Andric   for (Module *M : ImportedModules) {
20420b57cec5SDimitry Andric     // Do not add any link flags when an implementation TU of a module imports
20430b57cec5SDimitry Andric     // a header of that same module.
20440b57cec5SDimitry Andric     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
20450b57cec5SDimitry Andric         !getLangOpts().isCompilingModule())
20460b57cec5SDimitry Andric       continue;
20470b57cec5SDimitry Andric     if (Visited.insert(M).second)
20480b57cec5SDimitry Andric       Stack.push_back(M);
20490b57cec5SDimitry Andric   }
20500b57cec5SDimitry Andric 
20510b57cec5SDimitry Andric   // Find all of the modules to import, making a little effort to prune
20520b57cec5SDimitry Andric   // non-leaf modules.
20530b57cec5SDimitry Andric   while (!Stack.empty()) {
20540b57cec5SDimitry Andric     clang::Module *Mod = Stack.pop_back_val();
20550b57cec5SDimitry Andric 
20560b57cec5SDimitry Andric     bool AnyChildren = false;
20570b57cec5SDimitry Andric 
20580b57cec5SDimitry Andric     // Visit the submodules of this module.
20590b57cec5SDimitry Andric     for (const auto &SM : Mod->submodules()) {
20600b57cec5SDimitry Andric       // Skip explicit children; they need to be explicitly imported to be
20610b57cec5SDimitry Andric       // linked against.
20620b57cec5SDimitry Andric       if (SM->IsExplicit)
20630b57cec5SDimitry Andric         continue;
20640b57cec5SDimitry Andric 
20650b57cec5SDimitry Andric       if (Visited.insert(SM).second) {
20660b57cec5SDimitry Andric         Stack.push_back(SM);
20670b57cec5SDimitry Andric         AnyChildren = true;
20680b57cec5SDimitry Andric       }
20690b57cec5SDimitry Andric     }
20700b57cec5SDimitry Andric 
20710b57cec5SDimitry Andric     // We didn't find any children, so add this module to the list of
20720b57cec5SDimitry Andric     // modules to link against.
20730b57cec5SDimitry Andric     if (!AnyChildren) {
20740b57cec5SDimitry Andric       LinkModules.insert(Mod);
20750b57cec5SDimitry Andric     }
20760b57cec5SDimitry Andric   }
20770b57cec5SDimitry Andric 
20780b57cec5SDimitry Andric   // Add link options for all of the imported modules in reverse topological
20790b57cec5SDimitry Andric   // order.  We don't do anything to try to order import link flags with respect
20800b57cec5SDimitry Andric   // to linker options inserted by things like #pragma comment().
20810b57cec5SDimitry Andric   SmallVector<llvm::MDNode *, 16> MetadataArgs;
20820b57cec5SDimitry Andric   Visited.clear();
20830b57cec5SDimitry Andric   for (Module *M : LinkModules)
20840b57cec5SDimitry Andric     if (Visited.insert(M).second)
20850b57cec5SDimitry Andric       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
20860b57cec5SDimitry Andric   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
20870b57cec5SDimitry Andric   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
20880b57cec5SDimitry Andric 
20890b57cec5SDimitry Andric   // Add the linker options metadata flag.
20900b57cec5SDimitry Andric   auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
20910b57cec5SDimitry Andric   for (auto *MD : LinkerOptionsMetadata)
20920b57cec5SDimitry Andric     NMD->addOperand(MD);
20930b57cec5SDimitry Andric }
20940b57cec5SDimitry Andric 
20950b57cec5SDimitry Andric void CodeGenModule::EmitDeferred() {
20960b57cec5SDimitry Andric   // Emit deferred declare target declarations.
20970b57cec5SDimitry Andric   if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
20980b57cec5SDimitry Andric     getOpenMPRuntime().emitDeferredTargetDecls();
20990b57cec5SDimitry Andric 
21000b57cec5SDimitry Andric   // Emit code for any potentially referenced deferred decls.  Since a
21010b57cec5SDimitry Andric   // previously unused static decl may become used during the generation of code
21020b57cec5SDimitry Andric   // for a static function, iterate until no changes are made.
21030b57cec5SDimitry Andric 
21040b57cec5SDimitry Andric   if (!DeferredVTables.empty()) {
21050b57cec5SDimitry Andric     EmitDeferredVTables();
21060b57cec5SDimitry Andric 
21070b57cec5SDimitry Andric     // Emitting a vtable doesn't directly cause more vtables to
21080b57cec5SDimitry Andric     // become deferred, although it can cause functions to be
21090b57cec5SDimitry Andric     // emitted that then need those vtables.
21100b57cec5SDimitry Andric     assert(DeferredVTables.empty());
21110b57cec5SDimitry Andric   }
21120b57cec5SDimitry Andric 
21130b57cec5SDimitry Andric   // Stop if we're out of both deferred vtables and deferred declarations.
21140b57cec5SDimitry Andric   if (DeferredDeclsToEmit.empty())
21150b57cec5SDimitry Andric     return;
21160b57cec5SDimitry Andric 
21170b57cec5SDimitry Andric   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
21180b57cec5SDimitry Andric   // work, it will not interfere with this.
21190b57cec5SDimitry Andric   std::vector<GlobalDecl> CurDeclsToEmit;
21200b57cec5SDimitry Andric   CurDeclsToEmit.swap(DeferredDeclsToEmit);
21210b57cec5SDimitry Andric 
21220b57cec5SDimitry Andric   for (GlobalDecl &D : CurDeclsToEmit) {
21230b57cec5SDimitry Andric     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
21240b57cec5SDimitry Andric     // to get GlobalValue with exactly the type we need, not something that
21250b57cec5SDimitry Andric     // might had been created for another decl with the same mangled name but
21260b57cec5SDimitry Andric     // different type.
21270b57cec5SDimitry Andric     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
21280b57cec5SDimitry Andric         GetAddrOfGlobal(D, ForDefinition));
21290b57cec5SDimitry Andric 
21300b57cec5SDimitry Andric     // In case of different address spaces, we may still get a cast, even with
21310b57cec5SDimitry Andric     // IsForDefinition equal to true. Query mangled names table to get
21320b57cec5SDimitry Andric     // GlobalValue.
21330b57cec5SDimitry Andric     if (!GV)
21340b57cec5SDimitry Andric       GV = GetGlobalValue(getMangledName(D));
21350b57cec5SDimitry Andric 
21360b57cec5SDimitry Andric     // Make sure GetGlobalValue returned non-null.
21370b57cec5SDimitry Andric     assert(GV);
21380b57cec5SDimitry Andric 
21390b57cec5SDimitry Andric     // Check to see if we've already emitted this.  This is necessary
21400b57cec5SDimitry Andric     // for a couple of reasons: first, decls can end up in the
21410b57cec5SDimitry Andric     // deferred-decls queue multiple times, and second, decls can end
21420b57cec5SDimitry Andric     // up with definitions in unusual ways (e.g. by an extern inline
21430b57cec5SDimitry Andric     // function acquiring a strong function redefinition).  Just
21440b57cec5SDimitry Andric     // ignore these cases.
21450b57cec5SDimitry Andric     if (!GV->isDeclaration())
21460b57cec5SDimitry Andric       continue;
21470b57cec5SDimitry Andric 
2148a7dea167SDimitry Andric     // If this is OpenMP, check if it is legal to emit this global normally.
2149a7dea167SDimitry Andric     if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
2150a7dea167SDimitry Andric       continue;
2151a7dea167SDimitry Andric 
21520b57cec5SDimitry Andric     // Otherwise, emit the definition and move on to the next one.
21530b57cec5SDimitry Andric     EmitGlobalDefinition(D, GV);
21540b57cec5SDimitry Andric 
21550b57cec5SDimitry Andric     // If we found out that we need to emit more decls, do that recursively.
21560b57cec5SDimitry Andric     // This has the advantage that the decls are emitted in a DFS and related
21570b57cec5SDimitry Andric     // ones are close together, which is convenient for testing.
21580b57cec5SDimitry Andric     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
21590b57cec5SDimitry Andric       EmitDeferred();
21600b57cec5SDimitry Andric       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
21610b57cec5SDimitry Andric     }
21620b57cec5SDimitry Andric   }
21630b57cec5SDimitry Andric }
21640b57cec5SDimitry Andric 
21650b57cec5SDimitry Andric void CodeGenModule::EmitVTablesOpportunistically() {
21660b57cec5SDimitry Andric   // Try to emit external vtables as available_externally if they have emitted
21670b57cec5SDimitry Andric   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
21680b57cec5SDimitry Andric   // is not allowed to create new references to things that need to be emitted
21690b57cec5SDimitry Andric   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
21700b57cec5SDimitry Andric 
21710b57cec5SDimitry Andric   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
21720b57cec5SDimitry Andric          && "Only emit opportunistic vtables with optimizations");
21730b57cec5SDimitry Andric 
21740b57cec5SDimitry Andric   for (const CXXRecordDecl *RD : OpportunisticVTables) {
21750b57cec5SDimitry Andric     assert(getVTables().isVTableExternal(RD) &&
21760b57cec5SDimitry Andric            "This queue should only contain external vtables");
21770b57cec5SDimitry Andric     if (getCXXABI().canSpeculativelyEmitVTable(RD))
21780b57cec5SDimitry Andric       VTables.GenerateClassData(RD);
21790b57cec5SDimitry Andric   }
21800b57cec5SDimitry Andric   OpportunisticVTables.clear();
21810b57cec5SDimitry Andric }
21820b57cec5SDimitry Andric 
21830b57cec5SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() {
21840b57cec5SDimitry Andric   if (Annotations.empty())
21850b57cec5SDimitry Andric     return;
21860b57cec5SDimitry Andric 
21870b57cec5SDimitry Andric   // Create a new global variable for the ConstantStruct in the Module.
21880b57cec5SDimitry Andric   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
21890b57cec5SDimitry Andric     Annotations[0]->getType(), Annotations.size()), Annotations);
21900b57cec5SDimitry Andric   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
21910b57cec5SDimitry Andric                                       llvm::GlobalValue::AppendingLinkage,
21920b57cec5SDimitry Andric                                       Array, "llvm.global.annotations");
21930b57cec5SDimitry Andric   gv->setSection(AnnotationSection);
21940b57cec5SDimitry Andric }
21950b57cec5SDimitry Andric 
21960b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
21970b57cec5SDimitry Andric   llvm::Constant *&AStr = AnnotationStrings[Str];
21980b57cec5SDimitry Andric   if (AStr)
21990b57cec5SDimitry Andric     return AStr;
22000b57cec5SDimitry Andric 
22010b57cec5SDimitry Andric   // Not found yet, create a new global.
22020b57cec5SDimitry Andric   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
22030b57cec5SDimitry Andric   auto *gv =
22040b57cec5SDimitry Andric       new llvm::GlobalVariable(getModule(), s->getType(), true,
22050b57cec5SDimitry Andric                                llvm::GlobalValue::PrivateLinkage, s, ".str");
22060b57cec5SDimitry Andric   gv->setSection(AnnotationSection);
22070b57cec5SDimitry Andric   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
22080b57cec5SDimitry Andric   AStr = gv;
22090b57cec5SDimitry Andric   return gv;
22100b57cec5SDimitry Andric }
22110b57cec5SDimitry Andric 
22120b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
22130b57cec5SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
22140b57cec5SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
22150b57cec5SDimitry Andric   if (PLoc.isValid())
22160b57cec5SDimitry Andric     return EmitAnnotationString(PLoc.getFilename());
22170b57cec5SDimitry Andric   return EmitAnnotationString(SM.getBufferName(Loc));
22180b57cec5SDimitry Andric }
22190b57cec5SDimitry Andric 
22200b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
22210b57cec5SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
22220b57cec5SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(L);
22230b57cec5SDimitry Andric   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
22240b57cec5SDimitry Andric     SM.getExpansionLineNumber(L);
22250b57cec5SDimitry Andric   return llvm::ConstantInt::get(Int32Ty, LineNo);
22260b57cec5SDimitry Andric }
22270b57cec5SDimitry Andric 
22280b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
22290b57cec5SDimitry Andric                                                 const AnnotateAttr *AA,
22300b57cec5SDimitry Andric                                                 SourceLocation L) {
22310b57cec5SDimitry Andric   // Get the globals for file name, annotation, and the line number.
22320b57cec5SDimitry Andric   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
22330b57cec5SDimitry Andric                  *UnitGV = EmitAnnotationUnit(L),
22340b57cec5SDimitry Andric                  *LineNoCst = EmitAnnotationLineNo(L);
22350b57cec5SDimitry Andric 
2236480093f4SDimitry Andric   llvm::Constant *ASZeroGV = GV;
2237480093f4SDimitry Andric   if (GV->getAddressSpace() != 0) {
2238480093f4SDimitry Andric     ASZeroGV = llvm::ConstantExpr::getAddrSpaceCast(
2239480093f4SDimitry Andric                    GV, GV->getValueType()->getPointerTo(0));
2240480093f4SDimitry Andric   }
2241480093f4SDimitry Andric 
22420b57cec5SDimitry Andric   // Create the ConstantStruct for the global annotation.
22430b57cec5SDimitry Andric   llvm::Constant *Fields[4] = {
2244480093f4SDimitry Andric     llvm::ConstantExpr::getBitCast(ASZeroGV, Int8PtrTy),
22450b57cec5SDimitry Andric     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
22460b57cec5SDimitry Andric     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
22470b57cec5SDimitry Andric     LineNoCst
22480b57cec5SDimitry Andric   };
22490b57cec5SDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
22500b57cec5SDimitry Andric }
22510b57cec5SDimitry Andric 
22520b57cec5SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
22530b57cec5SDimitry Andric                                          llvm::GlobalValue *GV) {
22540b57cec5SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
22550b57cec5SDimitry Andric   // Get the struct elements for these annotations.
22560b57cec5SDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
22570b57cec5SDimitry Andric     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
22580b57cec5SDimitry Andric }
22590b57cec5SDimitry Andric 
22600b57cec5SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
22610b57cec5SDimitry Andric                                            llvm::Function *Fn,
22620b57cec5SDimitry Andric                                            SourceLocation Loc) const {
22630b57cec5SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
22640b57cec5SDimitry Andric   // Blacklist by function name.
22650b57cec5SDimitry Andric   if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
22660b57cec5SDimitry Andric     return true;
22670b57cec5SDimitry Andric   // Blacklist by location.
22680b57cec5SDimitry Andric   if (Loc.isValid())
22690b57cec5SDimitry Andric     return SanitizerBL.isBlacklistedLocation(Kind, Loc);
22700b57cec5SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
22710b57cec5SDimitry Andric   // it's located in the main file.
22720b57cec5SDimitry Andric   auto &SM = Context.getSourceManager();
22730b57cec5SDimitry Andric   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
22740b57cec5SDimitry Andric     return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
22750b57cec5SDimitry Andric   }
22760b57cec5SDimitry Andric   return false;
22770b57cec5SDimitry Andric }
22780b57cec5SDimitry Andric 
22790b57cec5SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
22800b57cec5SDimitry Andric                                            SourceLocation Loc, QualType Ty,
22810b57cec5SDimitry Andric                                            StringRef Category) const {
22820b57cec5SDimitry Andric   // For now globals can be blacklisted only in ASan and KASan.
22830b57cec5SDimitry Andric   const SanitizerMask EnabledAsanMask =
22840b57cec5SDimitry Andric       LangOpts.Sanitize.Mask &
22850b57cec5SDimitry Andric       (SanitizerKind::Address | SanitizerKind::KernelAddress |
22860b57cec5SDimitry Andric        SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress |
22870b57cec5SDimitry Andric        SanitizerKind::MemTag);
22880b57cec5SDimitry Andric   if (!EnabledAsanMask)
22890b57cec5SDimitry Andric     return false;
22900b57cec5SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
22910b57cec5SDimitry Andric   if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
22920b57cec5SDimitry Andric     return true;
22930b57cec5SDimitry Andric   if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
22940b57cec5SDimitry Andric     return true;
22950b57cec5SDimitry Andric   // Check global type.
22960b57cec5SDimitry Andric   if (!Ty.isNull()) {
22970b57cec5SDimitry Andric     // Drill down the array types: if global variable of a fixed type is
22980b57cec5SDimitry Andric     // blacklisted, we also don't instrument arrays of them.
22990b57cec5SDimitry Andric     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
23000b57cec5SDimitry Andric       Ty = AT->getElementType();
23010b57cec5SDimitry Andric     Ty = Ty.getCanonicalType().getUnqualifiedType();
23020b57cec5SDimitry Andric     // We allow to blacklist only record types (classes, structs etc.)
23030b57cec5SDimitry Andric     if (Ty->isRecordType()) {
23040b57cec5SDimitry Andric       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
23050b57cec5SDimitry Andric       if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
23060b57cec5SDimitry Andric         return true;
23070b57cec5SDimitry Andric     }
23080b57cec5SDimitry Andric   }
23090b57cec5SDimitry Andric   return false;
23100b57cec5SDimitry Andric }
23110b57cec5SDimitry Andric 
23120b57cec5SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
23130b57cec5SDimitry Andric                                    StringRef Category) const {
23140b57cec5SDimitry Andric   const auto &XRayFilter = getContext().getXRayFilter();
23150b57cec5SDimitry Andric   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
23160b57cec5SDimitry Andric   auto Attr = ImbueAttr::NONE;
23170b57cec5SDimitry Andric   if (Loc.isValid())
23180b57cec5SDimitry Andric     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
23190b57cec5SDimitry Andric   if (Attr == ImbueAttr::NONE)
23200b57cec5SDimitry Andric     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
23210b57cec5SDimitry Andric   switch (Attr) {
23220b57cec5SDimitry Andric   case ImbueAttr::NONE:
23230b57cec5SDimitry Andric     return false;
23240b57cec5SDimitry Andric   case ImbueAttr::ALWAYS:
23250b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
23260b57cec5SDimitry Andric     break;
23270b57cec5SDimitry Andric   case ImbueAttr::ALWAYS_ARG1:
23280b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
23290b57cec5SDimitry Andric     Fn->addFnAttr("xray-log-args", "1");
23300b57cec5SDimitry Andric     break;
23310b57cec5SDimitry Andric   case ImbueAttr::NEVER:
23320b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-never");
23330b57cec5SDimitry Andric     break;
23340b57cec5SDimitry Andric   }
23350b57cec5SDimitry Andric   return true;
23360b57cec5SDimitry Andric }
23370b57cec5SDimitry Andric 
23380b57cec5SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
23390b57cec5SDimitry Andric   // Never defer when EmitAllDecls is specified.
23400b57cec5SDimitry Andric   if (LangOpts.EmitAllDecls)
23410b57cec5SDimitry Andric     return true;
23420b57cec5SDimitry Andric 
23430b57cec5SDimitry Andric   if (CodeGenOpts.KeepStaticConsts) {
23440b57cec5SDimitry Andric     const auto *VD = dyn_cast<VarDecl>(Global);
23450b57cec5SDimitry Andric     if (VD && VD->getType().isConstQualified() &&
23460b57cec5SDimitry Andric         VD->getStorageDuration() == SD_Static)
23470b57cec5SDimitry Andric       return true;
23480b57cec5SDimitry Andric   }
23490b57cec5SDimitry Andric 
23500b57cec5SDimitry Andric   return getContext().DeclMustBeEmitted(Global);
23510b57cec5SDimitry Andric }
23520b57cec5SDimitry Andric 
23530b57cec5SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
2354a7dea167SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
23550b57cec5SDimitry Andric     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
23560b57cec5SDimitry Andric       // Implicit template instantiations may change linkage if they are later
23570b57cec5SDimitry Andric       // explicitly instantiated, so they should not be emitted eagerly.
23580b57cec5SDimitry Andric       return false;
2359a7dea167SDimitry Andric     // In OpenMP 5.0 function may be marked as device_type(nohost) and we should
2360a7dea167SDimitry Andric     // not emit them eagerly unless we sure that the function must be emitted on
2361a7dea167SDimitry Andric     // the host.
2362a7dea167SDimitry Andric     if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd &&
2363a7dea167SDimitry Andric         !LangOpts.OpenMPIsDevice &&
2364a7dea167SDimitry Andric         !OMPDeclareTargetDeclAttr::getDeviceType(FD) &&
2365a7dea167SDimitry Andric         !FD->isUsed(/*CheckUsedAttr=*/false) && !FD->isReferenced())
2366a7dea167SDimitry Andric       return false;
2367a7dea167SDimitry Andric   }
23680b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(Global))
23690b57cec5SDimitry Andric     if (Context.getInlineVariableDefinitionKind(VD) ==
23700b57cec5SDimitry Andric         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
23710b57cec5SDimitry Andric       // A definition of an inline constexpr static data member may change
23720b57cec5SDimitry Andric       // linkage later if it's redeclared outside the class.
23730b57cec5SDimitry Andric       return false;
23740b57cec5SDimitry Andric   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
23750b57cec5SDimitry Andric   // codegen for global variables, because they may be marked as threadprivate.
23760b57cec5SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
23770b57cec5SDimitry Andric       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
23780b57cec5SDimitry Andric       !isTypeConstant(Global->getType(), false) &&
23790b57cec5SDimitry Andric       !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
23800b57cec5SDimitry Andric     return false;
23810b57cec5SDimitry Andric 
23820b57cec5SDimitry Andric   return true;
23830b57cec5SDimitry Andric }
23840b57cec5SDimitry Andric 
23850b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
23860b57cec5SDimitry Andric     const CXXUuidofExpr* E) {
23870b57cec5SDimitry Andric   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
23880b57cec5SDimitry Andric   // well-formed.
23890b57cec5SDimitry Andric   StringRef Uuid = E->getUuidStr();
23900b57cec5SDimitry Andric   std::string Name = "_GUID_" + Uuid.lower();
23910b57cec5SDimitry Andric   std::replace(Name.begin(), Name.end(), '-', '_');
23920b57cec5SDimitry Andric 
23930b57cec5SDimitry Andric   // The UUID descriptor should be pointer aligned.
23940b57cec5SDimitry Andric   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
23950b57cec5SDimitry Andric 
23960b57cec5SDimitry Andric   // Look for an existing global.
23970b57cec5SDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
23980b57cec5SDimitry Andric     return ConstantAddress(GV, Alignment);
23990b57cec5SDimitry Andric 
24000b57cec5SDimitry Andric   llvm::Constant *Init = EmitUuidofInitializer(Uuid);
24010b57cec5SDimitry Andric   assert(Init && "failed to initialize as constant");
24020b57cec5SDimitry Andric 
24030b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
24040b57cec5SDimitry Andric       getModule(), Init->getType(),
24050b57cec5SDimitry Andric       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
24060b57cec5SDimitry Andric   if (supportsCOMDAT())
24070b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
24080b57cec5SDimitry Andric   setDSOLocal(GV);
24090b57cec5SDimitry Andric   return ConstantAddress(GV, Alignment);
24100b57cec5SDimitry Andric }
24110b57cec5SDimitry Andric 
24120b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
24130b57cec5SDimitry Andric   const AliasAttr *AA = VD->getAttr<AliasAttr>();
24140b57cec5SDimitry Andric   assert(AA && "No alias?");
24150b57cec5SDimitry Andric 
24160b57cec5SDimitry Andric   CharUnits Alignment = getContext().getDeclAlign(VD);
24170b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
24180b57cec5SDimitry Andric 
24190b57cec5SDimitry Andric   // See if there is already something with the target's name in the module.
24200b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
24210b57cec5SDimitry Andric   if (Entry) {
24220b57cec5SDimitry Andric     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
24230b57cec5SDimitry Andric     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
24240b57cec5SDimitry Andric     return ConstantAddress(Ptr, Alignment);
24250b57cec5SDimitry Andric   }
24260b57cec5SDimitry Andric 
24270b57cec5SDimitry Andric   llvm::Constant *Aliasee;
24280b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(DeclTy))
24290b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
24300b57cec5SDimitry Andric                                       GlobalDecl(cast<FunctionDecl>(VD)),
24310b57cec5SDimitry Andric                                       /*ForVTable=*/false);
24320b57cec5SDimitry Andric   else
24330b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
24340b57cec5SDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
24350b57cec5SDimitry Andric                                     nullptr);
24360b57cec5SDimitry Andric 
24370b57cec5SDimitry Andric   auto *F = cast<llvm::GlobalValue>(Aliasee);
24380b57cec5SDimitry Andric   F->setLinkage(llvm::Function::ExternalWeakLinkage);
24390b57cec5SDimitry Andric   WeakRefReferences.insert(F);
24400b57cec5SDimitry Andric 
24410b57cec5SDimitry Andric   return ConstantAddress(Aliasee, Alignment);
24420b57cec5SDimitry Andric }
24430b57cec5SDimitry Andric 
24440b57cec5SDimitry Andric void CodeGenModule::EmitGlobal(GlobalDecl GD) {
24450b57cec5SDimitry Andric   const auto *Global = cast<ValueDecl>(GD.getDecl());
24460b57cec5SDimitry Andric 
24470b57cec5SDimitry Andric   // Weak references don't produce any output by themselves.
24480b57cec5SDimitry Andric   if (Global->hasAttr<WeakRefAttr>())
24490b57cec5SDimitry Andric     return;
24500b57cec5SDimitry Andric 
24510b57cec5SDimitry Andric   // If this is an alias definition (which otherwise looks like a declaration)
24520b57cec5SDimitry Andric   // emit it now.
24530b57cec5SDimitry Andric   if (Global->hasAttr<AliasAttr>())
24540b57cec5SDimitry Andric     return EmitAliasDefinition(GD);
24550b57cec5SDimitry Andric 
24560b57cec5SDimitry Andric   // IFunc like an alias whose value is resolved at runtime by calling resolver.
24570b57cec5SDimitry Andric   if (Global->hasAttr<IFuncAttr>())
24580b57cec5SDimitry Andric     return emitIFuncDefinition(GD);
24590b57cec5SDimitry Andric 
24600b57cec5SDimitry Andric   // If this is a cpu_dispatch multiversion function, emit the resolver.
24610b57cec5SDimitry Andric   if (Global->hasAttr<CPUDispatchAttr>())
24620b57cec5SDimitry Andric     return emitCPUDispatchDefinition(GD);
24630b57cec5SDimitry Andric 
24640b57cec5SDimitry Andric   // If this is CUDA, be selective about which declarations we emit.
24650b57cec5SDimitry Andric   if (LangOpts.CUDA) {
24660b57cec5SDimitry Andric     if (LangOpts.CUDAIsDevice) {
24670b57cec5SDimitry Andric       if (!Global->hasAttr<CUDADeviceAttr>() &&
24680b57cec5SDimitry Andric           !Global->hasAttr<CUDAGlobalAttr>() &&
24690b57cec5SDimitry Andric           !Global->hasAttr<CUDAConstantAttr>() &&
24700b57cec5SDimitry Andric           !Global->hasAttr<CUDASharedAttr>() &&
24710b57cec5SDimitry Andric           !(LangOpts.HIP && Global->hasAttr<HIPPinnedShadowAttr>()))
24720b57cec5SDimitry Andric         return;
24730b57cec5SDimitry Andric     } else {
24740b57cec5SDimitry Andric       // We need to emit host-side 'shadows' for all global
24750b57cec5SDimitry Andric       // device-side variables because the CUDA runtime needs their
24760b57cec5SDimitry Andric       // size and host-side address in order to provide access to
24770b57cec5SDimitry Andric       // their device-side incarnations.
24780b57cec5SDimitry Andric 
24790b57cec5SDimitry Andric       // So device-only functions are the only things we skip.
24800b57cec5SDimitry Andric       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
24810b57cec5SDimitry Andric           Global->hasAttr<CUDADeviceAttr>())
24820b57cec5SDimitry Andric         return;
24830b57cec5SDimitry Andric 
24840b57cec5SDimitry Andric       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
24850b57cec5SDimitry Andric              "Expected Variable or Function");
24860b57cec5SDimitry Andric     }
24870b57cec5SDimitry Andric   }
24880b57cec5SDimitry Andric 
24890b57cec5SDimitry Andric   if (LangOpts.OpenMP) {
2490a7dea167SDimitry Andric     // If this is OpenMP, check if it is legal to emit this global normally.
24910b57cec5SDimitry Andric     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
24920b57cec5SDimitry Andric       return;
24930b57cec5SDimitry Andric     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
24940b57cec5SDimitry Andric       if (MustBeEmitted(Global))
24950b57cec5SDimitry Andric         EmitOMPDeclareReduction(DRD);
24960b57cec5SDimitry Andric       return;
24970b57cec5SDimitry Andric     } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
24980b57cec5SDimitry Andric       if (MustBeEmitted(Global))
24990b57cec5SDimitry Andric         EmitOMPDeclareMapper(DMD);
25000b57cec5SDimitry Andric       return;
25010b57cec5SDimitry Andric     }
25020b57cec5SDimitry Andric   }
25030b57cec5SDimitry Andric 
25040b57cec5SDimitry Andric   // Ignore declarations, they will be emitted on their first use.
25050b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
25060b57cec5SDimitry Andric     // Forward declarations are emitted lazily on first use.
25070b57cec5SDimitry Andric     if (!FD->doesThisDeclarationHaveABody()) {
25080b57cec5SDimitry Andric       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
25090b57cec5SDimitry Andric         return;
25100b57cec5SDimitry Andric 
25110b57cec5SDimitry Andric       StringRef MangledName = getMangledName(GD);
25120b57cec5SDimitry Andric 
25130b57cec5SDimitry Andric       // Compute the function info and LLVM type.
25140b57cec5SDimitry Andric       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
25150b57cec5SDimitry Andric       llvm::Type *Ty = getTypes().GetFunctionType(FI);
25160b57cec5SDimitry Andric 
25170b57cec5SDimitry Andric       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
25180b57cec5SDimitry Andric                               /*DontDefer=*/false);
25190b57cec5SDimitry Andric       return;
25200b57cec5SDimitry Andric     }
25210b57cec5SDimitry Andric   } else {
25220b57cec5SDimitry Andric     const auto *VD = cast<VarDecl>(Global);
25230b57cec5SDimitry Andric     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
25240b57cec5SDimitry Andric     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
25250b57cec5SDimitry Andric         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
25260b57cec5SDimitry Andric       if (LangOpts.OpenMP) {
25270b57cec5SDimitry Andric         // Emit declaration of the must-be-emitted declare target variable.
25280b57cec5SDimitry Andric         if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
25290b57cec5SDimitry Andric                 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
25300b57cec5SDimitry Andric           bool UnifiedMemoryEnabled =
25310b57cec5SDimitry Andric               getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
25320b57cec5SDimitry Andric           if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
25330b57cec5SDimitry Andric               !UnifiedMemoryEnabled) {
25340b57cec5SDimitry Andric             (void)GetAddrOfGlobalVar(VD);
25350b57cec5SDimitry Andric           } else {
25360b57cec5SDimitry Andric             assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
25370b57cec5SDimitry Andric                     (*Res == OMPDeclareTargetDeclAttr::MT_To &&
25380b57cec5SDimitry Andric                      UnifiedMemoryEnabled)) &&
25390b57cec5SDimitry Andric                    "Link clause or to clause with unified memory expected.");
25400b57cec5SDimitry Andric             (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
25410b57cec5SDimitry Andric           }
25420b57cec5SDimitry Andric 
25430b57cec5SDimitry Andric           return;
25440b57cec5SDimitry Andric         }
25450b57cec5SDimitry Andric       }
25460b57cec5SDimitry Andric       // If this declaration may have caused an inline variable definition to
25470b57cec5SDimitry Andric       // change linkage, make sure that it's emitted.
25480b57cec5SDimitry Andric       if (Context.getInlineVariableDefinitionKind(VD) ==
25490b57cec5SDimitry Andric           ASTContext::InlineVariableDefinitionKind::Strong)
25500b57cec5SDimitry Andric         GetAddrOfGlobalVar(VD);
25510b57cec5SDimitry Andric       return;
25520b57cec5SDimitry Andric     }
25530b57cec5SDimitry Andric   }
25540b57cec5SDimitry Andric 
25550b57cec5SDimitry Andric   // Defer code generation to first use when possible, e.g. if this is an inline
25560b57cec5SDimitry Andric   // function. If the global must always be emitted, do it eagerly if possible
25570b57cec5SDimitry Andric   // to benefit from cache locality.
25580b57cec5SDimitry Andric   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
25590b57cec5SDimitry Andric     // Emit the definition if it can't be deferred.
25600b57cec5SDimitry Andric     EmitGlobalDefinition(GD);
25610b57cec5SDimitry Andric     return;
25620b57cec5SDimitry Andric   }
25630b57cec5SDimitry Andric 
2564a7dea167SDimitry Andric     // Check if this must be emitted as declare variant.
2565a7dea167SDimitry Andric   if (LangOpts.OpenMP && isa<FunctionDecl>(Global) && OpenMPRuntime &&
2566a7dea167SDimitry Andric       OpenMPRuntime->emitDeclareVariant(GD, /*IsForDefinition=*/false))
2567a7dea167SDimitry Andric     return;
2568a7dea167SDimitry Andric 
25690b57cec5SDimitry Andric   // If we're deferring emission of a C++ variable with an
25700b57cec5SDimitry Andric   // initializer, remember the order in which it appeared in the file.
25710b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
25720b57cec5SDimitry Andric       cast<VarDecl>(Global)->hasInit()) {
25730b57cec5SDimitry Andric     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
25740b57cec5SDimitry Andric     CXXGlobalInits.push_back(nullptr);
25750b57cec5SDimitry Andric   }
25760b57cec5SDimitry Andric 
25770b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
25780b57cec5SDimitry Andric   if (GetGlobalValue(MangledName) != nullptr) {
25790b57cec5SDimitry Andric     // The value has already been used and should therefore be emitted.
25800b57cec5SDimitry Andric     addDeferredDeclToEmit(GD);
25810b57cec5SDimitry Andric   } else if (MustBeEmitted(Global)) {
25820b57cec5SDimitry Andric     // The value must be emitted, but cannot be emitted eagerly.
25830b57cec5SDimitry Andric     assert(!MayBeEmittedEagerly(Global));
25840b57cec5SDimitry Andric     addDeferredDeclToEmit(GD);
25850b57cec5SDimitry Andric   } else {
25860b57cec5SDimitry Andric     // Otherwise, remember that we saw a deferred decl with this name.  The
25870b57cec5SDimitry Andric     // first use of the mangled name will cause it to move into
25880b57cec5SDimitry Andric     // DeferredDeclsToEmit.
25890b57cec5SDimitry Andric     DeferredDecls[MangledName] = GD;
25900b57cec5SDimitry Andric   }
25910b57cec5SDimitry Andric }
25920b57cec5SDimitry Andric 
25930b57cec5SDimitry Andric // Check if T is a class type with a destructor that's not dllimport.
25940b57cec5SDimitry Andric static bool HasNonDllImportDtor(QualType T) {
25950b57cec5SDimitry Andric   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
25960b57cec5SDimitry Andric     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
25970b57cec5SDimitry Andric       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
25980b57cec5SDimitry Andric         return true;
25990b57cec5SDimitry Andric 
26000b57cec5SDimitry Andric   return false;
26010b57cec5SDimitry Andric }
26020b57cec5SDimitry Andric 
26030b57cec5SDimitry Andric namespace {
26040b57cec5SDimitry Andric   struct FunctionIsDirectlyRecursive
26050b57cec5SDimitry Andric       : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
26060b57cec5SDimitry Andric     const StringRef Name;
26070b57cec5SDimitry Andric     const Builtin::Context &BI;
26080b57cec5SDimitry Andric     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
26090b57cec5SDimitry Andric         : Name(N), BI(C) {}
26100b57cec5SDimitry Andric 
26110b57cec5SDimitry Andric     bool VisitCallExpr(const CallExpr *E) {
26120b57cec5SDimitry Andric       const FunctionDecl *FD = E->getDirectCallee();
26130b57cec5SDimitry Andric       if (!FD)
26140b57cec5SDimitry Andric         return false;
26150b57cec5SDimitry Andric       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
26160b57cec5SDimitry Andric       if (Attr && Name == Attr->getLabel())
26170b57cec5SDimitry Andric         return true;
26180b57cec5SDimitry Andric       unsigned BuiltinID = FD->getBuiltinID();
26190b57cec5SDimitry Andric       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
26200b57cec5SDimitry Andric         return false;
26210b57cec5SDimitry Andric       StringRef BuiltinName = BI.getName(BuiltinID);
26220b57cec5SDimitry Andric       if (BuiltinName.startswith("__builtin_") &&
26230b57cec5SDimitry Andric           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
26240b57cec5SDimitry Andric         return true;
26250b57cec5SDimitry Andric       }
26260b57cec5SDimitry Andric       return false;
26270b57cec5SDimitry Andric     }
26280b57cec5SDimitry Andric 
26290b57cec5SDimitry Andric     bool VisitStmt(const Stmt *S) {
26300b57cec5SDimitry Andric       for (const Stmt *Child : S->children())
26310b57cec5SDimitry Andric         if (Child && this->Visit(Child))
26320b57cec5SDimitry Andric           return true;
26330b57cec5SDimitry Andric       return false;
26340b57cec5SDimitry Andric     }
26350b57cec5SDimitry Andric   };
26360b57cec5SDimitry Andric 
26370b57cec5SDimitry Andric   // Make sure we're not referencing non-imported vars or functions.
26380b57cec5SDimitry Andric   struct DLLImportFunctionVisitor
26390b57cec5SDimitry Andric       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
26400b57cec5SDimitry Andric     bool SafeToInline = true;
26410b57cec5SDimitry Andric 
26420b57cec5SDimitry Andric     bool shouldVisitImplicitCode() const { return true; }
26430b57cec5SDimitry Andric 
26440b57cec5SDimitry Andric     bool VisitVarDecl(VarDecl *VD) {
26450b57cec5SDimitry Andric       if (VD->getTLSKind()) {
26460b57cec5SDimitry Andric         // A thread-local variable cannot be imported.
26470b57cec5SDimitry Andric         SafeToInline = false;
26480b57cec5SDimitry Andric         return SafeToInline;
26490b57cec5SDimitry Andric       }
26500b57cec5SDimitry Andric 
26510b57cec5SDimitry Andric       // A variable definition might imply a destructor call.
26520b57cec5SDimitry Andric       if (VD->isThisDeclarationADefinition())
26530b57cec5SDimitry Andric         SafeToInline = !HasNonDllImportDtor(VD->getType());
26540b57cec5SDimitry Andric 
26550b57cec5SDimitry Andric       return SafeToInline;
26560b57cec5SDimitry Andric     }
26570b57cec5SDimitry Andric 
26580b57cec5SDimitry Andric     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
26590b57cec5SDimitry Andric       if (const auto *D = E->getTemporary()->getDestructor())
26600b57cec5SDimitry Andric         SafeToInline = D->hasAttr<DLLImportAttr>();
26610b57cec5SDimitry Andric       return SafeToInline;
26620b57cec5SDimitry Andric     }
26630b57cec5SDimitry Andric 
26640b57cec5SDimitry Andric     bool VisitDeclRefExpr(DeclRefExpr *E) {
26650b57cec5SDimitry Andric       ValueDecl *VD = E->getDecl();
26660b57cec5SDimitry Andric       if (isa<FunctionDecl>(VD))
26670b57cec5SDimitry Andric         SafeToInline = VD->hasAttr<DLLImportAttr>();
26680b57cec5SDimitry Andric       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
26690b57cec5SDimitry Andric         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
26700b57cec5SDimitry Andric       return SafeToInline;
26710b57cec5SDimitry Andric     }
26720b57cec5SDimitry Andric 
26730b57cec5SDimitry Andric     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
26740b57cec5SDimitry Andric       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
26750b57cec5SDimitry Andric       return SafeToInline;
26760b57cec5SDimitry Andric     }
26770b57cec5SDimitry Andric 
26780b57cec5SDimitry Andric     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
26790b57cec5SDimitry Andric       CXXMethodDecl *M = E->getMethodDecl();
26800b57cec5SDimitry Andric       if (!M) {
26810b57cec5SDimitry Andric         // Call through a pointer to member function. This is safe to inline.
26820b57cec5SDimitry Andric         SafeToInline = true;
26830b57cec5SDimitry Andric       } else {
26840b57cec5SDimitry Andric         SafeToInline = M->hasAttr<DLLImportAttr>();
26850b57cec5SDimitry Andric       }
26860b57cec5SDimitry Andric       return SafeToInline;
26870b57cec5SDimitry Andric     }
26880b57cec5SDimitry Andric 
26890b57cec5SDimitry Andric     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
26900b57cec5SDimitry Andric       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
26910b57cec5SDimitry Andric       return SafeToInline;
26920b57cec5SDimitry Andric     }
26930b57cec5SDimitry Andric 
26940b57cec5SDimitry Andric     bool VisitCXXNewExpr(CXXNewExpr *E) {
26950b57cec5SDimitry Andric       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
26960b57cec5SDimitry Andric       return SafeToInline;
26970b57cec5SDimitry Andric     }
26980b57cec5SDimitry Andric   };
26990b57cec5SDimitry Andric }
27000b57cec5SDimitry Andric 
27010b57cec5SDimitry Andric // isTriviallyRecursive - Check if this function calls another
27020b57cec5SDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin,
27030b57cec5SDimitry Andric // ends up pointing to itself.
27040b57cec5SDimitry Andric bool
27050b57cec5SDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
27060b57cec5SDimitry Andric   StringRef Name;
27070b57cec5SDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
27080b57cec5SDimitry Andric     // asm labels are a special kind of mangling we have to support.
27090b57cec5SDimitry Andric     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
27100b57cec5SDimitry Andric     if (!Attr)
27110b57cec5SDimitry Andric       return false;
27120b57cec5SDimitry Andric     Name = Attr->getLabel();
27130b57cec5SDimitry Andric   } else {
27140b57cec5SDimitry Andric     Name = FD->getName();
27150b57cec5SDimitry Andric   }
27160b57cec5SDimitry Andric 
27170b57cec5SDimitry Andric   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
27180b57cec5SDimitry Andric   const Stmt *Body = FD->getBody();
27190b57cec5SDimitry Andric   return Body ? Walker.Visit(Body) : false;
27200b57cec5SDimitry Andric }
27210b57cec5SDimitry Andric 
27220b57cec5SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
27230b57cec5SDimitry Andric   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
27240b57cec5SDimitry Andric     return true;
27250b57cec5SDimitry Andric   const auto *F = cast<FunctionDecl>(GD.getDecl());
27260b57cec5SDimitry Andric   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
27270b57cec5SDimitry Andric     return false;
27280b57cec5SDimitry Andric 
27290b57cec5SDimitry Andric   if (F->hasAttr<DLLImportAttr>()) {
27300b57cec5SDimitry Andric     // Check whether it would be safe to inline this dllimport function.
27310b57cec5SDimitry Andric     DLLImportFunctionVisitor Visitor;
27320b57cec5SDimitry Andric     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
27330b57cec5SDimitry Andric     if (!Visitor.SafeToInline)
27340b57cec5SDimitry Andric       return false;
27350b57cec5SDimitry Andric 
27360b57cec5SDimitry Andric     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
27370b57cec5SDimitry Andric       // Implicit destructor invocations aren't captured in the AST, so the
27380b57cec5SDimitry Andric       // check above can't see them. Check for them manually here.
27390b57cec5SDimitry Andric       for (const Decl *Member : Dtor->getParent()->decls())
27400b57cec5SDimitry Andric         if (isa<FieldDecl>(Member))
27410b57cec5SDimitry Andric           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
27420b57cec5SDimitry Andric             return false;
27430b57cec5SDimitry Andric       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
27440b57cec5SDimitry Andric         if (HasNonDllImportDtor(B.getType()))
27450b57cec5SDimitry Andric           return false;
27460b57cec5SDimitry Andric     }
27470b57cec5SDimitry Andric   }
27480b57cec5SDimitry Andric 
27490b57cec5SDimitry Andric   // PR9614. Avoid cases where the source code is lying to us. An available
27500b57cec5SDimitry Andric   // externally function should have an equivalent function somewhere else,
27510b57cec5SDimitry Andric   // but a function that calls itself is clearly not equivalent to the real
27520b57cec5SDimitry Andric   // implementation.
27530b57cec5SDimitry Andric   // This happens in glibc's btowc and in some configure checks.
27540b57cec5SDimitry Andric   return !isTriviallyRecursive(F);
27550b57cec5SDimitry Andric }
27560b57cec5SDimitry Andric 
27570b57cec5SDimitry Andric bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
27580b57cec5SDimitry Andric   return CodeGenOpts.OptimizationLevel > 0;
27590b57cec5SDimitry Andric }
27600b57cec5SDimitry Andric 
27610b57cec5SDimitry Andric void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
27620b57cec5SDimitry Andric                                                        llvm::GlobalValue *GV) {
27630b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
27640b57cec5SDimitry Andric 
27650b57cec5SDimitry Andric   if (FD->isCPUSpecificMultiVersion()) {
27660b57cec5SDimitry Andric     auto *Spec = FD->getAttr<CPUSpecificAttr>();
27670b57cec5SDimitry Andric     for (unsigned I = 0; I < Spec->cpus_size(); ++I)
27680b57cec5SDimitry Andric       EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
27690b57cec5SDimitry Andric     // Requires multiple emits.
27700b57cec5SDimitry Andric   } else
27710b57cec5SDimitry Andric     EmitGlobalFunctionDefinition(GD, GV);
27720b57cec5SDimitry Andric }
27730b57cec5SDimitry Andric 
2774a7dea167SDimitry Andric void CodeGenModule::emitOpenMPDeviceFunctionRedefinition(
2775a7dea167SDimitry Andric     GlobalDecl OldGD, GlobalDecl NewGD, llvm::GlobalValue *GV) {
2776a7dea167SDimitry Andric   assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2777a7dea167SDimitry Andric          OpenMPRuntime && "Expected OpenMP device mode.");
2778a7dea167SDimitry Andric   const auto *D = cast<FunctionDecl>(OldGD.getDecl());
2779a7dea167SDimitry Andric 
2780a7dea167SDimitry Andric   // Compute the function info and LLVM type.
2781a7dea167SDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(OldGD);
2782a7dea167SDimitry Andric   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2783a7dea167SDimitry Andric 
2784a7dea167SDimitry Andric   // Get or create the prototype for the function.
2785a7dea167SDimitry Andric   if (!GV || (GV->getType()->getElementType() != Ty)) {
2786a7dea167SDimitry Andric     GV = cast<llvm::GlobalValue>(GetOrCreateLLVMFunction(
2787a7dea167SDimitry Andric         getMangledName(OldGD), Ty, GlobalDecl(), /*ForVTable=*/false,
2788a7dea167SDimitry Andric         /*DontDefer=*/true, /*IsThunk=*/false, llvm::AttributeList(),
2789a7dea167SDimitry Andric         ForDefinition));
2790a7dea167SDimitry Andric     SetFunctionAttributes(OldGD, cast<llvm::Function>(GV),
2791a7dea167SDimitry Andric                           /*IsIncompleteFunction=*/false,
2792a7dea167SDimitry Andric                           /*IsThunk=*/false);
2793a7dea167SDimitry Andric   }
2794a7dea167SDimitry Andric   // We need to set linkage and visibility on the function before
2795a7dea167SDimitry Andric   // generating code for it because various parts of IR generation
2796a7dea167SDimitry Andric   // want to propagate this information down (e.g. to local static
2797a7dea167SDimitry Andric   // declarations).
2798a7dea167SDimitry Andric   auto *Fn = cast<llvm::Function>(GV);
2799a7dea167SDimitry Andric   setFunctionLinkage(OldGD, Fn);
2800a7dea167SDimitry Andric 
2801a7dea167SDimitry Andric   // FIXME: this is redundant with part of
2802a7dea167SDimitry Andric   // setFunctionDefinitionAttributes
2803a7dea167SDimitry Andric   setGVProperties(Fn, OldGD);
2804a7dea167SDimitry Andric 
2805a7dea167SDimitry Andric   MaybeHandleStaticInExternC(D, Fn);
2806a7dea167SDimitry Andric 
2807a7dea167SDimitry Andric   maybeSetTrivialComdat(*D, *Fn);
2808a7dea167SDimitry Andric 
2809a7dea167SDimitry Andric   CodeGenFunction(*this).GenerateCode(NewGD, Fn, FI);
2810a7dea167SDimitry Andric 
2811a7dea167SDimitry Andric   setNonAliasAttributes(OldGD, Fn);
2812a7dea167SDimitry Andric   SetLLVMFunctionAttributesForDefinition(D, Fn);
2813a7dea167SDimitry Andric 
2814a7dea167SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
2815a7dea167SDimitry Andric     AddGlobalAnnotations(D, Fn);
2816a7dea167SDimitry Andric }
2817a7dea167SDimitry Andric 
28180b57cec5SDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
28190b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
28200b57cec5SDimitry Andric 
28210b57cec5SDimitry Andric   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
28220b57cec5SDimitry Andric                                  Context.getSourceManager(),
28230b57cec5SDimitry Andric                                  "Generating code for declaration");
28240b57cec5SDimitry Andric 
28250b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
28260b57cec5SDimitry Andric     // At -O0, don't generate IR for functions with available_externally
28270b57cec5SDimitry Andric     // linkage.
28280b57cec5SDimitry Andric     if (!shouldEmitFunction(GD))
28290b57cec5SDimitry Andric       return;
28300b57cec5SDimitry Andric 
28310b57cec5SDimitry Andric     llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
28320b57cec5SDimitry Andric       std::string Name;
28330b57cec5SDimitry Andric       llvm::raw_string_ostream OS(Name);
28340b57cec5SDimitry Andric       FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
28350b57cec5SDimitry Andric                                /*Qualified=*/true);
28360b57cec5SDimitry Andric       return Name;
28370b57cec5SDimitry Andric     });
28380b57cec5SDimitry Andric 
28390b57cec5SDimitry Andric     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
28400b57cec5SDimitry Andric       // Make sure to emit the definition(s) before we emit the thunks.
28410b57cec5SDimitry Andric       // This is necessary for the generation of certain thunks.
28420b57cec5SDimitry Andric       if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
28430b57cec5SDimitry Andric         ABI->emitCXXStructor(GD);
28440b57cec5SDimitry Andric       else if (FD->isMultiVersion())
28450b57cec5SDimitry Andric         EmitMultiVersionFunctionDefinition(GD, GV);
28460b57cec5SDimitry Andric       else
28470b57cec5SDimitry Andric         EmitGlobalFunctionDefinition(GD, GV);
28480b57cec5SDimitry Andric 
28490b57cec5SDimitry Andric       if (Method->isVirtual())
28500b57cec5SDimitry Andric         getVTables().EmitThunks(GD);
28510b57cec5SDimitry Andric 
28520b57cec5SDimitry Andric       return;
28530b57cec5SDimitry Andric     }
28540b57cec5SDimitry Andric 
28550b57cec5SDimitry Andric     if (FD->isMultiVersion())
28560b57cec5SDimitry Andric       return EmitMultiVersionFunctionDefinition(GD, GV);
28570b57cec5SDimitry Andric     return EmitGlobalFunctionDefinition(GD, GV);
28580b57cec5SDimitry Andric   }
28590b57cec5SDimitry Andric 
28600b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
28610b57cec5SDimitry Andric     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
28620b57cec5SDimitry Andric 
28630b57cec5SDimitry Andric   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
28640b57cec5SDimitry Andric }
28650b57cec5SDimitry Andric 
28660b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
28670b57cec5SDimitry Andric                                                       llvm::Function *NewFn);
28680b57cec5SDimitry Andric 
28690b57cec5SDimitry Andric static unsigned
28700b57cec5SDimitry Andric TargetMVPriority(const TargetInfo &TI,
28710b57cec5SDimitry Andric                  const CodeGenFunction::MultiVersionResolverOption &RO) {
28720b57cec5SDimitry Andric   unsigned Priority = 0;
28730b57cec5SDimitry Andric   for (StringRef Feat : RO.Conditions.Features)
28740b57cec5SDimitry Andric     Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
28750b57cec5SDimitry Andric 
28760b57cec5SDimitry Andric   if (!RO.Conditions.Architecture.empty())
28770b57cec5SDimitry Andric     Priority = std::max(
28780b57cec5SDimitry Andric         Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
28790b57cec5SDimitry Andric   return Priority;
28800b57cec5SDimitry Andric }
28810b57cec5SDimitry Andric 
28820b57cec5SDimitry Andric void CodeGenModule::emitMultiVersionFunctions() {
28830b57cec5SDimitry Andric   for (GlobalDecl GD : MultiVersionFuncs) {
28840b57cec5SDimitry Andric     SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
28850b57cec5SDimitry Andric     const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
28860b57cec5SDimitry Andric     getContext().forEachMultiversionedFunctionVersion(
28870b57cec5SDimitry Andric         FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
28880b57cec5SDimitry Andric           GlobalDecl CurGD{
28890b57cec5SDimitry Andric               (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
28900b57cec5SDimitry Andric           StringRef MangledName = getMangledName(CurGD);
28910b57cec5SDimitry Andric           llvm::Constant *Func = GetGlobalValue(MangledName);
28920b57cec5SDimitry Andric           if (!Func) {
28930b57cec5SDimitry Andric             if (CurFD->isDefined()) {
28940b57cec5SDimitry Andric               EmitGlobalFunctionDefinition(CurGD, nullptr);
28950b57cec5SDimitry Andric               Func = GetGlobalValue(MangledName);
28960b57cec5SDimitry Andric             } else {
28970b57cec5SDimitry Andric               const CGFunctionInfo &FI =
28980b57cec5SDimitry Andric                   getTypes().arrangeGlobalDeclaration(GD);
28990b57cec5SDimitry Andric               llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
29000b57cec5SDimitry Andric               Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
29010b57cec5SDimitry Andric                                        /*DontDefer=*/false, ForDefinition);
29020b57cec5SDimitry Andric             }
29030b57cec5SDimitry Andric             assert(Func && "This should have just been created");
29040b57cec5SDimitry Andric           }
29050b57cec5SDimitry Andric 
29060b57cec5SDimitry Andric           const auto *TA = CurFD->getAttr<TargetAttr>();
29070b57cec5SDimitry Andric           llvm::SmallVector<StringRef, 8> Feats;
29080b57cec5SDimitry Andric           TA->getAddedFeatures(Feats);
29090b57cec5SDimitry Andric 
29100b57cec5SDimitry Andric           Options.emplace_back(cast<llvm::Function>(Func),
29110b57cec5SDimitry Andric                                TA->getArchitecture(), Feats);
29120b57cec5SDimitry Andric         });
29130b57cec5SDimitry Andric 
29140b57cec5SDimitry Andric     llvm::Function *ResolverFunc;
29150b57cec5SDimitry Andric     const TargetInfo &TI = getTarget();
29160b57cec5SDimitry Andric 
2917a7dea167SDimitry Andric     if (TI.supportsIFunc() || FD->isTargetMultiVersion()) {
29180b57cec5SDimitry Andric       ResolverFunc = cast<llvm::Function>(
29190b57cec5SDimitry Andric           GetGlobalValue((getMangledName(GD) + ".resolver").str()));
2920a7dea167SDimitry Andric       ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
2921a7dea167SDimitry Andric     } else {
29220b57cec5SDimitry Andric       ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
2923a7dea167SDimitry Andric     }
29240b57cec5SDimitry Andric 
29250b57cec5SDimitry Andric     if (supportsCOMDAT())
29260b57cec5SDimitry Andric       ResolverFunc->setComdat(
29270b57cec5SDimitry Andric           getModule().getOrInsertComdat(ResolverFunc->getName()));
29280b57cec5SDimitry Andric 
29290b57cec5SDimitry Andric     llvm::stable_sort(
29300b57cec5SDimitry Andric         Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
29310b57cec5SDimitry Andric                        const CodeGenFunction::MultiVersionResolverOption &RHS) {
29320b57cec5SDimitry Andric           return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
29330b57cec5SDimitry Andric         });
29340b57cec5SDimitry Andric     CodeGenFunction CGF(*this);
29350b57cec5SDimitry Andric     CGF.EmitMultiVersionResolver(ResolverFunc, Options);
29360b57cec5SDimitry Andric   }
29370b57cec5SDimitry Andric }
29380b57cec5SDimitry Andric 
29390b57cec5SDimitry Andric void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
29400b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
29410b57cec5SDimitry Andric   assert(FD && "Not a FunctionDecl?");
29420b57cec5SDimitry Andric   const auto *DD = FD->getAttr<CPUDispatchAttr>();
29430b57cec5SDimitry Andric   assert(DD && "Not a cpu_dispatch Function?");
29440b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
29450b57cec5SDimitry Andric 
29460b57cec5SDimitry Andric   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
29470b57cec5SDimitry Andric     const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
29480b57cec5SDimitry Andric     DeclTy = getTypes().GetFunctionType(FInfo);
29490b57cec5SDimitry Andric   }
29500b57cec5SDimitry Andric 
29510b57cec5SDimitry Andric   StringRef ResolverName = getMangledName(GD);
29520b57cec5SDimitry Andric 
29530b57cec5SDimitry Andric   llvm::Type *ResolverType;
29540b57cec5SDimitry Andric   GlobalDecl ResolverGD;
29550b57cec5SDimitry Andric   if (getTarget().supportsIFunc())
29560b57cec5SDimitry Andric     ResolverType = llvm::FunctionType::get(
29570b57cec5SDimitry Andric         llvm::PointerType::get(DeclTy,
29580b57cec5SDimitry Andric                                Context.getTargetAddressSpace(FD->getType())),
29590b57cec5SDimitry Andric         false);
29600b57cec5SDimitry Andric   else {
29610b57cec5SDimitry Andric     ResolverType = DeclTy;
29620b57cec5SDimitry Andric     ResolverGD = GD;
29630b57cec5SDimitry Andric   }
29640b57cec5SDimitry Andric 
29650b57cec5SDimitry Andric   auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
29660b57cec5SDimitry Andric       ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
2967a7dea167SDimitry Andric   ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
2968a7dea167SDimitry Andric   if (supportsCOMDAT())
2969a7dea167SDimitry Andric     ResolverFunc->setComdat(
2970a7dea167SDimitry Andric         getModule().getOrInsertComdat(ResolverFunc->getName()));
29710b57cec5SDimitry Andric 
29720b57cec5SDimitry Andric   SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
29730b57cec5SDimitry Andric   const TargetInfo &Target = getTarget();
29740b57cec5SDimitry Andric   unsigned Index = 0;
29750b57cec5SDimitry Andric   for (const IdentifierInfo *II : DD->cpus()) {
29760b57cec5SDimitry Andric     // Get the name of the target function so we can look it up/create it.
29770b57cec5SDimitry Andric     std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
29780b57cec5SDimitry Andric                               getCPUSpecificMangling(*this, II->getName());
29790b57cec5SDimitry Andric 
29800b57cec5SDimitry Andric     llvm::Constant *Func = GetGlobalValue(MangledName);
29810b57cec5SDimitry Andric 
29820b57cec5SDimitry Andric     if (!Func) {
29830b57cec5SDimitry Andric       GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
29840b57cec5SDimitry Andric       if (ExistingDecl.getDecl() &&
29850b57cec5SDimitry Andric           ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
29860b57cec5SDimitry Andric         EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
29870b57cec5SDimitry Andric         Func = GetGlobalValue(MangledName);
29880b57cec5SDimitry Andric       } else {
29890b57cec5SDimitry Andric         if (!ExistingDecl.getDecl())
29900b57cec5SDimitry Andric           ExistingDecl = GD.getWithMultiVersionIndex(Index);
29910b57cec5SDimitry Andric 
29920b57cec5SDimitry Andric       Func = GetOrCreateLLVMFunction(
29930b57cec5SDimitry Andric           MangledName, DeclTy, ExistingDecl,
29940b57cec5SDimitry Andric           /*ForVTable=*/false, /*DontDefer=*/true,
29950b57cec5SDimitry Andric           /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
29960b57cec5SDimitry Andric       }
29970b57cec5SDimitry Andric     }
29980b57cec5SDimitry Andric 
29990b57cec5SDimitry Andric     llvm::SmallVector<StringRef, 32> Features;
30000b57cec5SDimitry Andric     Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
30010b57cec5SDimitry Andric     llvm::transform(Features, Features.begin(),
30020b57cec5SDimitry Andric                     [](StringRef Str) { return Str.substr(1); });
30030b57cec5SDimitry Andric     Features.erase(std::remove_if(
30040b57cec5SDimitry Andric         Features.begin(), Features.end(), [&Target](StringRef Feat) {
30050b57cec5SDimitry Andric           return !Target.validateCpuSupports(Feat);
30060b57cec5SDimitry Andric         }), Features.end());
30070b57cec5SDimitry Andric     Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
30080b57cec5SDimitry Andric     ++Index;
30090b57cec5SDimitry Andric   }
30100b57cec5SDimitry Andric 
30110b57cec5SDimitry Andric   llvm::sort(
30120b57cec5SDimitry Andric       Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
30130b57cec5SDimitry Andric                   const CodeGenFunction::MultiVersionResolverOption &RHS) {
30140b57cec5SDimitry Andric         return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
30150b57cec5SDimitry Andric                CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
30160b57cec5SDimitry Andric       });
30170b57cec5SDimitry Andric 
30180b57cec5SDimitry Andric   // If the list contains multiple 'default' versions, such as when it contains
30190b57cec5SDimitry Andric   // 'pentium' and 'generic', don't emit the call to the generic one (since we
30200b57cec5SDimitry Andric   // always run on at least a 'pentium'). We do this by deleting the 'least
30210b57cec5SDimitry Andric   // advanced' (read, lowest mangling letter).
30220b57cec5SDimitry Andric   while (Options.size() > 1 &&
30230b57cec5SDimitry Andric          CodeGenFunction::GetX86CpuSupportsMask(
30240b57cec5SDimitry Andric              (Options.end() - 2)->Conditions.Features) == 0) {
30250b57cec5SDimitry Andric     StringRef LHSName = (Options.end() - 2)->Function->getName();
30260b57cec5SDimitry Andric     StringRef RHSName = (Options.end() - 1)->Function->getName();
30270b57cec5SDimitry Andric     if (LHSName.compare(RHSName) < 0)
30280b57cec5SDimitry Andric       Options.erase(Options.end() - 2);
30290b57cec5SDimitry Andric     else
30300b57cec5SDimitry Andric       Options.erase(Options.end() - 1);
30310b57cec5SDimitry Andric   }
30320b57cec5SDimitry Andric 
30330b57cec5SDimitry Andric   CodeGenFunction CGF(*this);
30340b57cec5SDimitry Andric   CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3035a7dea167SDimitry Andric 
3036a7dea167SDimitry Andric   if (getTarget().supportsIFunc()) {
3037a7dea167SDimitry Andric     std::string AliasName = getMangledNameImpl(
3038a7dea167SDimitry Andric         *this, GD, FD, /*OmitMultiVersionMangling=*/true);
3039a7dea167SDimitry Andric     llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
3040a7dea167SDimitry Andric     if (!AliasFunc) {
3041a7dea167SDimitry Andric       auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction(
3042a7dea167SDimitry Andric           AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true,
3043a7dea167SDimitry Andric           /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition));
3044a7dea167SDimitry Andric       auto *GA = llvm::GlobalAlias::create(
3045a7dea167SDimitry Andric          DeclTy, 0, getFunctionLinkage(GD), AliasName, IFunc, &getModule());
3046a7dea167SDimitry Andric       GA->setLinkage(llvm::Function::WeakODRLinkage);
3047a7dea167SDimitry Andric       SetCommonAttributes(GD, GA);
3048a7dea167SDimitry Andric     }
3049a7dea167SDimitry Andric   }
30500b57cec5SDimitry Andric }
30510b57cec5SDimitry Andric 
30520b57cec5SDimitry Andric /// If a dispatcher for the specified mangled name is not in the module, create
30530b57cec5SDimitry Andric /// and return an llvm Function with the specified type.
30540b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
30550b57cec5SDimitry Andric     GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
30560b57cec5SDimitry Andric   std::string MangledName =
30570b57cec5SDimitry Andric       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
30580b57cec5SDimitry Andric 
30590b57cec5SDimitry Andric   // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
30600b57cec5SDimitry Andric   // a separate resolver).
30610b57cec5SDimitry Andric   std::string ResolverName = MangledName;
30620b57cec5SDimitry Andric   if (getTarget().supportsIFunc())
30630b57cec5SDimitry Andric     ResolverName += ".ifunc";
30640b57cec5SDimitry Andric   else if (FD->isTargetMultiVersion())
30650b57cec5SDimitry Andric     ResolverName += ".resolver";
30660b57cec5SDimitry Andric 
30670b57cec5SDimitry Andric   // If this already exists, just return that one.
30680b57cec5SDimitry Andric   if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
30690b57cec5SDimitry Andric     return ResolverGV;
30700b57cec5SDimitry Andric 
30710b57cec5SDimitry Andric   // Since this is the first time we've created this IFunc, make sure
30720b57cec5SDimitry Andric   // that we put this multiversioned function into the list to be
30730b57cec5SDimitry Andric   // replaced later if necessary (target multiversioning only).
30740b57cec5SDimitry Andric   if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
30750b57cec5SDimitry Andric     MultiVersionFuncs.push_back(GD);
30760b57cec5SDimitry Andric 
30770b57cec5SDimitry Andric   if (getTarget().supportsIFunc()) {
30780b57cec5SDimitry Andric     llvm::Type *ResolverType = llvm::FunctionType::get(
30790b57cec5SDimitry Andric         llvm::PointerType::get(
30800b57cec5SDimitry Andric             DeclTy, getContext().getTargetAddressSpace(FD->getType())),
30810b57cec5SDimitry Andric         false);
30820b57cec5SDimitry Andric     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
30830b57cec5SDimitry Andric         MangledName + ".resolver", ResolverType, GlobalDecl{},
30840b57cec5SDimitry Andric         /*ForVTable=*/false);
30850b57cec5SDimitry Andric     llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
3086a7dea167SDimitry Andric         DeclTy, 0, llvm::Function::WeakODRLinkage, "", Resolver, &getModule());
30870b57cec5SDimitry Andric     GIF->setName(ResolverName);
30880b57cec5SDimitry Andric     SetCommonAttributes(FD, GIF);
30890b57cec5SDimitry Andric 
30900b57cec5SDimitry Andric     return GIF;
30910b57cec5SDimitry Andric   }
30920b57cec5SDimitry Andric 
30930b57cec5SDimitry Andric   llvm::Constant *Resolver = GetOrCreateLLVMFunction(
30940b57cec5SDimitry Andric       ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
30950b57cec5SDimitry Andric   assert(isa<llvm::GlobalValue>(Resolver) &&
30960b57cec5SDimitry Andric          "Resolver should be created for the first time");
30970b57cec5SDimitry Andric   SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
30980b57cec5SDimitry Andric   return Resolver;
30990b57cec5SDimitry Andric }
31000b57cec5SDimitry Andric 
31010b57cec5SDimitry Andric /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
31020b57cec5SDimitry Andric /// module, create and return an llvm Function with the specified type. If there
31030b57cec5SDimitry Andric /// is something in the module with the specified name, return it potentially
31040b57cec5SDimitry Andric /// bitcasted to the right type.
31050b57cec5SDimitry Andric ///
31060b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this.  This is used
31070b57cec5SDimitry Andric /// to set the attributes on the function when it is first created.
31080b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
31090b57cec5SDimitry Andric     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
31100b57cec5SDimitry Andric     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
31110b57cec5SDimitry Andric     ForDefinition_t IsForDefinition) {
31120b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
31130b57cec5SDimitry Andric 
31140b57cec5SDimitry Andric   // Any attempts to use a MultiVersion function should result in retrieving
31150b57cec5SDimitry Andric   // the iFunc instead. Name Mangling will handle the rest of the changes.
31160b57cec5SDimitry Andric   if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
31170b57cec5SDimitry Andric     // For the device mark the function as one that should be emitted.
31180b57cec5SDimitry Andric     if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
31190b57cec5SDimitry Andric         !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
31200b57cec5SDimitry Andric         !DontDefer && !IsForDefinition) {
31210b57cec5SDimitry Andric       if (const FunctionDecl *FDDef = FD->getDefinition()) {
31220b57cec5SDimitry Andric         GlobalDecl GDDef;
31230b57cec5SDimitry Andric         if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
31240b57cec5SDimitry Andric           GDDef = GlobalDecl(CD, GD.getCtorType());
31250b57cec5SDimitry Andric         else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
31260b57cec5SDimitry Andric           GDDef = GlobalDecl(DD, GD.getDtorType());
31270b57cec5SDimitry Andric         else
31280b57cec5SDimitry Andric           GDDef = GlobalDecl(FDDef);
31290b57cec5SDimitry Andric         EmitGlobal(GDDef);
31300b57cec5SDimitry Andric       }
31310b57cec5SDimitry Andric     }
3132a7dea167SDimitry Andric     // Check if this must be emitted as declare variant and emit reference to
3133a7dea167SDimitry Andric     // the the declare variant function.
3134a7dea167SDimitry Andric     if (LangOpts.OpenMP && OpenMPRuntime)
3135a7dea167SDimitry Andric       (void)OpenMPRuntime->emitDeclareVariant(GD, /*IsForDefinition=*/true);
31360b57cec5SDimitry Andric 
31370b57cec5SDimitry Andric     if (FD->isMultiVersion()) {
31380b57cec5SDimitry Andric       const auto *TA = FD->getAttr<TargetAttr>();
31390b57cec5SDimitry Andric       if (TA && TA->isDefaultVersion())
31400b57cec5SDimitry Andric         UpdateMultiVersionNames(GD, FD);
31410b57cec5SDimitry Andric       if (!IsForDefinition)
31420b57cec5SDimitry Andric         return GetOrCreateMultiVersionResolver(GD, Ty, FD);
31430b57cec5SDimitry Andric     }
31440b57cec5SDimitry Andric   }
31450b57cec5SDimitry Andric 
31460b57cec5SDimitry Andric   // Lookup the entry, lazily creating it if necessary.
31470b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
31480b57cec5SDimitry Andric   if (Entry) {
31490b57cec5SDimitry Andric     if (WeakRefReferences.erase(Entry)) {
31500b57cec5SDimitry Andric       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
31510b57cec5SDimitry Andric       if (FD && !FD->hasAttr<WeakAttr>())
31520b57cec5SDimitry Andric         Entry->setLinkage(llvm::Function::ExternalLinkage);
31530b57cec5SDimitry Andric     }
31540b57cec5SDimitry Andric 
31550b57cec5SDimitry Andric     // Handle dropped DLL attributes.
31560b57cec5SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
31570b57cec5SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
31580b57cec5SDimitry Andric       setDSOLocal(Entry);
31590b57cec5SDimitry Andric     }
31600b57cec5SDimitry Andric 
31610b57cec5SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
31620b57cec5SDimitry Andric     // error.
31630b57cec5SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
31640b57cec5SDimitry Andric       GlobalDecl OtherGD;
31650b57cec5SDimitry Andric       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
31660b57cec5SDimitry Andric       // to make sure that we issue an error only once.
31670b57cec5SDimitry Andric       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
31680b57cec5SDimitry Andric           (GD.getCanonicalDecl().getDecl() !=
31690b57cec5SDimitry Andric            OtherGD.getCanonicalDecl().getDecl()) &&
31700b57cec5SDimitry Andric           DiagnosedConflictingDefinitions.insert(GD).second) {
31710b57cec5SDimitry Andric         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
31720b57cec5SDimitry Andric             << MangledName;
31730b57cec5SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
31740b57cec5SDimitry Andric                           diag::note_previous_definition);
31750b57cec5SDimitry Andric       }
31760b57cec5SDimitry Andric     }
31770b57cec5SDimitry Andric 
31780b57cec5SDimitry Andric     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
31790b57cec5SDimitry Andric         (Entry->getType()->getElementType() == Ty)) {
31800b57cec5SDimitry Andric       return Entry;
31810b57cec5SDimitry Andric     }
31820b57cec5SDimitry Andric 
31830b57cec5SDimitry Andric     // Make sure the result is of the correct type.
31840b57cec5SDimitry Andric     // (If function is requested for a definition, we always need to create a new
31850b57cec5SDimitry Andric     // function, not just return a bitcast.)
31860b57cec5SDimitry Andric     if (!IsForDefinition)
31870b57cec5SDimitry Andric       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
31880b57cec5SDimitry Andric   }
31890b57cec5SDimitry Andric 
31900b57cec5SDimitry Andric   // This function doesn't have a complete type (for example, the return
31910b57cec5SDimitry Andric   // type is an incomplete struct). Use a fake type instead, and make
31920b57cec5SDimitry Andric   // sure not to try to set attributes.
31930b57cec5SDimitry Andric   bool IsIncompleteFunction = false;
31940b57cec5SDimitry Andric 
31950b57cec5SDimitry Andric   llvm::FunctionType *FTy;
31960b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(Ty)) {
31970b57cec5SDimitry Andric     FTy = cast<llvm::FunctionType>(Ty);
31980b57cec5SDimitry Andric   } else {
31990b57cec5SDimitry Andric     FTy = llvm::FunctionType::get(VoidTy, false);
32000b57cec5SDimitry Andric     IsIncompleteFunction = true;
32010b57cec5SDimitry Andric   }
32020b57cec5SDimitry Andric 
32030b57cec5SDimitry Andric   llvm::Function *F =
32040b57cec5SDimitry Andric       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
32050b57cec5SDimitry Andric                              Entry ? StringRef() : MangledName, &getModule());
32060b57cec5SDimitry Andric 
32070b57cec5SDimitry Andric   // If we already created a function with the same mangled name (but different
32080b57cec5SDimitry Andric   // type) before, take its name and add it to the list of functions to be
32090b57cec5SDimitry Andric   // replaced with F at the end of CodeGen.
32100b57cec5SDimitry Andric   //
32110b57cec5SDimitry Andric   // This happens if there is a prototype for a function (e.g. "int f()") and
32120b57cec5SDimitry Andric   // then a definition of a different type (e.g. "int f(int x)").
32130b57cec5SDimitry Andric   if (Entry) {
32140b57cec5SDimitry Andric     F->takeName(Entry);
32150b57cec5SDimitry Andric 
32160b57cec5SDimitry Andric     // This might be an implementation of a function without a prototype, in
32170b57cec5SDimitry Andric     // which case, try to do special replacement of calls which match the new
32180b57cec5SDimitry Andric     // prototype.  The really key thing here is that we also potentially drop
32190b57cec5SDimitry Andric     // arguments from the call site so as to make a direct call, which makes the
32200b57cec5SDimitry Andric     // inliner happier and suppresses a number of optimizer warnings (!) about
32210b57cec5SDimitry Andric     // dropping arguments.
32220b57cec5SDimitry Andric     if (!Entry->use_empty()) {
32230b57cec5SDimitry Andric       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
32240b57cec5SDimitry Andric       Entry->removeDeadConstantUsers();
32250b57cec5SDimitry Andric     }
32260b57cec5SDimitry Andric 
32270b57cec5SDimitry Andric     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
32280b57cec5SDimitry Andric         F, Entry->getType()->getElementType()->getPointerTo());
32290b57cec5SDimitry Andric     addGlobalValReplacement(Entry, BC);
32300b57cec5SDimitry Andric   }
32310b57cec5SDimitry Andric 
32320b57cec5SDimitry Andric   assert(F->getName() == MangledName && "name was uniqued!");
32330b57cec5SDimitry Andric   if (D)
32340b57cec5SDimitry Andric     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
32350b57cec5SDimitry Andric   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
32360b57cec5SDimitry Andric     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
32370b57cec5SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
32380b57cec5SDimitry Andric   }
32390b57cec5SDimitry Andric 
32400b57cec5SDimitry Andric   if (!DontDefer) {
32410b57cec5SDimitry Andric     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
32420b57cec5SDimitry Andric     // each other bottoming out with the base dtor.  Therefore we emit non-base
32430b57cec5SDimitry Andric     // dtors on usage, even if there is no dtor definition in the TU.
32440b57cec5SDimitry Andric     if (D && isa<CXXDestructorDecl>(D) &&
32450b57cec5SDimitry Andric         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
32460b57cec5SDimitry Andric                                            GD.getDtorType()))
32470b57cec5SDimitry Andric       addDeferredDeclToEmit(GD);
32480b57cec5SDimitry Andric 
32490b57cec5SDimitry Andric     // This is the first use or definition of a mangled name.  If there is a
32500b57cec5SDimitry Andric     // deferred decl with this name, remember that we need to emit it at the end
32510b57cec5SDimitry Andric     // of the file.
32520b57cec5SDimitry Andric     auto DDI = DeferredDecls.find(MangledName);
32530b57cec5SDimitry Andric     if (DDI != DeferredDecls.end()) {
32540b57cec5SDimitry Andric       // Move the potentially referenced deferred decl to the
32550b57cec5SDimitry Andric       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
32560b57cec5SDimitry Andric       // don't need it anymore).
32570b57cec5SDimitry Andric       addDeferredDeclToEmit(DDI->second);
32580b57cec5SDimitry Andric       DeferredDecls.erase(DDI);
32590b57cec5SDimitry Andric 
32600b57cec5SDimitry Andric       // Otherwise, there are cases we have to worry about where we're
32610b57cec5SDimitry Andric       // using a declaration for which we must emit a definition but where
32620b57cec5SDimitry Andric       // we might not find a top-level definition:
32630b57cec5SDimitry Andric       //   - member functions defined inline in their classes
32640b57cec5SDimitry Andric       //   - friend functions defined inline in some class
32650b57cec5SDimitry Andric       //   - special member functions with implicit definitions
32660b57cec5SDimitry Andric       // If we ever change our AST traversal to walk into class methods,
32670b57cec5SDimitry Andric       // this will be unnecessary.
32680b57cec5SDimitry Andric       //
32690b57cec5SDimitry Andric       // We also don't emit a definition for a function if it's going to be an
32700b57cec5SDimitry Andric       // entry in a vtable, unless it's already marked as used.
32710b57cec5SDimitry Andric     } else if (getLangOpts().CPlusPlus && D) {
32720b57cec5SDimitry Andric       // Look for a declaration that's lexically in a record.
32730b57cec5SDimitry Andric       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
32740b57cec5SDimitry Andric            FD = FD->getPreviousDecl()) {
32750b57cec5SDimitry Andric         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
32760b57cec5SDimitry Andric           if (FD->doesThisDeclarationHaveABody()) {
32770b57cec5SDimitry Andric             addDeferredDeclToEmit(GD.getWithDecl(FD));
32780b57cec5SDimitry Andric             break;
32790b57cec5SDimitry Andric           }
32800b57cec5SDimitry Andric         }
32810b57cec5SDimitry Andric       }
32820b57cec5SDimitry Andric     }
32830b57cec5SDimitry Andric   }
32840b57cec5SDimitry Andric 
32850b57cec5SDimitry Andric   // Make sure the result is of the requested type.
32860b57cec5SDimitry Andric   if (!IsIncompleteFunction) {
32870b57cec5SDimitry Andric     assert(F->getType()->getElementType() == Ty);
32880b57cec5SDimitry Andric     return F;
32890b57cec5SDimitry Andric   }
32900b57cec5SDimitry Andric 
32910b57cec5SDimitry Andric   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
32920b57cec5SDimitry Andric   return llvm::ConstantExpr::getBitCast(F, PTy);
32930b57cec5SDimitry Andric }
32940b57cec5SDimitry Andric 
32950b57cec5SDimitry Andric /// GetAddrOfFunction - Return the address of the given function.  If Ty is
32960b57cec5SDimitry Andric /// non-null, then this function will use the specified type if it has to
32970b57cec5SDimitry Andric /// create it (this occurs when we see a definition of the function).
32980b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
32990b57cec5SDimitry Andric                                                  llvm::Type *Ty,
33000b57cec5SDimitry Andric                                                  bool ForVTable,
33010b57cec5SDimitry Andric                                                  bool DontDefer,
33020b57cec5SDimitry Andric                                               ForDefinition_t IsForDefinition) {
33030b57cec5SDimitry Andric   // If there was no specific requested type, just convert it now.
33040b57cec5SDimitry Andric   if (!Ty) {
33050b57cec5SDimitry Andric     const auto *FD = cast<FunctionDecl>(GD.getDecl());
33060b57cec5SDimitry Andric     Ty = getTypes().ConvertType(FD->getType());
33070b57cec5SDimitry Andric   }
33080b57cec5SDimitry Andric 
33090b57cec5SDimitry Andric   // Devirtualized destructor calls may come through here instead of via
33100b57cec5SDimitry Andric   // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
33110b57cec5SDimitry Andric   // of the complete destructor when necessary.
33120b57cec5SDimitry Andric   if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
33130b57cec5SDimitry Andric     if (getTarget().getCXXABI().isMicrosoft() &&
33140b57cec5SDimitry Andric         GD.getDtorType() == Dtor_Complete &&
33150b57cec5SDimitry Andric         DD->getParent()->getNumVBases() == 0)
33160b57cec5SDimitry Andric       GD = GlobalDecl(DD, Dtor_Base);
33170b57cec5SDimitry Andric   }
33180b57cec5SDimitry Andric 
33190b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
33200b57cec5SDimitry Andric   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
33210b57cec5SDimitry Andric                                  /*IsThunk=*/false, llvm::AttributeList(),
33220b57cec5SDimitry Andric                                  IsForDefinition);
33230b57cec5SDimitry Andric }
33240b57cec5SDimitry Andric 
33250b57cec5SDimitry Andric static const FunctionDecl *
33260b57cec5SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
33270b57cec5SDimitry Andric   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
33280b57cec5SDimitry Andric   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
33290b57cec5SDimitry Andric 
33300b57cec5SDimitry Andric   IdentifierInfo &CII = C.Idents.get(Name);
33310b57cec5SDimitry Andric   for (const auto &Result : DC->lookup(&CII))
33320b57cec5SDimitry Andric     if (const auto FD = dyn_cast<FunctionDecl>(Result))
33330b57cec5SDimitry Andric       return FD;
33340b57cec5SDimitry Andric 
33350b57cec5SDimitry Andric   if (!C.getLangOpts().CPlusPlus)
33360b57cec5SDimitry Andric     return nullptr;
33370b57cec5SDimitry Andric 
33380b57cec5SDimitry Andric   // Demangle the premangled name from getTerminateFn()
33390b57cec5SDimitry Andric   IdentifierInfo &CXXII =
33400b57cec5SDimitry Andric       (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
33410b57cec5SDimitry Andric           ? C.Idents.get("terminate")
33420b57cec5SDimitry Andric           : C.Idents.get(Name);
33430b57cec5SDimitry Andric 
33440b57cec5SDimitry Andric   for (const auto &N : {"__cxxabiv1", "std"}) {
33450b57cec5SDimitry Andric     IdentifierInfo &NS = C.Idents.get(N);
33460b57cec5SDimitry Andric     for (const auto &Result : DC->lookup(&NS)) {
33470b57cec5SDimitry Andric       NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
33480b57cec5SDimitry Andric       if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
33490b57cec5SDimitry Andric         for (const auto &Result : LSD->lookup(&NS))
33500b57cec5SDimitry Andric           if ((ND = dyn_cast<NamespaceDecl>(Result)))
33510b57cec5SDimitry Andric             break;
33520b57cec5SDimitry Andric 
33530b57cec5SDimitry Andric       if (ND)
33540b57cec5SDimitry Andric         for (const auto &Result : ND->lookup(&CXXII))
33550b57cec5SDimitry Andric           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
33560b57cec5SDimitry Andric             return FD;
33570b57cec5SDimitry Andric     }
33580b57cec5SDimitry Andric   }
33590b57cec5SDimitry Andric 
33600b57cec5SDimitry Andric   return nullptr;
33610b57cec5SDimitry Andric }
33620b57cec5SDimitry Andric 
33630b57cec5SDimitry Andric /// CreateRuntimeFunction - Create a new runtime function with the specified
33640b57cec5SDimitry Andric /// type and name.
33650b57cec5SDimitry Andric llvm::FunctionCallee
33660b57cec5SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
3367480093f4SDimitry Andric                                      llvm::AttributeList ExtraAttrs, bool Local,
3368480093f4SDimitry Andric                                      bool AssumeConvergent) {
3369480093f4SDimitry Andric   if (AssumeConvergent) {
3370480093f4SDimitry Andric     ExtraAttrs =
3371480093f4SDimitry Andric         ExtraAttrs.addAttribute(VMContext, llvm::AttributeList::FunctionIndex,
3372480093f4SDimitry Andric                                 llvm::Attribute::Convergent);
3373480093f4SDimitry Andric   }
3374480093f4SDimitry Andric 
33750b57cec5SDimitry Andric   llvm::Constant *C =
33760b57cec5SDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
33770b57cec5SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false,
33780b57cec5SDimitry Andric                               ExtraAttrs);
33790b57cec5SDimitry Andric 
33800b57cec5SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C)) {
33810b57cec5SDimitry Andric     if (F->empty()) {
33820b57cec5SDimitry Andric       F->setCallingConv(getRuntimeCC());
33830b57cec5SDimitry Andric 
33840b57cec5SDimitry Andric       // In Windows Itanium environments, try to mark runtime functions
33850b57cec5SDimitry Andric       // dllimport. For Mingw and MSVC, don't. We don't really know if the user
33860b57cec5SDimitry Andric       // will link their standard library statically or dynamically. Marking
33870b57cec5SDimitry Andric       // functions imported when they are not imported can cause linker errors
33880b57cec5SDimitry Andric       // and warnings.
33890b57cec5SDimitry Andric       if (!Local && getTriple().isWindowsItaniumEnvironment() &&
33900b57cec5SDimitry Andric           !getCodeGenOpts().LTOVisibilityPublicStd) {
33910b57cec5SDimitry Andric         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
33920b57cec5SDimitry Andric         if (!FD || FD->hasAttr<DLLImportAttr>()) {
33930b57cec5SDimitry Andric           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
33940b57cec5SDimitry Andric           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
33950b57cec5SDimitry Andric         }
33960b57cec5SDimitry Andric       }
33970b57cec5SDimitry Andric       setDSOLocal(F);
33980b57cec5SDimitry Andric     }
33990b57cec5SDimitry Andric   }
34000b57cec5SDimitry Andric 
34010b57cec5SDimitry Andric   return {FTy, C};
34020b57cec5SDimitry Andric }
34030b57cec5SDimitry Andric 
34040b57cec5SDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted
34050b57cec5SDimitry Andric /// as a constant.
34060b57cec5SDimitry Andric ///
34070b57cec5SDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs
34080b57cec5SDimitry Andric /// will not be considered. The caller will need to verify that the object is
34090b57cec5SDimitry Andric /// not written to during its construction.
34100b57cec5SDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
34110b57cec5SDimitry Andric   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
34120b57cec5SDimitry Andric     return false;
34130b57cec5SDimitry Andric 
34140b57cec5SDimitry Andric   if (Context.getLangOpts().CPlusPlus) {
34150b57cec5SDimitry Andric     if (const CXXRecordDecl *Record
34160b57cec5SDimitry Andric           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
34170b57cec5SDimitry Andric       return ExcludeCtor && !Record->hasMutableFields() &&
34180b57cec5SDimitry Andric              Record->hasTrivialDestructor();
34190b57cec5SDimitry Andric   }
34200b57cec5SDimitry Andric 
34210b57cec5SDimitry Andric   return true;
34220b57cec5SDimitry Andric }
34230b57cec5SDimitry Andric 
34240b57cec5SDimitry Andric /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
34250b57cec5SDimitry Andric /// create and return an llvm GlobalVariable with the specified type.  If there
34260b57cec5SDimitry Andric /// is something in the module with the specified name, return it potentially
34270b57cec5SDimitry Andric /// bitcasted to the right type.
34280b57cec5SDimitry Andric ///
34290b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this.  This is used
34300b57cec5SDimitry Andric /// to set the attributes on the global when it is first created.
34310b57cec5SDimitry Andric ///
34320b57cec5SDimitry Andric /// If IsForDefinition is true, it is guaranteed that an actual global with
34330b57cec5SDimitry Andric /// type Ty will be returned, not conversion of a variable with the same
34340b57cec5SDimitry Andric /// mangled name but some other type.
34350b57cec5SDimitry Andric llvm::Constant *
34360b57cec5SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
34370b57cec5SDimitry Andric                                      llvm::PointerType *Ty,
34380b57cec5SDimitry Andric                                      const VarDecl *D,
34390b57cec5SDimitry Andric                                      ForDefinition_t IsForDefinition) {
34400b57cec5SDimitry Andric   // Lookup the entry, lazily creating it if necessary.
34410b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
34420b57cec5SDimitry Andric   if (Entry) {
34430b57cec5SDimitry Andric     if (WeakRefReferences.erase(Entry)) {
34440b57cec5SDimitry Andric       if (D && !D->hasAttr<WeakAttr>())
34450b57cec5SDimitry Andric         Entry->setLinkage(llvm::Function::ExternalLinkage);
34460b57cec5SDimitry Andric     }
34470b57cec5SDimitry Andric 
34480b57cec5SDimitry Andric     // Handle dropped DLL attributes.
34490b57cec5SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
34500b57cec5SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
34510b57cec5SDimitry Andric 
34520b57cec5SDimitry Andric     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
34530b57cec5SDimitry Andric       getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
34540b57cec5SDimitry Andric 
34550b57cec5SDimitry Andric     if (Entry->getType() == Ty)
34560b57cec5SDimitry Andric       return Entry;
34570b57cec5SDimitry Andric 
34580b57cec5SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
34590b57cec5SDimitry Andric     // error.
34600b57cec5SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
34610b57cec5SDimitry Andric       GlobalDecl OtherGD;
34620b57cec5SDimitry Andric       const VarDecl *OtherD;
34630b57cec5SDimitry Andric 
34640b57cec5SDimitry Andric       // Check that D is not yet in DiagnosedConflictingDefinitions is required
34650b57cec5SDimitry Andric       // to make sure that we issue an error only once.
34660b57cec5SDimitry Andric       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
34670b57cec5SDimitry Andric           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
34680b57cec5SDimitry Andric           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
34690b57cec5SDimitry Andric           OtherD->hasInit() &&
34700b57cec5SDimitry Andric           DiagnosedConflictingDefinitions.insert(D).second) {
34710b57cec5SDimitry Andric         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
34720b57cec5SDimitry Andric             << MangledName;
34730b57cec5SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
34740b57cec5SDimitry Andric                           diag::note_previous_definition);
34750b57cec5SDimitry Andric       }
34760b57cec5SDimitry Andric     }
34770b57cec5SDimitry Andric 
34780b57cec5SDimitry Andric     // Make sure the result is of the correct type.
34790b57cec5SDimitry Andric     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
34800b57cec5SDimitry Andric       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
34810b57cec5SDimitry Andric 
34820b57cec5SDimitry Andric     // (If global is requested for a definition, we always need to create a new
34830b57cec5SDimitry Andric     // global, not just return a bitcast.)
34840b57cec5SDimitry Andric     if (!IsForDefinition)
34850b57cec5SDimitry Andric       return llvm::ConstantExpr::getBitCast(Entry, Ty);
34860b57cec5SDimitry Andric   }
34870b57cec5SDimitry Andric 
34880b57cec5SDimitry Andric   auto AddrSpace = GetGlobalVarAddressSpace(D);
34890b57cec5SDimitry Andric   auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
34900b57cec5SDimitry Andric 
34910b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
34920b57cec5SDimitry Andric       getModule(), Ty->getElementType(), false,
34930b57cec5SDimitry Andric       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
34940b57cec5SDimitry Andric       llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
34950b57cec5SDimitry Andric 
34960b57cec5SDimitry Andric   // If we already created a global with the same mangled name (but different
34970b57cec5SDimitry Andric   // type) before, take its name and remove it from its parent.
34980b57cec5SDimitry Andric   if (Entry) {
34990b57cec5SDimitry Andric     GV->takeName(Entry);
35000b57cec5SDimitry Andric 
35010b57cec5SDimitry Andric     if (!Entry->use_empty()) {
35020b57cec5SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
35030b57cec5SDimitry Andric           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
35040b57cec5SDimitry Andric       Entry->replaceAllUsesWith(NewPtrForOldDecl);
35050b57cec5SDimitry Andric     }
35060b57cec5SDimitry Andric 
35070b57cec5SDimitry Andric     Entry->eraseFromParent();
35080b57cec5SDimitry Andric   }
35090b57cec5SDimitry Andric 
35100b57cec5SDimitry Andric   // This is the first use or definition of a mangled name.  If there is a
35110b57cec5SDimitry Andric   // deferred decl with this name, remember that we need to emit it at the end
35120b57cec5SDimitry Andric   // of the file.
35130b57cec5SDimitry Andric   auto DDI = DeferredDecls.find(MangledName);
35140b57cec5SDimitry Andric   if (DDI != DeferredDecls.end()) {
35150b57cec5SDimitry Andric     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
35160b57cec5SDimitry Andric     // list, and remove it from DeferredDecls (since we don't need it anymore).
35170b57cec5SDimitry Andric     addDeferredDeclToEmit(DDI->second);
35180b57cec5SDimitry Andric     DeferredDecls.erase(DDI);
35190b57cec5SDimitry Andric   }
35200b57cec5SDimitry Andric 
35210b57cec5SDimitry Andric   // Handle things which are present even on external declarations.
35220b57cec5SDimitry Andric   if (D) {
35230b57cec5SDimitry Andric     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
35240b57cec5SDimitry Andric       getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
35250b57cec5SDimitry Andric 
35260b57cec5SDimitry Andric     // FIXME: This code is overly simple and should be merged with other global
35270b57cec5SDimitry Andric     // handling.
35280b57cec5SDimitry Andric     GV->setConstant(isTypeConstant(D->getType(), false));
35290b57cec5SDimitry Andric 
3530a7dea167SDimitry Andric     GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
35310b57cec5SDimitry Andric 
35320b57cec5SDimitry Andric     setLinkageForGV(GV, D);
35330b57cec5SDimitry Andric 
35340b57cec5SDimitry Andric     if (D->getTLSKind()) {
35350b57cec5SDimitry Andric       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
35360b57cec5SDimitry Andric         CXXThreadLocals.push_back(D);
35370b57cec5SDimitry Andric       setTLSMode(GV, *D);
35380b57cec5SDimitry Andric     }
35390b57cec5SDimitry Andric 
35400b57cec5SDimitry Andric     setGVProperties(GV, D);
35410b57cec5SDimitry Andric 
35420b57cec5SDimitry Andric     // If required by the ABI, treat declarations of static data members with
35430b57cec5SDimitry Andric     // inline initializers as definitions.
35440b57cec5SDimitry Andric     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
35450b57cec5SDimitry Andric       EmitGlobalVarDefinition(D);
35460b57cec5SDimitry Andric     }
35470b57cec5SDimitry Andric 
35480b57cec5SDimitry Andric     // Emit section information for extern variables.
35490b57cec5SDimitry Andric     if (D->hasExternalStorage()) {
35500b57cec5SDimitry Andric       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
35510b57cec5SDimitry Andric         GV->setSection(SA->getName());
35520b57cec5SDimitry Andric     }
35530b57cec5SDimitry Andric 
35540b57cec5SDimitry Andric     // Handle XCore specific ABI requirements.
35550b57cec5SDimitry Andric     if (getTriple().getArch() == llvm::Triple::xcore &&
35560b57cec5SDimitry Andric         D->getLanguageLinkage() == CLanguageLinkage &&
35570b57cec5SDimitry Andric         D->getType().isConstant(Context) &&
35580b57cec5SDimitry Andric         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
35590b57cec5SDimitry Andric       GV->setSection(".cp.rodata");
35600b57cec5SDimitry Andric 
35610b57cec5SDimitry Andric     // Check if we a have a const declaration with an initializer, we may be
35620b57cec5SDimitry Andric     // able to emit it as available_externally to expose it's value to the
35630b57cec5SDimitry Andric     // optimizer.
35640b57cec5SDimitry Andric     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
35650b57cec5SDimitry Andric         D->getType().isConstQualified() && !GV->hasInitializer() &&
35660b57cec5SDimitry Andric         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
35670b57cec5SDimitry Andric       const auto *Record =
35680b57cec5SDimitry Andric           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
35690b57cec5SDimitry Andric       bool HasMutableFields = Record && Record->hasMutableFields();
35700b57cec5SDimitry Andric       if (!HasMutableFields) {
35710b57cec5SDimitry Andric         const VarDecl *InitDecl;
35720b57cec5SDimitry Andric         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
35730b57cec5SDimitry Andric         if (InitExpr) {
35740b57cec5SDimitry Andric           ConstantEmitter emitter(*this);
35750b57cec5SDimitry Andric           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
35760b57cec5SDimitry Andric           if (Init) {
35770b57cec5SDimitry Andric             auto *InitType = Init->getType();
35780b57cec5SDimitry Andric             if (GV->getType()->getElementType() != InitType) {
35790b57cec5SDimitry Andric               // The type of the initializer does not match the definition.
35800b57cec5SDimitry Andric               // This happens when an initializer has a different type from
35810b57cec5SDimitry Andric               // the type of the global (because of padding at the end of a
35820b57cec5SDimitry Andric               // structure for instance).
35830b57cec5SDimitry Andric               GV->setName(StringRef());
35840b57cec5SDimitry Andric               // Make a new global with the correct type, this is now guaranteed
35850b57cec5SDimitry Andric               // to work.
35860b57cec5SDimitry Andric               auto *NewGV = cast<llvm::GlobalVariable>(
3587a7dea167SDimitry Andric                   GetAddrOfGlobalVar(D, InitType, IsForDefinition)
3588a7dea167SDimitry Andric                       ->stripPointerCasts());
35890b57cec5SDimitry Andric 
35900b57cec5SDimitry Andric               // Erase the old global, since it is no longer used.
35910b57cec5SDimitry Andric               GV->eraseFromParent();
35920b57cec5SDimitry Andric               GV = NewGV;
35930b57cec5SDimitry Andric             } else {
35940b57cec5SDimitry Andric               GV->setInitializer(Init);
35950b57cec5SDimitry Andric               GV->setConstant(true);
35960b57cec5SDimitry Andric               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
35970b57cec5SDimitry Andric             }
35980b57cec5SDimitry Andric             emitter.finalize(GV);
35990b57cec5SDimitry Andric           }
36000b57cec5SDimitry Andric         }
36010b57cec5SDimitry Andric       }
36020b57cec5SDimitry Andric     }
36030b57cec5SDimitry Andric   }
36040b57cec5SDimitry Andric 
3605480093f4SDimitry Andric   if (GV->isDeclaration())
3606480093f4SDimitry Andric     getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
3607480093f4SDimitry Andric 
36080b57cec5SDimitry Andric   LangAS ExpectedAS =
36090b57cec5SDimitry Andric       D ? D->getType().getAddressSpace()
36100b57cec5SDimitry Andric         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
36110b57cec5SDimitry Andric   assert(getContext().getTargetAddressSpace(ExpectedAS) ==
36120b57cec5SDimitry Andric          Ty->getPointerAddressSpace());
36130b57cec5SDimitry Andric   if (AddrSpace != ExpectedAS)
36140b57cec5SDimitry Andric     return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
36150b57cec5SDimitry Andric                                                        ExpectedAS, Ty);
36160b57cec5SDimitry Andric 
36170b57cec5SDimitry Andric   return GV;
36180b57cec5SDimitry Andric }
36190b57cec5SDimitry Andric 
36200b57cec5SDimitry Andric llvm::Constant *
36210b57cec5SDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
36220b57cec5SDimitry Andric                                ForDefinition_t IsForDefinition) {
36230b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
36240b57cec5SDimitry Andric   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
36250b57cec5SDimitry Andric     return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
36260b57cec5SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
36270b57cec5SDimitry Andric   else if (isa<CXXMethodDecl>(D)) {
36280b57cec5SDimitry Andric     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
36290b57cec5SDimitry Andric         cast<CXXMethodDecl>(D));
36300b57cec5SDimitry Andric     auto Ty = getTypes().GetFunctionType(*FInfo);
36310b57cec5SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
36320b57cec5SDimitry Andric                              IsForDefinition);
36330b57cec5SDimitry Andric   } else if (isa<FunctionDecl>(D)) {
36340b57cec5SDimitry Andric     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
36350b57cec5SDimitry Andric     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
36360b57cec5SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
36370b57cec5SDimitry Andric                              IsForDefinition);
36380b57cec5SDimitry Andric   } else
36390b57cec5SDimitry Andric     return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
36400b57cec5SDimitry Andric                               IsForDefinition);
36410b57cec5SDimitry Andric }
36420b57cec5SDimitry Andric 
36430b57cec5SDimitry Andric llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
36440b57cec5SDimitry Andric     StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
36450b57cec5SDimitry Andric     unsigned Alignment) {
36460b57cec5SDimitry Andric   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
36470b57cec5SDimitry Andric   llvm::GlobalVariable *OldGV = nullptr;
36480b57cec5SDimitry Andric 
36490b57cec5SDimitry Andric   if (GV) {
36500b57cec5SDimitry Andric     // Check if the variable has the right type.
36510b57cec5SDimitry Andric     if (GV->getType()->getElementType() == Ty)
36520b57cec5SDimitry Andric       return GV;
36530b57cec5SDimitry Andric 
36540b57cec5SDimitry Andric     // Because C++ name mangling, the only way we can end up with an already
36550b57cec5SDimitry Andric     // existing global with the same name is if it has been declared extern "C".
36560b57cec5SDimitry Andric     assert(GV->isDeclaration() && "Declaration has wrong type!");
36570b57cec5SDimitry Andric     OldGV = GV;
36580b57cec5SDimitry Andric   }
36590b57cec5SDimitry Andric 
36600b57cec5SDimitry Andric   // Create a new variable.
36610b57cec5SDimitry Andric   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
36620b57cec5SDimitry Andric                                 Linkage, nullptr, Name);
36630b57cec5SDimitry Andric 
36640b57cec5SDimitry Andric   if (OldGV) {
36650b57cec5SDimitry Andric     // Replace occurrences of the old variable if needed.
36660b57cec5SDimitry Andric     GV->takeName(OldGV);
36670b57cec5SDimitry Andric 
36680b57cec5SDimitry Andric     if (!OldGV->use_empty()) {
36690b57cec5SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
36700b57cec5SDimitry Andric       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
36710b57cec5SDimitry Andric       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
36720b57cec5SDimitry Andric     }
36730b57cec5SDimitry Andric 
36740b57cec5SDimitry Andric     OldGV->eraseFromParent();
36750b57cec5SDimitry Andric   }
36760b57cec5SDimitry Andric 
36770b57cec5SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker() &&
36780b57cec5SDimitry Andric       !GV->hasAvailableExternallyLinkage())
36790b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
36800b57cec5SDimitry Andric 
3681a7dea167SDimitry Andric   GV->setAlignment(llvm::MaybeAlign(Alignment));
36820b57cec5SDimitry Andric 
36830b57cec5SDimitry Andric   return GV;
36840b57cec5SDimitry Andric }
36850b57cec5SDimitry Andric 
36860b57cec5SDimitry Andric /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
36870b57cec5SDimitry Andric /// given global variable.  If Ty is non-null and if the global doesn't exist,
36880b57cec5SDimitry Andric /// then it will be created with the specified type instead of whatever the
36890b57cec5SDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guaranteed
36900b57cec5SDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a
36910b57cec5SDimitry Andric /// variable with the same mangled name but some other type.
36920b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
36930b57cec5SDimitry Andric                                                   llvm::Type *Ty,
36940b57cec5SDimitry Andric                                            ForDefinition_t IsForDefinition) {
36950b57cec5SDimitry Andric   assert(D->hasGlobalStorage() && "Not a global variable");
36960b57cec5SDimitry Andric   QualType ASTTy = D->getType();
36970b57cec5SDimitry Andric   if (!Ty)
36980b57cec5SDimitry Andric     Ty = getTypes().ConvertTypeForMem(ASTTy);
36990b57cec5SDimitry Andric 
37000b57cec5SDimitry Andric   llvm::PointerType *PTy =
37010b57cec5SDimitry Andric     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
37020b57cec5SDimitry Andric 
37030b57cec5SDimitry Andric   StringRef MangledName = getMangledName(D);
37040b57cec5SDimitry Andric   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
37050b57cec5SDimitry Andric }
37060b57cec5SDimitry Andric 
37070b57cec5SDimitry Andric /// CreateRuntimeVariable - Create a new runtime global variable with the
37080b57cec5SDimitry Andric /// specified type and name.
37090b57cec5SDimitry Andric llvm::Constant *
37100b57cec5SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
37110b57cec5SDimitry Andric                                      StringRef Name) {
37120b57cec5SDimitry Andric   auto PtrTy =
37130b57cec5SDimitry Andric       getContext().getLangOpts().OpenCL
37140b57cec5SDimitry Andric           ? llvm::PointerType::get(
37150b57cec5SDimitry Andric                 Ty, getContext().getTargetAddressSpace(LangAS::opencl_global))
37160b57cec5SDimitry Andric           : llvm::PointerType::getUnqual(Ty);
37170b57cec5SDimitry Andric   auto *Ret = GetOrCreateLLVMGlobal(Name, PtrTy, nullptr);
37180b57cec5SDimitry Andric   setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
37190b57cec5SDimitry Andric   return Ret;
37200b57cec5SDimitry Andric }
37210b57cec5SDimitry Andric 
37220b57cec5SDimitry Andric void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
37230b57cec5SDimitry Andric   assert(!D->getInit() && "Cannot emit definite definitions here!");
37240b57cec5SDimitry Andric 
37250b57cec5SDimitry Andric   StringRef MangledName = getMangledName(D);
37260b57cec5SDimitry Andric   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
37270b57cec5SDimitry Andric 
37280b57cec5SDimitry Andric   // We already have a definition, not declaration, with the same mangled name.
37290b57cec5SDimitry Andric   // Emitting of declaration is not required (and actually overwrites emitted
37300b57cec5SDimitry Andric   // definition).
37310b57cec5SDimitry Andric   if (GV && !GV->isDeclaration())
37320b57cec5SDimitry Andric     return;
37330b57cec5SDimitry Andric 
37340b57cec5SDimitry Andric   // If we have not seen a reference to this variable yet, place it into the
37350b57cec5SDimitry Andric   // deferred declarations table to be emitted if needed later.
37360b57cec5SDimitry Andric   if (!MustBeEmitted(D) && !GV) {
37370b57cec5SDimitry Andric       DeferredDecls[MangledName] = D;
37380b57cec5SDimitry Andric       return;
37390b57cec5SDimitry Andric   }
37400b57cec5SDimitry Andric 
37410b57cec5SDimitry Andric   // The tentative definition is the only definition.
37420b57cec5SDimitry Andric   EmitGlobalVarDefinition(D);
37430b57cec5SDimitry Andric }
37440b57cec5SDimitry Andric 
3745480093f4SDimitry Andric void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
3746480093f4SDimitry Andric   EmitExternalVarDeclaration(D);
3747480093f4SDimitry Andric }
3748480093f4SDimitry Andric 
37490b57cec5SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
37500b57cec5SDimitry Andric   return Context.toCharUnitsFromBits(
37510b57cec5SDimitry Andric       getDataLayout().getTypeStoreSizeInBits(Ty));
37520b57cec5SDimitry Andric }
37530b57cec5SDimitry Andric 
37540b57cec5SDimitry Andric LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
37550b57cec5SDimitry Andric   LangAS AddrSpace = LangAS::Default;
37560b57cec5SDimitry Andric   if (LangOpts.OpenCL) {
37570b57cec5SDimitry Andric     AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
37580b57cec5SDimitry Andric     assert(AddrSpace == LangAS::opencl_global ||
37590b57cec5SDimitry Andric            AddrSpace == LangAS::opencl_constant ||
37600b57cec5SDimitry Andric            AddrSpace == LangAS::opencl_local ||
37610b57cec5SDimitry Andric            AddrSpace >= LangAS::FirstTargetAddressSpace);
37620b57cec5SDimitry Andric     return AddrSpace;
37630b57cec5SDimitry Andric   }
37640b57cec5SDimitry Andric 
37650b57cec5SDimitry Andric   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
37660b57cec5SDimitry Andric     if (D && D->hasAttr<CUDAConstantAttr>())
37670b57cec5SDimitry Andric       return LangAS::cuda_constant;
37680b57cec5SDimitry Andric     else if (D && D->hasAttr<CUDASharedAttr>())
37690b57cec5SDimitry Andric       return LangAS::cuda_shared;
37700b57cec5SDimitry Andric     else if (D && D->hasAttr<CUDADeviceAttr>())
37710b57cec5SDimitry Andric       return LangAS::cuda_device;
37720b57cec5SDimitry Andric     else if (D && D->getType().isConstQualified())
37730b57cec5SDimitry Andric       return LangAS::cuda_constant;
37740b57cec5SDimitry Andric     else
37750b57cec5SDimitry Andric       return LangAS::cuda_device;
37760b57cec5SDimitry Andric   }
37770b57cec5SDimitry Andric 
37780b57cec5SDimitry Andric   if (LangOpts.OpenMP) {
37790b57cec5SDimitry Andric     LangAS AS;
37800b57cec5SDimitry Andric     if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
37810b57cec5SDimitry Andric       return AS;
37820b57cec5SDimitry Andric   }
37830b57cec5SDimitry Andric   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
37840b57cec5SDimitry Andric }
37850b57cec5SDimitry Andric 
37860b57cec5SDimitry Andric LangAS CodeGenModule::getStringLiteralAddressSpace() const {
37870b57cec5SDimitry Andric   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
37880b57cec5SDimitry Andric   if (LangOpts.OpenCL)
37890b57cec5SDimitry Andric     return LangAS::opencl_constant;
37900b57cec5SDimitry Andric   if (auto AS = getTarget().getConstantAddressSpace())
37910b57cec5SDimitry Andric     return AS.getValue();
37920b57cec5SDimitry Andric   return LangAS::Default;
37930b57cec5SDimitry Andric }
37940b57cec5SDimitry Andric 
37950b57cec5SDimitry Andric // In address space agnostic languages, string literals are in default address
37960b57cec5SDimitry Andric // space in AST. However, certain targets (e.g. amdgcn) request them to be
37970b57cec5SDimitry Andric // emitted in constant address space in LLVM IR. To be consistent with other
37980b57cec5SDimitry Andric // parts of AST, string literal global variables in constant address space
37990b57cec5SDimitry Andric // need to be casted to default address space before being put into address
38000b57cec5SDimitry Andric // map and referenced by other part of CodeGen.
38010b57cec5SDimitry Andric // In OpenCL, string literals are in constant address space in AST, therefore
38020b57cec5SDimitry Andric // they should not be casted to default address space.
38030b57cec5SDimitry Andric static llvm::Constant *
38040b57cec5SDimitry Andric castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
38050b57cec5SDimitry Andric                                        llvm::GlobalVariable *GV) {
38060b57cec5SDimitry Andric   llvm::Constant *Cast = GV;
38070b57cec5SDimitry Andric   if (!CGM.getLangOpts().OpenCL) {
38080b57cec5SDimitry Andric     if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
38090b57cec5SDimitry Andric       if (AS != LangAS::Default)
38100b57cec5SDimitry Andric         Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
38110b57cec5SDimitry Andric             CGM, GV, AS.getValue(), LangAS::Default,
38120b57cec5SDimitry Andric             GV->getValueType()->getPointerTo(
38130b57cec5SDimitry Andric                 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
38140b57cec5SDimitry Andric     }
38150b57cec5SDimitry Andric   }
38160b57cec5SDimitry Andric   return Cast;
38170b57cec5SDimitry Andric }
38180b57cec5SDimitry Andric 
38190b57cec5SDimitry Andric template<typename SomeDecl>
38200b57cec5SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
38210b57cec5SDimitry Andric                                                llvm::GlobalValue *GV) {
38220b57cec5SDimitry Andric   if (!getLangOpts().CPlusPlus)
38230b57cec5SDimitry Andric     return;
38240b57cec5SDimitry Andric 
38250b57cec5SDimitry Andric   // Must have 'used' attribute, or else inline assembly can't rely on
38260b57cec5SDimitry Andric   // the name existing.
38270b57cec5SDimitry Andric   if (!D->template hasAttr<UsedAttr>())
38280b57cec5SDimitry Andric     return;
38290b57cec5SDimitry Andric 
38300b57cec5SDimitry Andric   // Must have internal linkage and an ordinary name.
38310b57cec5SDimitry Andric   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
38320b57cec5SDimitry Andric     return;
38330b57cec5SDimitry Andric 
38340b57cec5SDimitry Andric   // Must be in an extern "C" context. Entities declared directly within
38350b57cec5SDimitry Andric   // a record are not extern "C" even if the record is in such a context.
38360b57cec5SDimitry Andric   const SomeDecl *First = D->getFirstDecl();
38370b57cec5SDimitry Andric   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
38380b57cec5SDimitry Andric     return;
38390b57cec5SDimitry Andric 
38400b57cec5SDimitry Andric   // OK, this is an internal linkage entity inside an extern "C" linkage
38410b57cec5SDimitry Andric   // specification. Make a note of that so we can give it the "expected"
38420b57cec5SDimitry Andric   // mangled name if nothing else is using that name.
38430b57cec5SDimitry Andric   std::pair<StaticExternCMap::iterator, bool> R =
38440b57cec5SDimitry Andric       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
38450b57cec5SDimitry Andric 
38460b57cec5SDimitry Andric   // If we have multiple internal linkage entities with the same name
38470b57cec5SDimitry Andric   // in extern "C" regions, none of them gets that name.
38480b57cec5SDimitry Andric   if (!R.second)
38490b57cec5SDimitry Andric     R.first->second = nullptr;
38500b57cec5SDimitry Andric }
38510b57cec5SDimitry Andric 
38520b57cec5SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
38530b57cec5SDimitry Andric   if (!CGM.supportsCOMDAT())
38540b57cec5SDimitry Andric     return false;
38550b57cec5SDimitry Andric 
38560b57cec5SDimitry Andric   // Do not set COMDAT attribute for CUDA/HIP stub functions to prevent
38570b57cec5SDimitry Andric   // them being "merged" by the COMDAT Folding linker optimization.
38580b57cec5SDimitry Andric   if (D.hasAttr<CUDAGlobalAttr>())
38590b57cec5SDimitry Andric     return false;
38600b57cec5SDimitry Andric 
38610b57cec5SDimitry Andric   if (D.hasAttr<SelectAnyAttr>())
38620b57cec5SDimitry Andric     return true;
38630b57cec5SDimitry Andric 
38640b57cec5SDimitry Andric   GVALinkage Linkage;
38650b57cec5SDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(&D))
38660b57cec5SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
38670b57cec5SDimitry Andric   else
38680b57cec5SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
38690b57cec5SDimitry Andric 
38700b57cec5SDimitry Andric   switch (Linkage) {
38710b57cec5SDimitry Andric   case GVA_Internal:
38720b57cec5SDimitry Andric   case GVA_AvailableExternally:
38730b57cec5SDimitry Andric   case GVA_StrongExternal:
38740b57cec5SDimitry Andric     return false;
38750b57cec5SDimitry Andric   case GVA_DiscardableODR:
38760b57cec5SDimitry Andric   case GVA_StrongODR:
38770b57cec5SDimitry Andric     return true;
38780b57cec5SDimitry Andric   }
38790b57cec5SDimitry Andric   llvm_unreachable("No such linkage");
38800b57cec5SDimitry Andric }
38810b57cec5SDimitry Andric 
38820b57cec5SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
38830b57cec5SDimitry Andric                                           llvm::GlobalObject &GO) {
38840b57cec5SDimitry Andric   if (!shouldBeInCOMDAT(*this, D))
38850b57cec5SDimitry Andric     return;
38860b57cec5SDimitry Andric   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
38870b57cec5SDimitry Andric }
38880b57cec5SDimitry Andric 
38890b57cec5SDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition.
38900b57cec5SDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
38910b57cec5SDimitry Andric                                             bool IsTentative) {
38920b57cec5SDimitry Andric   // OpenCL global variables of sampler type are translated to function calls,
38930b57cec5SDimitry Andric   // therefore no need to be translated.
38940b57cec5SDimitry Andric   QualType ASTTy = D->getType();
38950b57cec5SDimitry Andric   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
38960b57cec5SDimitry Andric     return;
38970b57cec5SDimitry Andric 
38980b57cec5SDimitry Andric   // If this is OpenMP device, check if it is legal to emit this global
38990b57cec5SDimitry Andric   // normally.
39000b57cec5SDimitry Andric   if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
39010b57cec5SDimitry Andric       OpenMPRuntime->emitTargetGlobalVariable(D))
39020b57cec5SDimitry Andric     return;
39030b57cec5SDimitry Andric 
39040b57cec5SDimitry Andric   llvm::Constant *Init = nullptr;
39050b57cec5SDimitry Andric   bool NeedsGlobalCtor = false;
3906a7dea167SDimitry Andric   bool NeedsGlobalDtor =
3907a7dea167SDimitry Andric       D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
39080b57cec5SDimitry Andric 
39090b57cec5SDimitry Andric   const VarDecl *InitDecl;
39100b57cec5SDimitry Andric   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
39110b57cec5SDimitry Andric 
39120b57cec5SDimitry Andric   Optional<ConstantEmitter> emitter;
39130b57cec5SDimitry Andric 
39140b57cec5SDimitry Andric   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
39150b57cec5SDimitry Andric   // as part of their declaration."  Sema has already checked for
39160b57cec5SDimitry Andric   // error cases, so we just need to set Init to UndefValue.
39170b57cec5SDimitry Andric   bool IsCUDASharedVar =
39180b57cec5SDimitry Andric       getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
39190b57cec5SDimitry Andric   // Shadows of initialized device-side global variables are also left
39200b57cec5SDimitry Andric   // undefined.
39210b57cec5SDimitry Andric   bool IsCUDAShadowVar =
39220b57cec5SDimitry Andric       !getLangOpts().CUDAIsDevice &&
39230b57cec5SDimitry Andric       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
39240b57cec5SDimitry Andric        D->hasAttr<CUDASharedAttr>());
39250b57cec5SDimitry Andric   // HIP pinned shadow of initialized host-side global variables are also
39260b57cec5SDimitry Andric   // left undefined.
39270b57cec5SDimitry Andric   bool IsHIPPinnedShadowVar =
39280b57cec5SDimitry Andric       getLangOpts().CUDAIsDevice && D->hasAttr<HIPPinnedShadowAttr>();
39290b57cec5SDimitry Andric   if (getLangOpts().CUDA &&
39300b57cec5SDimitry Andric       (IsCUDASharedVar || IsCUDAShadowVar || IsHIPPinnedShadowVar))
39310b57cec5SDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
39320b57cec5SDimitry Andric   else if (!InitExpr) {
39330b57cec5SDimitry Andric     // This is a tentative definition; tentative definitions are
39340b57cec5SDimitry Andric     // implicitly initialized with { 0 }.
39350b57cec5SDimitry Andric     //
39360b57cec5SDimitry Andric     // Note that tentative definitions are only emitted at the end of
39370b57cec5SDimitry Andric     // a translation unit, so they should never have incomplete
39380b57cec5SDimitry Andric     // type. In addition, EmitTentativeDefinition makes sure that we
39390b57cec5SDimitry Andric     // never attempt to emit a tentative definition if a real one
39400b57cec5SDimitry Andric     // exists. A use may still exists, however, so we still may need
39410b57cec5SDimitry Andric     // to do a RAUW.
39420b57cec5SDimitry Andric     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
39430b57cec5SDimitry Andric     Init = EmitNullConstant(D->getType());
39440b57cec5SDimitry Andric   } else {
39450b57cec5SDimitry Andric     initializedGlobalDecl = GlobalDecl(D);
39460b57cec5SDimitry Andric     emitter.emplace(*this);
39470b57cec5SDimitry Andric     Init = emitter->tryEmitForInitializer(*InitDecl);
39480b57cec5SDimitry Andric 
39490b57cec5SDimitry Andric     if (!Init) {
39500b57cec5SDimitry Andric       QualType T = InitExpr->getType();
39510b57cec5SDimitry Andric       if (D->getType()->isReferenceType())
39520b57cec5SDimitry Andric         T = D->getType();
39530b57cec5SDimitry Andric 
39540b57cec5SDimitry Andric       if (getLangOpts().CPlusPlus) {
39550b57cec5SDimitry Andric         Init = EmitNullConstant(T);
39560b57cec5SDimitry Andric         NeedsGlobalCtor = true;
39570b57cec5SDimitry Andric       } else {
39580b57cec5SDimitry Andric         ErrorUnsupported(D, "static initializer");
39590b57cec5SDimitry Andric         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
39600b57cec5SDimitry Andric       }
39610b57cec5SDimitry Andric     } else {
39620b57cec5SDimitry Andric       // We don't need an initializer, so remove the entry for the delayed
39630b57cec5SDimitry Andric       // initializer position (just in case this entry was delayed) if we
39640b57cec5SDimitry Andric       // also don't need to register a destructor.
39650b57cec5SDimitry Andric       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
39660b57cec5SDimitry Andric         DelayedCXXInitPosition.erase(D);
39670b57cec5SDimitry Andric     }
39680b57cec5SDimitry Andric   }
39690b57cec5SDimitry Andric 
39700b57cec5SDimitry Andric   llvm::Type* InitType = Init->getType();
39710b57cec5SDimitry Andric   llvm::Constant *Entry =
39720b57cec5SDimitry Andric       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
39730b57cec5SDimitry Andric 
3974a7dea167SDimitry Andric   // Strip off pointer casts if we got them.
3975a7dea167SDimitry Andric   Entry = Entry->stripPointerCasts();
39760b57cec5SDimitry Andric 
39770b57cec5SDimitry Andric   // Entry is now either a Function or GlobalVariable.
39780b57cec5SDimitry Andric   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
39790b57cec5SDimitry Andric 
39800b57cec5SDimitry Andric   // We have a definition after a declaration with the wrong type.
39810b57cec5SDimitry Andric   // We must make a new GlobalVariable* and update everything that used OldGV
39820b57cec5SDimitry Andric   // (a declaration or tentative definition) with the new GlobalVariable*
39830b57cec5SDimitry Andric   // (which will be a definition).
39840b57cec5SDimitry Andric   //
39850b57cec5SDimitry Andric   // This happens if there is a prototype for a global (e.g.
39860b57cec5SDimitry Andric   // "extern int x[];") and then a definition of a different type (e.g.
39870b57cec5SDimitry Andric   // "int x[10];"). This also happens when an initializer has a different type
39880b57cec5SDimitry Andric   // from the type of the global (this happens with unions).
39890b57cec5SDimitry Andric   if (!GV || GV->getType()->getElementType() != InitType ||
39900b57cec5SDimitry Andric       GV->getType()->getAddressSpace() !=
39910b57cec5SDimitry Andric           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
39920b57cec5SDimitry Andric 
39930b57cec5SDimitry Andric     // Move the old entry aside so that we'll create a new one.
39940b57cec5SDimitry Andric     Entry->setName(StringRef());
39950b57cec5SDimitry Andric 
39960b57cec5SDimitry Andric     // Make a new global with the correct type, this is now guaranteed to work.
39970b57cec5SDimitry Andric     GV = cast<llvm::GlobalVariable>(
3998a7dea167SDimitry Andric         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
3999a7dea167SDimitry Andric             ->stripPointerCasts());
40000b57cec5SDimitry Andric 
40010b57cec5SDimitry Andric     // Replace all uses of the old global with the new global
40020b57cec5SDimitry Andric     llvm::Constant *NewPtrForOldDecl =
40030b57cec5SDimitry Andric         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
40040b57cec5SDimitry Andric     Entry->replaceAllUsesWith(NewPtrForOldDecl);
40050b57cec5SDimitry Andric 
40060b57cec5SDimitry Andric     // Erase the old global, since it is no longer used.
40070b57cec5SDimitry Andric     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
40080b57cec5SDimitry Andric   }
40090b57cec5SDimitry Andric 
40100b57cec5SDimitry Andric   MaybeHandleStaticInExternC(D, GV);
40110b57cec5SDimitry Andric 
40120b57cec5SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
40130b57cec5SDimitry Andric     AddGlobalAnnotations(D, GV);
40140b57cec5SDimitry Andric 
40150b57cec5SDimitry Andric   // Set the llvm linkage type as appropriate.
40160b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
40170b57cec5SDimitry Andric       getLLVMLinkageVarDefinition(D, GV->isConstant());
40180b57cec5SDimitry Andric 
40190b57cec5SDimitry Andric   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
40200b57cec5SDimitry Andric   // the device. [...]"
40210b57cec5SDimitry Andric   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
40220b57cec5SDimitry Andric   // __device__, declares a variable that: [...]
40230b57cec5SDimitry Andric   // Is accessible from all the threads within the grid and from the host
40240b57cec5SDimitry Andric   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
40250b57cec5SDimitry Andric   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
40260b57cec5SDimitry Andric   if (GV && LangOpts.CUDA) {
40270b57cec5SDimitry Andric     if (LangOpts.CUDAIsDevice) {
40280b57cec5SDimitry Andric       if (Linkage != llvm::GlobalValue::InternalLinkage &&
40290b57cec5SDimitry Andric           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()))
40300b57cec5SDimitry Andric         GV->setExternallyInitialized(true);
40310b57cec5SDimitry Andric     } else {
40320b57cec5SDimitry Andric       // Host-side shadows of external declarations of device-side
40330b57cec5SDimitry Andric       // global variables become internal definitions. These have to
40340b57cec5SDimitry Andric       // be internal in order to prevent name conflicts with global
40350b57cec5SDimitry Andric       // host variables with the same name in a different TUs.
40360b57cec5SDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
40370b57cec5SDimitry Andric           D->hasAttr<HIPPinnedShadowAttr>()) {
40380b57cec5SDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
40390b57cec5SDimitry Andric 
40400b57cec5SDimitry Andric         // Shadow variables and their properties must be registered
40410b57cec5SDimitry Andric         // with CUDA runtime.
40420b57cec5SDimitry Andric         unsigned Flags = 0;
40430b57cec5SDimitry Andric         if (!D->hasDefinition())
40440b57cec5SDimitry Andric           Flags |= CGCUDARuntime::ExternDeviceVar;
40450b57cec5SDimitry Andric         if (D->hasAttr<CUDAConstantAttr>())
40460b57cec5SDimitry Andric           Flags |= CGCUDARuntime::ConstantDeviceVar;
40470b57cec5SDimitry Andric         // Extern global variables will be registered in the TU where they are
40480b57cec5SDimitry Andric         // defined.
40490b57cec5SDimitry Andric         if (!D->hasExternalStorage())
40500b57cec5SDimitry Andric           getCUDARuntime().registerDeviceVar(D, *GV, Flags);
40510b57cec5SDimitry Andric       } else if (D->hasAttr<CUDASharedAttr>())
40520b57cec5SDimitry Andric         // __shared__ variables are odd. Shadows do get created, but
40530b57cec5SDimitry Andric         // they are not registered with the CUDA runtime, so they
40540b57cec5SDimitry Andric         // can't really be used to access their device-side
40550b57cec5SDimitry Andric         // counterparts. It's not clear yet whether it's nvcc's bug or
40560b57cec5SDimitry Andric         // a feature, but we've got to do the same for compatibility.
40570b57cec5SDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
40580b57cec5SDimitry Andric     }
40590b57cec5SDimitry Andric   }
40600b57cec5SDimitry Andric 
40610b57cec5SDimitry Andric   if (!IsHIPPinnedShadowVar)
40620b57cec5SDimitry Andric     GV->setInitializer(Init);
40630b57cec5SDimitry Andric   if (emitter) emitter->finalize(GV);
40640b57cec5SDimitry Andric 
40650b57cec5SDimitry Andric   // If it is safe to mark the global 'constant', do so now.
40660b57cec5SDimitry Andric   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
40670b57cec5SDimitry Andric                   isTypeConstant(D->getType(), true));
40680b57cec5SDimitry Andric 
40690b57cec5SDimitry Andric   // If it is in a read-only section, mark it 'constant'.
40700b57cec5SDimitry Andric   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
40710b57cec5SDimitry Andric     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
40720b57cec5SDimitry Andric     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
40730b57cec5SDimitry Andric       GV->setConstant(true);
40740b57cec5SDimitry Andric   }
40750b57cec5SDimitry Andric 
4076a7dea167SDimitry Andric   GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
40770b57cec5SDimitry Andric 
40780b57cec5SDimitry Andric   // On Darwin, if the normal linkage of a C++ thread_local variable is
40790b57cec5SDimitry Andric   // LinkOnce or Weak, we keep the normal linkage to prevent multiple
40800b57cec5SDimitry Andric   // copies within a linkage unit; otherwise, the backing variable has
40810b57cec5SDimitry Andric   // internal linkage and all accesses should just be calls to the
40820b57cec5SDimitry Andric   // Itanium-specified entry point, which has the normal linkage of the
40830b57cec5SDimitry Andric   // variable. This is to preserve the ability to change the implementation
40840b57cec5SDimitry Andric   // behind the scenes.
40850b57cec5SDimitry Andric   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
40860b57cec5SDimitry Andric       Context.getTargetInfo().getTriple().isOSDarwin() &&
40870b57cec5SDimitry Andric       !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
40880b57cec5SDimitry Andric       !llvm::GlobalVariable::isWeakLinkage(Linkage))
40890b57cec5SDimitry Andric     Linkage = llvm::GlobalValue::InternalLinkage;
40900b57cec5SDimitry Andric 
40910b57cec5SDimitry Andric   GV->setLinkage(Linkage);
40920b57cec5SDimitry Andric   if (D->hasAttr<DLLImportAttr>())
40930b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
40940b57cec5SDimitry Andric   else if (D->hasAttr<DLLExportAttr>())
40950b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
40960b57cec5SDimitry Andric   else
40970b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
40980b57cec5SDimitry Andric 
40990b57cec5SDimitry Andric   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
41000b57cec5SDimitry Andric     // common vars aren't constant even if declared const.
41010b57cec5SDimitry Andric     GV->setConstant(false);
41020b57cec5SDimitry Andric     // Tentative definition of global variables may be initialized with
41030b57cec5SDimitry Andric     // non-zero null pointers. In this case they should have weak linkage
41040b57cec5SDimitry Andric     // since common linkage must have zero initializer and must not have
41050b57cec5SDimitry Andric     // explicit section therefore cannot have non-zero initial value.
41060b57cec5SDimitry Andric     if (!GV->getInitializer()->isNullValue())
41070b57cec5SDimitry Andric       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
41080b57cec5SDimitry Andric   }
41090b57cec5SDimitry Andric 
41100b57cec5SDimitry Andric   setNonAliasAttributes(D, GV);
41110b57cec5SDimitry Andric 
41120b57cec5SDimitry Andric   if (D->getTLSKind() && !GV->isThreadLocal()) {
41130b57cec5SDimitry Andric     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
41140b57cec5SDimitry Andric       CXXThreadLocals.push_back(D);
41150b57cec5SDimitry Andric     setTLSMode(GV, *D);
41160b57cec5SDimitry Andric   }
41170b57cec5SDimitry Andric 
41180b57cec5SDimitry Andric   maybeSetTrivialComdat(*D, *GV);
41190b57cec5SDimitry Andric 
41200b57cec5SDimitry Andric   // Emit the initializer function if necessary.
41210b57cec5SDimitry Andric   if (NeedsGlobalCtor || NeedsGlobalDtor)
41220b57cec5SDimitry Andric     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
41230b57cec5SDimitry Andric 
41240b57cec5SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
41250b57cec5SDimitry Andric 
41260b57cec5SDimitry Andric   // Emit global variable debug information.
41270b57cec5SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
4128480093f4SDimitry Andric     if (getCodeGenOpts().hasReducedDebugInfo())
41290b57cec5SDimitry Andric       DI->EmitGlobalVariable(GV, D);
41300b57cec5SDimitry Andric }
41310b57cec5SDimitry Andric 
4132480093f4SDimitry Andric void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
4133480093f4SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
4134480093f4SDimitry Andric     if (getCodeGenOpts().hasReducedDebugInfo()) {
4135480093f4SDimitry Andric       QualType ASTTy = D->getType();
4136480093f4SDimitry Andric       llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
4137480093f4SDimitry Andric       llvm::PointerType *PTy =
4138480093f4SDimitry Andric           llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
4139480093f4SDimitry Andric       llvm::Constant *GV = GetOrCreateLLVMGlobal(D->getName(), PTy, D);
4140480093f4SDimitry Andric       DI->EmitExternalVariable(
4141480093f4SDimitry Andric           cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
4142480093f4SDimitry Andric     }
4143480093f4SDimitry Andric }
4144480093f4SDimitry Andric 
41450b57cec5SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context,
41460b57cec5SDimitry Andric                                       CodeGenModule &CGM, const VarDecl *D,
41470b57cec5SDimitry Andric                                       bool NoCommon) {
41480b57cec5SDimitry Andric   // Don't give variables common linkage if -fno-common was specified unless it
41490b57cec5SDimitry Andric   // was overridden by a NoCommon attribute.
41500b57cec5SDimitry Andric   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
41510b57cec5SDimitry Andric     return true;
41520b57cec5SDimitry Andric 
41530b57cec5SDimitry Andric   // C11 6.9.2/2:
41540b57cec5SDimitry Andric   //   A declaration of an identifier for an object that has file scope without
41550b57cec5SDimitry Andric   //   an initializer, and without a storage-class specifier or with the
41560b57cec5SDimitry Andric   //   storage-class specifier static, constitutes a tentative definition.
41570b57cec5SDimitry Andric   if (D->getInit() || D->hasExternalStorage())
41580b57cec5SDimitry Andric     return true;
41590b57cec5SDimitry Andric 
41600b57cec5SDimitry Andric   // A variable cannot be both common and exist in a section.
41610b57cec5SDimitry Andric   if (D->hasAttr<SectionAttr>())
41620b57cec5SDimitry Andric     return true;
41630b57cec5SDimitry Andric 
41640b57cec5SDimitry Andric   // A variable cannot be both common and exist in a section.
41650b57cec5SDimitry Andric   // We don't try to determine which is the right section in the front-end.
41660b57cec5SDimitry Andric   // If no specialized section name is applicable, it will resort to default.
41670b57cec5SDimitry Andric   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
41680b57cec5SDimitry Andric       D->hasAttr<PragmaClangDataSectionAttr>() ||
4169a7dea167SDimitry Andric       D->hasAttr<PragmaClangRelroSectionAttr>() ||
41700b57cec5SDimitry Andric       D->hasAttr<PragmaClangRodataSectionAttr>())
41710b57cec5SDimitry Andric     return true;
41720b57cec5SDimitry Andric 
41730b57cec5SDimitry Andric   // Thread local vars aren't considered common linkage.
41740b57cec5SDimitry Andric   if (D->getTLSKind())
41750b57cec5SDimitry Andric     return true;
41760b57cec5SDimitry Andric 
41770b57cec5SDimitry Andric   // Tentative definitions marked with WeakImportAttr are true definitions.
41780b57cec5SDimitry Andric   if (D->hasAttr<WeakImportAttr>())
41790b57cec5SDimitry Andric     return true;
41800b57cec5SDimitry Andric 
41810b57cec5SDimitry Andric   // A variable cannot be both common and exist in a comdat.
41820b57cec5SDimitry Andric   if (shouldBeInCOMDAT(CGM, *D))
41830b57cec5SDimitry Andric     return true;
41840b57cec5SDimitry Andric 
41850b57cec5SDimitry Andric   // Declarations with a required alignment do not have common linkage in MSVC
41860b57cec5SDimitry Andric   // mode.
41870b57cec5SDimitry Andric   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
41880b57cec5SDimitry Andric     if (D->hasAttr<AlignedAttr>())
41890b57cec5SDimitry Andric       return true;
41900b57cec5SDimitry Andric     QualType VarType = D->getType();
41910b57cec5SDimitry Andric     if (Context.isAlignmentRequired(VarType))
41920b57cec5SDimitry Andric       return true;
41930b57cec5SDimitry Andric 
41940b57cec5SDimitry Andric     if (const auto *RT = VarType->getAs<RecordType>()) {
41950b57cec5SDimitry Andric       const RecordDecl *RD = RT->getDecl();
41960b57cec5SDimitry Andric       for (const FieldDecl *FD : RD->fields()) {
41970b57cec5SDimitry Andric         if (FD->isBitField())
41980b57cec5SDimitry Andric           continue;
41990b57cec5SDimitry Andric         if (FD->hasAttr<AlignedAttr>())
42000b57cec5SDimitry Andric           return true;
42010b57cec5SDimitry Andric         if (Context.isAlignmentRequired(FD->getType()))
42020b57cec5SDimitry Andric           return true;
42030b57cec5SDimitry Andric       }
42040b57cec5SDimitry Andric     }
42050b57cec5SDimitry Andric   }
42060b57cec5SDimitry Andric 
42070b57cec5SDimitry Andric   // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
42080b57cec5SDimitry Andric   // common symbols, so symbols with greater alignment requirements cannot be
42090b57cec5SDimitry Andric   // common.
42100b57cec5SDimitry Andric   // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
42110b57cec5SDimitry Andric   // alignments for common symbols via the aligncomm directive, so this
42120b57cec5SDimitry Andric   // restriction only applies to MSVC environments.
42130b57cec5SDimitry Andric   if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
42140b57cec5SDimitry Andric       Context.getTypeAlignIfKnown(D->getType()) >
42150b57cec5SDimitry Andric           Context.toBits(CharUnits::fromQuantity(32)))
42160b57cec5SDimitry Andric     return true;
42170b57cec5SDimitry Andric 
42180b57cec5SDimitry Andric   return false;
42190b57cec5SDimitry Andric }
42200b57cec5SDimitry Andric 
42210b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
42220b57cec5SDimitry Andric     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
42230b57cec5SDimitry Andric   if (Linkage == GVA_Internal)
42240b57cec5SDimitry Andric     return llvm::Function::InternalLinkage;
42250b57cec5SDimitry Andric 
42260b57cec5SDimitry Andric   if (D->hasAttr<WeakAttr>()) {
42270b57cec5SDimitry Andric     if (IsConstantVariable)
42280b57cec5SDimitry Andric       return llvm::GlobalVariable::WeakODRLinkage;
42290b57cec5SDimitry Andric     else
42300b57cec5SDimitry Andric       return llvm::GlobalVariable::WeakAnyLinkage;
42310b57cec5SDimitry Andric   }
42320b57cec5SDimitry Andric 
42330b57cec5SDimitry Andric   if (const auto *FD = D->getAsFunction())
42340b57cec5SDimitry Andric     if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
42350b57cec5SDimitry Andric       return llvm::GlobalVariable::LinkOnceAnyLinkage;
42360b57cec5SDimitry Andric 
42370b57cec5SDimitry Andric   // We are guaranteed to have a strong definition somewhere else,
42380b57cec5SDimitry Andric   // so we can use available_externally linkage.
42390b57cec5SDimitry Andric   if (Linkage == GVA_AvailableExternally)
42400b57cec5SDimitry Andric     return llvm::GlobalValue::AvailableExternallyLinkage;
42410b57cec5SDimitry Andric 
42420b57cec5SDimitry Andric   // Note that Apple's kernel linker doesn't support symbol
42430b57cec5SDimitry Andric   // coalescing, so we need to avoid linkonce and weak linkages there.
42440b57cec5SDimitry Andric   // Normally, this means we just map to internal, but for explicit
42450b57cec5SDimitry Andric   // instantiations we'll map to external.
42460b57cec5SDimitry Andric 
42470b57cec5SDimitry Andric   // In C++, the compiler has to emit a definition in every translation unit
42480b57cec5SDimitry Andric   // that references the function.  We should use linkonce_odr because
42490b57cec5SDimitry Andric   // a) if all references in this translation unit are optimized away, we
42500b57cec5SDimitry Andric   // don't need to codegen it.  b) if the function persists, it needs to be
42510b57cec5SDimitry Andric   // merged with other definitions. c) C++ has the ODR, so we know the
42520b57cec5SDimitry Andric   // definition is dependable.
42530b57cec5SDimitry Andric   if (Linkage == GVA_DiscardableODR)
42540b57cec5SDimitry Andric     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
42550b57cec5SDimitry Andric                                             : llvm::Function::InternalLinkage;
42560b57cec5SDimitry Andric 
42570b57cec5SDimitry Andric   // An explicit instantiation of a template has weak linkage, since
42580b57cec5SDimitry Andric   // explicit instantiations can occur in multiple translation units
42590b57cec5SDimitry Andric   // and must all be equivalent. However, we are not allowed to
42600b57cec5SDimitry Andric   // throw away these explicit instantiations.
42610b57cec5SDimitry Andric   //
42620b57cec5SDimitry Andric   // We don't currently support CUDA device code spread out across multiple TUs,
42630b57cec5SDimitry Andric   // so say that CUDA templates are either external (for kernels) or internal.
42640b57cec5SDimitry Andric   // This lets llvm perform aggressive inter-procedural optimizations.
42650b57cec5SDimitry Andric   if (Linkage == GVA_StrongODR) {
42660b57cec5SDimitry Andric     if (Context.getLangOpts().AppleKext)
42670b57cec5SDimitry Andric       return llvm::Function::ExternalLinkage;
42680b57cec5SDimitry Andric     if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
42690b57cec5SDimitry Andric       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
42700b57cec5SDimitry Andric                                           : llvm::Function::InternalLinkage;
42710b57cec5SDimitry Andric     return llvm::Function::WeakODRLinkage;
42720b57cec5SDimitry Andric   }
42730b57cec5SDimitry Andric 
42740b57cec5SDimitry Andric   // C++ doesn't have tentative definitions and thus cannot have common
42750b57cec5SDimitry Andric   // linkage.
42760b57cec5SDimitry Andric   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
42770b57cec5SDimitry Andric       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
42780b57cec5SDimitry Andric                                  CodeGenOpts.NoCommon))
42790b57cec5SDimitry Andric     return llvm::GlobalVariable::CommonLinkage;
42800b57cec5SDimitry Andric 
42810b57cec5SDimitry Andric   // selectany symbols are externally visible, so use weak instead of
42820b57cec5SDimitry Andric   // linkonce.  MSVC optimizes away references to const selectany globals, so
42830b57cec5SDimitry Andric   // all definitions should be the same and ODR linkage should be used.
42840b57cec5SDimitry Andric   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
42850b57cec5SDimitry Andric   if (D->hasAttr<SelectAnyAttr>())
42860b57cec5SDimitry Andric     return llvm::GlobalVariable::WeakODRLinkage;
42870b57cec5SDimitry Andric 
42880b57cec5SDimitry Andric   // Otherwise, we have strong external linkage.
42890b57cec5SDimitry Andric   assert(Linkage == GVA_StrongExternal);
42900b57cec5SDimitry Andric   return llvm::GlobalVariable::ExternalLinkage;
42910b57cec5SDimitry Andric }
42920b57cec5SDimitry Andric 
42930b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
42940b57cec5SDimitry Andric     const VarDecl *VD, bool IsConstant) {
42950b57cec5SDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
42960b57cec5SDimitry Andric   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
42970b57cec5SDimitry Andric }
42980b57cec5SDimitry Andric 
42990b57cec5SDimitry Andric /// Replace the uses of a function that was declared with a non-proto type.
43000b57cec5SDimitry Andric /// We want to silently drop extra arguments from call sites
43010b57cec5SDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
43020b57cec5SDimitry Andric                                           llvm::Function *newFn) {
43030b57cec5SDimitry Andric   // Fast path.
43040b57cec5SDimitry Andric   if (old->use_empty()) return;
43050b57cec5SDimitry Andric 
43060b57cec5SDimitry Andric   llvm::Type *newRetTy = newFn->getReturnType();
43070b57cec5SDimitry Andric   SmallVector<llvm::Value*, 4> newArgs;
43080b57cec5SDimitry Andric   SmallVector<llvm::OperandBundleDef, 1> newBundles;
43090b57cec5SDimitry Andric 
43100b57cec5SDimitry Andric   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
43110b57cec5SDimitry Andric          ui != ue; ) {
43120b57cec5SDimitry Andric     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
43130b57cec5SDimitry Andric     llvm::User *user = use->getUser();
43140b57cec5SDimitry Andric 
43150b57cec5SDimitry Andric     // Recognize and replace uses of bitcasts.  Most calls to
43160b57cec5SDimitry Andric     // unprototyped functions will use bitcasts.
43170b57cec5SDimitry Andric     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
43180b57cec5SDimitry Andric       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
43190b57cec5SDimitry Andric         replaceUsesOfNonProtoConstant(bitcast, newFn);
43200b57cec5SDimitry Andric       continue;
43210b57cec5SDimitry Andric     }
43220b57cec5SDimitry Andric 
43230b57cec5SDimitry Andric     // Recognize calls to the function.
43240b57cec5SDimitry Andric     llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
43250b57cec5SDimitry Andric     if (!callSite) continue;
43260b57cec5SDimitry Andric     if (!callSite->isCallee(&*use))
43270b57cec5SDimitry Andric       continue;
43280b57cec5SDimitry Andric 
43290b57cec5SDimitry Andric     // If the return types don't match exactly, then we can't
43300b57cec5SDimitry Andric     // transform this call unless it's dead.
43310b57cec5SDimitry Andric     if (callSite->getType() != newRetTy && !callSite->use_empty())
43320b57cec5SDimitry Andric       continue;
43330b57cec5SDimitry Andric 
43340b57cec5SDimitry Andric     // Get the call site's attribute list.
43350b57cec5SDimitry Andric     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
43360b57cec5SDimitry Andric     llvm::AttributeList oldAttrs = callSite->getAttributes();
43370b57cec5SDimitry Andric 
43380b57cec5SDimitry Andric     // If the function was passed too few arguments, don't transform.
43390b57cec5SDimitry Andric     unsigned newNumArgs = newFn->arg_size();
43400b57cec5SDimitry Andric     if (callSite->arg_size() < newNumArgs)
43410b57cec5SDimitry Andric       continue;
43420b57cec5SDimitry Andric 
43430b57cec5SDimitry Andric     // If extra arguments were passed, we silently drop them.
43440b57cec5SDimitry Andric     // If any of the types mismatch, we don't transform.
43450b57cec5SDimitry Andric     unsigned argNo = 0;
43460b57cec5SDimitry Andric     bool dontTransform = false;
43470b57cec5SDimitry Andric     for (llvm::Argument &A : newFn->args()) {
43480b57cec5SDimitry Andric       if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
43490b57cec5SDimitry Andric         dontTransform = true;
43500b57cec5SDimitry Andric         break;
43510b57cec5SDimitry Andric       }
43520b57cec5SDimitry Andric 
43530b57cec5SDimitry Andric       // Add any parameter attributes.
43540b57cec5SDimitry Andric       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
43550b57cec5SDimitry Andric       argNo++;
43560b57cec5SDimitry Andric     }
43570b57cec5SDimitry Andric     if (dontTransform)
43580b57cec5SDimitry Andric       continue;
43590b57cec5SDimitry Andric 
43600b57cec5SDimitry Andric     // Okay, we can transform this.  Create the new call instruction and copy
43610b57cec5SDimitry Andric     // over the required information.
43620b57cec5SDimitry Andric     newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
43630b57cec5SDimitry Andric 
43640b57cec5SDimitry Andric     // Copy over any operand bundles.
43650b57cec5SDimitry Andric     callSite->getOperandBundlesAsDefs(newBundles);
43660b57cec5SDimitry Andric 
43670b57cec5SDimitry Andric     llvm::CallBase *newCall;
43680b57cec5SDimitry Andric     if (dyn_cast<llvm::CallInst>(callSite)) {
43690b57cec5SDimitry Andric       newCall =
43700b57cec5SDimitry Andric           llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
43710b57cec5SDimitry Andric     } else {
43720b57cec5SDimitry Andric       auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
43730b57cec5SDimitry Andric       newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
43740b57cec5SDimitry Andric                                          oldInvoke->getUnwindDest(), newArgs,
43750b57cec5SDimitry Andric                                          newBundles, "", callSite);
43760b57cec5SDimitry Andric     }
43770b57cec5SDimitry Andric     newArgs.clear(); // for the next iteration
43780b57cec5SDimitry Andric 
43790b57cec5SDimitry Andric     if (!newCall->getType()->isVoidTy())
43800b57cec5SDimitry Andric       newCall->takeName(callSite);
43810b57cec5SDimitry Andric     newCall->setAttributes(llvm::AttributeList::get(
43820b57cec5SDimitry Andric         newFn->getContext(), oldAttrs.getFnAttributes(),
43830b57cec5SDimitry Andric         oldAttrs.getRetAttributes(), newArgAttrs));
43840b57cec5SDimitry Andric     newCall->setCallingConv(callSite->getCallingConv());
43850b57cec5SDimitry Andric 
43860b57cec5SDimitry Andric     // Finally, remove the old call, replacing any uses with the new one.
43870b57cec5SDimitry Andric     if (!callSite->use_empty())
43880b57cec5SDimitry Andric       callSite->replaceAllUsesWith(newCall);
43890b57cec5SDimitry Andric 
43900b57cec5SDimitry Andric     // Copy debug location attached to CI.
43910b57cec5SDimitry Andric     if (callSite->getDebugLoc())
43920b57cec5SDimitry Andric       newCall->setDebugLoc(callSite->getDebugLoc());
43930b57cec5SDimitry Andric 
43940b57cec5SDimitry Andric     callSite->eraseFromParent();
43950b57cec5SDimitry Andric   }
43960b57cec5SDimitry Andric }
43970b57cec5SDimitry Andric 
43980b57cec5SDimitry Andric /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
43990b57cec5SDimitry Andric /// implement a function with no prototype, e.g. "int foo() {}".  If there are
44000b57cec5SDimitry Andric /// existing call uses of the old function in the module, this adjusts them to
44010b57cec5SDimitry Andric /// call the new function directly.
44020b57cec5SDimitry Andric ///
44030b57cec5SDimitry Andric /// This is not just a cleanup: the always_inline pass requires direct calls to
44040b57cec5SDimitry Andric /// functions to be able to inline them.  If there is a bitcast in the way, it
44050b57cec5SDimitry Andric /// won't inline them.  Instcombine normally deletes these calls, but it isn't
44060b57cec5SDimitry Andric /// run at -O0.
44070b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
44080b57cec5SDimitry Andric                                                       llvm::Function *NewFn) {
44090b57cec5SDimitry Andric   // If we're redefining a global as a function, don't transform it.
44100b57cec5SDimitry Andric   if (!isa<llvm::Function>(Old)) return;
44110b57cec5SDimitry Andric 
44120b57cec5SDimitry Andric   replaceUsesOfNonProtoConstant(Old, NewFn);
44130b57cec5SDimitry Andric }
44140b57cec5SDimitry Andric 
44150b57cec5SDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
44160b57cec5SDimitry Andric   auto DK = VD->isThisDeclarationADefinition();
44170b57cec5SDimitry Andric   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
44180b57cec5SDimitry Andric     return;
44190b57cec5SDimitry Andric 
44200b57cec5SDimitry Andric   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
44210b57cec5SDimitry Andric   // If we have a definition, this might be a deferred decl. If the
44220b57cec5SDimitry Andric   // instantiation is explicit, make sure we emit it at the end.
44230b57cec5SDimitry Andric   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
44240b57cec5SDimitry Andric     GetAddrOfGlobalVar(VD);
44250b57cec5SDimitry Andric 
44260b57cec5SDimitry Andric   EmitTopLevelDecl(VD);
44270b57cec5SDimitry Andric }
44280b57cec5SDimitry Andric 
44290b57cec5SDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
44300b57cec5SDimitry Andric                                                  llvm::GlobalValue *GV) {
4431a7dea167SDimitry Andric   // Check if this must be emitted as declare variant.
4432a7dea167SDimitry Andric   if (LangOpts.OpenMP && OpenMPRuntime &&
4433a7dea167SDimitry Andric       OpenMPRuntime->emitDeclareVariant(GD, /*IsForDefinition=*/true))
4434a7dea167SDimitry Andric     return;
4435a7dea167SDimitry Andric 
44360b57cec5SDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
44370b57cec5SDimitry Andric 
44380b57cec5SDimitry Andric   // Compute the function info and LLVM type.
44390b57cec5SDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
44400b57cec5SDimitry Andric   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
44410b57cec5SDimitry Andric 
44420b57cec5SDimitry Andric   // Get or create the prototype for the function.
44430b57cec5SDimitry Andric   if (!GV || (GV->getType()->getElementType() != Ty))
44440b57cec5SDimitry Andric     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
44450b57cec5SDimitry Andric                                                    /*DontDefer=*/true,
44460b57cec5SDimitry Andric                                                    ForDefinition));
44470b57cec5SDimitry Andric 
44480b57cec5SDimitry Andric   // Already emitted.
44490b57cec5SDimitry Andric   if (!GV->isDeclaration())
44500b57cec5SDimitry Andric     return;
44510b57cec5SDimitry Andric 
44520b57cec5SDimitry Andric   // We need to set linkage and visibility on the function before
44530b57cec5SDimitry Andric   // generating code for it because various parts of IR generation
44540b57cec5SDimitry Andric   // want to propagate this information down (e.g. to local static
44550b57cec5SDimitry Andric   // declarations).
44560b57cec5SDimitry Andric   auto *Fn = cast<llvm::Function>(GV);
44570b57cec5SDimitry Andric   setFunctionLinkage(GD, Fn);
44580b57cec5SDimitry Andric 
44590b57cec5SDimitry Andric   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
44600b57cec5SDimitry Andric   setGVProperties(Fn, GD);
44610b57cec5SDimitry Andric 
44620b57cec5SDimitry Andric   MaybeHandleStaticInExternC(D, Fn);
44630b57cec5SDimitry Andric 
44640b57cec5SDimitry Andric 
44650b57cec5SDimitry Andric   maybeSetTrivialComdat(*D, *Fn);
44660b57cec5SDimitry Andric 
44670b57cec5SDimitry Andric   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
44680b57cec5SDimitry Andric 
44690b57cec5SDimitry Andric   setNonAliasAttributes(GD, Fn);
44700b57cec5SDimitry Andric   SetLLVMFunctionAttributesForDefinition(D, Fn);
44710b57cec5SDimitry Andric 
44720b57cec5SDimitry Andric   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
44730b57cec5SDimitry Andric     AddGlobalCtor(Fn, CA->getPriority());
44740b57cec5SDimitry Andric   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
44750b57cec5SDimitry Andric     AddGlobalDtor(Fn, DA->getPriority());
44760b57cec5SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
44770b57cec5SDimitry Andric     AddGlobalAnnotations(D, Fn);
44780b57cec5SDimitry Andric }
44790b57cec5SDimitry Andric 
44800b57cec5SDimitry Andric void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
44810b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
44820b57cec5SDimitry Andric   const AliasAttr *AA = D->getAttr<AliasAttr>();
44830b57cec5SDimitry Andric   assert(AA && "Not an alias?");
44840b57cec5SDimitry Andric 
44850b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
44860b57cec5SDimitry Andric 
44870b57cec5SDimitry Andric   if (AA->getAliasee() == MangledName) {
44880b57cec5SDimitry Andric     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
44890b57cec5SDimitry Andric     return;
44900b57cec5SDimitry Andric   }
44910b57cec5SDimitry Andric 
44920b57cec5SDimitry Andric   // If there is a definition in the module, then it wins over the alias.
44930b57cec5SDimitry Andric   // This is dubious, but allow it to be safe.  Just ignore the alias.
44940b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
44950b57cec5SDimitry Andric   if (Entry && !Entry->isDeclaration())
44960b57cec5SDimitry Andric     return;
44970b57cec5SDimitry Andric 
44980b57cec5SDimitry Andric   Aliases.push_back(GD);
44990b57cec5SDimitry Andric 
45000b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
45010b57cec5SDimitry Andric 
45020b57cec5SDimitry Andric   // Create a reference to the named value.  This ensures that it is emitted
45030b57cec5SDimitry Andric   // if a deferred decl.
45040b57cec5SDimitry Andric   llvm::Constant *Aliasee;
45050b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
45060b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(DeclTy)) {
45070b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
45080b57cec5SDimitry Andric                                       /*ForVTable=*/false);
45090b57cec5SDimitry Andric     LT = getFunctionLinkage(GD);
45100b57cec5SDimitry Andric   } else {
45110b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
45120b57cec5SDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
45130b57cec5SDimitry Andric                                     /*D=*/nullptr);
45140b57cec5SDimitry Andric     LT = getLLVMLinkageVarDefinition(cast<VarDecl>(GD.getDecl()),
45150b57cec5SDimitry Andric                                      D->getType().isConstQualified());
45160b57cec5SDimitry Andric   }
45170b57cec5SDimitry Andric 
45180b57cec5SDimitry Andric   // Create the new alias itself, but don't set a name yet.
45190b57cec5SDimitry Andric   auto *GA =
45200b57cec5SDimitry Andric       llvm::GlobalAlias::create(DeclTy, 0, LT, "", Aliasee, &getModule());
45210b57cec5SDimitry Andric 
45220b57cec5SDimitry Andric   if (Entry) {
45230b57cec5SDimitry Andric     if (GA->getAliasee() == Entry) {
45240b57cec5SDimitry Andric       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
45250b57cec5SDimitry Andric       return;
45260b57cec5SDimitry Andric     }
45270b57cec5SDimitry Andric 
45280b57cec5SDimitry Andric     assert(Entry->isDeclaration());
45290b57cec5SDimitry Andric 
45300b57cec5SDimitry Andric     // If there is a declaration in the module, then we had an extern followed
45310b57cec5SDimitry Andric     // by the alias, as in:
45320b57cec5SDimitry Andric     //   extern int test6();
45330b57cec5SDimitry Andric     //   ...
45340b57cec5SDimitry Andric     //   int test6() __attribute__((alias("test7")));
45350b57cec5SDimitry Andric     //
45360b57cec5SDimitry Andric     // Remove it and replace uses of it with the alias.
45370b57cec5SDimitry Andric     GA->takeName(Entry);
45380b57cec5SDimitry Andric 
45390b57cec5SDimitry Andric     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
45400b57cec5SDimitry Andric                                                           Entry->getType()));
45410b57cec5SDimitry Andric     Entry->eraseFromParent();
45420b57cec5SDimitry Andric   } else {
45430b57cec5SDimitry Andric     GA->setName(MangledName);
45440b57cec5SDimitry Andric   }
45450b57cec5SDimitry Andric 
45460b57cec5SDimitry Andric   // Set attributes which are particular to an alias; this is a
45470b57cec5SDimitry Andric   // specialization of the attributes which may be set on a global
45480b57cec5SDimitry Andric   // variable/function.
45490b57cec5SDimitry Andric   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
45500b57cec5SDimitry Andric       D->isWeakImported()) {
45510b57cec5SDimitry Andric     GA->setLinkage(llvm::Function::WeakAnyLinkage);
45520b57cec5SDimitry Andric   }
45530b57cec5SDimitry Andric 
45540b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
45550b57cec5SDimitry Andric     if (VD->getTLSKind())
45560b57cec5SDimitry Andric       setTLSMode(GA, *VD);
45570b57cec5SDimitry Andric 
45580b57cec5SDimitry Andric   SetCommonAttributes(GD, GA);
45590b57cec5SDimitry Andric }
45600b57cec5SDimitry Andric 
45610b57cec5SDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
45620b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
45630b57cec5SDimitry Andric   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
45640b57cec5SDimitry Andric   assert(IFA && "Not an ifunc?");
45650b57cec5SDimitry Andric 
45660b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
45670b57cec5SDimitry Andric 
45680b57cec5SDimitry Andric   if (IFA->getResolver() == MangledName) {
45690b57cec5SDimitry Andric     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
45700b57cec5SDimitry Andric     return;
45710b57cec5SDimitry Andric   }
45720b57cec5SDimitry Andric 
45730b57cec5SDimitry Andric   // Report an error if some definition overrides ifunc.
45740b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
45750b57cec5SDimitry Andric   if (Entry && !Entry->isDeclaration()) {
45760b57cec5SDimitry Andric     GlobalDecl OtherGD;
45770b57cec5SDimitry Andric     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
45780b57cec5SDimitry Andric         DiagnosedConflictingDefinitions.insert(GD).second) {
45790b57cec5SDimitry Andric       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
45800b57cec5SDimitry Andric           << MangledName;
45810b57cec5SDimitry Andric       Diags.Report(OtherGD.getDecl()->getLocation(),
45820b57cec5SDimitry Andric                    diag::note_previous_definition);
45830b57cec5SDimitry Andric     }
45840b57cec5SDimitry Andric     return;
45850b57cec5SDimitry Andric   }
45860b57cec5SDimitry Andric 
45870b57cec5SDimitry Andric   Aliases.push_back(GD);
45880b57cec5SDimitry Andric 
45890b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
45900b57cec5SDimitry Andric   llvm::Constant *Resolver =
45910b57cec5SDimitry Andric       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
45920b57cec5SDimitry Andric                               /*ForVTable=*/false);
45930b57cec5SDimitry Andric   llvm::GlobalIFunc *GIF =
45940b57cec5SDimitry Andric       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
45950b57cec5SDimitry Andric                                 "", Resolver, &getModule());
45960b57cec5SDimitry Andric   if (Entry) {
45970b57cec5SDimitry Andric     if (GIF->getResolver() == Entry) {
45980b57cec5SDimitry Andric       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
45990b57cec5SDimitry Andric       return;
46000b57cec5SDimitry Andric     }
46010b57cec5SDimitry Andric     assert(Entry->isDeclaration());
46020b57cec5SDimitry Andric 
46030b57cec5SDimitry Andric     // If there is a declaration in the module, then we had an extern followed
46040b57cec5SDimitry Andric     // by the ifunc, as in:
46050b57cec5SDimitry Andric     //   extern int test();
46060b57cec5SDimitry Andric     //   ...
46070b57cec5SDimitry Andric     //   int test() __attribute__((ifunc("resolver")));
46080b57cec5SDimitry Andric     //
46090b57cec5SDimitry Andric     // Remove it and replace uses of it with the ifunc.
46100b57cec5SDimitry Andric     GIF->takeName(Entry);
46110b57cec5SDimitry Andric 
46120b57cec5SDimitry Andric     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
46130b57cec5SDimitry Andric                                                           Entry->getType()));
46140b57cec5SDimitry Andric     Entry->eraseFromParent();
46150b57cec5SDimitry Andric   } else
46160b57cec5SDimitry Andric     GIF->setName(MangledName);
46170b57cec5SDimitry Andric 
46180b57cec5SDimitry Andric   SetCommonAttributes(GD, GIF);
46190b57cec5SDimitry Andric }
46200b57cec5SDimitry Andric 
46210b57cec5SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
46220b57cec5SDimitry Andric                                             ArrayRef<llvm::Type*> Tys) {
46230b57cec5SDimitry Andric   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
46240b57cec5SDimitry Andric                                          Tys);
46250b57cec5SDimitry Andric }
46260b57cec5SDimitry Andric 
46270b57cec5SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> &
46280b57cec5SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
46290b57cec5SDimitry Andric                          const StringLiteral *Literal, bool TargetIsLSB,
46300b57cec5SDimitry Andric                          bool &IsUTF16, unsigned &StringLength) {
46310b57cec5SDimitry Andric   StringRef String = Literal->getString();
46320b57cec5SDimitry Andric   unsigned NumBytes = String.size();
46330b57cec5SDimitry Andric 
46340b57cec5SDimitry Andric   // Check for simple case.
46350b57cec5SDimitry Andric   if (!Literal->containsNonAsciiOrNull()) {
46360b57cec5SDimitry Andric     StringLength = NumBytes;
46370b57cec5SDimitry Andric     return *Map.insert(std::make_pair(String, nullptr)).first;
46380b57cec5SDimitry Andric   }
46390b57cec5SDimitry Andric 
46400b57cec5SDimitry Andric   // Otherwise, convert the UTF8 literals into a string of shorts.
46410b57cec5SDimitry Andric   IsUTF16 = true;
46420b57cec5SDimitry Andric 
46430b57cec5SDimitry Andric   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
46440b57cec5SDimitry Andric   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
46450b57cec5SDimitry Andric   llvm::UTF16 *ToPtr = &ToBuf[0];
46460b57cec5SDimitry Andric 
46470b57cec5SDimitry Andric   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
46480b57cec5SDimitry Andric                                  ToPtr + NumBytes, llvm::strictConversion);
46490b57cec5SDimitry Andric 
46500b57cec5SDimitry Andric   // ConvertUTF8toUTF16 returns the length in ToPtr.
46510b57cec5SDimitry Andric   StringLength = ToPtr - &ToBuf[0];
46520b57cec5SDimitry Andric 
46530b57cec5SDimitry Andric   // Add an explicit null.
46540b57cec5SDimitry Andric   *ToPtr = 0;
46550b57cec5SDimitry Andric   return *Map.insert(std::make_pair(
46560b57cec5SDimitry Andric                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
46570b57cec5SDimitry Andric                                    (StringLength + 1) * 2),
46580b57cec5SDimitry Andric                          nullptr)).first;
46590b57cec5SDimitry Andric }
46600b57cec5SDimitry Andric 
46610b57cec5SDimitry Andric ConstantAddress
46620b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
46630b57cec5SDimitry Andric   unsigned StringLength = 0;
46640b57cec5SDimitry Andric   bool isUTF16 = false;
46650b57cec5SDimitry Andric   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
46660b57cec5SDimitry Andric       GetConstantCFStringEntry(CFConstantStringMap, Literal,
46670b57cec5SDimitry Andric                                getDataLayout().isLittleEndian(), isUTF16,
46680b57cec5SDimitry Andric                                StringLength);
46690b57cec5SDimitry Andric 
46700b57cec5SDimitry Andric   if (auto *C = Entry.second)
46710b57cec5SDimitry Andric     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
46720b57cec5SDimitry Andric 
46730b57cec5SDimitry Andric   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
46740b57cec5SDimitry Andric   llvm::Constant *Zeros[] = { Zero, Zero };
46750b57cec5SDimitry Andric 
46760b57cec5SDimitry Andric   const ASTContext &Context = getContext();
46770b57cec5SDimitry Andric   const llvm::Triple &Triple = getTriple();
46780b57cec5SDimitry Andric 
46790b57cec5SDimitry Andric   const auto CFRuntime = getLangOpts().CFRuntime;
46800b57cec5SDimitry Andric   const bool IsSwiftABI =
46810b57cec5SDimitry Andric       static_cast<unsigned>(CFRuntime) >=
46820b57cec5SDimitry Andric       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
46830b57cec5SDimitry Andric   const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
46840b57cec5SDimitry Andric 
46850b57cec5SDimitry Andric   // If we don't already have it, get __CFConstantStringClassReference.
46860b57cec5SDimitry Andric   if (!CFConstantStringClassRef) {
46870b57cec5SDimitry Andric     const char *CFConstantStringClassName = "__CFConstantStringClassReference";
46880b57cec5SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
46890b57cec5SDimitry Andric     Ty = llvm::ArrayType::get(Ty, 0);
46900b57cec5SDimitry Andric 
46910b57cec5SDimitry Andric     switch (CFRuntime) {
46920b57cec5SDimitry Andric     default: break;
46930b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
46940b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift5_0:
46950b57cec5SDimitry Andric       CFConstantStringClassName =
46960b57cec5SDimitry Andric           Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
46970b57cec5SDimitry Andric                               : "$s10Foundation19_NSCFConstantStringCN";
46980b57cec5SDimitry Andric       Ty = IntPtrTy;
46990b57cec5SDimitry Andric       break;
47000b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift4_2:
47010b57cec5SDimitry Andric       CFConstantStringClassName =
47020b57cec5SDimitry Andric           Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
47030b57cec5SDimitry Andric                               : "$S10Foundation19_NSCFConstantStringCN";
47040b57cec5SDimitry Andric       Ty = IntPtrTy;
47050b57cec5SDimitry Andric       break;
47060b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift4_1:
47070b57cec5SDimitry Andric       CFConstantStringClassName =
47080b57cec5SDimitry Andric           Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
47090b57cec5SDimitry Andric                               : "__T010Foundation19_NSCFConstantStringCN";
47100b57cec5SDimitry Andric       Ty = IntPtrTy;
47110b57cec5SDimitry Andric       break;
47120b57cec5SDimitry Andric     }
47130b57cec5SDimitry Andric 
47140b57cec5SDimitry Andric     llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
47150b57cec5SDimitry Andric 
47160b57cec5SDimitry Andric     if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
47170b57cec5SDimitry Andric       llvm::GlobalValue *GV = nullptr;
47180b57cec5SDimitry Andric 
47190b57cec5SDimitry Andric       if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
47200b57cec5SDimitry Andric         IdentifierInfo &II = Context.Idents.get(GV->getName());
47210b57cec5SDimitry Andric         TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
47220b57cec5SDimitry Andric         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
47230b57cec5SDimitry Andric 
47240b57cec5SDimitry Andric         const VarDecl *VD = nullptr;
47250b57cec5SDimitry Andric         for (const auto &Result : DC->lookup(&II))
47260b57cec5SDimitry Andric           if ((VD = dyn_cast<VarDecl>(Result)))
47270b57cec5SDimitry Andric             break;
47280b57cec5SDimitry Andric 
47290b57cec5SDimitry Andric         if (Triple.isOSBinFormatELF()) {
47300b57cec5SDimitry Andric           if (!VD)
47310b57cec5SDimitry Andric             GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
47320b57cec5SDimitry Andric         } else {
47330b57cec5SDimitry Andric           GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
47340b57cec5SDimitry Andric           if (!VD || !VD->hasAttr<DLLExportAttr>())
47350b57cec5SDimitry Andric             GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
47360b57cec5SDimitry Andric           else
47370b57cec5SDimitry Andric             GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
47380b57cec5SDimitry Andric         }
47390b57cec5SDimitry Andric 
47400b57cec5SDimitry Andric         setDSOLocal(GV);
47410b57cec5SDimitry Andric       }
47420b57cec5SDimitry Andric     }
47430b57cec5SDimitry Andric 
47440b57cec5SDimitry Andric     // Decay array -> ptr
47450b57cec5SDimitry Andric     CFConstantStringClassRef =
47460b57cec5SDimitry Andric         IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
47470b57cec5SDimitry Andric                    : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
47480b57cec5SDimitry Andric   }
47490b57cec5SDimitry Andric 
47500b57cec5SDimitry Andric   QualType CFTy = Context.getCFConstantStringType();
47510b57cec5SDimitry Andric 
47520b57cec5SDimitry Andric   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
47530b57cec5SDimitry Andric 
47540b57cec5SDimitry Andric   ConstantInitBuilder Builder(*this);
47550b57cec5SDimitry Andric   auto Fields = Builder.beginStruct(STy);
47560b57cec5SDimitry Andric 
47570b57cec5SDimitry Andric   // Class pointer.
47580b57cec5SDimitry Andric   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
47590b57cec5SDimitry Andric 
47600b57cec5SDimitry Andric   // Flags.
47610b57cec5SDimitry Andric   if (IsSwiftABI) {
47620b57cec5SDimitry Andric     Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
47630b57cec5SDimitry Andric     Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
47640b57cec5SDimitry Andric   } else {
47650b57cec5SDimitry Andric     Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
47660b57cec5SDimitry Andric   }
47670b57cec5SDimitry Andric 
47680b57cec5SDimitry Andric   // String pointer.
47690b57cec5SDimitry Andric   llvm::Constant *C = nullptr;
47700b57cec5SDimitry Andric   if (isUTF16) {
47710b57cec5SDimitry Andric     auto Arr = llvm::makeArrayRef(
47720b57cec5SDimitry Andric         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
47730b57cec5SDimitry Andric         Entry.first().size() / 2);
47740b57cec5SDimitry Andric     C = llvm::ConstantDataArray::get(VMContext, Arr);
47750b57cec5SDimitry Andric   } else {
47760b57cec5SDimitry Andric     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
47770b57cec5SDimitry Andric   }
47780b57cec5SDimitry Andric 
47790b57cec5SDimitry Andric   // Note: -fwritable-strings doesn't make the backing store strings of
47800b57cec5SDimitry Andric   // CFStrings writable. (See <rdar://problem/10657500>)
47810b57cec5SDimitry Andric   auto *GV =
47820b57cec5SDimitry Andric       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
47830b57cec5SDimitry Andric                                llvm::GlobalValue::PrivateLinkage, C, ".str");
47840b57cec5SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
47850b57cec5SDimitry Andric   // Don't enforce the target's minimum global alignment, since the only use
47860b57cec5SDimitry Andric   // of the string is via this class initializer.
47870b57cec5SDimitry Andric   CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
47880b57cec5SDimitry Andric                             : Context.getTypeAlignInChars(Context.CharTy);
4789a7dea167SDimitry Andric   GV->setAlignment(Align.getAsAlign());
47900b57cec5SDimitry Andric 
47910b57cec5SDimitry Andric   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
47920b57cec5SDimitry Andric   // Without it LLVM can merge the string with a non unnamed_addr one during
47930b57cec5SDimitry Andric   // LTO.  Doing that changes the section it ends in, which surprises ld64.
47940b57cec5SDimitry Andric   if (Triple.isOSBinFormatMachO())
47950b57cec5SDimitry Andric     GV->setSection(isUTF16 ? "__TEXT,__ustring"
47960b57cec5SDimitry Andric                            : "__TEXT,__cstring,cstring_literals");
47970b57cec5SDimitry Andric   // Make sure the literal ends up in .rodata to allow for safe ICF and for
47980b57cec5SDimitry Andric   // the static linker to adjust permissions to read-only later on.
47990b57cec5SDimitry Andric   else if (Triple.isOSBinFormatELF())
48000b57cec5SDimitry Andric     GV->setSection(".rodata");
48010b57cec5SDimitry Andric 
48020b57cec5SDimitry Andric   // String.
48030b57cec5SDimitry Andric   llvm::Constant *Str =
48040b57cec5SDimitry Andric       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
48050b57cec5SDimitry Andric 
48060b57cec5SDimitry Andric   if (isUTF16)
48070b57cec5SDimitry Andric     // Cast the UTF16 string to the correct type.
48080b57cec5SDimitry Andric     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
48090b57cec5SDimitry Andric   Fields.add(Str);
48100b57cec5SDimitry Andric 
48110b57cec5SDimitry Andric   // String length.
48120b57cec5SDimitry Andric   llvm::IntegerType *LengthTy =
48130b57cec5SDimitry Andric       llvm::IntegerType::get(getModule().getContext(),
48140b57cec5SDimitry Andric                              Context.getTargetInfo().getLongWidth());
48150b57cec5SDimitry Andric   if (IsSwiftABI) {
48160b57cec5SDimitry Andric     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
48170b57cec5SDimitry Andric         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
48180b57cec5SDimitry Andric       LengthTy = Int32Ty;
48190b57cec5SDimitry Andric     else
48200b57cec5SDimitry Andric       LengthTy = IntPtrTy;
48210b57cec5SDimitry Andric   }
48220b57cec5SDimitry Andric   Fields.addInt(LengthTy, StringLength);
48230b57cec5SDimitry Andric 
4824a7dea167SDimitry Andric   // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
4825a7dea167SDimitry Andric   // properly aligned on 32-bit platforms.
4826a7dea167SDimitry Andric   CharUnits Alignment =
4827a7dea167SDimitry Andric       IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
48280b57cec5SDimitry Andric 
48290b57cec5SDimitry Andric   // The struct.
48300b57cec5SDimitry Andric   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
48310b57cec5SDimitry Andric                                     /*isConstant=*/false,
48320b57cec5SDimitry Andric                                     llvm::GlobalVariable::PrivateLinkage);
48330b57cec5SDimitry Andric   GV->addAttribute("objc_arc_inert");
48340b57cec5SDimitry Andric   switch (Triple.getObjectFormat()) {
48350b57cec5SDimitry Andric   case llvm::Triple::UnknownObjectFormat:
48360b57cec5SDimitry Andric     llvm_unreachable("unknown file format");
48370b57cec5SDimitry Andric   case llvm::Triple::XCOFF:
48380b57cec5SDimitry Andric     llvm_unreachable("XCOFF is not yet implemented");
48390b57cec5SDimitry Andric   case llvm::Triple::COFF:
48400b57cec5SDimitry Andric   case llvm::Triple::ELF:
48410b57cec5SDimitry Andric   case llvm::Triple::Wasm:
48420b57cec5SDimitry Andric     GV->setSection("cfstring");
48430b57cec5SDimitry Andric     break;
48440b57cec5SDimitry Andric   case llvm::Triple::MachO:
48450b57cec5SDimitry Andric     GV->setSection("__DATA,__cfstring");
48460b57cec5SDimitry Andric     break;
48470b57cec5SDimitry Andric   }
48480b57cec5SDimitry Andric   Entry.second = GV;
48490b57cec5SDimitry Andric 
48500b57cec5SDimitry Andric   return ConstantAddress(GV, Alignment);
48510b57cec5SDimitry Andric }
48520b57cec5SDimitry Andric 
48530b57cec5SDimitry Andric bool CodeGenModule::getExpressionLocationsEnabled() const {
48540b57cec5SDimitry Andric   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
48550b57cec5SDimitry Andric }
48560b57cec5SDimitry Andric 
48570b57cec5SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() {
48580b57cec5SDimitry Andric   if (ObjCFastEnumerationStateType.isNull()) {
48590b57cec5SDimitry Andric     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
48600b57cec5SDimitry Andric     D->startDefinition();
48610b57cec5SDimitry Andric 
48620b57cec5SDimitry Andric     QualType FieldTypes[] = {
48630b57cec5SDimitry Andric       Context.UnsignedLongTy,
48640b57cec5SDimitry Andric       Context.getPointerType(Context.getObjCIdType()),
48650b57cec5SDimitry Andric       Context.getPointerType(Context.UnsignedLongTy),
48660b57cec5SDimitry Andric       Context.getConstantArrayType(Context.UnsignedLongTy,
4867a7dea167SDimitry Andric                            llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
48680b57cec5SDimitry Andric     };
48690b57cec5SDimitry Andric 
48700b57cec5SDimitry Andric     for (size_t i = 0; i < 4; ++i) {
48710b57cec5SDimitry Andric       FieldDecl *Field = FieldDecl::Create(Context,
48720b57cec5SDimitry Andric                                            D,
48730b57cec5SDimitry Andric                                            SourceLocation(),
48740b57cec5SDimitry Andric                                            SourceLocation(), nullptr,
48750b57cec5SDimitry Andric                                            FieldTypes[i], /*TInfo=*/nullptr,
48760b57cec5SDimitry Andric                                            /*BitWidth=*/nullptr,
48770b57cec5SDimitry Andric                                            /*Mutable=*/false,
48780b57cec5SDimitry Andric                                            ICIS_NoInit);
48790b57cec5SDimitry Andric       Field->setAccess(AS_public);
48800b57cec5SDimitry Andric       D->addDecl(Field);
48810b57cec5SDimitry Andric     }
48820b57cec5SDimitry Andric 
48830b57cec5SDimitry Andric     D->completeDefinition();
48840b57cec5SDimitry Andric     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
48850b57cec5SDimitry Andric   }
48860b57cec5SDimitry Andric 
48870b57cec5SDimitry Andric   return ObjCFastEnumerationStateType;
48880b57cec5SDimitry Andric }
48890b57cec5SDimitry Andric 
48900b57cec5SDimitry Andric llvm::Constant *
48910b57cec5SDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
48920b57cec5SDimitry Andric   assert(!E->getType()->isPointerType() && "Strings are always arrays");
48930b57cec5SDimitry Andric 
48940b57cec5SDimitry Andric   // Don't emit it as the address of the string, emit the string data itself
48950b57cec5SDimitry Andric   // as an inline array.
48960b57cec5SDimitry Andric   if (E->getCharByteWidth() == 1) {
48970b57cec5SDimitry Andric     SmallString<64> Str(E->getString());
48980b57cec5SDimitry Andric 
48990b57cec5SDimitry Andric     // Resize the string to the right size, which is indicated by its type.
49000b57cec5SDimitry Andric     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
49010b57cec5SDimitry Andric     Str.resize(CAT->getSize().getZExtValue());
49020b57cec5SDimitry Andric     return llvm::ConstantDataArray::getString(VMContext, Str, false);
49030b57cec5SDimitry Andric   }
49040b57cec5SDimitry Andric 
49050b57cec5SDimitry Andric   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
49060b57cec5SDimitry Andric   llvm::Type *ElemTy = AType->getElementType();
49070b57cec5SDimitry Andric   unsigned NumElements = AType->getNumElements();
49080b57cec5SDimitry Andric 
49090b57cec5SDimitry Andric   // Wide strings have either 2-byte or 4-byte elements.
49100b57cec5SDimitry Andric   if (ElemTy->getPrimitiveSizeInBits() == 16) {
49110b57cec5SDimitry Andric     SmallVector<uint16_t, 32> Elements;
49120b57cec5SDimitry Andric     Elements.reserve(NumElements);
49130b57cec5SDimitry Andric 
49140b57cec5SDimitry Andric     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
49150b57cec5SDimitry Andric       Elements.push_back(E->getCodeUnit(i));
49160b57cec5SDimitry Andric     Elements.resize(NumElements);
49170b57cec5SDimitry Andric     return llvm::ConstantDataArray::get(VMContext, Elements);
49180b57cec5SDimitry Andric   }
49190b57cec5SDimitry Andric 
49200b57cec5SDimitry Andric   assert(ElemTy->getPrimitiveSizeInBits() == 32);
49210b57cec5SDimitry Andric   SmallVector<uint32_t, 32> Elements;
49220b57cec5SDimitry Andric   Elements.reserve(NumElements);
49230b57cec5SDimitry Andric 
49240b57cec5SDimitry Andric   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
49250b57cec5SDimitry Andric     Elements.push_back(E->getCodeUnit(i));
49260b57cec5SDimitry Andric   Elements.resize(NumElements);
49270b57cec5SDimitry Andric   return llvm::ConstantDataArray::get(VMContext, Elements);
49280b57cec5SDimitry Andric }
49290b57cec5SDimitry Andric 
49300b57cec5SDimitry Andric static llvm::GlobalVariable *
49310b57cec5SDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
49320b57cec5SDimitry Andric                       CodeGenModule &CGM, StringRef GlobalName,
49330b57cec5SDimitry Andric                       CharUnits Alignment) {
49340b57cec5SDimitry Andric   unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
49350b57cec5SDimitry Andric       CGM.getStringLiteralAddressSpace());
49360b57cec5SDimitry Andric 
49370b57cec5SDimitry Andric   llvm::Module &M = CGM.getModule();
49380b57cec5SDimitry Andric   // Create a global variable for this string
49390b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
49400b57cec5SDimitry Andric       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
49410b57cec5SDimitry Andric       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
4942a7dea167SDimitry Andric   GV->setAlignment(Alignment.getAsAlign());
49430b57cec5SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
49440b57cec5SDimitry Andric   if (GV->isWeakForLinker()) {
49450b57cec5SDimitry Andric     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
49460b57cec5SDimitry Andric     GV->setComdat(M.getOrInsertComdat(GV->getName()));
49470b57cec5SDimitry Andric   }
49480b57cec5SDimitry Andric   CGM.setDSOLocal(GV);
49490b57cec5SDimitry Andric 
49500b57cec5SDimitry Andric   return GV;
49510b57cec5SDimitry Andric }
49520b57cec5SDimitry Andric 
49530b57cec5SDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
49540b57cec5SDimitry Andric /// constant array for the given string literal.
49550b57cec5SDimitry Andric ConstantAddress
49560b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
49570b57cec5SDimitry Andric                                                   StringRef Name) {
49580b57cec5SDimitry Andric   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
49590b57cec5SDimitry Andric 
49600b57cec5SDimitry Andric   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
49610b57cec5SDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
49620b57cec5SDimitry Andric   if (!LangOpts.WritableStrings) {
49630b57cec5SDimitry Andric     Entry = &ConstantStringMap[C];
49640b57cec5SDimitry Andric     if (auto GV = *Entry) {
49650b57cec5SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
4966a7dea167SDimitry Andric         GV->setAlignment(Alignment.getAsAlign());
49670b57cec5SDimitry Andric       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
49680b57cec5SDimitry Andric                              Alignment);
49690b57cec5SDimitry Andric     }
49700b57cec5SDimitry Andric   }
49710b57cec5SDimitry Andric 
49720b57cec5SDimitry Andric   SmallString<256> MangledNameBuffer;
49730b57cec5SDimitry Andric   StringRef GlobalVariableName;
49740b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
49750b57cec5SDimitry Andric 
49760b57cec5SDimitry Andric   // Mangle the string literal if that's how the ABI merges duplicate strings.
49770b57cec5SDimitry Andric   // Don't do it if they are writable, since we don't want writes in one TU to
49780b57cec5SDimitry Andric   // affect strings in another.
49790b57cec5SDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
49800b57cec5SDimitry Andric       !LangOpts.WritableStrings) {
49810b57cec5SDimitry Andric     llvm::raw_svector_ostream Out(MangledNameBuffer);
49820b57cec5SDimitry Andric     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
49830b57cec5SDimitry Andric     LT = llvm::GlobalValue::LinkOnceODRLinkage;
49840b57cec5SDimitry Andric     GlobalVariableName = MangledNameBuffer;
49850b57cec5SDimitry Andric   } else {
49860b57cec5SDimitry Andric     LT = llvm::GlobalValue::PrivateLinkage;
49870b57cec5SDimitry Andric     GlobalVariableName = Name;
49880b57cec5SDimitry Andric   }
49890b57cec5SDimitry Andric 
49900b57cec5SDimitry Andric   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
49910b57cec5SDimitry Andric   if (Entry)
49920b57cec5SDimitry Andric     *Entry = GV;
49930b57cec5SDimitry Andric 
49940b57cec5SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
49950b57cec5SDimitry Andric                                   QualType());
49960b57cec5SDimitry Andric 
49970b57cec5SDimitry Andric   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
49980b57cec5SDimitry Andric                          Alignment);
49990b57cec5SDimitry Andric }
50000b57cec5SDimitry Andric 
50010b57cec5SDimitry Andric /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
50020b57cec5SDimitry Andric /// array for the given ObjCEncodeExpr node.
50030b57cec5SDimitry Andric ConstantAddress
50040b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
50050b57cec5SDimitry Andric   std::string Str;
50060b57cec5SDimitry Andric   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
50070b57cec5SDimitry Andric 
50080b57cec5SDimitry Andric   return GetAddrOfConstantCString(Str);
50090b57cec5SDimitry Andric }
50100b57cec5SDimitry Andric 
50110b57cec5SDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing
50120b57cec5SDimitry Andric /// the literal and a terminating '\0' character.
50130b57cec5SDimitry Andric /// The result has pointer to array type.
50140b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString(
50150b57cec5SDimitry Andric     const std::string &Str, const char *GlobalName) {
50160b57cec5SDimitry Andric   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
50170b57cec5SDimitry Andric   CharUnits Alignment =
50180b57cec5SDimitry Andric     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
50190b57cec5SDimitry Andric 
50200b57cec5SDimitry Andric   llvm::Constant *C =
50210b57cec5SDimitry Andric       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
50220b57cec5SDimitry Andric 
50230b57cec5SDimitry Andric   // Don't share any string literals if strings aren't constant.
50240b57cec5SDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
50250b57cec5SDimitry Andric   if (!LangOpts.WritableStrings) {
50260b57cec5SDimitry Andric     Entry = &ConstantStringMap[C];
50270b57cec5SDimitry Andric     if (auto GV = *Entry) {
50280b57cec5SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
5029a7dea167SDimitry Andric         GV->setAlignment(Alignment.getAsAlign());
50300b57cec5SDimitry Andric       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
50310b57cec5SDimitry Andric                              Alignment);
50320b57cec5SDimitry Andric     }
50330b57cec5SDimitry Andric   }
50340b57cec5SDimitry Andric 
50350b57cec5SDimitry Andric   // Get the default prefix if a name wasn't specified.
50360b57cec5SDimitry Andric   if (!GlobalName)
50370b57cec5SDimitry Andric     GlobalName = ".str";
50380b57cec5SDimitry Andric   // Create a global variable for this.
50390b57cec5SDimitry Andric   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
50400b57cec5SDimitry Andric                                   GlobalName, Alignment);
50410b57cec5SDimitry Andric   if (Entry)
50420b57cec5SDimitry Andric     *Entry = GV;
50430b57cec5SDimitry Andric 
50440b57cec5SDimitry Andric   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
50450b57cec5SDimitry Andric                          Alignment);
50460b57cec5SDimitry Andric }
50470b57cec5SDimitry Andric 
50480b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
50490b57cec5SDimitry Andric     const MaterializeTemporaryExpr *E, const Expr *Init) {
50500b57cec5SDimitry Andric   assert((E->getStorageDuration() == SD_Static ||
50510b57cec5SDimitry Andric           E->getStorageDuration() == SD_Thread) && "not a global temporary");
50520b57cec5SDimitry Andric   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
50530b57cec5SDimitry Andric 
50540b57cec5SDimitry Andric   // If we're not materializing a subobject of the temporary, keep the
50550b57cec5SDimitry Andric   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
50560b57cec5SDimitry Andric   QualType MaterializedType = Init->getType();
5057480093f4SDimitry Andric   if (Init == E->getSubExpr())
50580b57cec5SDimitry Andric     MaterializedType = E->getType();
50590b57cec5SDimitry Andric 
50600b57cec5SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
50610b57cec5SDimitry Andric 
50620b57cec5SDimitry Andric   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
50630b57cec5SDimitry Andric     return ConstantAddress(Slot, Align);
50640b57cec5SDimitry Andric 
50650b57cec5SDimitry Andric   // FIXME: If an externally-visible declaration extends multiple temporaries,
50660b57cec5SDimitry Andric   // we need to give each temporary the same name in every translation unit (and
50670b57cec5SDimitry Andric   // we also need to make the temporaries externally-visible).
50680b57cec5SDimitry Andric   SmallString<256> Name;
50690b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Name);
50700b57cec5SDimitry Andric   getCXXABI().getMangleContext().mangleReferenceTemporary(
50710b57cec5SDimitry Andric       VD, E->getManglingNumber(), Out);
50720b57cec5SDimitry Andric 
50730b57cec5SDimitry Andric   APValue *Value = nullptr;
5074a7dea167SDimitry Andric   if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
5075a7dea167SDimitry Andric     // If the initializer of the extending declaration is a constant
5076a7dea167SDimitry Andric     // initializer, we should have a cached constant initializer for this
5077a7dea167SDimitry Andric     // temporary. Note that this might have a different value from the value
5078a7dea167SDimitry Andric     // computed by evaluating the initializer if the surrounding constant
5079a7dea167SDimitry Andric     // expression modifies the temporary.
5080480093f4SDimitry Andric     Value = E->getOrCreateValue(false);
50810b57cec5SDimitry Andric   }
50820b57cec5SDimitry Andric 
50830b57cec5SDimitry Andric   // Try evaluating it now, it might have a constant initializer.
50840b57cec5SDimitry Andric   Expr::EvalResult EvalResult;
50850b57cec5SDimitry Andric   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
50860b57cec5SDimitry Andric       !EvalResult.hasSideEffects())
50870b57cec5SDimitry Andric     Value = &EvalResult.Val;
50880b57cec5SDimitry Andric 
50890b57cec5SDimitry Andric   LangAS AddrSpace =
50900b57cec5SDimitry Andric       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
50910b57cec5SDimitry Andric 
50920b57cec5SDimitry Andric   Optional<ConstantEmitter> emitter;
50930b57cec5SDimitry Andric   llvm::Constant *InitialValue = nullptr;
50940b57cec5SDimitry Andric   bool Constant = false;
50950b57cec5SDimitry Andric   llvm::Type *Type;
50960b57cec5SDimitry Andric   if (Value) {
50970b57cec5SDimitry Andric     // The temporary has a constant initializer, use it.
50980b57cec5SDimitry Andric     emitter.emplace(*this);
50990b57cec5SDimitry Andric     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
51000b57cec5SDimitry Andric                                                MaterializedType);
51010b57cec5SDimitry Andric     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
51020b57cec5SDimitry Andric     Type = InitialValue->getType();
51030b57cec5SDimitry Andric   } else {
51040b57cec5SDimitry Andric     // No initializer, the initialization will be provided when we
51050b57cec5SDimitry Andric     // initialize the declaration which performed lifetime extension.
51060b57cec5SDimitry Andric     Type = getTypes().ConvertTypeForMem(MaterializedType);
51070b57cec5SDimitry Andric   }
51080b57cec5SDimitry Andric 
51090b57cec5SDimitry Andric   // Create a global variable for this lifetime-extended temporary.
51100b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
51110b57cec5SDimitry Andric       getLLVMLinkageVarDefinition(VD, Constant);
51120b57cec5SDimitry Andric   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
51130b57cec5SDimitry Andric     const VarDecl *InitVD;
51140b57cec5SDimitry Andric     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
51150b57cec5SDimitry Andric         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
51160b57cec5SDimitry Andric       // Temporaries defined inside a class get linkonce_odr linkage because the
51170b57cec5SDimitry Andric       // class can be defined in multiple translation units.
51180b57cec5SDimitry Andric       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
51190b57cec5SDimitry Andric     } else {
51200b57cec5SDimitry Andric       // There is no need for this temporary to have external linkage if the
51210b57cec5SDimitry Andric       // VarDecl has external linkage.
51220b57cec5SDimitry Andric       Linkage = llvm::GlobalVariable::InternalLinkage;
51230b57cec5SDimitry Andric     }
51240b57cec5SDimitry Andric   }
51250b57cec5SDimitry Andric   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
51260b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
51270b57cec5SDimitry Andric       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
51280b57cec5SDimitry Andric       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
51290b57cec5SDimitry Andric   if (emitter) emitter->finalize(GV);
51300b57cec5SDimitry Andric   setGVProperties(GV, VD);
5131a7dea167SDimitry Andric   GV->setAlignment(Align.getAsAlign());
51320b57cec5SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker())
51330b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
51340b57cec5SDimitry Andric   if (VD->getTLSKind())
51350b57cec5SDimitry Andric     setTLSMode(GV, *VD);
51360b57cec5SDimitry Andric   llvm::Constant *CV = GV;
51370b57cec5SDimitry Andric   if (AddrSpace != LangAS::Default)
51380b57cec5SDimitry Andric     CV = getTargetCodeGenInfo().performAddrSpaceCast(
51390b57cec5SDimitry Andric         *this, GV, AddrSpace, LangAS::Default,
51400b57cec5SDimitry Andric         Type->getPointerTo(
51410b57cec5SDimitry Andric             getContext().getTargetAddressSpace(LangAS::Default)));
51420b57cec5SDimitry Andric   MaterializedGlobalTemporaryMap[E] = CV;
51430b57cec5SDimitry Andric   return ConstantAddress(CV, Align);
51440b57cec5SDimitry Andric }
51450b57cec5SDimitry Andric 
51460b57cec5SDimitry Andric /// EmitObjCPropertyImplementations - Emit information for synthesized
51470b57cec5SDimitry Andric /// properties for an implementation.
51480b57cec5SDimitry Andric void CodeGenModule::EmitObjCPropertyImplementations(const
51490b57cec5SDimitry Andric                                                     ObjCImplementationDecl *D) {
51500b57cec5SDimitry Andric   for (const auto *PID : D->property_impls()) {
51510b57cec5SDimitry Andric     // Dynamic is just for type-checking.
51520b57cec5SDimitry Andric     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
51530b57cec5SDimitry Andric       ObjCPropertyDecl *PD = PID->getPropertyDecl();
51540b57cec5SDimitry Andric 
51550b57cec5SDimitry Andric       // Determine which methods need to be implemented, some may have
51560b57cec5SDimitry Andric       // been overridden. Note that ::isPropertyAccessor is not the method
51570b57cec5SDimitry Andric       // we want, that just indicates if the decl came from a
51580b57cec5SDimitry Andric       // property. What we want to know is if the method is defined in
51590b57cec5SDimitry Andric       // this implementation.
5160480093f4SDimitry Andric       auto *Getter = PID->getGetterMethodDecl();
5161480093f4SDimitry Andric       if (!Getter || Getter->isSynthesizedAccessorStub())
51620b57cec5SDimitry Andric         CodeGenFunction(*this).GenerateObjCGetter(
51630b57cec5SDimitry Andric             const_cast<ObjCImplementationDecl *>(D), PID);
5164480093f4SDimitry Andric       auto *Setter = PID->getSetterMethodDecl();
5165480093f4SDimitry Andric       if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
51660b57cec5SDimitry Andric         CodeGenFunction(*this).GenerateObjCSetter(
51670b57cec5SDimitry Andric                                  const_cast<ObjCImplementationDecl *>(D), PID);
51680b57cec5SDimitry Andric     }
51690b57cec5SDimitry Andric   }
51700b57cec5SDimitry Andric }
51710b57cec5SDimitry Andric 
51720b57cec5SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) {
51730b57cec5SDimitry Andric   const ObjCInterfaceDecl *iface = impl->getClassInterface();
51740b57cec5SDimitry Andric   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
51750b57cec5SDimitry Andric        ivar; ivar = ivar->getNextIvar())
51760b57cec5SDimitry Andric     if (ivar->getType().isDestructedType())
51770b57cec5SDimitry Andric       return true;
51780b57cec5SDimitry Andric 
51790b57cec5SDimitry Andric   return false;
51800b57cec5SDimitry Andric }
51810b57cec5SDimitry Andric 
51820b57cec5SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM,
51830b57cec5SDimitry Andric                                    ObjCImplementationDecl *D) {
51840b57cec5SDimitry Andric   CodeGenFunction CGF(CGM);
51850b57cec5SDimitry Andric   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
51860b57cec5SDimitry Andric        E = D->init_end(); B != E; ++B) {
51870b57cec5SDimitry Andric     CXXCtorInitializer *CtorInitExp = *B;
51880b57cec5SDimitry Andric     Expr *Init = CtorInitExp->getInit();
51890b57cec5SDimitry Andric     if (!CGF.isTrivialInitializer(Init))
51900b57cec5SDimitry Andric       return false;
51910b57cec5SDimitry Andric   }
51920b57cec5SDimitry Andric   return true;
51930b57cec5SDimitry Andric }
51940b57cec5SDimitry Andric 
51950b57cec5SDimitry Andric /// EmitObjCIvarInitializations - Emit information for ivar initialization
51960b57cec5SDimitry Andric /// for an implementation.
51970b57cec5SDimitry Andric void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
51980b57cec5SDimitry Andric   // We might need a .cxx_destruct even if we don't have any ivar initializers.
51990b57cec5SDimitry Andric   if (needsDestructMethod(D)) {
52000b57cec5SDimitry Andric     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
52010b57cec5SDimitry Andric     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5202480093f4SDimitry Andric     ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
5203480093f4SDimitry Andric         getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5204480093f4SDimitry Andric         getContext().VoidTy, nullptr, D,
52050b57cec5SDimitry Andric         /*isInstance=*/true, /*isVariadic=*/false,
5206480093f4SDimitry Andric         /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5207480093f4SDimitry Andric         /*isImplicitlyDeclared=*/true,
52080b57cec5SDimitry Andric         /*isDefined=*/false, ObjCMethodDecl::Required);
52090b57cec5SDimitry Andric     D->addInstanceMethod(DTORMethod);
52100b57cec5SDimitry Andric     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
52110b57cec5SDimitry Andric     D->setHasDestructors(true);
52120b57cec5SDimitry Andric   }
52130b57cec5SDimitry Andric 
52140b57cec5SDimitry Andric   // If the implementation doesn't have any ivar initializers, we don't need
52150b57cec5SDimitry Andric   // a .cxx_construct.
52160b57cec5SDimitry Andric   if (D->getNumIvarInitializers() == 0 ||
52170b57cec5SDimitry Andric       AllTrivialInitializers(*this, D))
52180b57cec5SDimitry Andric     return;
52190b57cec5SDimitry Andric 
52200b57cec5SDimitry Andric   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
52210b57cec5SDimitry Andric   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
52220b57cec5SDimitry Andric   // The constructor returns 'self'.
5223480093f4SDimitry Andric   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
5224480093f4SDimitry Andric       getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5225480093f4SDimitry Andric       getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
52260b57cec5SDimitry Andric       /*isVariadic=*/false,
5227480093f4SDimitry Andric       /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
52280b57cec5SDimitry Andric       /*isImplicitlyDeclared=*/true,
5229480093f4SDimitry Andric       /*isDefined=*/false, ObjCMethodDecl::Required);
52300b57cec5SDimitry Andric   D->addInstanceMethod(CTORMethod);
52310b57cec5SDimitry Andric   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
52320b57cec5SDimitry Andric   D->setHasNonZeroConstructors(true);
52330b57cec5SDimitry Andric }
52340b57cec5SDimitry Andric 
52350b57cec5SDimitry Andric // EmitLinkageSpec - Emit all declarations in a linkage spec.
52360b57cec5SDimitry Andric void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
52370b57cec5SDimitry Andric   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
5238480093f4SDimitry Andric       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
52390b57cec5SDimitry Andric     ErrorUnsupported(LSD, "linkage spec");
52400b57cec5SDimitry Andric     return;
52410b57cec5SDimitry Andric   }
52420b57cec5SDimitry Andric 
52430b57cec5SDimitry Andric   EmitDeclContext(LSD);
52440b57cec5SDimitry Andric }
52450b57cec5SDimitry Andric 
52460b57cec5SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
52470b57cec5SDimitry Andric   for (auto *I : DC->decls()) {
52480b57cec5SDimitry Andric     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
52490b57cec5SDimitry Andric     // are themselves considered "top-level", so EmitTopLevelDecl on an
52500b57cec5SDimitry Andric     // ObjCImplDecl does not recursively visit them. We need to do that in
52510b57cec5SDimitry Andric     // case they're nested inside another construct (LinkageSpecDecl /
52520b57cec5SDimitry Andric     // ExportDecl) that does stop them from being considered "top-level".
52530b57cec5SDimitry Andric     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
52540b57cec5SDimitry Andric       for (auto *M : OID->methods())
52550b57cec5SDimitry Andric         EmitTopLevelDecl(M);
52560b57cec5SDimitry Andric     }
52570b57cec5SDimitry Andric 
52580b57cec5SDimitry Andric     EmitTopLevelDecl(I);
52590b57cec5SDimitry Andric   }
52600b57cec5SDimitry Andric }
52610b57cec5SDimitry Andric 
52620b57cec5SDimitry Andric /// EmitTopLevelDecl - Emit code for a single top level declaration.
52630b57cec5SDimitry Andric void CodeGenModule::EmitTopLevelDecl(Decl *D) {
52640b57cec5SDimitry Andric   // Ignore dependent declarations.
52650b57cec5SDimitry Andric   if (D->isTemplated())
52660b57cec5SDimitry Andric     return;
52670b57cec5SDimitry Andric 
52680b57cec5SDimitry Andric   switch (D->getKind()) {
52690b57cec5SDimitry Andric   case Decl::CXXConversion:
52700b57cec5SDimitry Andric   case Decl::CXXMethod:
52710b57cec5SDimitry Andric   case Decl::Function:
52720b57cec5SDimitry Andric     EmitGlobal(cast<FunctionDecl>(D));
52730b57cec5SDimitry Andric     // Always provide some coverage mapping
52740b57cec5SDimitry Andric     // even for the functions that aren't emitted.
52750b57cec5SDimitry Andric     AddDeferredUnusedCoverageMapping(D);
52760b57cec5SDimitry Andric     break;
52770b57cec5SDimitry Andric 
52780b57cec5SDimitry Andric   case Decl::CXXDeductionGuide:
52790b57cec5SDimitry Andric     // Function-like, but does not result in code emission.
52800b57cec5SDimitry Andric     break;
52810b57cec5SDimitry Andric 
52820b57cec5SDimitry Andric   case Decl::Var:
52830b57cec5SDimitry Andric   case Decl::Decomposition:
52840b57cec5SDimitry Andric   case Decl::VarTemplateSpecialization:
52850b57cec5SDimitry Andric     EmitGlobal(cast<VarDecl>(D));
52860b57cec5SDimitry Andric     if (auto *DD = dyn_cast<DecompositionDecl>(D))
52870b57cec5SDimitry Andric       for (auto *B : DD->bindings())
52880b57cec5SDimitry Andric         if (auto *HD = B->getHoldingVar())
52890b57cec5SDimitry Andric           EmitGlobal(HD);
52900b57cec5SDimitry Andric     break;
52910b57cec5SDimitry Andric 
52920b57cec5SDimitry Andric   // Indirect fields from global anonymous structs and unions can be
52930b57cec5SDimitry Andric   // ignored; only the actual variable requires IR gen support.
52940b57cec5SDimitry Andric   case Decl::IndirectField:
52950b57cec5SDimitry Andric     break;
52960b57cec5SDimitry Andric 
52970b57cec5SDimitry Andric   // C++ Decls
52980b57cec5SDimitry Andric   case Decl::Namespace:
52990b57cec5SDimitry Andric     EmitDeclContext(cast<NamespaceDecl>(D));
53000b57cec5SDimitry Andric     break;
53010b57cec5SDimitry Andric   case Decl::ClassTemplateSpecialization: {
53020b57cec5SDimitry Andric     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
53030b57cec5SDimitry Andric     if (DebugInfo &&
53040b57cec5SDimitry Andric         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
53050b57cec5SDimitry Andric         Spec->hasDefinition())
53060b57cec5SDimitry Andric       DebugInfo->completeTemplateDefinition(*Spec);
53070b57cec5SDimitry Andric   } LLVM_FALLTHROUGH;
53080b57cec5SDimitry Andric   case Decl::CXXRecord:
53090b57cec5SDimitry Andric     if (DebugInfo) {
53100b57cec5SDimitry Andric       if (auto *ES = D->getASTContext().getExternalSource())
53110b57cec5SDimitry Andric         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
53120b57cec5SDimitry Andric           DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
53130b57cec5SDimitry Andric     }
53140b57cec5SDimitry Andric     // Emit any static data members, they may be definitions.
53150b57cec5SDimitry Andric     for (auto *I : cast<CXXRecordDecl>(D)->decls())
53160b57cec5SDimitry Andric       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
53170b57cec5SDimitry Andric         EmitTopLevelDecl(I);
53180b57cec5SDimitry Andric     break;
53190b57cec5SDimitry Andric     // No code generation needed.
53200b57cec5SDimitry Andric   case Decl::UsingShadow:
53210b57cec5SDimitry Andric   case Decl::ClassTemplate:
53220b57cec5SDimitry Andric   case Decl::VarTemplate:
53230b57cec5SDimitry Andric   case Decl::Concept:
53240b57cec5SDimitry Andric   case Decl::VarTemplatePartialSpecialization:
53250b57cec5SDimitry Andric   case Decl::FunctionTemplate:
53260b57cec5SDimitry Andric   case Decl::TypeAliasTemplate:
53270b57cec5SDimitry Andric   case Decl::Block:
53280b57cec5SDimitry Andric   case Decl::Empty:
53290b57cec5SDimitry Andric   case Decl::Binding:
53300b57cec5SDimitry Andric     break;
53310b57cec5SDimitry Andric   case Decl::Using:          // using X; [C++]
53320b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
53330b57cec5SDimitry Andric         DI->EmitUsingDecl(cast<UsingDecl>(*D));
53340b57cec5SDimitry Andric     return;
53350b57cec5SDimitry Andric   case Decl::NamespaceAlias:
53360b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
53370b57cec5SDimitry Andric         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
53380b57cec5SDimitry Andric     return;
53390b57cec5SDimitry Andric   case Decl::UsingDirective: // using namespace X; [C++]
53400b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
53410b57cec5SDimitry Andric       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
53420b57cec5SDimitry Andric     return;
53430b57cec5SDimitry Andric   case Decl::CXXConstructor:
53440b57cec5SDimitry Andric     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
53450b57cec5SDimitry Andric     break;
53460b57cec5SDimitry Andric   case Decl::CXXDestructor:
53470b57cec5SDimitry Andric     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
53480b57cec5SDimitry Andric     break;
53490b57cec5SDimitry Andric 
53500b57cec5SDimitry Andric   case Decl::StaticAssert:
53510b57cec5SDimitry Andric     // Nothing to do.
53520b57cec5SDimitry Andric     break;
53530b57cec5SDimitry Andric 
53540b57cec5SDimitry Andric   // Objective-C Decls
53550b57cec5SDimitry Andric 
53560b57cec5SDimitry Andric   // Forward declarations, no (immediate) code generation.
53570b57cec5SDimitry Andric   case Decl::ObjCInterface:
53580b57cec5SDimitry Andric   case Decl::ObjCCategory:
53590b57cec5SDimitry Andric     break;
53600b57cec5SDimitry Andric 
53610b57cec5SDimitry Andric   case Decl::ObjCProtocol: {
53620b57cec5SDimitry Andric     auto *Proto = cast<ObjCProtocolDecl>(D);
53630b57cec5SDimitry Andric     if (Proto->isThisDeclarationADefinition())
53640b57cec5SDimitry Andric       ObjCRuntime->GenerateProtocol(Proto);
53650b57cec5SDimitry Andric     break;
53660b57cec5SDimitry Andric   }
53670b57cec5SDimitry Andric 
53680b57cec5SDimitry Andric   case Decl::ObjCCategoryImpl:
53690b57cec5SDimitry Andric     // Categories have properties but don't support synthesize so we
53700b57cec5SDimitry Andric     // can ignore them here.
53710b57cec5SDimitry Andric     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
53720b57cec5SDimitry Andric     break;
53730b57cec5SDimitry Andric 
53740b57cec5SDimitry Andric   case Decl::ObjCImplementation: {
53750b57cec5SDimitry Andric     auto *OMD = cast<ObjCImplementationDecl>(D);
53760b57cec5SDimitry Andric     EmitObjCPropertyImplementations(OMD);
53770b57cec5SDimitry Andric     EmitObjCIvarInitializations(OMD);
53780b57cec5SDimitry Andric     ObjCRuntime->GenerateClass(OMD);
53790b57cec5SDimitry Andric     // Emit global variable debug information.
53800b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
5381480093f4SDimitry Andric       if (getCodeGenOpts().hasReducedDebugInfo())
53820b57cec5SDimitry Andric         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
53830b57cec5SDimitry Andric             OMD->getClassInterface()), OMD->getLocation());
53840b57cec5SDimitry Andric     break;
53850b57cec5SDimitry Andric   }
53860b57cec5SDimitry Andric   case Decl::ObjCMethod: {
53870b57cec5SDimitry Andric     auto *OMD = cast<ObjCMethodDecl>(D);
53880b57cec5SDimitry Andric     // If this is not a prototype, emit the body.
53890b57cec5SDimitry Andric     if (OMD->getBody())
53900b57cec5SDimitry Andric       CodeGenFunction(*this).GenerateObjCMethod(OMD);
53910b57cec5SDimitry Andric     break;
53920b57cec5SDimitry Andric   }
53930b57cec5SDimitry Andric   case Decl::ObjCCompatibleAlias:
53940b57cec5SDimitry Andric     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
53950b57cec5SDimitry Andric     break;
53960b57cec5SDimitry Andric 
53970b57cec5SDimitry Andric   case Decl::PragmaComment: {
53980b57cec5SDimitry Andric     const auto *PCD = cast<PragmaCommentDecl>(D);
53990b57cec5SDimitry Andric     switch (PCD->getCommentKind()) {
54000b57cec5SDimitry Andric     case PCK_Unknown:
54010b57cec5SDimitry Andric       llvm_unreachable("unexpected pragma comment kind");
54020b57cec5SDimitry Andric     case PCK_Linker:
54030b57cec5SDimitry Andric       AppendLinkerOptions(PCD->getArg());
54040b57cec5SDimitry Andric       break;
54050b57cec5SDimitry Andric     case PCK_Lib:
54060b57cec5SDimitry Andric         AddDependentLib(PCD->getArg());
54070b57cec5SDimitry Andric       break;
54080b57cec5SDimitry Andric     case PCK_Compiler:
54090b57cec5SDimitry Andric     case PCK_ExeStr:
54100b57cec5SDimitry Andric     case PCK_User:
54110b57cec5SDimitry Andric       break; // We ignore all of these.
54120b57cec5SDimitry Andric     }
54130b57cec5SDimitry Andric     break;
54140b57cec5SDimitry Andric   }
54150b57cec5SDimitry Andric 
54160b57cec5SDimitry Andric   case Decl::PragmaDetectMismatch: {
54170b57cec5SDimitry Andric     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
54180b57cec5SDimitry Andric     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
54190b57cec5SDimitry Andric     break;
54200b57cec5SDimitry Andric   }
54210b57cec5SDimitry Andric 
54220b57cec5SDimitry Andric   case Decl::LinkageSpec:
54230b57cec5SDimitry Andric     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
54240b57cec5SDimitry Andric     break;
54250b57cec5SDimitry Andric 
54260b57cec5SDimitry Andric   case Decl::FileScopeAsm: {
54270b57cec5SDimitry Andric     // File-scope asm is ignored during device-side CUDA compilation.
54280b57cec5SDimitry Andric     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
54290b57cec5SDimitry Andric       break;
54300b57cec5SDimitry Andric     // File-scope asm is ignored during device-side OpenMP compilation.
54310b57cec5SDimitry Andric     if (LangOpts.OpenMPIsDevice)
54320b57cec5SDimitry Andric       break;
54330b57cec5SDimitry Andric     auto *AD = cast<FileScopeAsmDecl>(D);
54340b57cec5SDimitry Andric     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
54350b57cec5SDimitry Andric     break;
54360b57cec5SDimitry Andric   }
54370b57cec5SDimitry Andric 
54380b57cec5SDimitry Andric   case Decl::Import: {
54390b57cec5SDimitry Andric     auto *Import = cast<ImportDecl>(D);
54400b57cec5SDimitry Andric 
54410b57cec5SDimitry Andric     // If we've already imported this module, we're done.
54420b57cec5SDimitry Andric     if (!ImportedModules.insert(Import->getImportedModule()))
54430b57cec5SDimitry Andric       break;
54440b57cec5SDimitry Andric 
54450b57cec5SDimitry Andric     // Emit debug information for direct imports.
54460b57cec5SDimitry Andric     if (!Import->getImportedOwningModule()) {
54470b57cec5SDimitry Andric       if (CGDebugInfo *DI = getModuleDebugInfo())
54480b57cec5SDimitry Andric         DI->EmitImportDecl(*Import);
54490b57cec5SDimitry Andric     }
54500b57cec5SDimitry Andric 
54510b57cec5SDimitry Andric     // Find all of the submodules and emit the module initializers.
54520b57cec5SDimitry Andric     llvm::SmallPtrSet<clang::Module *, 16> Visited;
54530b57cec5SDimitry Andric     SmallVector<clang::Module *, 16> Stack;
54540b57cec5SDimitry Andric     Visited.insert(Import->getImportedModule());
54550b57cec5SDimitry Andric     Stack.push_back(Import->getImportedModule());
54560b57cec5SDimitry Andric 
54570b57cec5SDimitry Andric     while (!Stack.empty()) {
54580b57cec5SDimitry Andric       clang::Module *Mod = Stack.pop_back_val();
54590b57cec5SDimitry Andric       if (!EmittedModuleInitializers.insert(Mod).second)
54600b57cec5SDimitry Andric         continue;
54610b57cec5SDimitry Andric 
54620b57cec5SDimitry Andric       for (auto *D : Context.getModuleInitializers(Mod))
54630b57cec5SDimitry Andric         EmitTopLevelDecl(D);
54640b57cec5SDimitry Andric 
54650b57cec5SDimitry Andric       // Visit the submodules of this module.
54660b57cec5SDimitry Andric       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
54670b57cec5SDimitry Andric                                              SubEnd = Mod->submodule_end();
54680b57cec5SDimitry Andric            Sub != SubEnd; ++Sub) {
54690b57cec5SDimitry Andric         // Skip explicit children; they need to be explicitly imported to emit
54700b57cec5SDimitry Andric         // the initializers.
54710b57cec5SDimitry Andric         if ((*Sub)->IsExplicit)
54720b57cec5SDimitry Andric           continue;
54730b57cec5SDimitry Andric 
54740b57cec5SDimitry Andric         if (Visited.insert(*Sub).second)
54750b57cec5SDimitry Andric           Stack.push_back(*Sub);
54760b57cec5SDimitry Andric       }
54770b57cec5SDimitry Andric     }
54780b57cec5SDimitry Andric     break;
54790b57cec5SDimitry Andric   }
54800b57cec5SDimitry Andric 
54810b57cec5SDimitry Andric   case Decl::Export:
54820b57cec5SDimitry Andric     EmitDeclContext(cast<ExportDecl>(D));
54830b57cec5SDimitry Andric     break;
54840b57cec5SDimitry Andric 
54850b57cec5SDimitry Andric   case Decl::OMPThreadPrivate:
54860b57cec5SDimitry Andric     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
54870b57cec5SDimitry Andric     break;
54880b57cec5SDimitry Andric 
54890b57cec5SDimitry Andric   case Decl::OMPAllocate:
54900b57cec5SDimitry Andric     break;
54910b57cec5SDimitry Andric 
54920b57cec5SDimitry Andric   case Decl::OMPDeclareReduction:
54930b57cec5SDimitry Andric     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
54940b57cec5SDimitry Andric     break;
54950b57cec5SDimitry Andric 
54960b57cec5SDimitry Andric   case Decl::OMPDeclareMapper:
54970b57cec5SDimitry Andric     EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
54980b57cec5SDimitry Andric     break;
54990b57cec5SDimitry Andric 
55000b57cec5SDimitry Andric   case Decl::OMPRequires:
55010b57cec5SDimitry Andric     EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
55020b57cec5SDimitry Andric     break;
55030b57cec5SDimitry Andric 
55040b57cec5SDimitry Andric   default:
55050b57cec5SDimitry Andric     // Make sure we handled everything we should, every other kind is a
55060b57cec5SDimitry Andric     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
55070b57cec5SDimitry Andric     // function. Need to recode Decl::Kind to do that easily.
55080b57cec5SDimitry Andric     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
55090b57cec5SDimitry Andric     break;
55100b57cec5SDimitry Andric   }
55110b57cec5SDimitry Andric }
55120b57cec5SDimitry Andric 
55130b57cec5SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
55140b57cec5SDimitry Andric   // Do we need to generate coverage mapping?
55150b57cec5SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
55160b57cec5SDimitry Andric     return;
55170b57cec5SDimitry Andric   switch (D->getKind()) {
55180b57cec5SDimitry Andric   case Decl::CXXConversion:
55190b57cec5SDimitry Andric   case Decl::CXXMethod:
55200b57cec5SDimitry Andric   case Decl::Function:
55210b57cec5SDimitry Andric   case Decl::ObjCMethod:
55220b57cec5SDimitry Andric   case Decl::CXXConstructor:
55230b57cec5SDimitry Andric   case Decl::CXXDestructor: {
55240b57cec5SDimitry Andric     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
55250b57cec5SDimitry Andric       return;
55260b57cec5SDimitry Andric     SourceManager &SM = getContext().getSourceManager();
55270b57cec5SDimitry Andric     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
55280b57cec5SDimitry Andric       return;
55290b57cec5SDimitry Andric     auto I = DeferredEmptyCoverageMappingDecls.find(D);
55300b57cec5SDimitry Andric     if (I == DeferredEmptyCoverageMappingDecls.end())
55310b57cec5SDimitry Andric       DeferredEmptyCoverageMappingDecls[D] = true;
55320b57cec5SDimitry Andric     break;
55330b57cec5SDimitry Andric   }
55340b57cec5SDimitry Andric   default:
55350b57cec5SDimitry Andric     break;
55360b57cec5SDimitry Andric   };
55370b57cec5SDimitry Andric }
55380b57cec5SDimitry Andric 
55390b57cec5SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
55400b57cec5SDimitry Andric   // Do we need to generate coverage mapping?
55410b57cec5SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
55420b57cec5SDimitry Andric     return;
55430b57cec5SDimitry Andric   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
55440b57cec5SDimitry Andric     if (Fn->isTemplateInstantiation())
55450b57cec5SDimitry Andric       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
55460b57cec5SDimitry Andric   }
55470b57cec5SDimitry Andric   auto I = DeferredEmptyCoverageMappingDecls.find(D);
55480b57cec5SDimitry Andric   if (I == DeferredEmptyCoverageMappingDecls.end())
55490b57cec5SDimitry Andric     DeferredEmptyCoverageMappingDecls[D] = false;
55500b57cec5SDimitry Andric   else
55510b57cec5SDimitry Andric     I->second = false;
55520b57cec5SDimitry Andric }
55530b57cec5SDimitry Andric 
55540b57cec5SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
55550b57cec5SDimitry Andric   // We call takeVector() here to avoid use-after-free.
55560b57cec5SDimitry Andric   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
55570b57cec5SDimitry Andric   // we deserialize function bodies to emit coverage info for them, and that
55580b57cec5SDimitry Andric   // deserializes more declarations. How should we handle that case?
55590b57cec5SDimitry Andric   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
55600b57cec5SDimitry Andric     if (!Entry.second)
55610b57cec5SDimitry Andric       continue;
55620b57cec5SDimitry Andric     const Decl *D = Entry.first;
55630b57cec5SDimitry Andric     switch (D->getKind()) {
55640b57cec5SDimitry Andric     case Decl::CXXConversion:
55650b57cec5SDimitry Andric     case Decl::CXXMethod:
55660b57cec5SDimitry Andric     case Decl::Function:
55670b57cec5SDimitry Andric     case Decl::ObjCMethod: {
55680b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
55690b57cec5SDimitry Andric       GlobalDecl GD(cast<FunctionDecl>(D));
55700b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
55710b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
55720b57cec5SDimitry Andric       break;
55730b57cec5SDimitry Andric     }
55740b57cec5SDimitry Andric     case Decl::CXXConstructor: {
55750b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
55760b57cec5SDimitry Andric       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
55770b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
55780b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
55790b57cec5SDimitry Andric       break;
55800b57cec5SDimitry Andric     }
55810b57cec5SDimitry Andric     case Decl::CXXDestructor: {
55820b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
55830b57cec5SDimitry Andric       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
55840b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
55850b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
55860b57cec5SDimitry Andric       break;
55870b57cec5SDimitry Andric     }
55880b57cec5SDimitry Andric     default:
55890b57cec5SDimitry Andric       break;
55900b57cec5SDimitry Andric     };
55910b57cec5SDimitry Andric   }
55920b57cec5SDimitry Andric }
55930b57cec5SDimitry Andric 
55940b57cec5SDimitry Andric /// Turns the given pointer into a constant.
55950b57cec5SDimitry Andric static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
55960b57cec5SDimitry Andric                                           const void *Ptr) {
55970b57cec5SDimitry Andric   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
55980b57cec5SDimitry Andric   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
55990b57cec5SDimitry Andric   return llvm::ConstantInt::get(i64, PtrInt);
56000b57cec5SDimitry Andric }
56010b57cec5SDimitry Andric 
56020b57cec5SDimitry Andric static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
56030b57cec5SDimitry Andric                                    llvm::NamedMDNode *&GlobalMetadata,
56040b57cec5SDimitry Andric                                    GlobalDecl D,
56050b57cec5SDimitry Andric                                    llvm::GlobalValue *Addr) {
56060b57cec5SDimitry Andric   if (!GlobalMetadata)
56070b57cec5SDimitry Andric     GlobalMetadata =
56080b57cec5SDimitry Andric       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
56090b57cec5SDimitry Andric 
56100b57cec5SDimitry Andric   // TODO: should we report variant information for ctors/dtors?
56110b57cec5SDimitry Andric   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
56120b57cec5SDimitry Andric                            llvm::ConstantAsMetadata::get(GetPointerConstant(
56130b57cec5SDimitry Andric                                CGM.getLLVMContext(), D.getDecl()))};
56140b57cec5SDimitry Andric   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
56150b57cec5SDimitry Andric }
56160b57cec5SDimitry Andric 
56170b57cec5SDimitry Andric /// For each function which is declared within an extern "C" region and marked
56180b57cec5SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled
56190b57cec5SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer
56200b57cec5SDimitry Andric /// to such functions with an unmangled name from inline assembly within the
56210b57cec5SDimitry Andric /// same translation unit.
56220b57cec5SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() {
56230b57cec5SDimitry Andric   if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
56240b57cec5SDimitry Andric     return;
56250b57cec5SDimitry Andric   for (auto &I : StaticExternCValues) {
56260b57cec5SDimitry Andric     IdentifierInfo *Name = I.first;
56270b57cec5SDimitry Andric     llvm::GlobalValue *Val = I.second;
56280b57cec5SDimitry Andric     if (Val && !getModule().getNamedValue(Name->getName()))
56290b57cec5SDimitry Andric       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
56300b57cec5SDimitry Andric   }
56310b57cec5SDimitry Andric }
56320b57cec5SDimitry Andric 
56330b57cec5SDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
56340b57cec5SDimitry Andric                                              GlobalDecl &Result) const {
56350b57cec5SDimitry Andric   auto Res = Manglings.find(MangledName);
56360b57cec5SDimitry Andric   if (Res == Manglings.end())
56370b57cec5SDimitry Andric     return false;
56380b57cec5SDimitry Andric   Result = Res->getValue();
56390b57cec5SDimitry Andric   return true;
56400b57cec5SDimitry Andric }
56410b57cec5SDimitry Andric 
56420b57cec5SDimitry Andric /// Emits metadata nodes associating all the global values in the
56430b57cec5SDimitry Andric /// current module with the Decls they came from.  This is useful for
56440b57cec5SDimitry Andric /// projects using IR gen as a subroutine.
56450b57cec5SDimitry Andric ///
56460b57cec5SDimitry Andric /// Since there's currently no way to associate an MDNode directly
56470b57cec5SDimitry Andric /// with an llvm::GlobalValue, we create a global named metadata
56480b57cec5SDimitry Andric /// with the name 'clang.global.decl.ptrs'.
56490b57cec5SDimitry Andric void CodeGenModule::EmitDeclMetadata() {
56500b57cec5SDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
56510b57cec5SDimitry Andric 
56520b57cec5SDimitry Andric   for (auto &I : MangledDeclNames) {
56530b57cec5SDimitry Andric     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
56540b57cec5SDimitry Andric     // Some mangled names don't necessarily have an associated GlobalValue
56550b57cec5SDimitry Andric     // in this module, e.g. if we mangled it for DebugInfo.
56560b57cec5SDimitry Andric     if (Addr)
56570b57cec5SDimitry Andric       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
56580b57cec5SDimitry Andric   }
56590b57cec5SDimitry Andric }
56600b57cec5SDimitry Andric 
56610b57cec5SDimitry Andric /// Emits metadata nodes for all the local variables in the current
56620b57cec5SDimitry Andric /// function.
56630b57cec5SDimitry Andric void CodeGenFunction::EmitDeclMetadata() {
56640b57cec5SDimitry Andric   if (LocalDeclMap.empty()) return;
56650b57cec5SDimitry Andric 
56660b57cec5SDimitry Andric   llvm::LLVMContext &Context = getLLVMContext();
56670b57cec5SDimitry Andric 
56680b57cec5SDimitry Andric   // Find the unique metadata ID for this name.
56690b57cec5SDimitry Andric   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
56700b57cec5SDimitry Andric 
56710b57cec5SDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
56720b57cec5SDimitry Andric 
56730b57cec5SDimitry Andric   for (auto &I : LocalDeclMap) {
56740b57cec5SDimitry Andric     const Decl *D = I.first;
56750b57cec5SDimitry Andric     llvm::Value *Addr = I.second.getPointer();
56760b57cec5SDimitry Andric     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
56770b57cec5SDimitry Andric       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
56780b57cec5SDimitry Andric       Alloca->setMetadata(
56790b57cec5SDimitry Andric           DeclPtrKind, llvm::MDNode::get(
56800b57cec5SDimitry Andric                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
56810b57cec5SDimitry Andric     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
56820b57cec5SDimitry Andric       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
56830b57cec5SDimitry Andric       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
56840b57cec5SDimitry Andric     }
56850b57cec5SDimitry Andric   }
56860b57cec5SDimitry Andric }
56870b57cec5SDimitry Andric 
56880b57cec5SDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() {
56890b57cec5SDimitry Andric   llvm::NamedMDNode *IdentMetadata =
56900b57cec5SDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.ident");
56910b57cec5SDimitry Andric   std::string Version = getClangFullVersion();
56920b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
56930b57cec5SDimitry Andric 
56940b57cec5SDimitry Andric   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
56950b57cec5SDimitry Andric   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
56960b57cec5SDimitry Andric }
56970b57cec5SDimitry Andric 
56980b57cec5SDimitry Andric void CodeGenModule::EmitCommandLineMetadata() {
56990b57cec5SDimitry Andric   llvm::NamedMDNode *CommandLineMetadata =
57000b57cec5SDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.commandline");
57010b57cec5SDimitry Andric   std::string CommandLine = getCodeGenOpts().RecordCommandLine;
57020b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
57030b57cec5SDimitry Andric 
57040b57cec5SDimitry Andric   llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
57050b57cec5SDimitry Andric   CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
57060b57cec5SDimitry Andric }
57070b57cec5SDimitry Andric 
57080b57cec5SDimitry Andric void CodeGenModule::EmitTargetMetadata() {
57090b57cec5SDimitry Andric   // Warning, new MangledDeclNames may be appended within this loop.
57100b57cec5SDimitry Andric   // We rely on MapVector insertions adding new elements to the end
57110b57cec5SDimitry Andric   // of the container.
57120b57cec5SDimitry Andric   // FIXME: Move this loop into the one target that needs it, and only
57130b57cec5SDimitry Andric   // loop over those declarations for which we couldn't emit the target
57140b57cec5SDimitry Andric   // metadata when we emitted the declaration.
57150b57cec5SDimitry Andric   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
57160b57cec5SDimitry Andric     auto Val = *(MangledDeclNames.begin() + I);
57170b57cec5SDimitry Andric     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
57180b57cec5SDimitry Andric     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
57190b57cec5SDimitry Andric     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
57200b57cec5SDimitry Andric   }
57210b57cec5SDimitry Andric }
57220b57cec5SDimitry Andric 
57230b57cec5SDimitry Andric void CodeGenModule::EmitCoverageFile() {
57240b57cec5SDimitry Andric   if (getCodeGenOpts().CoverageDataFile.empty() &&
57250b57cec5SDimitry Andric       getCodeGenOpts().CoverageNotesFile.empty())
57260b57cec5SDimitry Andric     return;
57270b57cec5SDimitry Andric 
57280b57cec5SDimitry Andric   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
57290b57cec5SDimitry Andric   if (!CUNode)
57300b57cec5SDimitry Andric     return;
57310b57cec5SDimitry Andric 
57320b57cec5SDimitry Andric   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
57330b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
57340b57cec5SDimitry Andric   auto *CoverageDataFile =
57350b57cec5SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
57360b57cec5SDimitry Andric   auto *CoverageNotesFile =
57370b57cec5SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
57380b57cec5SDimitry Andric   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
57390b57cec5SDimitry Andric     llvm::MDNode *CU = CUNode->getOperand(i);
57400b57cec5SDimitry Andric     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
57410b57cec5SDimitry Andric     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
57420b57cec5SDimitry Andric   }
57430b57cec5SDimitry Andric }
57440b57cec5SDimitry Andric 
57450b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
57460b57cec5SDimitry Andric   // Sema has checked that all uuid strings are of the form
57470b57cec5SDimitry Andric   // "12345678-1234-1234-1234-1234567890ab".
57480b57cec5SDimitry Andric   assert(Uuid.size() == 36);
57490b57cec5SDimitry Andric   for (unsigned i = 0; i < 36; ++i) {
57500b57cec5SDimitry Andric     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
57510b57cec5SDimitry Andric     else                                         assert(isHexDigit(Uuid[i]));
57520b57cec5SDimitry Andric   }
57530b57cec5SDimitry Andric 
57540b57cec5SDimitry Andric   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
57550b57cec5SDimitry Andric   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
57560b57cec5SDimitry Andric 
57570b57cec5SDimitry Andric   llvm::Constant *Field3[8];
57580b57cec5SDimitry Andric   for (unsigned Idx = 0; Idx < 8; ++Idx)
57590b57cec5SDimitry Andric     Field3[Idx] = llvm::ConstantInt::get(
57600b57cec5SDimitry Andric         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
57610b57cec5SDimitry Andric 
57620b57cec5SDimitry Andric   llvm::Constant *Fields[4] = {
57630b57cec5SDimitry Andric     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
57640b57cec5SDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
57650b57cec5SDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
57660b57cec5SDimitry Andric     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
57670b57cec5SDimitry Andric   };
57680b57cec5SDimitry Andric 
57690b57cec5SDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
57700b57cec5SDimitry Andric }
57710b57cec5SDimitry Andric 
57720b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
57730b57cec5SDimitry Andric                                                        bool ForEH) {
57740b57cec5SDimitry Andric   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
57750b57cec5SDimitry Andric   // FIXME: should we even be calling this method if RTTI is disabled
57760b57cec5SDimitry Andric   // and it's not for EH?
57770b57cec5SDimitry Andric   if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice)
57780b57cec5SDimitry Andric     return llvm::Constant::getNullValue(Int8PtrTy);
57790b57cec5SDimitry Andric 
57800b57cec5SDimitry Andric   if (ForEH && Ty->isObjCObjectPointerType() &&
57810b57cec5SDimitry Andric       LangOpts.ObjCRuntime.isGNUFamily())
57820b57cec5SDimitry Andric     return ObjCRuntime->GetEHType(Ty);
57830b57cec5SDimitry Andric 
57840b57cec5SDimitry Andric   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
57850b57cec5SDimitry Andric }
57860b57cec5SDimitry Andric 
57870b57cec5SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
57880b57cec5SDimitry Andric   // Do not emit threadprivates in simd-only mode.
57890b57cec5SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
57900b57cec5SDimitry Andric     return;
57910b57cec5SDimitry Andric   for (auto RefExpr : D->varlists()) {
57920b57cec5SDimitry Andric     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
57930b57cec5SDimitry Andric     bool PerformInit =
57940b57cec5SDimitry Andric         VD->getAnyInitializer() &&
57950b57cec5SDimitry Andric         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
57960b57cec5SDimitry Andric                                                         /*ForRef=*/false);
57970b57cec5SDimitry Andric 
57980b57cec5SDimitry Andric     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
57990b57cec5SDimitry Andric     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
58000b57cec5SDimitry Andric             VD, Addr, RefExpr->getBeginLoc(), PerformInit))
58010b57cec5SDimitry Andric       CXXGlobalInits.push_back(InitFunction);
58020b57cec5SDimitry Andric   }
58030b57cec5SDimitry Andric }
58040b57cec5SDimitry Andric 
58050b57cec5SDimitry Andric llvm::Metadata *
58060b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
58070b57cec5SDimitry Andric                                             StringRef Suffix) {
58080b57cec5SDimitry Andric   llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
58090b57cec5SDimitry Andric   if (InternalId)
58100b57cec5SDimitry Andric     return InternalId;
58110b57cec5SDimitry Andric 
58120b57cec5SDimitry Andric   if (isExternallyVisible(T->getLinkage())) {
58130b57cec5SDimitry Andric     std::string OutName;
58140b57cec5SDimitry Andric     llvm::raw_string_ostream Out(OutName);
58150b57cec5SDimitry Andric     getCXXABI().getMangleContext().mangleTypeName(T, Out);
58160b57cec5SDimitry Andric     Out << Suffix;
58170b57cec5SDimitry Andric 
58180b57cec5SDimitry Andric     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
58190b57cec5SDimitry Andric   } else {
58200b57cec5SDimitry Andric     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
58210b57cec5SDimitry Andric                                            llvm::ArrayRef<llvm::Metadata *>());
58220b57cec5SDimitry Andric   }
58230b57cec5SDimitry Andric 
58240b57cec5SDimitry Andric   return InternalId;
58250b57cec5SDimitry Andric }
58260b57cec5SDimitry Andric 
58270b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
58280b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
58290b57cec5SDimitry Andric }
58300b57cec5SDimitry Andric 
58310b57cec5SDimitry Andric llvm::Metadata *
58320b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
58330b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
58340b57cec5SDimitry Andric }
58350b57cec5SDimitry Andric 
58360b57cec5SDimitry Andric // Generalize pointer types to a void pointer with the qualifiers of the
58370b57cec5SDimitry Andric // originally pointed-to type, e.g. 'const char *' and 'char * const *'
58380b57cec5SDimitry Andric // generalize to 'const void *' while 'char *' and 'const char **' generalize to
58390b57cec5SDimitry Andric // 'void *'.
58400b57cec5SDimitry Andric static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
58410b57cec5SDimitry Andric   if (!Ty->isPointerType())
58420b57cec5SDimitry Andric     return Ty;
58430b57cec5SDimitry Andric 
58440b57cec5SDimitry Andric   return Ctx.getPointerType(
58450b57cec5SDimitry Andric       QualType(Ctx.VoidTy).withCVRQualifiers(
58460b57cec5SDimitry Andric           Ty->getPointeeType().getCVRQualifiers()));
58470b57cec5SDimitry Andric }
58480b57cec5SDimitry Andric 
58490b57cec5SDimitry Andric // Apply type generalization to a FunctionType's return and argument types
58500b57cec5SDimitry Andric static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
58510b57cec5SDimitry Andric   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
58520b57cec5SDimitry Andric     SmallVector<QualType, 8> GeneralizedParams;
58530b57cec5SDimitry Andric     for (auto &Param : FnType->param_types())
58540b57cec5SDimitry Andric       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
58550b57cec5SDimitry Andric 
58560b57cec5SDimitry Andric     return Ctx.getFunctionType(
58570b57cec5SDimitry Andric         GeneralizeType(Ctx, FnType->getReturnType()),
58580b57cec5SDimitry Andric         GeneralizedParams, FnType->getExtProtoInfo());
58590b57cec5SDimitry Andric   }
58600b57cec5SDimitry Andric 
58610b57cec5SDimitry Andric   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
58620b57cec5SDimitry Andric     return Ctx.getFunctionNoProtoType(
58630b57cec5SDimitry Andric         GeneralizeType(Ctx, FnType->getReturnType()));
58640b57cec5SDimitry Andric 
58650b57cec5SDimitry Andric   llvm_unreachable("Encountered unknown FunctionType");
58660b57cec5SDimitry Andric }
58670b57cec5SDimitry Andric 
58680b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
58690b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
58700b57cec5SDimitry Andric                                       GeneralizedMetadataIdMap, ".generalized");
58710b57cec5SDimitry Andric }
58720b57cec5SDimitry Andric 
58730b57cec5SDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier.
58740b57cec5SDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const {
58750b57cec5SDimitry Andric   // Returns true if at least one of vtable-based CFI checkers is enabled and
58760b57cec5SDimitry Andric   // is not in the trapping mode.
58770b57cec5SDimitry Andric   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
58780b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
58790b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
58800b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
58810b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
58820b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
58830b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
58840b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
58850b57cec5SDimitry Andric }
58860b57cec5SDimitry Andric 
58870b57cec5SDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
58880b57cec5SDimitry Andric                                           CharUnits Offset,
58890b57cec5SDimitry Andric                                           const CXXRecordDecl *RD) {
58900b57cec5SDimitry Andric   llvm::Metadata *MD =
58910b57cec5SDimitry Andric       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
58920b57cec5SDimitry Andric   VTable->addTypeMetadata(Offset.getQuantity(), MD);
58930b57cec5SDimitry Andric 
58940b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
58950b57cec5SDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
58960b57cec5SDimitry Andric       VTable->addTypeMetadata(Offset.getQuantity(),
58970b57cec5SDimitry Andric                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
58980b57cec5SDimitry Andric 
58990b57cec5SDimitry Andric   if (NeedAllVtablesTypeId()) {
59000b57cec5SDimitry Andric     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
59010b57cec5SDimitry Andric     VTable->addTypeMetadata(Offset.getQuantity(), MD);
59020b57cec5SDimitry Andric   }
59030b57cec5SDimitry Andric }
59040b57cec5SDimitry Andric 
59050b57cec5SDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
59060b57cec5SDimitry Andric   if (!SanStats)
5907a7dea167SDimitry Andric     SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
59080b57cec5SDimitry Andric 
59090b57cec5SDimitry Andric   return *SanStats;
59100b57cec5SDimitry Andric }
59110b57cec5SDimitry Andric llvm::Value *
59120b57cec5SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
59130b57cec5SDimitry Andric                                                   CodeGenFunction &CGF) {
59140b57cec5SDimitry Andric   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
59150b57cec5SDimitry Andric   auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
59160b57cec5SDimitry Andric   auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
59170b57cec5SDimitry Andric   return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
59180b57cec5SDimitry Andric                                 "__translate_sampler_initializer"),
59190b57cec5SDimitry Andric                                 {C});
59200b57cec5SDimitry Andric }
5921