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