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