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"
22af732203SDimitry Andric #include "CGOpenMPRuntimeAMDGCN.h"
230b57cec5SDimitry Andric #include "CGOpenMPRuntimeNVPTX.h"
240b57cec5SDimitry Andric #include "CodeGenFunction.h"
250b57cec5SDimitry Andric #include "CodeGenPGO.h"
260b57cec5SDimitry Andric #include "ConstantEmitter.h"
270b57cec5SDimitry Andric #include "CoverageMappingGen.h"
280b57cec5SDimitry Andric #include "TargetInfo.h"
290b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
300b57cec5SDimitry Andric #include "clang/AST/CharUnits.h"
310b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h"
320b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h"
330b57cec5SDimitry Andric #include "clang/AST/DeclTemplate.h"
340b57cec5SDimitry Andric #include "clang/AST/Mangle.h"
350b57cec5SDimitry Andric #include "clang/AST/RecordLayout.h"
360b57cec5SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
370b57cec5SDimitry Andric #include "clang/AST/StmtVisitor.h"
380b57cec5SDimitry Andric #include "clang/Basic/Builtins.h"
390b57cec5SDimitry Andric #include "clang/Basic/CharInfo.h"
400b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
410b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h"
425ffd83dbSDimitry Andric #include "clang/Basic/FileManager.h"
430b57cec5SDimitry Andric #include "clang/Basic/Module.h"
440b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h"
450b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h"
460b57cec5SDimitry Andric #include "clang/Basic/Version.h"
470b57cec5SDimitry Andric #include "clang/CodeGen/ConstantInitBuilder.h"
480b57cec5SDimitry Andric #include "clang/Frontend/FrontendDiagnostic.h"
490b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h"
500b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
510b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
52480093f4SDimitry Andric #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
530b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h"
540b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
550b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
560b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
570b57cec5SDimitry Andric #include "llvm/IR/Module.h"
580b57cec5SDimitry Andric #include "llvm/IR/ProfileSummary.h"
590b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfReader.h"
600b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h"
61480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
620b57cec5SDimitry Andric #include "llvm/Support/ConvertUTF.h"
630b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
640b57cec5SDimitry Andric #include "llvm/Support/MD5.h"
650b57cec5SDimitry Andric #include "llvm/Support/TimeProfiler.h"
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric using namespace clang;
680b57cec5SDimitry Andric using namespace CodeGen;
690b57cec5SDimitry Andric 
700b57cec5SDimitry Andric static llvm::cl::opt<bool> LimitedCoverage(
710b57cec5SDimitry Andric     "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
720b57cec5SDimitry Andric     llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
730b57cec5SDimitry Andric     llvm::cl::init(false));
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric static const char AnnotationSection[] = "llvm.metadata";
760b57cec5SDimitry Andric 
createCXXABI(CodeGenModule & CGM)770b57cec5SDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
785f7ddb14SDimitry Andric   switch (CGM.getContext().getCXXABIKind()) {
79af732203SDimitry Andric   case TargetCXXABI::AppleARM64:
80480093f4SDimitry Andric   case TargetCXXABI::Fuchsia:
810b57cec5SDimitry Andric   case TargetCXXABI::GenericAArch64:
820b57cec5SDimitry Andric   case TargetCXXABI::GenericARM:
830b57cec5SDimitry Andric   case TargetCXXABI::iOS:
840b57cec5SDimitry Andric   case TargetCXXABI::WatchOS:
850b57cec5SDimitry Andric   case TargetCXXABI::GenericMIPS:
860b57cec5SDimitry Andric   case TargetCXXABI::GenericItanium:
870b57cec5SDimitry Andric   case TargetCXXABI::WebAssembly:
885ffd83dbSDimitry Andric   case TargetCXXABI::XL:
890b57cec5SDimitry Andric     return CreateItaniumCXXABI(CGM);
900b57cec5SDimitry Andric   case TargetCXXABI::Microsoft:
910b57cec5SDimitry Andric     return CreateMicrosoftCXXABI(CGM);
920b57cec5SDimitry Andric   }
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric   llvm_unreachable("invalid C++ ABI kind");
950b57cec5SDimitry Andric }
960b57cec5SDimitry Andric 
CodeGenModule(ASTContext & C,const HeaderSearchOptions & HSO,const PreprocessorOptions & PPO,const CodeGenOptions & CGO,llvm::Module & M,DiagnosticsEngine & diags,CoverageSourceInfo * CoverageInfo)970b57cec5SDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
980b57cec5SDimitry Andric                              const PreprocessorOptions &PPO,
990b57cec5SDimitry Andric                              const CodeGenOptions &CGO, llvm::Module &M,
1000b57cec5SDimitry Andric                              DiagnosticsEngine &diags,
1010b57cec5SDimitry Andric                              CoverageSourceInfo *CoverageInfo)
1020b57cec5SDimitry Andric     : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
1030b57cec5SDimitry Andric       PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
1040b57cec5SDimitry Andric       Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
1050b57cec5SDimitry Andric       VMContext(M.getContext()), Types(*this), VTables(*this),
1060b57cec5SDimitry Andric       SanitizerMD(new SanitizerMetadata(*this)) {
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric   // Initialize the type cache.
1090b57cec5SDimitry Andric   llvm::LLVMContext &LLVMContext = M.getContext();
1100b57cec5SDimitry Andric   VoidTy = llvm::Type::getVoidTy(LLVMContext);
1110b57cec5SDimitry Andric   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
1120b57cec5SDimitry Andric   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
1130b57cec5SDimitry Andric   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
1140b57cec5SDimitry Andric   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
1150b57cec5SDimitry Andric   HalfTy = llvm::Type::getHalfTy(LLVMContext);
1165ffd83dbSDimitry Andric   BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
1170b57cec5SDimitry Andric   FloatTy = llvm::Type::getFloatTy(LLVMContext);
1180b57cec5SDimitry Andric   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
1190b57cec5SDimitry Andric   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
1200b57cec5SDimitry Andric   PointerAlignInBytes =
1210b57cec5SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
1220b57cec5SDimitry Andric   SizeSizeInBytes =
1230b57cec5SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
1240b57cec5SDimitry Andric   IntAlignInBytes =
1250b57cec5SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
126af732203SDimitry Andric   CharTy =
127af732203SDimitry Andric     llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth());
1280b57cec5SDimitry Andric   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
1290b57cec5SDimitry Andric   IntPtrTy = llvm::IntegerType::get(LLVMContext,
1300b57cec5SDimitry Andric     C.getTargetInfo().getMaxPointerWidth());
1310b57cec5SDimitry Andric   Int8PtrTy = Int8Ty->getPointerTo(0);
1320b57cec5SDimitry Andric   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
1330b57cec5SDimitry Andric   AllocaInt8PtrTy = Int8Ty->getPointerTo(
1340b57cec5SDimitry Andric       M.getDataLayout().getAllocaAddrSpace());
1350b57cec5SDimitry Andric   ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric   if (LangOpts.ObjC)
1400b57cec5SDimitry Andric     createObjCRuntime();
1410b57cec5SDimitry Andric   if (LangOpts.OpenCL)
1420b57cec5SDimitry Andric     createOpenCLRuntime();
1430b57cec5SDimitry Andric   if (LangOpts.OpenMP)
1440b57cec5SDimitry Andric     createOpenMPRuntime();
1450b57cec5SDimitry Andric   if (LangOpts.CUDA)
1460b57cec5SDimitry Andric     createCUDARuntime();
1470b57cec5SDimitry Andric 
1480b57cec5SDimitry Andric   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
1490b57cec5SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
1500b57cec5SDimitry Andric       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
1510b57cec5SDimitry Andric     TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
1520b57cec5SDimitry Andric                                getCXXABI().getMangleContext()));
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric   // If debug info or coverage generation is enabled, create the CGDebugInfo
1550b57cec5SDimitry Andric   // object.
1560b57cec5SDimitry Andric   if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
1570b57cec5SDimitry Andric       CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
1580b57cec5SDimitry Andric     DebugInfo.reset(new CGDebugInfo(*this));
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric   Block.GlobalUniqueCount = 0;
1610b57cec5SDimitry Andric 
1620b57cec5SDimitry Andric   if (C.getLangOpts().ObjC)
1630b57cec5SDimitry Andric     ObjCData.reset(new ObjCEntrypoints());
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric   if (CodeGenOpts.hasProfileClangUse()) {
1660b57cec5SDimitry Andric     auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
1670b57cec5SDimitry Andric         CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile);
1680b57cec5SDimitry Andric     if (auto E = ReaderOrErr.takeError()) {
1690b57cec5SDimitry Andric       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1700b57cec5SDimitry Andric                                               "Could not read profile %0: %1");
1710b57cec5SDimitry Andric       llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
1720b57cec5SDimitry Andric         getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
1730b57cec5SDimitry Andric                                   << EI.message();
1740b57cec5SDimitry Andric       });
1750b57cec5SDimitry Andric     } else
1760b57cec5SDimitry Andric       PGOReader = std::move(ReaderOrErr.get());
1770b57cec5SDimitry Andric   }
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric   // If coverage mapping generation is enabled, create the
1800b57cec5SDimitry Andric   // CoverageMappingModuleGen object.
1810b57cec5SDimitry Andric   if (CodeGenOpts.CoverageMapping)
1820b57cec5SDimitry Andric     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
1835f7ddb14SDimitry Andric 
1845f7ddb14SDimitry Andric   // Generate the module name hash here if needed.
1855f7ddb14SDimitry Andric   if (CodeGenOpts.UniqueInternalLinkageNames &&
1865f7ddb14SDimitry Andric       !getModule().getSourceFileName().empty()) {
1875f7ddb14SDimitry Andric     std::string Path = getModule().getSourceFileName();
1885f7ddb14SDimitry Andric     // Check if a path substitution is needed from the MacroPrefixMap.
189*2e2f8eacSDimitry Andric     for (const auto &Entry : LangOpts.MacroPrefixMap)
1905f7ddb14SDimitry Andric       if (Path.rfind(Entry.first, 0) != std::string::npos) {
1915f7ddb14SDimitry Andric         Path = Entry.second + Path.substr(Entry.first.size());
1925f7ddb14SDimitry Andric         break;
1935f7ddb14SDimitry Andric       }
1945f7ddb14SDimitry Andric     llvm::MD5 Md5;
1955f7ddb14SDimitry Andric     Md5.update(Path);
1965f7ddb14SDimitry Andric     llvm::MD5::MD5Result R;
1975f7ddb14SDimitry Andric     Md5.final(R);
1985f7ddb14SDimitry Andric     SmallString<32> Str;
1995f7ddb14SDimitry Andric     llvm::MD5::stringifyResult(R, Str);
2005f7ddb14SDimitry Andric     // Convert MD5hash to Decimal. Demangler suffixes can either contain
2015f7ddb14SDimitry Andric     // numbers or characters but not both.
2025f7ddb14SDimitry Andric     llvm::APInt IntHash(128, Str.str(), 16);
2035f7ddb14SDimitry Andric     // Prepend "__uniq" before the hash for tools like profilers to understand
2045f7ddb14SDimitry Andric     // that this symbol is of internal linkage type.  The "__uniq" is the
2055f7ddb14SDimitry Andric     // pre-determined prefix that is used to tell tools that this symbol was
2065f7ddb14SDimitry Andric     // created with -funique-internal-linakge-symbols and the tools can strip or
2075f7ddb14SDimitry Andric     // keep the prefix as needed.
2085f7ddb14SDimitry Andric     ModuleNameHash = (Twine(".__uniq.") +
2095f7ddb14SDimitry Andric         Twine(toString(IntHash, /* Radix = */ 10, /* Signed = */false))).str();
2105f7ddb14SDimitry Andric   }
2110b57cec5SDimitry Andric }
2120b57cec5SDimitry Andric 
~CodeGenModule()2130b57cec5SDimitry Andric CodeGenModule::~CodeGenModule() {}
2140b57cec5SDimitry Andric 
createObjCRuntime()2150b57cec5SDimitry Andric void CodeGenModule::createObjCRuntime() {
2160b57cec5SDimitry Andric   // This is just isGNUFamily(), but we want to force implementors of
2170b57cec5SDimitry Andric   // new ABIs to decide how best to do this.
2180b57cec5SDimitry Andric   switch (LangOpts.ObjCRuntime.getKind()) {
2190b57cec5SDimitry Andric   case ObjCRuntime::GNUstep:
2200b57cec5SDimitry Andric   case ObjCRuntime::GCC:
2210b57cec5SDimitry Andric   case ObjCRuntime::ObjFW:
2220b57cec5SDimitry Andric     ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
2230b57cec5SDimitry Andric     return;
2240b57cec5SDimitry Andric 
2250b57cec5SDimitry Andric   case ObjCRuntime::FragileMacOSX:
2260b57cec5SDimitry Andric   case ObjCRuntime::MacOSX:
2270b57cec5SDimitry Andric   case ObjCRuntime::iOS:
2280b57cec5SDimitry Andric   case ObjCRuntime::WatchOS:
2290b57cec5SDimitry Andric     ObjCRuntime.reset(CreateMacObjCRuntime(*this));
2300b57cec5SDimitry Andric     return;
2310b57cec5SDimitry Andric   }
2320b57cec5SDimitry Andric   llvm_unreachable("bad runtime kind");
2330b57cec5SDimitry Andric }
2340b57cec5SDimitry Andric 
createOpenCLRuntime()2350b57cec5SDimitry Andric void CodeGenModule::createOpenCLRuntime() {
2360b57cec5SDimitry Andric   OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
2370b57cec5SDimitry Andric }
2380b57cec5SDimitry Andric 
createOpenMPRuntime()2390b57cec5SDimitry Andric void CodeGenModule::createOpenMPRuntime() {
2400b57cec5SDimitry Andric   // Select a specialized code generation class based on the target, if any.
2410b57cec5SDimitry Andric   // If it does not exist use the default implementation.
2420b57cec5SDimitry Andric   switch (getTriple().getArch()) {
2430b57cec5SDimitry Andric   case llvm::Triple::nvptx:
2440b57cec5SDimitry Andric   case llvm::Triple::nvptx64:
2450b57cec5SDimitry Andric     assert(getLangOpts().OpenMPIsDevice &&
2460b57cec5SDimitry Andric            "OpenMP NVPTX is only prepared to deal with device code.");
2470b57cec5SDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
2480b57cec5SDimitry Andric     break;
249af732203SDimitry Andric   case llvm::Triple::amdgcn:
250af732203SDimitry Andric     assert(getLangOpts().OpenMPIsDevice &&
251af732203SDimitry Andric            "OpenMP AMDGCN is only prepared to deal with device code.");
252af732203SDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntimeAMDGCN(*this));
253af732203SDimitry Andric     break;
2540b57cec5SDimitry Andric   default:
2550b57cec5SDimitry Andric     if (LangOpts.OpenMPSimd)
2560b57cec5SDimitry Andric       OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
2570b57cec5SDimitry Andric     else
2580b57cec5SDimitry Andric       OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
2590b57cec5SDimitry Andric     break;
2600b57cec5SDimitry Andric   }
2610b57cec5SDimitry Andric }
2620b57cec5SDimitry Andric 
createCUDARuntime()2630b57cec5SDimitry Andric void CodeGenModule::createCUDARuntime() {
2640b57cec5SDimitry Andric   CUDARuntime.reset(CreateNVCUDARuntime(*this));
2650b57cec5SDimitry Andric }
2660b57cec5SDimitry Andric 
addReplacement(StringRef Name,llvm::Constant * C)2670b57cec5SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
2680b57cec5SDimitry Andric   Replacements[Name] = C;
2690b57cec5SDimitry Andric }
2700b57cec5SDimitry Andric 
applyReplacements()2710b57cec5SDimitry Andric void CodeGenModule::applyReplacements() {
2720b57cec5SDimitry Andric   for (auto &I : Replacements) {
2730b57cec5SDimitry Andric     StringRef MangledName = I.first();
2740b57cec5SDimitry Andric     llvm::Constant *Replacement = I.second;
2750b57cec5SDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2760b57cec5SDimitry Andric     if (!Entry)
2770b57cec5SDimitry Andric       continue;
2780b57cec5SDimitry Andric     auto *OldF = cast<llvm::Function>(Entry);
2790b57cec5SDimitry Andric     auto *NewF = dyn_cast<llvm::Function>(Replacement);
2800b57cec5SDimitry Andric     if (!NewF) {
2810b57cec5SDimitry Andric       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
2820b57cec5SDimitry Andric         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
2830b57cec5SDimitry Andric       } else {
2840b57cec5SDimitry Andric         auto *CE = cast<llvm::ConstantExpr>(Replacement);
2850b57cec5SDimitry Andric         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2860b57cec5SDimitry Andric                CE->getOpcode() == llvm::Instruction::GetElementPtr);
2870b57cec5SDimitry Andric         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
2880b57cec5SDimitry Andric       }
2890b57cec5SDimitry Andric     }
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric     // Replace old with new, but keep the old order.
2920b57cec5SDimitry Andric     OldF->replaceAllUsesWith(Replacement);
2930b57cec5SDimitry Andric     if (NewF) {
2940b57cec5SDimitry Andric       NewF->removeFromParent();
2950b57cec5SDimitry Andric       OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
2960b57cec5SDimitry Andric                                                        NewF);
2970b57cec5SDimitry Andric     }
2980b57cec5SDimitry Andric     OldF->eraseFromParent();
2990b57cec5SDimitry Andric   }
3000b57cec5SDimitry Andric }
3010b57cec5SDimitry Andric 
addGlobalValReplacement(llvm::GlobalValue * GV,llvm::Constant * C)3020b57cec5SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
3030b57cec5SDimitry Andric   GlobalValReplacements.push_back(std::make_pair(GV, C));
3040b57cec5SDimitry Andric }
3050b57cec5SDimitry Andric 
applyGlobalValReplacements()3060b57cec5SDimitry Andric void CodeGenModule::applyGlobalValReplacements() {
3070b57cec5SDimitry Andric   for (auto &I : GlobalValReplacements) {
3080b57cec5SDimitry Andric     llvm::GlobalValue *GV = I.first;
3090b57cec5SDimitry Andric     llvm::Constant *C = I.second;
3100b57cec5SDimitry Andric 
3110b57cec5SDimitry Andric     GV->replaceAllUsesWith(C);
3120b57cec5SDimitry Andric     GV->eraseFromParent();
3130b57cec5SDimitry Andric   }
3140b57cec5SDimitry Andric }
3150b57cec5SDimitry Andric 
3160b57cec5SDimitry Andric // This is only used in aliases that we created and we know they have a
3170b57cec5SDimitry Andric // linear structure.
getAliasedGlobal(const llvm::GlobalIndirectSymbol & GIS)3180b57cec5SDimitry Andric static const llvm::GlobalObject *getAliasedGlobal(
3190b57cec5SDimitry Andric     const llvm::GlobalIndirectSymbol &GIS) {
3200b57cec5SDimitry Andric   llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
3210b57cec5SDimitry Andric   const llvm::Constant *C = &GIS;
3220b57cec5SDimitry Andric   for (;;) {
3230b57cec5SDimitry Andric     C = C->stripPointerCasts();
3240b57cec5SDimitry Andric     if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
3250b57cec5SDimitry Andric       return GO;
3260b57cec5SDimitry Andric     // stripPointerCasts will not walk over weak aliases.
3270b57cec5SDimitry Andric     auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
3280b57cec5SDimitry Andric     if (!GIS2)
3290b57cec5SDimitry Andric       return nullptr;
3300b57cec5SDimitry Andric     if (!Visited.insert(GIS2).second)
3310b57cec5SDimitry Andric       return nullptr;
3320b57cec5SDimitry Andric     C = GIS2->getIndirectSymbol();
3330b57cec5SDimitry Andric   }
3340b57cec5SDimitry Andric }
3350b57cec5SDimitry Andric 
checkAliases()3360b57cec5SDimitry Andric void CodeGenModule::checkAliases() {
3370b57cec5SDimitry Andric   // Check if the constructed aliases are well formed. It is really unfortunate
3380b57cec5SDimitry Andric   // that we have to do this in CodeGen, but we only construct mangled names
3390b57cec5SDimitry Andric   // and aliases during codegen.
3400b57cec5SDimitry Andric   bool Error = false;
3410b57cec5SDimitry Andric   DiagnosticsEngine &Diags = getDiags();
3420b57cec5SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
3430b57cec5SDimitry Andric     const auto *D = cast<ValueDecl>(GD.getDecl());
3440b57cec5SDimitry Andric     SourceLocation Location;
3450b57cec5SDimitry Andric     bool IsIFunc = D->hasAttr<IFuncAttr>();
3460b57cec5SDimitry Andric     if (const Attr *A = D->getDefiningAttr())
3470b57cec5SDimitry Andric       Location = A->getLocation();
3480b57cec5SDimitry Andric     else
3490b57cec5SDimitry Andric       llvm_unreachable("Not an alias or ifunc?");
3500b57cec5SDimitry Andric     StringRef MangledName = getMangledName(GD);
3510b57cec5SDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3520b57cec5SDimitry Andric     auto *Alias  = cast<llvm::GlobalIndirectSymbol>(Entry);
3530b57cec5SDimitry Andric     const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
3540b57cec5SDimitry Andric     if (!GV) {
3550b57cec5SDimitry Andric       Error = true;
3560b57cec5SDimitry Andric       Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
3570b57cec5SDimitry Andric     } else if (GV->isDeclaration()) {
3580b57cec5SDimitry Andric       Error = true;
3590b57cec5SDimitry Andric       Diags.Report(Location, diag::err_alias_to_undefined)
3600b57cec5SDimitry Andric           << IsIFunc << IsIFunc;
3610b57cec5SDimitry Andric     } else if (IsIFunc) {
3620b57cec5SDimitry Andric       // Check resolver function type.
3630b57cec5SDimitry Andric       llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
3640b57cec5SDimitry Andric           GV->getType()->getPointerElementType());
3650b57cec5SDimitry Andric       assert(FTy);
3660b57cec5SDimitry Andric       if (!FTy->getReturnType()->isPointerTy())
3670b57cec5SDimitry Andric         Diags.Report(Location, diag::err_ifunc_resolver_return);
3680b57cec5SDimitry Andric     }
3690b57cec5SDimitry Andric 
3700b57cec5SDimitry Andric     llvm::Constant *Aliasee = Alias->getIndirectSymbol();
3710b57cec5SDimitry Andric     llvm::GlobalValue *AliaseeGV;
3720b57cec5SDimitry Andric     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
3730b57cec5SDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
3740b57cec5SDimitry Andric     else
3750b57cec5SDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
3760b57cec5SDimitry Andric 
3770b57cec5SDimitry Andric     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
3780b57cec5SDimitry Andric       StringRef AliasSection = SA->getName();
3790b57cec5SDimitry Andric       if (AliasSection != AliaseeGV->getSection())
3800b57cec5SDimitry Andric         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
3810b57cec5SDimitry Andric             << AliasSection << IsIFunc << IsIFunc;
3820b57cec5SDimitry Andric     }
3830b57cec5SDimitry Andric 
3840b57cec5SDimitry Andric     // We have to handle alias to weak aliases in here. LLVM itself disallows
3850b57cec5SDimitry Andric     // this since the object semantics would not match the IL one. For
3860b57cec5SDimitry Andric     // compatibility with gcc we implement it by just pointing the alias
3870b57cec5SDimitry Andric     // to its aliasee's aliasee. We also warn, since the user is probably
3880b57cec5SDimitry Andric     // expecting the link to be weak.
3890b57cec5SDimitry Andric     if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
3900b57cec5SDimitry Andric       if (GA->isInterposable()) {
3910b57cec5SDimitry Andric         Diags.Report(Location, diag::warn_alias_to_weak_alias)
3920b57cec5SDimitry Andric             << GV->getName() << GA->getName() << IsIFunc;
3930b57cec5SDimitry Andric         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3940b57cec5SDimitry Andric             GA->getIndirectSymbol(), Alias->getType());
3950b57cec5SDimitry Andric         Alias->setIndirectSymbol(Aliasee);
3960b57cec5SDimitry Andric       }
3970b57cec5SDimitry Andric     }
3980b57cec5SDimitry Andric   }
3990b57cec5SDimitry Andric   if (!Error)
4000b57cec5SDimitry Andric     return;
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
4030b57cec5SDimitry Andric     StringRef MangledName = getMangledName(GD);
4040b57cec5SDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
405af732203SDimitry Andric     auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
4060b57cec5SDimitry Andric     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
4070b57cec5SDimitry Andric     Alias->eraseFromParent();
4080b57cec5SDimitry Andric   }
4090b57cec5SDimitry Andric }
4100b57cec5SDimitry Andric 
clear()4110b57cec5SDimitry Andric void CodeGenModule::clear() {
4120b57cec5SDimitry Andric   DeferredDeclsToEmit.clear();
4130b57cec5SDimitry Andric   if (OpenMPRuntime)
4140b57cec5SDimitry Andric     OpenMPRuntime->clear();
4150b57cec5SDimitry Andric }
4160b57cec5SDimitry Andric 
reportDiagnostics(DiagnosticsEngine & Diags,StringRef MainFile)4170b57cec5SDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
4180b57cec5SDimitry Andric                                        StringRef MainFile) {
4190b57cec5SDimitry Andric   if (!hasDiagnostics())
4200b57cec5SDimitry Andric     return;
4210b57cec5SDimitry Andric   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
4220b57cec5SDimitry Andric     if (MainFile.empty())
4230b57cec5SDimitry Andric       MainFile = "<stdin>";
4240b57cec5SDimitry Andric     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
4250b57cec5SDimitry Andric   } else {
4260b57cec5SDimitry Andric     if (Mismatched > 0)
4270b57cec5SDimitry Andric       Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric     if (Missing > 0)
4300b57cec5SDimitry Andric       Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
4310b57cec5SDimitry Andric   }
4320b57cec5SDimitry Andric }
4330b57cec5SDimitry Andric 
setVisibilityFromDLLStorageClass(const clang::LangOptions & LO,llvm::Module & M)434af732203SDimitry Andric static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO,
435af732203SDimitry Andric                                              llvm::Module &M) {
436af732203SDimitry Andric   if (!LO.VisibilityFromDLLStorageClass)
437af732203SDimitry Andric     return;
438af732203SDimitry Andric 
439af732203SDimitry Andric   llvm::GlobalValue::VisibilityTypes DLLExportVisibility =
440af732203SDimitry Andric       CodeGenModule::GetLLVMVisibility(LO.getDLLExportVisibility());
441af732203SDimitry Andric   llvm::GlobalValue::VisibilityTypes NoDLLStorageClassVisibility =
442af732203SDimitry Andric       CodeGenModule::GetLLVMVisibility(LO.getNoDLLStorageClassVisibility());
443af732203SDimitry Andric   llvm::GlobalValue::VisibilityTypes ExternDeclDLLImportVisibility =
444af732203SDimitry Andric       CodeGenModule::GetLLVMVisibility(LO.getExternDeclDLLImportVisibility());
445af732203SDimitry Andric   llvm::GlobalValue::VisibilityTypes ExternDeclNoDLLStorageClassVisibility =
446af732203SDimitry Andric       CodeGenModule::GetLLVMVisibility(
447af732203SDimitry Andric           LO.getExternDeclNoDLLStorageClassVisibility());
448af732203SDimitry Andric 
449af732203SDimitry Andric   for (llvm::GlobalValue &GV : M.global_values()) {
450af732203SDimitry Andric     if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
451af732203SDimitry Andric       continue;
452af732203SDimitry Andric 
453af732203SDimitry Andric     // Reset DSO locality before setting the visibility. This removes
454af732203SDimitry Andric     // any effects that visibility options and annotations may have
455af732203SDimitry Andric     // had on the DSO locality. Setting the visibility will implicitly set
456af732203SDimitry Andric     // appropriate globals to DSO Local; however, this will be pessimistic
457af732203SDimitry Andric     // w.r.t. to the normal compiler IRGen.
458af732203SDimitry Andric     GV.setDSOLocal(false);
459af732203SDimitry Andric 
460af732203SDimitry Andric     if (GV.isDeclarationForLinker()) {
461af732203SDimitry Andric       GV.setVisibility(GV.getDLLStorageClass() ==
462af732203SDimitry Andric                                llvm::GlobalValue::DLLImportStorageClass
463af732203SDimitry Andric                            ? ExternDeclDLLImportVisibility
464af732203SDimitry Andric                            : ExternDeclNoDLLStorageClassVisibility);
465af732203SDimitry Andric     } else {
466af732203SDimitry Andric       GV.setVisibility(GV.getDLLStorageClass() ==
467af732203SDimitry Andric                                llvm::GlobalValue::DLLExportStorageClass
468af732203SDimitry Andric                            ? DLLExportVisibility
469af732203SDimitry Andric                            : NoDLLStorageClassVisibility);
470af732203SDimitry Andric     }
471af732203SDimitry Andric 
472af732203SDimitry Andric     GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
473af732203SDimitry Andric   }
474af732203SDimitry Andric }
475af732203SDimitry Andric 
Release()4760b57cec5SDimitry Andric void CodeGenModule::Release() {
4770b57cec5SDimitry Andric   EmitDeferred();
4780b57cec5SDimitry Andric   EmitVTablesOpportunistically();
4790b57cec5SDimitry Andric   applyGlobalValReplacements();
4800b57cec5SDimitry Andric   applyReplacements();
4810b57cec5SDimitry Andric   checkAliases();
4820b57cec5SDimitry Andric   emitMultiVersionFunctions();
4830b57cec5SDimitry Andric   EmitCXXGlobalInitFunc();
4845ffd83dbSDimitry Andric   EmitCXXGlobalCleanUpFunc();
4850b57cec5SDimitry Andric   registerGlobalDtorsWithAtExit();
4860b57cec5SDimitry Andric   EmitCXXThreadLocalInitFunc();
4870b57cec5SDimitry Andric   if (ObjCRuntime)
4880b57cec5SDimitry Andric     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
4890b57cec5SDimitry Andric       AddGlobalCtor(ObjCInitFunction);
4905f7ddb14SDimitry Andric   if (Context.getLangOpts().CUDA && CUDARuntime) {
4915f7ddb14SDimitry Andric     if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
4920b57cec5SDimitry Andric       AddGlobalCtor(CudaCtorFunction);
4930b57cec5SDimitry Andric   }
4940b57cec5SDimitry Andric   if (OpenMPRuntime) {
4950b57cec5SDimitry Andric     if (llvm::Function *OpenMPRequiresDirectiveRegFun =
4960b57cec5SDimitry Andric             OpenMPRuntime->emitRequiresDirectiveRegFun()) {
4970b57cec5SDimitry Andric       AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
4980b57cec5SDimitry Andric     }
499a7dea167SDimitry Andric     OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
5000b57cec5SDimitry Andric     OpenMPRuntime->clear();
5010b57cec5SDimitry Andric   }
5020b57cec5SDimitry Andric   if (PGOReader) {
5030b57cec5SDimitry Andric     getModule().setProfileSummary(
5040b57cec5SDimitry Andric         PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
5050b57cec5SDimitry Andric         llvm::ProfileSummary::PSK_Instr);
5060b57cec5SDimitry Andric     if (PGOStats.hasDiagnostics())
5070b57cec5SDimitry Andric       PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
5080b57cec5SDimitry Andric   }
5090b57cec5SDimitry Andric   EmitCtorList(GlobalCtors, "llvm.global_ctors");
5100b57cec5SDimitry Andric   EmitCtorList(GlobalDtors, "llvm.global_dtors");
5110b57cec5SDimitry Andric   EmitGlobalAnnotations();
5120b57cec5SDimitry Andric   EmitStaticExternCAliases();
5130b57cec5SDimitry Andric   EmitDeferredUnusedCoverageMappings();
5145f7ddb14SDimitry Andric   CodeGenPGO(*this).setValueProfilingFlag(getModule());
5150b57cec5SDimitry Andric   if (CoverageMapping)
5160b57cec5SDimitry Andric     CoverageMapping->emit();
5170b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
5180b57cec5SDimitry Andric     CodeGenFunction(*this).EmitCfiCheckFail();
5190b57cec5SDimitry Andric     CodeGenFunction(*this).EmitCfiCheckStub();
5200b57cec5SDimitry Andric   }
5210b57cec5SDimitry Andric   emitAtAvailableLinkGuard();
5225ffd83dbSDimitry Andric   if (Context.getTargetInfo().getTriple().isWasm() &&
5235ffd83dbSDimitry Andric       !Context.getTargetInfo().getTriple().isOSEmscripten()) {
5245ffd83dbSDimitry Andric     EmitMainVoidAlias();
5255ffd83dbSDimitry Andric   }
5265f7ddb14SDimitry Andric 
5275f7ddb14SDimitry Andric   // Emit reference of __amdgpu_device_library_preserve_asan_functions to
5285f7ddb14SDimitry Andric   // preserve ASAN functions in bitcode libraries.
5295f7ddb14SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::Address) && getTriple().isAMDGPU()) {
5305f7ddb14SDimitry Andric     auto *FT = llvm::FunctionType::get(VoidTy, {});
5315f7ddb14SDimitry Andric     auto *F = llvm::Function::Create(
5325f7ddb14SDimitry Andric         FT, llvm::GlobalValue::ExternalLinkage,
5335f7ddb14SDimitry Andric         "__amdgpu_device_library_preserve_asan_functions", &getModule());
5345f7ddb14SDimitry Andric     auto *Var = new llvm::GlobalVariable(
5355f7ddb14SDimitry Andric         getModule(), FT->getPointerTo(),
5365f7ddb14SDimitry Andric         /*isConstant=*/true, llvm::GlobalValue::WeakAnyLinkage, F,
5375f7ddb14SDimitry Andric         "__amdgpu_device_library_preserve_asan_functions_ptr", nullptr,
5385f7ddb14SDimitry Andric         llvm::GlobalVariable::NotThreadLocal);
5395f7ddb14SDimitry Andric     addCompilerUsedGlobal(Var);
5405f7ddb14SDimitry Andric   }
5415f7ddb14SDimitry Andric 
5420b57cec5SDimitry Andric   emitLLVMUsed();
5430b57cec5SDimitry Andric   if (SanStats)
5440b57cec5SDimitry Andric     SanStats->finish();
5450b57cec5SDimitry Andric 
5460b57cec5SDimitry Andric   if (CodeGenOpts.Autolink &&
5470b57cec5SDimitry Andric       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
5480b57cec5SDimitry Andric     EmitModuleLinkOptions();
5490b57cec5SDimitry Andric   }
5500b57cec5SDimitry Andric 
5510b57cec5SDimitry Andric   // On ELF we pass the dependent library specifiers directly to the linker
5520b57cec5SDimitry Andric   // without manipulating them. This is in contrast to other platforms where
5530b57cec5SDimitry Andric   // they are mapped to a specific linker option by the compiler. This
5540b57cec5SDimitry Andric   // difference is a result of the greater variety of ELF linkers and the fact
5550b57cec5SDimitry Andric   // that ELF linkers tend to handle libraries in a more complicated fashion
5560b57cec5SDimitry Andric   // than on other platforms. This forces us to defer handling the dependent
5570b57cec5SDimitry Andric   // libs to the linker.
5580b57cec5SDimitry Andric   //
5590b57cec5SDimitry Andric   // CUDA/HIP device and host libraries are different. Currently there is no
5600b57cec5SDimitry Andric   // way to differentiate dependent libraries for host or device. Existing
5610b57cec5SDimitry Andric   // usage of #pragma comment(lib, *) is intended for host libraries on
5620b57cec5SDimitry Andric   // Windows. Therefore emit llvm.dependent-libraries only for host.
5630b57cec5SDimitry Andric   if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
5640b57cec5SDimitry Andric     auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
5650b57cec5SDimitry Andric     for (auto *MD : ELFDependentLibraries)
5660b57cec5SDimitry Andric       NMD->addOperand(MD);
5670b57cec5SDimitry Andric   }
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric   // Record mregparm value now so it is visible through rest of codegen.
5700b57cec5SDimitry Andric   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
5710b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
5720b57cec5SDimitry Andric                               CodeGenOpts.NumRegisterParameters);
5730b57cec5SDimitry Andric 
5740b57cec5SDimitry Andric   if (CodeGenOpts.DwarfVersion) {
575480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
5760b57cec5SDimitry Andric                               CodeGenOpts.DwarfVersion);
5770b57cec5SDimitry Andric   }
5785ffd83dbSDimitry Andric 
5795f7ddb14SDimitry Andric   if (CodeGenOpts.Dwarf64)
5805f7ddb14SDimitry Andric     getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1);
5815f7ddb14SDimitry Andric 
5825ffd83dbSDimitry Andric   if (Context.getLangOpts().SemanticInterposition)
5835ffd83dbSDimitry Andric     // Require various optimization to respect semantic interposition.
5845ffd83dbSDimitry Andric     getModule().setSemanticInterposition(1);
5855ffd83dbSDimitry Andric 
5860b57cec5SDimitry Andric   if (CodeGenOpts.EmitCodeView) {
5870b57cec5SDimitry Andric     // Indicate that we want CodeView in the metadata.
5880b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
5890b57cec5SDimitry Andric   }
5900b57cec5SDimitry Andric   if (CodeGenOpts.CodeViewGHash) {
5910b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
5920b57cec5SDimitry Andric   }
5930b57cec5SDimitry Andric   if (CodeGenOpts.ControlFlowGuard) {
594480093f4SDimitry Andric     // Function ID tables and checks for Control Flow Guard (cfguard=2).
595480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2);
596480093f4SDimitry Andric   } else if (CodeGenOpts.ControlFlowGuardNoChecks) {
597480093f4SDimitry Andric     // Function ID tables for Control Flow Guard (cfguard=1).
598480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
5990b57cec5SDimitry Andric   }
6005f7ddb14SDimitry Andric   if (CodeGenOpts.EHContGuard) {
6015f7ddb14SDimitry Andric     // Function ID tables for EH Continuation Guard.
6025f7ddb14SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1);
6035f7ddb14SDimitry Andric   }
6040b57cec5SDimitry Andric   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
6050b57cec5SDimitry Andric     // We don't support LTO with 2 with different StrictVTablePointers
6060b57cec5SDimitry Andric     // FIXME: we could support it by stripping all the information introduced
6070b57cec5SDimitry Andric     // by StrictVTablePointers.
6080b57cec5SDimitry Andric 
6090b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
6100b57cec5SDimitry Andric 
6110b57cec5SDimitry Andric     llvm::Metadata *Ops[2] = {
6120b57cec5SDimitry Andric               llvm::MDString::get(VMContext, "StrictVTablePointers"),
6130b57cec5SDimitry Andric               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
6140b57cec5SDimitry Andric                   llvm::Type::getInt32Ty(VMContext), 1))};
6150b57cec5SDimitry Andric 
6160b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Require,
6170b57cec5SDimitry Andric                               "StrictVTablePointersRequirement",
6180b57cec5SDimitry Andric                               llvm::MDNode::get(VMContext, Ops));
6190b57cec5SDimitry Andric   }
6205ffd83dbSDimitry Andric   if (getModuleDebugInfo())
6210b57cec5SDimitry Andric     // We support a single version in the linked module. The LLVM
6220b57cec5SDimitry Andric     // parser will drop debug info with a different version number
6230b57cec5SDimitry Andric     // (and warn about it, too).
6240b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
6250b57cec5SDimitry Andric                               llvm::DEBUG_METADATA_VERSION);
6260b57cec5SDimitry Andric 
6270b57cec5SDimitry Andric   // We need to record the widths of enums and wchar_t, so that we can generate
6280b57cec5SDimitry Andric   // the correct build attributes in the ARM backend. wchar_size is also used by
6290b57cec5SDimitry Andric   // TargetLibraryInfo.
6300b57cec5SDimitry Andric   uint64_t WCharWidth =
6310b57cec5SDimitry Andric       Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
6320b57cec5SDimitry Andric   getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
6330b57cec5SDimitry Andric 
6340b57cec5SDimitry Andric   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
6350b57cec5SDimitry Andric   if (   Arch == llvm::Triple::arm
6360b57cec5SDimitry Andric       || Arch == llvm::Triple::armeb
6370b57cec5SDimitry Andric       || Arch == llvm::Triple::thumb
6380b57cec5SDimitry Andric       || Arch == llvm::Triple::thumbeb) {
6390b57cec5SDimitry Andric     // The minimum width of an enum in bytes
6400b57cec5SDimitry Andric     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
6410b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
6420b57cec5SDimitry Andric   }
6430b57cec5SDimitry Andric 
64413138422SDimitry Andric   if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) {
64513138422SDimitry Andric     StringRef ABIStr = Target.getABI();
64613138422SDimitry Andric     llvm::LLVMContext &Ctx = TheModule.getContext();
64713138422SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "target-abi",
64813138422SDimitry Andric                               llvm::MDString::get(Ctx, ABIStr));
64913138422SDimitry Andric   }
65013138422SDimitry Andric 
6510b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
6520b57cec5SDimitry Andric     // Indicate that we want cross-DSO control flow integrity checks.
6530b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
6540b57cec5SDimitry Andric   }
6550b57cec5SDimitry Andric 
6565ffd83dbSDimitry Andric   if (CodeGenOpts.WholeProgramVTables) {
6575ffd83dbSDimitry Andric     // Indicate whether VFE was enabled for this module, so that the
6585ffd83dbSDimitry Andric     // vcall_visibility metadata added under whole program vtables is handled
6595ffd83dbSDimitry Andric     // appropriately in the optimizer.
6605ffd83dbSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim",
6615ffd83dbSDimitry Andric                               CodeGenOpts.VirtualFunctionElimination);
6625ffd83dbSDimitry Andric   }
6635ffd83dbSDimitry Andric 
664a7dea167SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
665a7dea167SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override,
666a7dea167SDimitry Andric                               "CFI Canonical Jump Tables",
667a7dea167SDimitry Andric                               CodeGenOpts.SanitizeCfiCanonicalJumpTables);
668a7dea167SDimitry Andric   }
669a7dea167SDimitry Andric 
6700b57cec5SDimitry Andric   if (CodeGenOpts.CFProtectionReturn &&
6710b57cec5SDimitry Andric       Target.checkCFProtectionReturnSupported(getDiags())) {
6720b57cec5SDimitry Andric     // Indicate that we want to instrument return control flow protection.
6730b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
6740b57cec5SDimitry Andric                               1);
6750b57cec5SDimitry Andric   }
6760b57cec5SDimitry Andric 
6770b57cec5SDimitry Andric   if (CodeGenOpts.CFProtectionBranch &&
6780b57cec5SDimitry Andric       Target.checkCFProtectionBranchSupported(getDiags())) {
6790b57cec5SDimitry Andric     // Indicate that we want to instrument branch control flow protection.
6800b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
6810b57cec5SDimitry Andric                               1);
6820b57cec5SDimitry Andric   }
6830b57cec5SDimitry Andric 
684af732203SDimitry Andric   if (Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 ||
685af732203SDimitry Andric       Arch == llvm::Triple::aarch64_be) {
686af732203SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error,
687af732203SDimitry Andric                               "branch-target-enforcement",
688af732203SDimitry Andric                               LangOpts.BranchTargetEnforcement);
689af732203SDimitry Andric 
690af732203SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "sign-return-address",
691af732203SDimitry Andric                               LangOpts.hasSignReturnAddress());
692af732203SDimitry Andric 
693af732203SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "sign-return-address-all",
694af732203SDimitry Andric                               LangOpts.isSignReturnAddressScopeAll());
695af732203SDimitry Andric 
696af732203SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error,
697af732203SDimitry Andric                               "sign-return-address-with-bkey",
698af732203SDimitry Andric                               !LangOpts.isSignReturnAddressWithAKey());
699af732203SDimitry Andric   }
700af732203SDimitry Andric 
701af732203SDimitry Andric   if (!CodeGenOpts.MemoryProfileOutput.empty()) {
702af732203SDimitry Andric     llvm::LLVMContext &Ctx = TheModule.getContext();
703af732203SDimitry Andric     getModule().addModuleFlag(
704af732203SDimitry Andric         llvm::Module::Error, "MemProfProfileFilename",
705af732203SDimitry Andric         llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
706af732203SDimitry Andric   }
707af732203SDimitry Andric 
7080b57cec5SDimitry Andric   if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
7090b57cec5SDimitry Andric     // Indicate whether __nvvm_reflect should be configured to flush denormal
7100b57cec5SDimitry Andric     // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
7110b57cec5SDimitry Andric     // property.)
7120b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
7135ffd83dbSDimitry Andric                               CodeGenOpts.FP32DenormalMode.Output !=
7145ffd83dbSDimitry Andric                                   llvm::DenormalMode::IEEE);
7150b57cec5SDimitry Andric   }
7160b57cec5SDimitry Andric 
7175f7ddb14SDimitry Andric   if (LangOpts.EHAsynch)
7185f7ddb14SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1);
7195f7ddb14SDimitry Andric 
7205f7ddb14SDimitry Andric   // Indicate whether this Module was compiled with -fopenmp
7215f7ddb14SDimitry Andric   if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
7225f7ddb14SDimitry Andric     getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP);
7235f7ddb14SDimitry Andric   if (getLangOpts().OpenMPIsDevice)
7245f7ddb14SDimitry Andric     getModule().addModuleFlag(llvm::Module::Max, "openmp-device",
7255f7ddb14SDimitry Andric                               LangOpts.OpenMP);
7265f7ddb14SDimitry Andric 
7270b57cec5SDimitry Andric   // Emit OpenCL specific module metadata: OpenCL/SPIR version.
7280b57cec5SDimitry Andric   if (LangOpts.OpenCL) {
7290b57cec5SDimitry Andric     EmitOpenCLMetadata();
7300b57cec5SDimitry Andric     // Emit SPIR version.
7310b57cec5SDimitry Andric     if (getTriple().isSPIR()) {
7320b57cec5SDimitry Andric       // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
7330b57cec5SDimitry Andric       // opencl.spir.version named metadata.
7340b57cec5SDimitry Andric       // C++ is backwards compatible with OpenCL v2.0.
7350b57cec5SDimitry Andric       auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
7360b57cec5SDimitry Andric       llvm::Metadata *SPIRVerElts[] = {
7370b57cec5SDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7380b57cec5SDimitry Andric               Int32Ty, Version / 100)),
7390b57cec5SDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7400b57cec5SDimitry Andric               Int32Ty, (Version / 100 > 1) ? 0 : 2))};
7410b57cec5SDimitry Andric       llvm::NamedMDNode *SPIRVerMD =
7420b57cec5SDimitry Andric           TheModule.getOrInsertNamedMetadata("opencl.spir.version");
7430b57cec5SDimitry Andric       llvm::LLVMContext &Ctx = TheModule.getContext();
7440b57cec5SDimitry Andric       SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
7450b57cec5SDimitry Andric     }
7460b57cec5SDimitry Andric   }
7470b57cec5SDimitry Andric 
7480b57cec5SDimitry Andric   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
7490b57cec5SDimitry Andric     assert(PLevel < 3 && "Invalid PIC Level");
7500b57cec5SDimitry Andric     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
7510b57cec5SDimitry Andric     if (Context.getLangOpts().PIE)
7520b57cec5SDimitry Andric       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
7530b57cec5SDimitry Andric   }
7540b57cec5SDimitry Andric 
7550b57cec5SDimitry Andric   if (getCodeGenOpts().CodeModel.size() > 0) {
7560b57cec5SDimitry Andric     unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
7570b57cec5SDimitry Andric                   .Case("tiny", llvm::CodeModel::Tiny)
7580b57cec5SDimitry Andric                   .Case("small", llvm::CodeModel::Small)
7590b57cec5SDimitry Andric                   .Case("kernel", llvm::CodeModel::Kernel)
7600b57cec5SDimitry Andric                   .Case("medium", llvm::CodeModel::Medium)
7610b57cec5SDimitry Andric                   .Case("large", llvm::CodeModel::Large)
7620b57cec5SDimitry Andric                   .Default(~0u);
7630b57cec5SDimitry Andric     if (CM != ~0u) {
7640b57cec5SDimitry Andric       llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
7650b57cec5SDimitry Andric       getModule().setCodeModel(codeModel);
7660b57cec5SDimitry Andric     }
7670b57cec5SDimitry Andric   }
7680b57cec5SDimitry Andric 
7690b57cec5SDimitry Andric   if (CodeGenOpts.NoPLT)
7700b57cec5SDimitry Andric     getModule().setRtLibUseGOT();
7715f7ddb14SDimitry Andric   if (CodeGenOpts.UnwindTables)
7725f7ddb14SDimitry Andric     getModule().setUwtable();
7735f7ddb14SDimitry Andric 
7745f7ddb14SDimitry Andric   switch (CodeGenOpts.getFramePointer()) {
7755f7ddb14SDimitry Andric   case CodeGenOptions::FramePointerKind::None:
7765f7ddb14SDimitry Andric     // 0 ("none") is the default.
7775f7ddb14SDimitry Andric     break;
7785f7ddb14SDimitry Andric   case CodeGenOptions::FramePointerKind::NonLeaf:
7795f7ddb14SDimitry Andric     getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
7805f7ddb14SDimitry Andric     break;
7815f7ddb14SDimitry Andric   case CodeGenOptions::FramePointerKind::All:
7825f7ddb14SDimitry Andric     getModule().setFramePointer(llvm::FramePointerKind::All);
7835f7ddb14SDimitry Andric     break;
7845f7ddb14SDimitry Andric   }
7850b57cec5SDimitry Andric 
7860b57cec5SDimitry Andric   SimplifyPersonality();
7870b57cec5SDimitry Andric 
7880b57cec5SDimitry Andric   if (getCodeGenOpts().EmitDeclMetadata)
7890b57cec5SDimitry Andric     EmitDeclMetadata();
7900b57cec5SDimitry Andric 
7910b57cec5SDimitry Andric   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
7920b57cec5SDimitry Andric     EmitCoverageFile();
7930b57cec5SDimitry Andric 
7945ffd83dbSDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
7955ffd83dbSDimitry Andric     DI->finalize();
7960b57cec5SDimitry Andric 
7970b57cec5SDimitry Andric   if (getCodeGenOpts().EmitVersionIdentMetadata)
7980b57cec5SDimitry Andric     EmitVersionIdentMetadata();
7990b57cec5SDimitry Andric 
8000b57cec5SDimitry Andric   if (!getCodeGenOpts().RecordCommandLine.empty())
8010b57cec5SDimitry Andric     EmitCommandLineMetadata();
8020b57cec5SDimitry Andric 
8035f7ddb14SDimitry Andric   if (!getCodeGenOpts().StackProtectorGuard.empty())
8045f7ddb14SDimitry Andric     getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard);
8055f7ddb14SDimitry Andric   if (!getCodeGenOpts().StackProtectorGuardReg.empty())
8065f7ddb14SDimitry Andric     getModule().setStackProtectorGuardReg(
8075f7ddb14SDimitry Andric         getCodeGenOpts().StackProtectorGuardReg);
8085f7ddb14SDimitry Andric   if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX)
8095f7ddb14SDimitry Andric     getModule().setStackProtectorGuardOffset(
8105f7ddb14SDimitry Andric         getCodeGenOpts().StackProtectorGuardOffset);
8115f7ddb14SDimitry Andric   if (getCodeGenOpts().StackAlignment)
8125f7ddb14SDimitry Andric     getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment);
8135f7ddb14SDimitry Andric 
8145ffd83dbSDimitry Andric   getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames);
8155ffd83dbSDimitry Andric 
8165ffd83dbSDimitry Andric   EmitBackendOptionsMetadata(getCodeGenOpts());
817af732203SDimitry Andric 
818af732203SDimitry Andric   // Set visibility from DLL storage class
819af732203SDimitry Andric   // We do this at the end of LLVM IR generation; after any operation
820af732203SDimitry Andric   // that might affect the DLL storage class or the visibility, and
821af732203SDimitry Andric   // before anything that might act on these.
822af732203SDimitry Andric   setVisibilityFromDLLStorageClass(LangOpts, getModule());
8230b57cec5SDimitry Andric }
8240b57cec5SDimitry Andric 
EmitOpenCLMetadata()8250b57cec5SDimitry Andric void CodeGenModule::EmitOpenCLMetadata() {
8260b57cec5SDimitry Andric   // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
8270b57cec5SDimitry Andric   // opencl.ocl.version named metadata node.
8280b57cec5SDimitry Andric   // C++ is backwards compatible with OpenCL v2.0.
8290b57cec5SDimitry Andric   // FIXME: We might need to add CXX version at some point too?
8300b57cec5SDimitry Andric   auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
8310b57cec5SDimitry Andric   llvm::Metadata *OCLVerElts[] = {
8320b57cec5SDimitry Andric       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
8330b57cec5SDimitry Andric           Int32Ty, Version / 100)),
8340b57cec5SDimitry Andric       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
8350b57cec5SDimitry Andric           Int32Ty, (Version % 100) / 10))};
8360b57cec5SDimitry Andric   llvm::NamedMDNode *OCLVerMD =
8370b57cec5SDimitry Andric       TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
8380b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
8390b57cec5SDimitry Andric   OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
8400b57cec5SDimitry Andric }
8410b57cec5SDimitry Andric 
EmitBackendOptionsMetadata(const CodeGenOptions CodeGenOpts)8425ffd83dbSDimitry Andric void CodeGenModule::EmitBackendOptionsMetadata(
8435ffd83dbSDimitry Andric     const CodeGenOptions CodeGenOpts) {
8445ffd83dbSDimitry Andric   switch (getTriple().getArch()) {
8455ffd83dbSDimitry Andric   default:
8465ffd83dbSDimitry Andric     break;
8475ffd83dbSDimitry Andric   case llvm::Triple::riscv32:
8485ffd83dbSDimitry Andric   case llvm::Triple::riscv64:
8495ffd83dbSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "SmallDataLimit",
8505ffd83dbSDimitry Andric                               CodeGenOpts.SmallDataLimit);
8515ffd83dbSDimitry Andric     break;
8525ffd83dbSDimitry Andric   }
8535ffd83dbSDimitry Andric }
8545ffd83dbSDimitry Andric 
UpdateCompletedType(const TagDecl * TD)8550b57cec5SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
8560b57cec5SDimitry Andric   // Make sure that this type is translated.
8570b57cec5SDimitry Andric   Types.UpdateCompletedType(TD);
8580b57cec5SDimitry Andric }
8590b57cec5SDimitry Andric 
RefreshTypeCacheForClass(const CXXRecordDecl * RD)8600b57cec5SDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
8610b57cec5SDimitry Andric   // Make sure that this type is translated.
8620b57cec5SDimitry Andric   Types.RefreshTypeCacheForClass(RD);
8630b57cec5SDimitry Andric }
8640b57cec5SDimitry Andric 
getTBAATypeInfo(QualType QTy)8650b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
8660b57cec5SDimitry Andric   if (!TBAA)
8670b57cec5SDimitry Andric     return nullptr;
8680b57cec5SDimitry Andric   return TBAA->getTypeInfo(QTy);
8690b57cec5SDimitry Andric }
8700b57cec5SDimitry Andric 
getTBAAAccessInfo(QualType AccessType)8710b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
8720b57cec5SDimitry Andric   if (!TBAA)
8730b57cec5SDimitry Andric     return TBAAAccessInfo();
8745ffd83dbSDimitry Andric   if (getLangOpts().CUDAIsDevice) {
8755ffd83dbSDimitry Andric     // As CUDA builtin surface/texture types are replaced, skip generating TBAA
8765ffd83dbSDimitry Andric     // access info.
8775ffd83dbSDimitry Andric     if (AccessType->isCUDADeviceBuiltinSurfaceType()) {
8785ffd83dbSDimitry Andric       if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() !=
8795ffd83dbSDimitry Andric           nullptr)
8805ffd83dbSDimitry Andric         return TBAAAccessInfo();
8815ffd83dbSDimitry Andric     } else if (AccessType->isCUDADeviceBuiltinTextureType()) {
8825ffd83dbSDimitry Andric       if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() !=
8835ffd83dbSDimitry Andric           nullptr)
8845ffd83dbSDimitry Andric         return TBAAAccessInfo();
8855ffd83dbSDimitry Andric     }
8865ffd83dbSDimitry Andric   }
8870b57cec5SDimitry Andric   return TBAA->getAccessInfo(AccessType);
8880b57cec5SDimitry Andric }
8890b57cec5SDimitry Andric 
8900b57cec5SDimitry Andric TBAAAccessInfo
getTBAAVTablePtrAccessInfo(llvm::Type * VTablePtrType)8910b57cec5SDimitry Andric CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
8920b57cec5SDimitry Andric   if (!TBAA)
8930b57cec5SDimitry Andric     return TBAAAccessInfo();
8940b57cec5SDimitry Andric   return TBAA->getVTablePtrAccessInfo(VTablePtrType);
8950b57cec5SDimitry Andric }
8960b57cec5SDimitry Andric 
getTBAAStructInfo(QualType QTy)8970b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
8980b57cec5SDimitry Andric   if (!TBAA)
8990b57cec5SDimitry Andric     return nullptr;
9000b57cec5SDimitry Andric   return TBAA->getTBAAStructInfo(QTy);
9010b57cec5SDimitry Andric }
9020b57cec5SDimitry Andric 
getTBAABaseTypeInfo(QualType QTy)9030b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
9040b57cec5SDimitry Andric   if (!TBAA)
9050b57cec5SDimitry Andric     return nullptr;
9060b57cec5SDimitry Andric   return TBAA->getBaseTypeInfo(QTy);
9070b57cec5SDimitry Andric }
9080b57cec5SDimitry Andric 
getTBAAAccessTagInfo(TBAAAccessInfo Info)9090b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
9100b57cec5SDimitry Andric   if (!TBAA)
9110b57cec5SDimitry Andric     return nullptr;
9120b57cec5SDimitry Andric   return TBAA->getAccessTagInfo(Info);
9130b57cec5SDimitry Andric }
9140b57cec5SDimitry Andric 
mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,TBAAAccessInfo TargetInfo)9150b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
9160b57cec5SDimitry Andric                                                    TBAAAccessInfo TargetInfo) {
9170b57cec5SDimitry Andric   if (!TBAA)
9180b57cec5SDimitry Andric     return TBAAAccessInfo();
9190b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
9200b57cec5SDimitry Andric }
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric TBAAAccessInfo
mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,TBAAAccessInfo InfoB)9230b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
9240b57cec5SDimitry Andric                                                    TBAAAccessInfo InfoB) {
9250b57cec5SDimitry Andric   if (!TBAA)
9260b57cec5SDimitry Andric     return TBAAAccessInfo();
9270b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
9280b57cec5SDimitry Andric }
9290b57cec5SDimitry Andric 
9300b57cec5SDimitry Andric TBAAAccessInfo
mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,TBAAAccessInfo SrcInfo)9310b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
9320b57cec5SDimitry Andric                                               TBAAAccessInfo SrcInfo) {
9330b57cec5SDimitry Andric   if (!TBAA)
9340b57cec5SDimitry Andric     return TBAAAccessInfo();
9350b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
9360b57cec5SDimitry Andric }
9370b57cec5SDimitry Andric 
DecorateInstructionWithTBAA(llvm::Instruction * Inst,TBAAAccessInfo TBAAInfo)9380b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
9390b57cec5SDimitry Andric                                                 TBAAAccessInfo TBAAInfo) {
9400b57cec5SDimitry Andric   if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
9410b57cec5SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
9420b57cec5SDimitry Andric }
9430b57cec5SDimitry Andric 
DecorateInstructionWithInvariantGroup(llvm::Instruction * I,const CXXRecordDecl * RD)9440b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup(
9450b57cec5SDimitry Andric     llvm::Instruction *I, const CXXRecordDecl *RD) {
9460b57cec5SDimitry Andric   I->setMetadata(llvm::LLVMContext::MD_invariant_group,
9470b57cec5SDimitry Andric                  llvm::MDNode::get(getLLVMContext(), {}));
9480b57cec5SDimitry Andric }
9490b57cec5SDimitry Andric 
Error(SourceLocation loc,StringRef message)9500b57cec5SDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) {
9510b57cec5SDimitry Andric   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
9520b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
9530b57cec5SDimitry Andric }
9540b57cec5SDimitry Andric 
9550b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the
9560b57cec5SDimitry Andric /// specified stmt yet.
ErrorUnsupported(const Stmt * S,const char * Type)9570b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
9580b57cec5SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
9590b57cec5SDimitry Andric                                                "cannot compile this %0 yet");
9600b57cec5SDimitry Andric   std::string Msg = Type;
9610b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
9620b57cec5SDimitry Andric       << Msg << S->getSourceRange();
9630b57cec5SDimitry Andric }
9640b57cec5SDimitry Andric 
9650b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the
9660b57cec5SDimitry Andric /// specified decl yet.
ErrorUnsupported(const Decl * D,const char * Type)9670b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
9680b57cec5SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
9690b57cec5SDimitry Andric                                                "cannot compile this %0 yet");
9700b57cec5SDimitry Andric   std::string Msg = Type;
9710b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
9720b57cec5SDimitry Andric }
9730b57cec5SDimitry Andric 
getSize(CharUnits size)9740b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
9750b57cec5SDimitry Andric   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
9760b57cec5SDimitry Andric }
9770b57cec5SDimitry Andric 
setGlobalVisibility(llvm::GlobalValue * GV,const NamedDecl * D) const9780b57cec5SDimitry Andric void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
9790b57cec5SDimitry Andric                                         const NamedDecl *D) const {
9800b57cec5SDimitry Andric   if (GV->hasDLLImportStorageClass())
9810b57cec5SDimitry Andric     return;
9820b57cec5SDimitry Andric   // Internal definitions always have default visibility.
9830b57cec5SDimitry Andric   if (GV->hasLocalLinkage()) {
9840b57cec5SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
9850b57cec5SDimitry Andric     return;
9860b57cec5SDimitry Andric   }
9870b57cec5SDimitry Andric   if (!D)
9880b57cec5SDimitry Andric     return;
9890b57cec5SDimitry Andric   // Set visibility for definitions, and for declarations if requested globally
9900b57cec5SDimitry Andric   // or set explicitly.
9910b57cec5SDimitry Andric   LinkageInfo LV = D->getLinkageAndVisibility();
9920b57cec5SDimitry Andric   if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
9930b57cec5SDimitry Andric       !GV->isDeclarationForLinker())
9940b57cec5SDimitry Andric     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
9950b57cec5SDimitry Andric }
9960b57cec5SDimitry Andric 
shouldAssumeDSOLocal(const CodeGenModule & CGM,llvm::GlobalValue * GV)9970b57cec5SDimitry Andric static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
9980b57cec5SDimitry Andric                                  llvm::GlobalValue *GV) {
9990b57cec5SDimitry Andric   if (GV->hasLocalLinkage())
10000b57cec5SDimitry Andric     return true;
10010b57cec5SDimitry Andric 
10020b57cec5SDimitry Andric   if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
10030b57cec5SDimitry Andric     return true;
10040b57cec5SDimitry Andric 
10050b57cec5SDimitry Andric   // DLLImport explicitly marks the GV as external.
10060b57cec5SDimitry Andric   if (GV->hasDLLImportStorageClass())
10070b57cec5SDimitry Andric     return false;
10080b57cec5SDimitry Andric 
10090b57cec5SDimitry Andric   const llvm::Triple &TT = CGM.getTriple();
10100b57cec5SDimitry Andric   if (TT.isWindowsGNUEnvironment()) {
10110b57cec5SDimitry Andric     // In MinGW, variables without DLLImport can still be automatically
10120b57cec5SDimitry Andric     // imported from a DLL by the linker; don't mark variables that
10130b57cec5SDimitry Andric     // potentially could come from another DLL as DSO local.
10145f7ddb14SDimitry Andric 
10155f7ddb14SDimitry Andric     // With EmulatedTLS, TLS variables can be autoimported from other DLLs
10165f7ddb14SDimitry Andric     // (and this actually happens in the public interface of libstdc++), so
10175f7ddb14SDimitry Andric     // such variables can't be marked as DSO local. (Native TLS variables
10185f7ddb14SDimitry Andric     // can't be dllimported at all, though.)
10190b57cec5SDimitry Andric     if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
10205f7ddb14SDimitry Andric         (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS))
10210b57cec5SDimitry Andric       return false;
10220b57cec5SDimitry Andric   }
10230b57cec5SDimitry Andric 
10240b57cec5SDimitry Andric   // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
10250b57cec5SDimitry Andric   // remain unresolved in the link, they can be resolved to zero, which is
10260b57cec5SDimitry Andric   // outside the current DSO.
10270b57cec5SDimitry Andric   if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
10280b57cec5SDimitry Andric     return false;
10290b57cec5SDimitry Andric 
10300b57cec5SDimitry Andric   // Every other GV is local on COFF.
10310b57cec5SDimitry Andric   // Make an exception for windows OS in the triple: Some firmware builds use
10320b57cec5SDimitry Andric   // *-win32-macho triples. This (accidentally?) produced windows relocations
10330b57cec5SDimitry Andric   // without GOT tables in older clang versions; Keep this behaviour.
10340b57cec5SDimitry Andric   // FIXME: even thread local variables?
10350b57cec5SDimitry Andric   if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
10360b57cec5SDimitry Andric     return true;
10370b57cec5SDimitry Andric 
10380b57cec5SDimitry Andric   // Only handle COFF and ELF for now.
10390b57cec5SDimitry Andric   if (!TT.isOSBinFormatELF())
10400b57cec5SDimitry Andric     return false;
10410b57cec5SDimitry Andric 
10425f7ddb14SDimitry Andric   // If this is not an executable, don't assume anything is local.
10435f7ddb14SDimitry Andric   const auto &CGOpts = CGM.getCodeGenOpts();
10445f7ddb14SDimitry Andric   llvm::Reloc::Model RM = CGOpts.RelocationModel;
10455f7ddb14SDimitry Andric   const auto &LOpts = CGM.getLangOpts();
1046af732203SDimitry Andric   if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1047af732203SDimitry Andric     // On ELF, if -fno-semantic-interposition is specified and the target
1048af732203SDimitry Andric     // supports local aliases, there will be neither CC1
1049af732203SDimitry Andric     // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set
10505f7ddb14SDimitry Andric     // dso_local on the function if using a local alias is preferable (can avoid
10515f7ddb14SDimitry Andric     // PLT indirection).
10525f7ddb14SDimitry Andric     if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias()))
10530b57cec5SDimitry Andric       return false;
1054af732203SDimitry Andric     return !(CGM.getLangOpts().SemanticInterposition ||
1055af732203SDimitry Andric              CGM.getLangOpts().HalfNoSemanticInterposition);
1056af732203SDimitry Andric   }
10570b57cec5SDimitry Andric 
10580b57cec5SDimitry Andric   // A definition cannot be preempted from an executable.
10590b57cec5SDimitry Andric   if (!GV->isDeclarationForLinker())
10600b57cec5SDimitry Andric     return true;
10610b57cec5SDimitry Andric 
10620b57cec5SDimitry Andric   // Most PIC code sequences that assume that a symbol is local cannot produce a
10630b57cec5SDimitry Andric   // 0 if it turns out the symbol is undefined. While this is ABI and relocation
10640b57cec5SDimitry Andric   // depended, it seems worth it to handle it here.
10650b57cec5SDimitry Andric   if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
10660b57cec5SDimitry Andric     return false;
10670b57cec5SDimitry Andric 
1068af732203SDimitry Andric   // PowerPC64 prefers TOC indirection to avoid copy relocations.
1069af732203SDimitry Andric   if (TT.isPPC64())
10700b57cec5SDimitry Andric     return false;
10710b57cec5SDimitry Andric 
1072af732203SDimitry Andric   if (CGOpts.DirectAccessExternalData) {
1073af732203SDimitry Andric     // If -fdirect-access-external-data (default for -fno-pic), set dso_local
1074af732203SDimitry Andric     // for non-thread-local variables. If the symbol is not defined in the
1075af732203SDimitry Andric     // executable, a copy relocation will be needed at link time. dso_local is
1076af732203SDimitry Andric     // excluded for thread-local variables because they generally don't support
1077af732203SDimitry Andric     // copy relocations.
10780b57cec5SDimitry Andric     if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1079af732203SDimitry Andric       if (!Var->isThreadLocal())
10800b57cec5SDimitry Andric         return true;
10810b57cec5SDimitry Andric 
1082af732203SDimitry Andric     // -fno-pic sets dso_local on a function declaration to allow direct
1083af732203SDimitry Andric     // accesses when taking its address (similar to a data symbol). If the
1084af732203SDimitry Andric     // function is not defined in the executable, a canonical PLT entry will be
1085af732203SDimitry Andric     // needed at link time. -fno-direct-access-external-data can avoid the
1086af732203SDimitry Andric     // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as
1087af732203SDimitry Andric     // it could just cause trouble without providing perceptible benefits.
10880b57cec5SDimitry Andric     if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
10890b57cec5SDimitry Andric       return true;
1090af732203SDimitry Andric   }
1091af732203SDimitry Andric 
1092af732203SDimitry Andric   // If we can use copy relocations we can assume it is local.
10930b57cec5SDimitry Andric 
10945ffd83dbSDimitry Andric   // Otherwise don't assume it is local.
10950b57cec5SDimitry Andric   return false;
10960b57cec5SDimitry Andric }
10970b57cec5SDimitry Andric 
setDSOLocal(llvm::GlobalValue * GV) const10980b57cec5SDimitry Andric void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
10990b57cec5SDimitry Andric   GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
11000b57cec5SDimitry Andric }
11010b57cec5SDimitry Andric 
setDLLImportDLLExport(llvm::GlobalValue * GV,GlobalDecl GD) const11020b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
11030b57cec5SDimitry Andric                                           GlobalDecl GD) const {
11040b57cec5SDimitry Andric   const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
11050b57cec5SDimitry Andric   // C++ destructors have a few C++ ABI specific special cases.
11060b57cec5SDimitry Andric   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
11070b57cec5SDimitry Andric     getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
11080b57cec5SDimitry Andric     return;
11090b57cec5SDimitry Andric   }
11100b57cec5SDimitry Andric   setDLLImportDLLExport(GV, D);
11110b57cec5SDimitry Andric }
11120b57cec5SDimitry Andric 
setDLLImportDLLExport(llvm::GlobalValue * GV,const NamedDecl * D) const11130b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
11140b57cec5SDimitry Andric                                           const NamedDecl *D) const {
11150b57cec5SDimitry Andric   if (D && D->isExternallyVisible()) {
11160b57cec5SDimitry Andric     if (D->hasAttr<DLLImportAttr>())
11170b57cec5SDimitry Andric       GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
11180b57cec5SDimitry Andric     else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
11190b57cec5SDimitry Andric       GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
11200b57cec5SDimitry Andric   }
11210b57cec5SDimitry Andric }
11220b57cec5SDimitry Andric 
setGVProperties(llvm::GlobalValue * GV,GlobalDecl GD) const11230b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
11240b57cec5SDimitry Andric                                     GlobalDecl GD) const {
11250b57cec5SDimitry Andric   setDLLImportDLLExport(GV, GD);
11260b57cec5SDimitry Andric   setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
11270b57cec5SDimitry Andric }
11280b57cec5SDimitry Andric 
setGVProperties(llvm::GlobalValue * GV,const NamedDecl * D) const11290b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
11300b57cec5SDimitry Andric                                     const NamedDecl *D) const {
11310b57cec5SDimitry Andric   setDLLImportDLLExport(GV, D);
11320b57cec5SDimitry Andric   setGVPropertiesAux(GV, D);
11330b57cec5SDimitry Andric }
11340b57cec5SDimitry Andric 
setGVPropertiesAux(llvm::GlobalValue * GV,const NamedDecl * D) const11350b57cec5SDimitry Andric void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
11360b57cec5SDimitry Andric                                        const NamedDecl *D) const {
11370b57cec5SDimitry Andric   setGlobalVisibility(GV, D);
11380b57cec5SDimitry Andric   setDSOLocal(GV);
11390b57cec5SDimitry Andric   GV->setPartition(CodeGenOpts.SymbolPartition);
11400b57cec5SDimitry Andric }
11410b57cec5SDimitry Andric 
GetLLVMTLSModel(StringRef S)11420b57cec5SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
11430b57cec5SDimitry Andric   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
11440b57cec5SDimitry Andric       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
11450b57cec5SDimitry Andric       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
11460b57cec5SDimitry Andric       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
11470b57cec5SDimitry Andric       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
11480b57cec5SDimitry Andric }
11490b57cec5SDimitry Andric 
11505ffd83dbSDimitry Andric llvm::GlobalVariable::ThreadLocalMode
GetDefaultLLVMTLSModel() const11515ffd83dbSDimitry Andric CodeGenModule::GetDefaultLLVMTLSModel() const {
11525ffd83dbSDimitry Andric   switch (CodeGenOpts.getDefaultTLSModel()) {
11530b57cec5SDimitry Andric   case CodeGenOptions::GeneralDynamicTLSModel:
11540b57cec5SDimitry Andric     return llvm::GlobalVariable::GeneralDynamicTLSModel;
11550b57cec5SDimitry Andric   case CodeGenOptions::LocalDynamicTLSModel:
11560b57cec5SDimitry Andric     return llvm::GlobalVariable::LocalDynamicTLSModel;
11570b57cec5SDimitry Andric   case CodeGenOptions::InitialExecTLSModel:
11580b57cec5SDimitry Andric     return llvm::GlobalVariable::InitialExecTLSModel;
11590b57cec5SDimitry Andric   case CodeGenOptions::LocalExecTLSModel:
11600b57cec5SDimitry Andric     return llvm::GlobalVariable::LocalExecTLSModel;
11610b57cec5SDimitry Andric   }
11620b57cec5SDimitry Andric   llvm_unreachable("Invalid TLS model!");
11630b57cec5SDimitry Andric }
11640b57cec5SDimitry Andric 
setTLSMode(llvm::GlobalValue * GV,const VarDecl & D) const11650b57cec5SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
11660b57cec5SDimitry Andric   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
11670b57cec5SDimitry Andric 
11680b57cec5SDimitry Andric   llvm::GlobalValue::ThreadLocalMode TLM;
11695ffd83dbSDimitry Andric   TLM = GetDefaultLLVMTLSModel();
11700b57cec5SDimitry Andric 
11710b57cec5SDimitry Andric   // Override the TLS model if it is explicitly specified.
11720b57cec5SDimitry Andric   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
11730b57cec5SDimitry Andric     TLM = GetLLVMTLSModel(Attr->getModel());
11740b57cec5SDimitry Andric   }
11750b57cec5SDimitry Andric 
11760b57cec5SDimitry Andric   GV->setThreadLocalMode(TLM);
11770b57cec5SDimitry Andric }
11780b57cec5SDimitry Andric 
getCPUSpecificMangling(const CodeGenModule & CGM,StringRef Name)11790b57cec5SDimitry Andric static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
11800b57cec5SDimitry Andric                                           StringRef Name) {
11810b57cec5SDimitry Andric   const TargetInfo &Target = CGM.getTarget();
11820b57cec5SDimitry Andric   return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
11830b57cec5SDimitry Andric }
11840b57cec5SDimitry Andric 
AppendCPUSpecificCPUDispatchMangling(const CodeGenModule & CGM,const CPUSpecificAttr * Attr,unsigned CPUIndex,raw_ostream & Out)11850b57cec5SDimitry Andric static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
11860b57cec5SDimitry Andric                                                  const CPUSpecificAttr *Attr,
11870b57cec5SDimitry Andric                                                  unsigned CPUIndex,
11880b57cec5SDimitry Andric                                                  raw_ostream &Out) {
11890b57cec5SDimitry Andric   // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
11900b57cec5SDimitry Andric   // supported.
11910b57cec5SDimitry Andric   if (Attr)
11920b57cec5SDimitry Andric     Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
11930b57cec5SDimitry Andric   else if (CGM.getTarget().supportsIFunc())
11940b57cec5SDimitry Andric     Out << ".resolver";
11950b57cec5SDimitry Andric }
11960b57cec5SDimitry Andric 
AppendTargetMangling(const CodeGenModule & CGM,const TargetAttr * Attr,raw_ostream & Out)11970b57cec5SDimitry Andric static void AppendTargetMangling(const CodeGenModule &CGM,
11980b57cec5SDimitry Andric                                  const TargetAttr *Attr, raw_ostream &Out) {
11990b57cec5SDimitry Andric   if (Attr->isDefaultVersion())
12000b57cec5SDimitry Andric     return;
12010b57cec5SDimitry Andric 
12020b57cec5SDimitry Andric   Out << '.';
12030b57cec5SDimitry Andric   const TargetInfo &Target = CGM.getTarget();
1204480093f4SDimitry Andric   ParsedTargetAttr Info =
12050b57cec5SDimitry Andric       Attr->parse([&Target](StringRef LHS, StringRef RHS) {
12060b57cec5SDimitry Andric         // Multiversioning doesn't allow "no-${feature}", so we can
12070b57cec5SDimitry Andric         // only have "+" prefixes here.
12080b57cec5SDimitry Andric         assert(LHS.startswith("+") && RHS.startswith("+") &&
12090b57cec5SDimitry Andric                "Features should always have a prefix.");
12100b57cec5SDimitry Andric         return Target.multiVersionSortPriority(LHS.substr(1)) >
12110b57cec5SDimitry Andric                Target.multiVersionSortPriority(RHS.substr(1));
12120b57cec5SDimitry Andric       });
12130b57cec5SDimitry Andric 
12140b57cec5SDimitry Andric   bool IsFirst = true;
12150b57cec5SDimitry Andric 
12160b57cec5SDimitry Andric   if (!Info.Architecture.empty()) {
12170b57cec5SDimitry Andric     IsFirst = false;
12180b57cec5SDimitry Andric     Out << "arch_" << Info.Architecture;
12190b57cec5SDimitry Andric   }
12200b57cec5SDimitry Andric 
12210b57cec5SDimitry Andric   for (StringRef Feat : Info.Features) {
12220b57cec5SDimitry Andric     if (!IsFirst)
12230b57cec5SDimitry Andric       Out << '_';
12240b57cec5SDimitry Andric     IsFirst = false;
12250b57cec5SDimitry Andric     Out << Feat.substr(1);
12260b57cec5SDimitry Andric   }
12270b57cec5SDimitry Andric }
12280b57cec5SDimitry Andric 
12295f7ddb14SDimitry Andric // Returns true if GD is a function decl with internal linkage and
12305f7ddb14SDimitry Andric // needs a unique suffix after the mangled name.
isUniqueInternalLinkageDecl(GlobalDecl GD,CodeGenModule & CGM)12315f7ddb14SDimitry Andric static bool isUniqueInternalLinkageDecl(GlobalDecl GD,
12325f7ddb14SDimitry Andric                                         CodeGenModule &CGM) {
12335f7ddb14SDimitry Andric   const Decl *D = GD.getDecl();
12345f7ddb14SDimitry Andric   return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) &&
12355f7ddb14SDimitry Andric          (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage);
12365f7ddb14SDimitry Andric }
12375f7ddb14SDimitry Andric 
getMangledNameImpl(CodeGenModule & CGM,GlobalDecl GD,const NamedDecl * ND,bool OmitMultiVersionMangling=false)12385f7ddb14SDimitry Andric static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD,
12390b57cec5SDimitry Andric                                       const NamedDecl *ND,
12400b57cec5SDimitry Andric                                       bool OmitMultiVersionMangling = false) {
12410b57cec5SDimitry Andric   SmallString<256> Buffer;
12420b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
12430b57cec5SDimitry Andric   MangleContext &MC = CGM.getCXXABI().getMangleContext();
12445f7ddb14SDimitry Andric   if (!CGM.getModuleNameHash().empty())
12455f7ddb14SDimitry Andric     MC.needsUniqueInternalLinkageNames();
12465f7ddb14SDimitry Andric   bool ShouldMangle = MC.shouldMangleDeclName(ND);
12475f7ddb14SDimitry Andric   if (ShouldMangle)
12485ffd83dbSDimitry Andric     MC.mangleName(GD.getWithDecl(ND), Out);
12495ffd83dbSDimitry Andric   else {
12500b57cec5SDimitry Andric     IdentifierInfo *II = ND->getIdentifier();
12510b57cec5SDimitry Andric     assert(II && "Attempt to mangle unnamed decl.");
12520b57cec5SDimitry Andric     const auto *FD = dyn_cast<FunctionDecl>(ND);
12530b57cec5SDimitry Andric 
12540b57cec5SDimitry Andric     if (FD &&
12550b57cec5SDimitry Andric         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
12560b57cec5SDimitry Andric       Out << "__regcall3__" << II->getName();
12575ffd83dbSDimitry Andric     } else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
12585ffd83dbSDimitry Andric                GD.getKernelReferenceKind() == KernelReferenceKind::Stub) {
12595ffd83dbSDimitry Andric       Out << "__device_stub__" << II->getName();
12600b57cec5SDimitry Andric     } else {
12610b57cec5SDimitry Andric       Out << II->getName();
12620b57cec5SDimitry Andric     }
12630b57cec5SDimitry Andric   }
12640b57cec5SDimitry Andric 
12655f7ddb14SDimitry Andric   // Check if the module name hash should be appended for internal linkage
12665f7ddb14SDimitry Andric   // symbols.   This should come before multi-version target suffixes are
12675f7ddb14SDimitry Andric   // appended. This is to keep the name and module hash suffix of the
12685f7ddb14SDimitry Andric   // internal linkage function together.  The unique suffix should only be
12695f7ddb14SDimitry Andric   // added when name mangling is done to make sure that the final name can
12705f7ddb14SDimitry Andric   // be properly demangled.  For example, for C functions without prototypes,
12715f7ddb14SDimitry Andric   // name mangling is not done and the unique suffix should not be appeneded
12725f7ddb14SDimitry Andric   // then.
12735f7ddb14SDimitry Andric   if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) {
12745f7ddb14SDimitry Andric     assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames &&
12755f7ddb14SDimitry Andric            "Hash computed when not explicitly requested");
12765f7ddb14SDimitry Andric     Out << CGM.getModuleNameHash();
12775f7ddb14SDimitry Andric   }
12785f7ddb14SDimitry Andric 
12790b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
12800b57cec5SDimitry Andric     if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
12810b57cec5SDimitry Andric       switch (FD->getMultiVersionKind()) {
12820b57cec5SDimitry Andric       case MultiVersionKind::CPUDispatch:
12830b57cec5SDimitry Andric       case MultiVersionKind::CPUSpecific:
12840b57cec5SDimitry Andric         AppendCPUSpecificCPUDispatchMangling(CGM,
12850b57cec5SDimitry Andric                                              FD->getAttr<CPUSpecificAttr>(),
12860b57cec5SDimitry Andric                                              GD.getMultiVersionIndex(), Out);
12870b57cec5SDimitry Andric         break;
12880b57cec5SDimitry Andric       case MultiVersionKind::Target:
12890b57cec5SDimitry Andric         AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
12900b57cec5SDimitry Andric         break;
12910b57cec5SDimitry Andric       case MultiVersionKind::None:
12920b57cec5SDimitry Andric         llvm_unreachable("None multiversion type isn't valid here");
12930b57cec5SDimitry Andric       }
12940b57cec5SDimitry Andric     }
12950b57cec5SDimitry Andric 
12965f7ddb14SDimitry Andric   // Make unique name for device side static file-scope variable for HIP.
12975f7ddb14SDimitry Andric   if (CGM.getContext().shouldExternalizeStaticVar(ND) &&
12985f7ddb14SDimitry Andric       CGM.getLangOpts().GPURelocatableDeviceCode &&
12995f7ddb14SDimitry Andric       CGM.getLangOpts().CUDAIsDevice && !CGM.getLangOpts().CUID.empty())
13005f7ddb14SDimitry Andric     CGM.printPostfixForExternalizedStaticVar(Out);
13015ffd83dbSDimitry Andric   return std::string(Out.str());
13020b57cec5SDimitry Andric }
13030b57cec5SDimitry Andric 
UpdateMultiVersionNames(GlobalDecl GD,const FunctionDecl * FD)13040b57cec5SDimitry Andric void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
13050b57cec5SDimitry Andric                                             const FunctionDecl *FD) {
13060b57cec5SDimitry Andric   if (!FD->isMultiVersion())
13070b57cec5SDimitry Andric     return;
13080b57cec5SDimitry Andric 
13090b57cec5SDimitry Andric   // Get the name of what this would be without the 'target' attribute.  This
13100b57cec5SDimitry Andric   // allows us to lookup the version that was emitted when this wasn't a
13110b57cec5SDimitry Andric   // multiversion function.
13120b57cec5SDimitry Andric   std::string NonTargetName =
13130b57cec5SDimitry Andric       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
13140b57cec5SDimitry Andric   GlobalDecl OtherGD;
13150b57cec5SDimitry Andric   if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
13160b57cec5SDimitry Andric     assert(OtherGD.getCanonicalDecl()
13170b57cec5SDimitry Andric                .getDecl()
13180b57cec5SDimitry Andric                ->getAsFunction()
13190b57cec5SDimitry Andric                ->isMultiVersion() &&
13200b57cec5SDimitry Andric            "Other GD should now be a multiversioned function");
13210b57cec5SDimitry Andric     // OtherFD is the version of this function that was mangled BEFORE
13220b57cec5SDimitry Andric     // becoming a MultiVersion function.  It potentially needs to be updated.
13230b57cec5SDimitry Andric     const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
13240b57cec5SDimitry Andric                                       .getDecl()
13250b57cec5SDimitry Andric                                       ->getAsFunction()
13260b57cec5SDimitry Andric                                       ->getMostRecentDecl();
13270b57cec5SDimitry Andric     std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
13280b57cec5SDimitry Andric     // This is so that if the initial version was already the 'default'
13290b57cec5SDimitry Andric     // version, we don't try to update it.
13300b57cec5SDimitry Andric     if (OtherName != NonTargetName) {
13310b57cec5SDimitry Andric       // Remove instead of erase, since others may have stored the StringRef
13320b57cec5SDimitry Andric       // to this.
13330b57cec5SDimitry Andric       const auto ExistingRecord = Manglings.find(NonTargetName);
13340b57cec5SDimitry Andric       if (ExistingRecord != std::end(Manglings))
13350b57cec5SDimitry Andric         Manglings.remove(&(*ExistingRecord));
13360b57cec5SDimitry Andric       auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
13370b57cec5SDimitry Andric       MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
13380b57cec5SDimitry Andric       if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
13390b57cec5SDimitry Andric         Entry->setName(OtherName);
13400b57cec5SDimitry Andric     }
13410b57cec5SDimitry Andric   }
13420b57cec5SDimitry Andric }
13430b57cec5SDimitry Andric 
getMangledName(GlobalDecl GD)13440b57cec5SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
13450b57cec5SDimitry Andric   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
13460b57cec5SDimitry Andric 
13470b57cec5SDimitry Andric   // Some ABIs don't have constructor variants.  Make sure that base and
13480b57cec5SDimitry Andric   // complete constructors get mangled the same.
13490b57cec5SDimitry Andric   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
13500b57cec5SDimitry Andric     if (!getTarget().getCXXABI().hasConstructorVariants()) {
13510b57cec5SDimitry Andric       CXXCtorType OrigCtorType = GD.getCtorType();
13520b57cec5SDimitry Andric       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
13530b57cec5SDimitry Andric       if (OrigCtorType == Ctor_Base)
13540b57cec5SDimitry Andric         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
13550b57cec5SDimitry Andric     }
13560b57cec5SDimitry Andric   }
13570b57cec5SDimitry Andric 
13585f7ddb14SDimitry Andric   // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a
13595f7ddb14SDimitry Andric   // static device variable depends on whether the variable is referenced by
13605f7ddb14SDimitry Andric   // a host or device host function. Therefore the mangled name cannot be
13615f7ddb14SDimitry Andric   // cached.
13625f7ddb14SDimitry Andric   if (!LangOpts.CUDAIsDevice ||
13635f7ddb14SDimitry Andric       !getContext().mayExternalizeStaticVar(GD.getDecl())) {
13640b57cec5SDimitry Andric     auto FoundName = MangledDeclNames.find(CanonicalGD);
13650b57cec5SDimitry Andric     if (FoundName != MangledDeclNames.end())
13660b57cec5SDimitry Andric       return FoundName->second;
13675f7ddb14SDimitry Andric   }
13680b57cec5SDimitry Andric 
13690b57cec5SDimitry Andric   // Keep the first result in the case of a mangling collision.
13700b57cec5SDimitry Andric   const auto *ND = cast<NamedDecl>(GD.getDecl());
13710b57cec5SDimitry Andric   std::string MangledName = getMangledNameImpl(*this, GD, ND);
13720b57cec5SDimitry Andric 
13735ffd83dbSDimitry Andric   // Ensure either we have different ABIs between host and device compilations,
13745ffd83dbSDimitry Andric   // says host compilation following MSVC ABI but device compilation follows
13755ffd83dbSDimitry Andric   // Itanium C++ ABI or, if they follow the same ABI, kernel names after
13765ffd83dbSDimitry Andric   // mangling should be the same after name stubbing. The later checking is
13775ffd83dbSDimitry Andric   // very important as the device kernel name being mangled in host-compilation
13785ffd83dbSDimitry Andric   // is used to resolve the device binaries to be executed. Inconsistent naming
13795ffd83dbSDimitry Andric   // result in undefined behavior. Even though we cannot check that naming
13805ffd83dbSDimitry Andric   // directly between host- and device-compilations, the host- and
13815ffd83dbSDimitry Andric   // device-mangling in host compilation could help catching certain ones.
13825ffd83dbSDimitry Andric   assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
13835ffd83dbSDimitry Andric          getLangOpts().CUDAIsDevice ||
13845ffd83dbSDimitry Andric          (getContext().getAuxTargetInfo() &&
13855ffd83dbSDimitry Andric           (getContext().getAuxTargetInfo()->getCXXABI() !=
13865ffd83dbSDimitry Andric            getContext().getTargetInfo().getCXXABI())) ||
13875ffd83dbSDimitry Andric          getCUDARuntime().getDeviceSideName(ND) ==
13885ffd83dbSDimitry Andric              getMangledNameImpl(
13895ffd83dbSDimitry Andric                  *this,
13905ffd83dbSDimitry Andric                  GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel),
13915ffd83dbSDimitry Andric                  ND));
13920b57cec5SDimitry Andric 
13930b57cec5SDimitry Andric   auto Result = Manglings.insert(std::make_pair(MangledName, GD));
13940b57cec5SDimitry Andric   return MangledDeclNames[CanonicalGD] = Result.first->first();
13950b57cec5SDimitry Andric }
13960b57cec5SDimitry Andric 
getBlockMangledName(GlobalDecl GD,const BlockDecl * BD)13970b57cec5SDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
13980b57cec5SDimitry Andric                                              const BlockDecl *BD) {
13990b57cec5SDimitry Andric   MangleContext &MangleCtx = getCXXABI().getMangleContext();
14000b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
14010b57cec5SDimitry Andric 
14020b57cec5SDimitry Andric   SmallString<256> Buffer;
14030b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
14040b57cec5SDimitry Andric   if (!D)
14050b57cec5SDimitry Andric     MangleCtx.mangleGlobalBlock(BD,
14060b57cec5SDimitry Andric       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
14070b57cec5SDimitry Andric   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
14080b57cec5SDimitry Andric     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
14090b57cec5SDimitry Andric   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
14100b57cec5SDimitry Andric     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
14110b57cec5SDimitry Andric   else
14120b57cec5SDimitry Andric     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
14130b57cec5SDimitry Andric 
14140b57cec5SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
14150b57cec5SDimitry Andric   return Result.first->first();
14160b57cec5SDimitry Andric }
14170b57cec5SDimitry Andric 
GetGlobalValue(StringRef Name)14180b57cec5SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
14190b57cec5SDimitry Andric   return getModule().getNamedValue(Name);
14200b57cec5SDimitry Andric }
14210b57cec5SDimitry Andric 
14220b57cec5SDimitry Andric /// AddGlobalCtor - Add a function to the list that will be called before
14230b57cec5SDimitry Andric /// main() runs.
AddGlobalCtor(llvm::Function * Ctor,int Priority,llvm::Constant * AssociatedData)14240b57cec5SDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
14250b57cec5SDimitry Andric                                   llvm::Constant *AssociatedData) {
14260b57cec5SDimitry Andric   // FIXME: Type coercion of void()* types.
14270b57cec5SDimitry Andric   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
14280b57cec5SDimitry Andric }
14290b57cec5SDimitry Andric 
14300b57cec5SDimitry Andric /// AddGlobalDtor - Add a function to the list that will be called
14310b57cec5SDimitry Andric /// when the module is unloaded.
AddGlobalDtor(llvm::Function * Dtor,int Priority,bool IsDtorAttrFunc)1432af732203SDimitry Andric void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority,
1433af732203SDimitry Andric                                   bool IsDtorAttrFunc) {
1434af732203SDimitry Andric   if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
1435af732203SDimitry Andric       (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) {
14360b57cec5SDimitry Andric     DtorsUsingAtExit[Priority].push_back(Dtor);
14370b57cec5SDimitry Andric     return;
14380b57cec5SDimitry Andric   }
14390b57cec5SDimitry Andric 
14400b57cec5SDimitry Andric   // FIXME: Type coercion of void()* types.
14410b57cec5SDimitry Andric   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
14420b57cec5SDimitry Andric }
14430b57cec5SDimitry Andric 
EmitCtorList(CtorList & Fns,const char * GlobalName)14440b57cec5SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
14450b57cec5SDimitry Andric   if (Fns.empty()) return;
14460b57cec5SDimitry Andric 
14470b57cec5SDimitry Andric   // Ctor function type is void()*.
14480b57cec5SDimitry Andric   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
14490b57cec5SDimitry Andric   llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
14500b57cec5SDimitry Andric       TheModule.getDataLayout().getProgramAddressSpace());
14510b57cec5SDimitry Andric 
14520b57cec5SDimitry Andric   // Get the type of a ctor entry, { i32, void ()*, i8* }.
14530b57cec5SDimitry Andric   llvm::StructType *CtorStructTy = llvm::StructType::get(
14540b57cec5SDimitry Andric       Int32Ty, CtorPFTy, VoidPtrTy);
14550b57cec5SDimitry Andric 
14560b57cec5SDimitry Andric   // Construct the constructor and destructor arrays.
14570b57cec5SDimitry Andric   ConstantInitBuilder builder(*this);
14580b57cec5SDimitry Andric   auto ctors = builder.beginArray(CtorStructTy);
14590b57cec5SDimitry Andric   for (const auto &I : Fns) {
14600b57cec5SDimitry Andric     auto ctor = ctors.beginStruct(CtorStructTy);
14610b57cec5SDimitry Andric     ctor.addInt(Int32Ty, I.Priority);
14620b57cec5SDimitry Andric     ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
14630b57cec5SDimitry Andric     if (I.AssociatedData)
14640b57cec5SDimitry Andric       ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
14650b57cec5SDimitry Andric     else
14660b57cec5SDimitry Andric       ctor.addNullPointer(VoidPtrTy);
14670b57cec5SDimitry Andric     ctor.finishAndAddTo(ctors);
14680b57cec5SDimitry Andric   }
14690b57cec5SDimitry Andric 
14700b57cec5SDimitry Andric   auto list =
14710b57cec5SDimitry Andric     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
14720b57cec5SDimitry Andric                                 /*constant*/ false,
14730b57cec5SDimitry Andric                                 llvm::GlobalValue::AppendingLinkage);
14740b57cec5SDimitry Andric 
14750b57cec5SDimitry Andric   // The LTO linker doesn't seem to like it when we set an alignment
14760b57cec5SDimitry Andric   // on appending variables.  Take it off as a workaround.
1477a7dea167SDimitry Andric   list->setAlignment(llvm::None);
14780b57cec5SDimitry Andric 
14790b57cec5SDimitry Andric   Fns.clear();
14800b57cec5SDimitry Andric }
14810b57cec5SDimitry Andric 
14820b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes
getFunctionLinkage(GlobalDecl GD)14830b57cec5SDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
14840b57cec5SDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
14850b57cec5SDimitry Andric 
14860b57cec5SDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
14870b57cec5SDimitry Andric 
14880b57cec5SDimitry Andric   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
14890b57cec5SDimitry Andric     return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
14900b57cec5SDimitry Andric 
14910b57cec5SDimitry Andric   if (isa<CXXConstructorDecl>(D) &&
14920b57cec5SDimitry Andric       cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
14930b57cec5SDimitry Andric       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14940b57cec5SDimitry Andric     // Our approach to inheriting constructors is fundamentally different from
14950b57cec5SDimitry Andric     // that used by the MS ABI, so keep our inheriting constructor thunks
14960b57cec5SDimitry Andric     // internal rather than trying to pick an unambiguous mangling for them.
14970b57cec5SDimitry Andric     return llvm::GlobalValue::InternalLinkage;
14980b57cec5SDimitry Andric   }
14990b57cec5SDimitry Andric 
15000b57cec5SDimitry Andric   return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false);
15010b57cec5SDimitry Andric }
15020b57cec5SDimitry Andric 
CreateCrossDsoCfiTypeId(llvm::Metadata * MD)15030b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
15040b57cec5SDimitry Andric   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
15050b57cec5SDimitry Andric   if (!MDS) return nullptr;
15060b57cec5SDimitry Andric 
15070b57cec5SDimitry Andric   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
15080b57cec5SDimitry Andric }
15090b57cec5SDimitry Andric 
SetLLVMFunctionAttributes(GlobalDecl GD,const CGFunctionInfo & Info,llvm::Function * F,bool IsThunk)15100b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
15110b57cec5SDimitry Andric                                               const CGFunctionInfo &Info,
15125f7ddb14SDimitry Andric                                               llvm::Function *F, bool IsThunk) {
15130b57cec5SDimitry Andric   unsigned CallingConv;
15140b57cec5SDimitry Andric   llvm::AttributeList PAL;
15155f7ddb14SDimitry Andric   ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv,
15165f7ddb14SDimitry Andric                          /*AttrOnCallSite=*/false, IsThunk);
15170b57cec5SDimitry Andric   F->setAttributes(PAL);
15180b57cec5SDimitry Andric   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
15190b57cec5SDimitry Andric }
15200b57cec5SDimitry Andric 
removeImageAccessQualifier(std::string & TyName)15210b57cec5SDimitry Andric static void removeImageAccessQualifier(std::string& TyName) {
15220b57cec5SDimitry Andric   std::string ReadOnlyQual("__read_only");
15230b57cec5SDimitry Andric   std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
15240b57cec5SDimitry Andric   if (ReadOnlyPos != std::string::npos)
15250b57cec5SDimitry Andric     // "+ 1" for the space after access qualifier.
15260b57cec5SDimitry Andric     TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
15270b57cec5SDimitry Andric   else {
15280b57cec5SDimitry Andric     std::string WriteOnlyQual("__write_only");
15290b57cec5SDimitry Andric     std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
15300b57cec5SDimitry Andric     if (WriteOnlyPos != std::string::npos)
15310b57cec5SDimitry Andric       TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
15320b57cec5SDimitry Andric     else {
15330b57cec5SDimitry Andric       std::string ReadWriteQual("__read_write");
15340b57cec5SDimitry Andric       std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
15350b57cec5SDimitry Andric       if (ReadWritePos != std::string::npos)
15360b57cec5SDimitry Andric         TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
15370b57cec5SDimitry Andric     }
15380b57cec5SDimitry Andric   }
15390b57cec5SDimitry Andric }
15400b57cec5SDimitry Andric 
15410b57cec5SDimitry Andric // Returns the address space id that should be produced to the
15420b57cec5SDimitry Andric // kernel_arg_addr_space metadata. This is always fixed to the ids
15430b57cec5SDimitry Andric // as specified in the SPIR 2.0 specification in order to differentiate
15440b57cec5SDimitry Andric // for example in clGetKernelArgInfo() implementation between the address
15450b57cec5SDimitry Andric // spaces with targets without unique mapping to the OpenCL address spaces
15460b57cec5SDimitry Andric // (basically all single AS CPUs).
ArgInfoAddressSpace(LangAS AS)15470b57cec5SDimitry Andric static unsigned ArgInfoAddressSpace(LangAS AS) {
15480b57cec5SDimitry Andric   switch (AS) {
1549af732203SDimitry Andric   case LangAS::opencl_global:
1550af732203SDimitry Andric     return 1;
1551af732203SDimitry Andric   case LangAS::opencl_constant:
1552af732203SDimitry Andric     return 2;
1553af732203SDimitry Andric   case LangAS::opencl_local:
1554af732203SDimitry Andric     return 3;
1555af732203SDimitry Andric   case LangAS::opencl_generic:
1556af732203SDimitry Andric     return 4; // Not in SPIR 2.0 specs.
1557af732203SDimitry Andric   case LangAS::opencl_global_device:
1558af732203SDimitry Andric     return 5;
1559af732203SDimitry Andric   case LangAS::opencl_global_host:
1560af732203SDimitry Andric     return 6;
15610b57cec5SDimitry Andric   default:
15620b57cec5SDimitry Andric     return 0; // Assume private.
15630b57cec5SDimitry Andric   }
15640b57cec5SDimitry Andric }
15650b57cec5SDimitry Andric 
GenOpenCLArgMetadata(llvm::Function * Fn,const FunctionDecl * FD,CodeGenFunction * CGF)15660b57cec5SDimitry Andric void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn,
15670b57cec5SDimitry Andric                                          const FunctionDecl *FD,
15680b57cec5SDimitry Andric                                          CodeGenFunction *CGF) {
15690b57cec5SDimitry Andric   assert(((FD && CGF) || (!FD && !CGF)) &&
15700b57cec5SDimitry Andric          "Incorrect use - FD and CGF should either be both null or not!");
15710b57cec5SDimitry Andric   // Create MDNodes that represent the kernel arg metadata.
15720b57cec5SDimitry Andric   // Each MDNode is a list in the form of "key", N number of values which is
15730b57cec5SDimitry Andric   // the same number of values as their are kernel arguments.
15740b57cec5SDimitry Andric 
15750b57cec5SDimitry Andric   const PrintingPolicy &Policy = Context.getPrintingPolicy();
15760b57cec5SDimitry Andric 
15770b57cec5SDimitry Andric   // MDNode for the kernel argument address space qualifiers.
15780b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> addressQuals;
15790b57cec5SDimitry Andric 
15800b57cec5SDimitry Andric   // MDNode for the kernel argument access qualifiers (images only).
15810b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> accessQuals;
15820b57cec5SDimitry Andric 
15830b57cec5SDimitry Andric   // MDNode for the kernel argument type names.
15840b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeNames;
15850b57cec5SDimitry Andric 
15860b57cec5SDimitry Andric   // MDNode for the kernel argument base type names.
15870b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
15880b57cec5SDimitry Andric 
15890b57cec5SDimitry Andric   // MDNode for the kernel argument type qualifiers.
15900b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeQuals;
15910b57cec5SDimitry Andric 
15920b57cec5SDimitry Andric   // MDNode for the kernel argument names.
15930b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argNames;
15940b57cec5SDimitry Andric 
15950b57cec5SDimitry Andric   if (FD && CGF)
15960b57cec5SDimitry Andric     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
15970b57cec5SDimitry Andric       const ParmVarDecl *parm = FD->getParamDecl(i);
15980b57cec5SDimitry Andric       QualType ty = parm->getType();
15990b57cec5SDimitry Andric       std::string typeQuals;
16000b57cec5SDimitry Andric 
16015f7ddb14SDimitry Andric       // Get image and pipe access qualifier:
16025f7ddb14SDimitry Andric       if (ty->isImageType() || ty->isPipeType()) {
16035f7ddb14SDimitry Andric         const Decl *PDecl = parm;
16045f7ddb14SDimitry Andric         if (auto *TD = dyn_cast<TypedefType>(ty))
16055f7ddb14SDimitry Andric           PDecl = TD->getDecl();
16065f7ddb14SDimitry Andric         const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
16075f7ddb14SDimitry Andric         if (A && A->isWriteOnly())
16085f7ddb14SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
16095f7ddb14SDimitry Andric         else if (A && A->isReadWrite())
16105f7ddb14SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
16115f7ddb14SDimitry Andric         else
16125f7ddb14SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
16135f7ddb14SDimitry Andric       } else
16145f7ddb14SDimitry Andric         accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
16155f7ddb14SDimitry Andric 
16165f7ddb14SDimitry Andric       // Get argument name.
16175f7ddb14SDimitry Andric       argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
16185f7ddb14SDimitry Andric 
16195f7ddb14SDimitry Andric       auto getTypeSpelling = [&](QualType Ty) {
16205f7ddb14SDimitry Andric         auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
16215f7ddb14SDimitry Andric 
16225f7ddb14SDimitry Andric         if (Ty.isCanonical()) {
16235f7ddb14SDimitry Andric           StringRef typeNameRef = typeName;
16245f7ddb14SDimitry Andric           // Turn "unsigned type" to "utype"
16255f7ddb14SDimitry Andric           if (typeNameRef.consume_front("unsigned "))
16265f7ddb14SDimitry Andric             return std::string("u") + typeNameRef.str();
16275f7ddb14SDimitry Andric           if (typeNameRef.consume_front("signed "))
16285f7ddb14SDimitry Andric             return typeNameRef.str();
16295f7ddb14SDimitry Andric         }
16305f7ddb14SDimitry Andric 
16315f7ddb14SDimitry Andric         return typeName;
16325f7ddb14SDimitry Andric       };
16335f7ddb14SDimitry Andric 
16340b57cec5SDimitry Andric       if (ty->isPointerType()) {
16350b57cec5SDimitry Andric         QualType pointeeTy = ty->getPointeeType();
16360b57cec5SDimitry Andric 
16370b57cec5SDimitry Andric         // Get address qualifier.
16380b57cec5SDimitry Andric         addressQuals.push_back(
16390b57cec5SDimitry Andric             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
16400b57cec5SDimitry Andric                 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
16410b57cec5SDimitry Andric 
16420b57cec5SDimitry Andric         // Get argument type name.
16435f7ddb14SDimitry Andric         std::string typeName = getTypeSpelling(pointeeTy) + "*";
16440b57cec5SDimitry Andric         std::string baseTypeName =
16455f7ddb14SDimitry Andric             getTypeSpelling(pointeeTy.getCanonicalType()) + "*";
16465f7ddb14SDimitry Andric         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
16470b57cec5SDimitry Andric         argBaseTypeNames.push_back(
16480b57cec5SDimitry Andric             llvm::MDString::get(VMContext, baseTypeName));
16490b57cec5SDimitry Andric 
16500b57cec5SDimitry Andric         // Get argument type qualifiers:
16510b57cec5SDimitry Andric         if (ty.isRestrictQualified())
16520b57cec5SDimitry Andric           typeQuals = "restrict";
16530b57cec5SDimitry Andric         if (pointeeTy.isConstQualified() ||
16540b57cec5SDimitry Andric             (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
16550b57cec5SDimitry Andric           typeQuals += typeQuals.empty() ? "const" : " const";
16560b57cec5SDimitry Andric         if (pointeeTy.isVolatileQualified())
16570b57cec5SDimitry Andric           typeQuals += typeQuals.empty() ? "volatile" : " volatile";
16580b57cec5SDimitry Andric       } else {
16590b57cec5SDimitry Andric         uint32_t AddrSpc = 0;
16600b57cec5SDimitry Andric         bool isPipe = ty->isPipeType();
16610b57cec5SDimitry Andric         if (ty->isImageType() || isPipe)
16620b57cec5SDimitry Andric           AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
16630b57cec5SDimitry Andric 
16640b57cec5SDimitry Andric         addressQuals.push_back(
16650b57cec5SDimitry Andric             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
16660b57cec5SDimitry Andric 
16670b57cec5SDimitry Andric         // Get argument type name.
16685f7ddb14SDimitry Andric         ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty;
16695f7ddb14SDimitry Andric         std::string typeName = getTypeSpelling(ty);
16705f7ddb14SDimitry Andric         std::string baseTypeName = getTypeSpelling(ty.getCanonicalType());
16710b57cec5SDimitry Andric 
16720b57cec5SDimitry Andric         // Remove access qualifiers on images
16730b57cec5SDimitry Andric         // (as they are inseparable from type in clang implementation,
16740b57cec5SDimitry Andric         // but OpenCL spec provides a special query to get access qualifier
16750b57cec5SDimitry Andric         // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
16760b57cec5SDimitry Andric         if (ty->isImageType()) {
16770b57cec5SDimitry Andric           removeImageAccessQualifier(typeName);
16780b57cec5SDimitry Andric           removeImageAccessQualifier(baseTypeName);
16790b57cec5SDimitry Andric         }
16800b57cec5SDimitry Andric 
16810b57cec5SDimitry Andric         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
16820b57cec5SDimitry Andric         argBaseTypeNames.push_back(
16830b57cec5SDimitry Andric             llvm::MDString::get(VMContext, baseTypeName));
16840b57cec5SDimitry Andric 
16850b57cec5SDimitry Andric         if (isPipe)
16860b57cec5SDimitry Andric           typeQuals = "pipe";
16870b57cec5SDimitry Andric       }
16880b57cec5SDimitry Andric       argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
16890b57cec5SDimitry Andric     }
16900b57cec5SDimitry Andric 
16910b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_addr_space",
16920b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, addressQuals));
16930b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_access_qual",
16940b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, accessQuals));
16950b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_type",
16960b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, argTypeNames));
16970b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_base_type",
16980b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, argBaseTypeNames));
16990b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_type_qual",
17000b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, argTypeQuals));
17010b57cec5SDimitry Andric   if (getCodeGenOpts().EmitOpenCLArgMetadata)
17020b57cec5SDimitry Andric     Fn->setMetadata("kernel_arg_name",
17030b57cec5SDimitry Andric                     llvm::MDNode::get(VMContext, argNames));
17040b57cec5SDimitry Andric }
17050b57cec5SDimitry Andric 
17060b57cec5SDimitry Andric /// Determines whether the language options require us to model
17070b57cec5SDimitry Andric /// unwind exceptions.  We treat -fexceptions as mandating this
17080b57cec5SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions
17090b57cec5SDimitry Andric /// enabled.  This means, for example, that C with -fexceptions
17100b57cec5SDimitry Andric /// enables this.
hasUnwindExceptions(const LangOptions & LangOpts)17110b57cec5SDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) {
17120b57cec5SDimitry Andric   // If exceptions are completely disabled, obviously this is false.
17130b57cec5SDimitry Andric   if (!LangOpts.Exceptions) return false;
17140b57cec5SDimitry Andric 
17150b57cec5SDimitry Andric   // If C++ exceptions are enabled, this is true.
17160b57cec5SDimitry Andric   if (LangOpts.CXXExceptions) return true;
17170b57cec5SDimitry Andric 
17180b57cec5SDimitry Andric   // If ObjC exceptions are enabled, this depends on the ABI.
17190b57cec5SDimitry Andric   if (LangOpts.ObjCExceptions) {
17200b57cec5SDimitry Andric     return LangOpts.ObjCRuntime.hasUnwindExceptions();
17210b57cec5SDimitry Andric   }
17220b57cec5SDimitry Andric 
17230b57cec5SDimitry Andric   return true;
17240b57cec5SDimitry Andric }
17250b57cec5SDimitry Andric 
requiresMemberFunctionPointerTypeMetadata(CodeGenModule & CGM,const CXXMethodDecl * MD)17260b57cec5SDimitry Andric static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
17270b57cec5SDimitry Andric                                                       const CXXMethodDecl *MD) {
17280b57cec5SDimitry Andric   // Check that the type metadata can ever actually be used by a call.
17290b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().LTOUnit ||
17300b57cec5SDimitry Andric       !CGM.HasHiddenLTOVisibility(MD->getParent()))
17310b57cec5SDimitry Andric     return false;
17320b57cec5SDimitry Andric 
17330b57cec5SDimitry Andric   // Only functions whose address can be taken with a member function pointer
17340b57cec5SDimitry Andric   // need this sort of type metadata.
17350b57cec5SDimitry Andric   return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
17360b57cec5SDimitry Andric          !isa<CXXDestructorDecl>(MD);
17370b57cec5SDimitry Andric }
17380b57cec5SDimitry Andric 
17390b57cec5SDimitry Andric std::vector<const CXXRecordDecl *>
getMostBaseClasses(const CXXRecordDecl * RD)17400b57cec5SDimitry Andric CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
17410b57cec5SDimitry Andric   llvm::SetVector<const CXXRecordDecl *> MostBases;
17420b57cec5SDimitry Andric 
17430b57cec5SDimitry Andric   std::function<void (const CXXRecordDecl *)> CollectMostBases;
17440b57cec5SDimitry Andric   CollectMostBases = [&](const CXXRecordDecl *RD) {
17450b57cec5SDimitry Andric     if (RD->getNumBases() == 0)
17460b57cec5SDimitry Andric       MostBases.insert(RD);
17470b57cec5SDimitry Andric     for (const CXXBaseSpecifier &B : RD->bases())
17480b57cec5SDimitry Andric       CollectMostBases(B.getType()->getAsCXXRecordDecl());
17490b57cec5SDimitry Andric   };
17500b57cec5SDimitry Andric   CollectMostBases(RD);
17510b57cec5SDimitry Andric   return MostBases.takeVector();
17520b57cec5SDimitry Andric }
17530b57cec5SDimitry Andric 
SetLLVMFunctionAttributesForDefinition(const Decl * D,llvm::Function * F)17540b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
17550b57cec5SDimitry Andric                                                            llvm::Function *F) {
17560b57cec5SDimitry Andric   llvm::AttrBuilder B;
17570b57cec5SDimitry Andric 
17580b57cec5SDimitry Andric   if (CodeGenOpts.UnwindTables)
17590b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::UWTable);
17600b57cec5SDimitry Andric 
17615ffd83dbSDimitry Andric   if (CodeGenOpts.StackClashProtector)
17625ffd83dbSDimitry Andric     B.addAttribute("probe-stack", "inline-asm");
17635ffd83dbSDimitry Andric 
17640b57cec5SDimitry Andric   if (!hasUnwindExceptions(LangOpts))
17650b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoUnwind);
17660b57cec5SDimitry Andric 
17670b57cec5SDimitry Andric   if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
17680b57cec5SDimitry Andric     if (LangOpts.getStackProtector() == LangOptions::SSPOn)
17690b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::StackProtect);
17700b57cec5SDimitry Andric     else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
17710b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::StackProtectStrong);
17720b57cec5SDimitry Andric     else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
17730b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::StackProtectReq);
17740b57cec5SDimitry Andric   }
17750b57cec5SDimitry Andric 
17760b57cec5SDimitry Andric   if (!D) {
17770b57cec5SDimitry Andric     // If we don't have a declaration to control inlining, the function isn't
17780b57cec5SDimitry Andric     // explicitly marked as alwaysinline for semantic reasons, and inlining is
17790b57cec5SDimitry Andric     // disabled, mark the function as noinline.
17800b57cec5SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
17810b57cec5SDimitry Andric         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
17820b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
17830b57cec5SDimitry Andric 
17840b57cec5SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
17850b57cec5SDimitry Andric     return;
17860b57cec5SDimitry Andric   }
17870b57cec5SDimitry Andric 
17880b57cec5SDimitry Andric   // Track whether we need to add the optnone LLVM attribute,
17890b57cec5SDimitry Andric   // starting with the default for this optimization level.
17900b57cec5SDimitry Andric   bool ShouldAddOptNone =
17910b57cec5SDimitry Andric       !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
17920b57cec5SDimitry Andric   // We can't add optnone in the following cases, it won't pass the verifier.
17930b57cec5SDimitry Andric   ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
17940b57cec5SDimitry Andric   ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
17950b57cec5SDimitry Andric 
1796480093f4SDimitry Andric   // Add optnone, but do so only if the function isn't always_inline.
1797480093f4SDimitry Andric   if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
1798480093f4SDimitry Andric       !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
17990b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::OptimizeNone);
18000b57cec5SDimitry Andric 
18010b57cec5SDimitry Andric     // OptimizeNone implies noinline; we should not be inlining such functions.
18020b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
18030b57cec5SDimitry Andric 
18040b57cec5SDimitry Andric     // We still need to handle naked functions even though optnone subsumes
18050b57cec5SDimitry Andric     // much of their semantics.
18060b57cec5SDimitry Andric     if (D->hasAttr<NakedAttr>())
18070b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::Naked);
18080b57cec5SDimitry Andric 
18090b57cec5SDimitry Andric     // OptimizeNone wins over OptimizeForSize and MinSize.
18100b57cec5SDimitry Andric     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
18110b57cec5SDimitry Andric     F->removeFnAttr(llvm::Attribute::MinSize);
18120b57cec5SDimitry Andric   } else if (D->hasAttr<NakedAttr>()) {
18130b57cec5SDimitry Andric     // Naked implies noinline: we should not be inlining such functions.
18140b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::Naked);
18150b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
18160b57cec5SDimitry Andric   } else if (D->hasAttr<NoDuplicateAttr>()) {
18170b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoDuplicate);
1818480093f4SDimitry Andric   } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1819480093f4SDimitry Andric     // Add noinline if the function isn't always_inline.
18200b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
18210b57cec5SDimitry Andric   } else if (D->hasAttr<AlwaysInlineAttr>() &&
18220b57cec5SDimitry Andric              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
18230b57cec5SDimitry Andric     // (noinline wins over always_inline, and we can't specify both in IR)
18240b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::AlwaysInline);
18250b57cec5SDimitry Andric   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
18260b57cec5SDimitry Andric     // If we're not inlining, then force everything that isn't always_inline to
18270b57cec5SDimitry Andric     // carry an explicit noinline attribute.
18280b57cec5SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
18290b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
18300b57cec5SDimitry Andric   } else {
18310b57cec5SDimitry Andric     // Otherwise, propagate the inline hint attribute and potentially use its
18320b57cec5SDimitry Andric     // absence to mark things as noinline.
18330b57cec5SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18340b57cec5SDimitry Andric       // Search function and template pattern redeclarations for inline.
18350b57cec5SDimitry Andric       auto CheckForInline = [](const FunctionDecl *FD) {
18360b57cec5SDimitry Andric         auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
18370b57cec5SDimitry Andric           return Redecl->isInlineSpecified();
18380b57cec5SDimitry Andric         };
18390b57cec5SDimitry Andric         if (any_of(FD->redecls(), CheckRedeclForInline))
18400b57cec5SDimitry Andric           return true;
18410b57cec5SDimitry Andric         const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
18420b57cec5SDimitry Andric         if (!Pattern)
18430b57cec5SDimitry Andric           return false;
18440b57cec5SDimitry Andric         return any_of(Pattern->redecls(), CheckRedeclForInline);
18450b57cec5SDimitry Andric       };
18460b57cec5SDimitry Andric       if (CheckForInline(FD)) {
18470b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::InlineHint);
18480b57cec5SDimitry Andric       } else if (CodeGenOpts.getInlining() ==
18490b57cec5SDimitry Andric                      CodeGenOptions::OnlyHintInlining &&
18500b57cec5SDimitry Andric                  !FD->isInlined() &&
18510b57cec5SDimitry Andric                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
18520b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::NoInline);
18530b57cec5SDimitry Andric       }
18540b57cec5SDimitry Andric     }
18550b57cec5SDimitry Andric   }
18560b57cec5SDimitry Andric 
18570b57cec5SDimitry Andric   // Add other optimization related attributes if we are optimizing this
18580b57cec5SDimitry Andric   // function.
18590b57cec5SDimitry Andric   if (!D->hasAttr<OptimizeNoneAttr>()) {
18600b57cec5SDimitry Andric     if (D->hasAttr<ColdAttr>()) {
18610b57cec5SDimitry Andric       if (!ShouldAddOptNone)
18620b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::OptimizeForSize);
18630b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::Cold);
18640b57cec5SDimitry Andric     }
1865af732203SDimitry Andric     if (D->hasAttr<HotAttr>())
1866af732203SDimitry Andric       B.addAttribute(llvm::Attribute::Hot);
18670b57cec5SDimitry Andric     if (D->hasAttr<MinSizeAttr>())
18680b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::MinSize);
18690b57cec5SDimitry Andric   }
18700b57cec5SDimitry Andric 
18710b57cec5SDimitry Andric   F->addAttributes(llvm::AttributeList::FunctionIndex, B);
18720b57cec5SDimitry Andric 
18730b57cec5SDimitry Andric   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
18740b57cec5SDimitry Andric   if (alignment)
1875a7dea167SDimitry Andric     F->setAlignment(llvm::Align(alignment));
18760b57cec5SDimitry Andric 
18770b57cec5SDimitry Andric   if (!D->hasAttr<AlignedAttr>())
18780b57cec5SDimitry Andric     if (LangOpts.FunctionAlignment)
1879a7dea167SDimitry Andric       F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
18800b57cec5SDimitry Andric 
18810b57cec5SDimitry Andric   // Some C++ ABIs require 2-byte alignment for member functions, in order to
18820b57cec5SDimitry Andric   // reserve a bit for differentiating between virtual and non-virtual member
18830b57cec5SDimitry Andric   // functions. If the current target's C++ ABI requires this and this is a
18840b57cec5SDimitry Andric   // member function, set its alignment accordingly.
18850b57cec5SDimitry Andric   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
18860b57cec5SDimitry Andric     if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1887a7dea167SDimitry Andric       F->setAlignment(llvm::Align(2));
18880b57cec5SDimitry Andric   }
18890b57cec5SDimitry Andric 
1890a7dea167SDimitry Andric   // In the cross-dso CFI mode with canonical jump tables, we want !type
1891a7dea167SDimitry Andric   // attributes on definitions only.
1892a7dea167SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso &&
1893a7dea167SDimitry Andric       CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
1894a7dea167SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1895a7dea167SDimitry Andric       // Skip available_externally functions. They won't be codegen'ed in the
1896a7dea167SDimitry Andric       // current module anyway.
1897a7dea167SDimitry Andric       if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
18980b57cec5SDimitry Andric         CreateFunctionTypeMetadataForIcall(FD, F);
1899a7dea167SDimitry Andric     }
1900a7dea167SDimitry Andric   }
19010b57cec5SDimitry Andric 
19020b57cec5SDimitry Andric   // Emit type metadata on member functions for member function pointer checks.
19030b57cec5SDimitry Andric   // These are only ever necessary on definitions; we're guaranteed that the
19040b57cec5SDimitry Andric   // definition will be present in the LTO unit as a result of LTO visibility.
19050b57cec5SDimitry Andric   auto *MD = dyn_cast<CXXMethodDecl>(D);
19060b57cec5SDimitry Andric   if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
19070b57cec5SDimitry Andric     for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
19080b57cec5SDimitry Andric       llvm::Metadata *Id =
19090b57cec5SDimitry Andric           CreateMetadataIdentifierForType(Context.getMemberPointerType(
19100b57cec5SDimitry Andric               MD->getType(), Context.getRecordType(Base).getTypePtr()));
19110b57cec5SDimitry Andric       F->addTypeMetadata(0, Id);
19120b57cec5SDimitry Andric     }
19130b57cec5SDimitry Andric   }
19140b57cec5SDimitry Andric }
19150b57cec5SDimitry Andric 
setLLVMFunctionFEnvAttributes(const FunctionDecl * D,llvm::Function * F)1916af732203SDimitry Andric void CodeGenModule::setLLVMFunctionFEnvAttributes(const FunctionDecl *D,
1917af732203SDimitry Andric                                                   llvm::Function *F) {
1918af732203SDimitry Andric   if (D->hasAttr<StrictFPAttr>()) {
1919af732203SDimitry Andric     llvm::AttrBuilder FuncAttrs;
1920af732203SDimitry Andric     FuncAttrs.addAttribute("strictfp");
1921af732203SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, FuncAttrs);
1922af732203SDimitry Andric   }
1923af732203SDimitry Andric }
1924af732203SDimitry Andric 
SetCommonAttributes(GlobalDecl GD,llvm::GlobalValue * GV)19250b57cec5SDimitry Andric void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
19260b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
19270b57cec5SDimitry Andric   if (dyn_cast_or_null<NamedDecl>(D))
19280b57cec5SDimitry Andric     setGVProperties(GV, GD);
19290b57cec5SDimitry Andric   else
19300b57cec5SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
19310b57cec5SDimitry Andric 
19320b57cec5SDimitry Andric   if (D && D->hasAttr<UsedAttr>())
19335f7ddb14SDimitry Andric     addUsedOrCompilerUsedGlobal(GV);
19340b57cec5SDimitry Andric 
19350b57cec5SDimitry Andric   if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
19360b57cec5SDimitry Andric     const auto *VD = cast<VarDecl>(D);
19370b57cec5SDimitry Andric     if (VD->getType().isConstQualified() &&
19380b57cec5SDimitry Andric         VD->getStorageDuration() == SD_Static)
19395f7ddb14SDimitry Andric       addUsedOrCompilerUsedGlobal(GV);
19400b57cec5SDimitry Andric   }
19410b57cec5SDimitry Andric }
19420b57cec5SDimitry Andric 
GetCPUAndFeaturesAttributes(GlobalDecl GD,llvm::AttrBuilder & Attrs)19430b57cec5SDimitry Andric bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
19440b57cec5SDimitry Andric                                                 llvm::AttrBuilder &Attrs) {
19450b57cec5SDimitry Andric   // Add target-cpu and target-features attributes to functions. If
19460b57cec5SDimitry Andric   // we have a decl for the function and it has a target attribute then
19470b57cec5SDimitry Andric   // parse that and add it to the feature set.
19480b57cec5SDimitry Andric   StringRef TargetCPU = getTarget().getTargetOpts().CPU;
1949af732203SDimitry Andric   StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU;
19500b57cec5SDimitry Andric   std::vector<std::string> Features;
19510b57cec5SDimitry Andric   const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
19520b57cec5SDimitry Andric   FD = FD ? FD->getMostRecentDecl() : FD;
19530b57cec5SDimitry Andric   const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
19540b57cec5SDimitry Andric   const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
19550b57cec5SDimitry Andric   bool AddedAttr = false;
19560b57cec5SDimitry Andric   if (TD || SD) {
19570b57cec5SDimitry Andric     llvm::StringMap<bool> FeatureMap;
1958480093f4SDimitry Andric     getContext().getFunctionFeatureMap(FeatureMap, GD);
19590b57cec5SDimitry Andric 
19600b57cec5SDimitry Andric     // Produce the canonical string for this set of features.
19610b57cec5SDimitry Andric     for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
19620b57cec5SDimitry Andric       Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
19630b57cec5SDimitry Andric 
19640b57cec5SDimitry Andric     // Now add the target-cpu and target-features to the function.
19650b57cec5SDimitry Andric     // While we populated the feature map above, we still need to
19660b57cec5SDimitry Andric     // get and parse the target attribute so we can get the cpu for
19670b57cec5SDimitry Andric     // the function.
19680b57cec5SDimitry Andric     if (TD) {
1969480093f4SDimitry Andric       ParsedTargetAttr ParsedAttr = TD->parse();
1970af732203SDimitry Andric       if (!ParsedAttr.Architecture.empty() &&
1971af732203SDimitry Andric           getTarget().isValidCPUName(ParsedAttr.Architecture)) {
19720b57cec5SDimitry Andric         TargetCPU = ParsedAttr.Architecture;
1973af732203SDimitry Andric         TuneCPU = ""; // Clear the tune CPU.
1974af732203SDimitry Andric       }
1975af732203SDimitry Andric       if (!ParsedAttr.Tune.empty() &&
1976af732203SDimitry Andric           getTarget().isValidCPUName(ParsedAttr.Tune))
1977af732203SDimitry Andric         TuneCPU = ParsedAttr.Tune;
19780b57cec5SDimitry Andric     }
19790b57cec5SDimitry Andric   } else {
19800b57cec5SDimitry Andric     // Otherwise just add the existing target cpu and target features to the
19810b57cec5SDimitry Andric     // function.
19820b57cec5SDimitry Andric     Features = getTarget().getTargetOpts().Features;
19830b57cec5SDimitry Andric   }
19840b57cec5SDimitry Andric 
1985af732203SDimitry Andric   if (!TargetCPU.empty()) {
19860b57cec5SDimitry Andric     Attrs.addAttribute("target-cpu", TargetCPU);
19870b57cec5SDimitry Andric     AddedAttr = true;
19880b57cec5SDimitry Andric   }
1989af732203SDimitry Andric   if (!TuneCPU.empty()) {
1990af732203SDimitry Andric     Attrs.addAttribute("tune-cpu", TuneCPU);
1991af732203SDimitry Andric     AddedAttr = true;
1992af732203SDimitry Andric   }
19930b57cec5SDimitry Andric   if (!Features.empty()) {
19940b57cec5SDimitry Andric     llvm::sort(Features);
19950b57cec5SDimitry Andric     Attrs.addAttribute("target-features", llvm::join(Features, ","));
19960b57cec5SDimitry Andric     AddedAttr = true;
19970b57cec5SDimitry Andric   }
19980b57cec5SDimitry Andric 
19990b57cec5SDimitry Andric   return AddedAttr;
20000b57cec5SDimitry Andric }
20010b57cec5SDimitry Andric 
setNonAliasAttributes(GlobalDecl GD,llvm::GlobalObject * GO)20020b57cec5SDimitry Andric void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
20030b57cec5SDimitry Andric                                           llvm::GlobalObject *GO) {
20040b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
20050b57cec5SDimitry Andric   SetCommonAttributes(GD, GO);
20060b57cec5SDimitry Andric 
20070b57cec5SDimitry Andric   if (D) {
20080b57cec5SDimitry Andric     if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
20095f7ddb14SDimitry Andric       if (D->hasAttr<RetainAttr>())
20105f7ddb14SDimitry Andric         addUsedGlobal(GV);
20110b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
20120b57cec5SDimitry Andric         GV->addAttribute("bss-section", SA->getName());
20130b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
20140b57cec5SDimitry Andric         GV->addAttribute("data-section", SA->getName());
20150b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
20160b57cec5SDimitry Andric         GV->addAttribute("rodata-section", SA->getName());
2017a7dea167SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
2018a7dea167SDimitry Andric         GV->addAttribute("relro-section", SA->getName());
20190b57cec5SDimitry Andric     }
20200b57cec5SDimitry Andric 
20210b57cec5SDimitry Andric     if (auto *F = dyn_cast<llvm::Function>(GO)) {
20225f7ddb14SDimitry Andric       if (D->hasAttr<RetainAttr>())
20235f7ddb14SDimitry Andric         addUsedGlobal(F);
20240b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
20250b57cec5SDimitry Andric         if (!D->getAttr<SectionAttr>())
20260b57cec5SDimitry Andric           F->addFnAttr("implicit-section-name", SA->getName());
20270b57cec5SDimitry Andric 
20280b57cec5SDimitry Andric       llvm::AttrBuilder Attrs;
20290b57cec5SDimitry Andric       if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
20300b57cec5SDimitry Andric         // We know that GetCPUAndFeaturesAttributes will always have the
20310b57cec5SDimitry Andric         // newest set, since it has the newest possible FunctionDecl, so the
20320b57cec5SDimitry Andric         // new ones should replace the old.
2033af732203SDimitry Andric         llvm::AttrBuilder RemoveAttrs;
2034af732203SDimitry Andric         RemoveAttrs.addAttribute("target-cpu");
2035af732203SDimitry Andric         RemoveAttrs.addAttribute("target-features");
2036af732203SDimitry Andric         RemoveAttrs.addAttribute("tune-cpu");
2037af732203SDimitry Andric         F->removeAttributes(llvm::AttributeList::FunctionIndex, RemoveAttrs);
20380b57cec5SDimitry Andric         F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
20390b57cec5SDimitry Andric       }
20400b57cec5SDimitry Andric     }
20410b57cec5SDimitry Andric 
20420b57cec5SDimitry Andric     if (const auto *CSA = D->getAttr<CodeSegAttr>())
20430b57cec5SDimitry Andric       GO->setSection(CSA->getName());
20440b57cec5SDimitry Andric     else if (const auto *SA = D->getAttr<SectionAttr>())
20450b57cec5SDimitry Andric       GO->setSection(SA->getName());
20460b57cec5SDimitry Andric   }
20470b57cec5SDimitry Andric 
20480b57cec5SDimitry Andric   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
20490b57cec5SDimitry Andric }
20500b57cec5SDimitry Andric 
SetInternalFunctionAttributes(GlobalDecl GD,llvm::Function * F,const CGFunctionInfo & FI)20510b57cec5SDimitry Andric void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
20520b57cec5SDimitry Andric                                                   llvm::Function *F,
20530b57cec5SDimitry Andric                                                   const CGFunctionInfo &FI) {
20540b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
20555f7ddb14SDimitry Andric   SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false);
20560b57cec5SDimitry Andric   SetLLVMFunctionAttributesForDefinition(D, F);
20570b57cec5SDimitry Andric 
20580b57cec5SDimitry Andric   F->setLinkage(llvm::Function::InternalLinkage);
20590b57cec5SDimitry Andric 
20600b57cec5SDimitry Andric   setNonAliasAttributes(GD, F);
20610b57cec5SDimitry Andric }
20620b57cec5SDimitry Andric 
setLinkageForGV(llvm::GlobalValue * GV,const NamedDecl * ND)20630b57cec5SDimitry Andric static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
20640b57cec5SDimitry Andric   // Set linkage and visibility in case we never see a definition.
20650b57cec5SDimitry Andric   LinkageInfo LV = ND->getLinkageAndVisibility();
20660b57cec5SDimitry Andric   // Don't set internal linkage on declarations.
20670b57cec5SDimitry Andric   // "extern_weak" is overloaded in LLVM; we probably should have
20680b57cec5SDimitry Andric   // separate linkage types for this.
20690b57cec5SDimitry Andric   if (isExternallyVisible(LV.getLinkage()) &&
20700b57cec5SDimitry Andric       (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
20710b57cec5SDimitry Andric     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
20720b57cec5SDimitry Andric }
20730b57cec5SDimitry Andric 
CreateFunctionTypeMetadataForIcall(const FunctionDecl * FD,llvm::Function * F)20740b57cec5SDimitry Andric void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
20750b57cec5SDimitry Andric                                                        llvm::Function *F) {
20760b57cec5SDimitry Andric   // Only if we are checking indirect calls.
20770b57cec5SDimitry Andric   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
20780b57cec5SDimitry Andric     return;
20790b57cec5SDimitry Andric 
20800b57cec5SDimitry Andric   // Non-static class methods are handled via vtable or member function pointer
20810b57cec5SDimitry Andric   // checks elsewhere.
20820b57cec5SDimitry Andric   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
20830b57cec5SDimitry Andric     return;
20840b57cec5SDimitry Andric 
20850b57cec5SDimitry Andric   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
20860b57cec5SDimitry Andric   F->addTypeMetadata(0, MD);
20870b57cec5SDimitry Andric   F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
20880b57cec5SDimitry Andric 
20890b57cec5SDimitry Andric   // Emit a hash-based bit set entry for cross-DSO calls.
20900b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
20910b57cec5SDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
20920b57cec5SDimitry Andric       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
20930b57cec5SDimitry Andric }
20940b57cec5SDimitry Andric 
SetFunctionAttributes(GlobalDecl GD,llvm::Function * F,bool IsIncompleteFunction,bool IsThunk)20950b57cec5SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
20960b57cec5SDimitry Andric                                           bool IsIncompleteFunction,
20970b57cec5SDimitry Andric                                           bool IsThunk) {
20980b57cec5SDimitry Andric 
20990b57cec5SDimitry Andric   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
21000b57cec5SDimitry Andric     // If this is an intrinsic function, set the function's attributes
21010b57cec5SDimitry Andric     // to the intrinsic's attributes.
21020b57cec5SDimitry Andric     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
21030b57cec5SDimitry Andric     return;
21040b57cec5SDimitry Andric   }
21050b57cec5SDimitry Andric 
21060b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
21070b57cec5SDimitry Andric 
21080b57cec5SDimitry Andric   if (!IsIncompleteFunction)
21095f7ddb14SDimitry Andric     SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F,
21105f7ddb14SDimitry Andric                               IsThunk);
21110b57cec5SDimitry Andric 
21120b57cec5SDimitry Andric   // Add the Returned attribute for "this", except for iOS 5 and earlier
21130b57cec5SDimitry Andric   // where substantial code, including the libstdc++ dylib, was compiled with
21140b57cec5SDimitry Andric   // GCC and does not actually return "this".
21150b57cec5SDimitry Andric   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
21160b57cec5SDimitry Andric       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
21170b57cec5SDimitry Andric     assert(!F->arg_empty() &&
21180b57cec5SDimitry Andric            F->arg_begin()->getType()
21190b57cec5SDimitry Andric              ->canLosslesslyBitCastTo(F->getReturnType()) &&
21200b57cec5SDimitry Andric            "unexpected this return");
21210b57cec5SDimitry Andric     F->addAttribute(1, llvm::Attribute::Returned);
21220b57cec5SDimitry Andric   }
21230b57cec5SDimitry Andric 
21240b57cec5SDimitry Andric   // Only a few attributes are set on declarations; these may later be
21250b57cec5SDimitry Andric   // overridden by a definition.
21260b57cec5SDimitry Andric 
21270b57cec5SDimitry Andric   setLinkageForGV(F, FD);
21280b57cec5SDimitry Andric   setGVProperties(F, FD);
21290b57cec5SDimitry Andric 
21300b57cec5SDimitry Andric   // Setup target-specific attributes.
21310b57cec5SDimitry Andric   if (!IsIncompleteFunction && F->isDeclaration())
21320b57cec5SDimitry Andric     getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
21330b57cec5SDimitry Andric 
21340b57cec5SDimitry Andric   if (const auto *CSA = FD->getAttr<CodeSegAttr>())
21350b57cec5SDimitry Andric     F->setSection(CSA->getName());
21360b57cec5SDimitry Andric   else if (const auto *SA = FD->getAttr<SectionAttr>())
21370b57cec5SDimitry Andric      F->setSection(SA->getName());
21380b57cec5SDimitry Andric 
2139d65cd7a5SDimitry Andric   // If we plan on emitting this inline builtin, we can't treat it as a builtin.
2140480093f4SDimitry Andric   if (FD->isInlineBuiltinDeclaration()) {
2141d65cd7a5SDimitry Andric     const FunctionDecl *FDBody;
2142d65cd7a5SDimitry Andric     bool HasBody = FD->hasBody(FDBody);
2143d65cd7a5SDimitry Andric     (void)HasBody;
2144d65cd7a5SDimitry Andric     assert(HasBody && "Inline builtin declarations should always have an "
2145d65cd7a5SDimitry Andric                       "available body!");
2146d65cd7a5SDimitry Andric     if (shouldEmitFunction(FDBody))
2147480093f4SDimitry Andric       F->addAttribute(llvm::AttributeList::FunctionIndex,
2148480093f4SDimitry Andric                       llvm::Attribute::NoBuiltin);
2149480093f4SDimitry Andric   }
2150480093f4SDimitry Andric 
21510b57cec5SDimitry Andric   if (FD->isReplaceableGlobalAllocationFunction()) {
21520b57cec5SDimitry Andric     // A replaceable global allocation function does not act like a builtin by
21530b57cec5SDimitry Andric     // default, only if it is invoked by a new-expression or delete-expression.
21540b57cec5SDimitry Andric     F->addAttribute(llvm::AttributeList::FunctionIndex,
21550b57cec5SDimitry Andric                     llvm::Attribute::NoBuiltin);
21560b57cec5SDimitry Andric   }
21570b57cec5SDimitry Andric 
21580b57cec5SDimitry Andric   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
21590b57cec5SDimitry Andric     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
21600b57cec5SDimitry Andric   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
21610b57cec5SDimitry Andric     if (MD->isVirtual())
21620b57cec5SDimitry Andric       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
21630b57cec5SDimitry Andric 
21640b57cec5SDimitry Andric   // Don't emit entries for function declarations in the cross-DSO mode. This
2165a7dea167SDimitry Andric   // is handled with better precision by the receiving DSO. But if jump tables
2166a7dea167SDimitry Andric   // are non-canonical then we need type metadata in order to produce the local
2167a7dea167SDimitry Andric   // jump table.
2168a7dea167SDimitry Andric   if (!CodeGenOpts.SanitizeCfiCrossDso ||
2169a7dea167SDimitry Andric       !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
21700b57cec5SDimitry Andric     CreateFunctionTypeMetadataForIcall(FD, F);
21710b57cec5SDimitry Andric 
21720b57cec5SDimitry Andric   if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
21730b57cec5SDimitry Andric     getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
21740b57cec5SDimitry Andric 
21750b57cec5SDimitry Andric   if (const auto *CB = FD->getAttr<CallbackAttr>()) {
21760b57cec5SDimitry Andric     // Annotate the callback behavior as metadata:
21770b57cec5SDimitry Andric     //  - The callback callee (as argument number).
21780b57cec5SDimitry Andric     //  - The callback payloads (as argument numbers).
21790b57cec5SDimitry Andric     llvm::LLVMContext &Ctx = F->getContext();
21800b57cec5SDimitry Andric     llvm::MDBuilder MDB(Ctx);
21810b57cec5SDimitry Andric 
21820b57cec5SDimitry Andric     // The payload indices are all but the first one in the encoding. The first
21830b57cec5SDimitry Andric     // identifies the callback callee.
21840b57cec5SDimitry Andric     int CalleeIdx = *CB->encoding_begin();
21850b57cec5SDimitry Andric     ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
21860b57cec5SDimitry Andric     F->addMetadata(llvm::LLVMContext::MD_callback,
21870b57cec5SDimitry Andric                    *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
21880b57cec5SDimitry Andric                                                CalleeIdx, PayloadIndices,
21890b57cec5SDimitry Andric                                                /* VarArgsArePassed */ false)}));
21900b57cec5SDimitry Andric   }
21910b57cec5SDimitry Andric }
21920b57cec5SDimitry Andric 
addUsedGlobal(llvm::GlobalValue * GV)21930b57cec5SDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
2194af732203SDimitry Andric   assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
21950b57cec5SDimitry Andric          "Only globals with definition can force usage.");
21960b57cec5SDimitry Andric   LLVMUsed.emplace_back(GV);
21970b57cec5SDimitry Andric }
21980b57cec5SDimitry Andric 
addCompilerUsedGlobal(llvm::GlobalValue * GV)21990b57cec5SDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
22000b57cec5SDimitry Andric   assert(!GV->isDeclaration() &&
22010b57cec5SDimitry Andric          "Only globals with definition can force usage.");
22020b57cec5SDimitry Andric   LLVMCompilerUsed.emplace_back(GV);
22030b57cec5SDimitry Andric }
22040b57cec5SDimitry Andric 
addUsedOrCompilerUsedGlobal(llvm::GlobalValue * GV)22055f7ddb14SDimitry Andric void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) {
22065f7ddb14SDimitry Andric   assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
22075f7ddb14SDimitry Andric          "Only globals with definition can force usage.");
22085f7ddb14SDimitry Andric   if (getTriple().isOSBinFormatELF())
22095f7ddb14SDimitry Andric     LLVMCompilerUsed.emplace_back(GV);
22105f7ddb14SDimitry Andric   else
22115f7ddb14SDimitry Andric     LLVMUsed.emplace_back(GV);
22125f7ddb14SDimitry Andric }
22135f7ddb14SDimitry Andric 
emitUsed(CodeGenModule & CGM,StringRef Name,std::vector<llvm::WeakTrackingVH> & List)22140b57cec5SDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name,
22150b57cec5SDimitry Andric                      std::vector<llvm::WeakTrackingVH> &List) {
22160b57cec5SDimitry Andric   // Don't create llvm.used if there is no need.
22170b57cec5SDimitry Andric   if (List.empty())
22180b57cec5SDimitry Andric     return;
22190b57cec5SDimitry Andric 
22200b57cec5SDimitry Andric   // Convert List to what ConstantArray needs.
22210b57cec5SDimitry Andric   SmallVector<llvm::Constant*, 8> UsedArray;
22220b57cec5SDimitry Andric   UsedArray.resize(List.size());
22230b57cec5SDimitry Andric   for (unsigned i = 0, e = List.size(); i != e; ++i) {
22240b57cec5SDimitry Andric     UsedArray[i] =
22250b57cec5SDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
22260b57cec5SDimitry Andric             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
22270b57cec5SDimitry Andric   }
22280b57cec5SDimitry Andric 
22290b57cec5SDimitry Andric   if (UsedArray.empty())
22300b57cec5SDimitry Andric     return;
22310b57cec5SDimitry Andric   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
22320b57cec5SDimitry Andric 
22330b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
22340b57cec5SDimitry Andric       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
22350b57cec5SDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), Name);
22360b57cec5SDimitry Andric 
22370b57cec5SDimitry Andric   GV->setSection("llvm.metadata");
22380b57cec5SDimitry Andric }
22390b57cec5SDimitry Andric 
emitLLVMUsed()22400b57cec5SDimitry Andric void CodeGenModule::emitLLVMUsed() {
22410b57cec5SDimitry Andric   emitUsed(*this, "llvm.used", LLVMUsed);
22420b57cec5SDimitry Andric   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
22430b57cec5SDimitry Andric }
22440b57cec5SDimitry Andric 
AppendLinkerOptions(StringRef Opts)22450b57cec5SDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
22460b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
22470b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
22480b57cec5SDimitry Andric }
22490b57cec5SDimitry Andric 
AddDetectMismatch(StringRef Name,StringRef Value)22500b57cec5SDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
22510b57cec5SDimitry Andric   llvm::SmallString<32> Opt;
22520b57cec5SDimitry Andric   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
2253480093f4SDimitry Andric   if (Opt.empty())
2254480093f4SDimitry Andric     return;
22550b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
22560b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
22570b57cec5SDimitry Andric }
22580b57cec5SDimitry Andric 
AddDependentLib(StringRef Lib)22590b57cec5SDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) {
22600b57cec5SDimitry Andric   auto &C = getLLVMContext();
22610b57cec5SDimitry Andric   if (getTarget().getTriple().isOSBinFormatELF()) {
22620b57cec5SDimitry Andric       ELFDependentLibraries.push_back(
22630b57cec5SDimitry Andric         llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
22640b57cec5SDimitry Andric     return;
22650b57cec5SDimitry Andric   }
22660b57cec5SDimitry Andric 
22670b57cec5SDimitry Andric   llvm::SmallString<24> Opt;
22680b57cec5SDimitry Andric   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
22690b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
22700b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
22710b57cec5SDimitry Andric }
22720b57cec5SDimitry Andric 
22730b57cec5SDimitry Andric /// Add link options implied by the given module, including modules
22740b57cec5SDimitry Andric /// it depends on, using a postorder walk.
addLinkOptionsPostorder(CodeGenModule & CGM,Module * Mod,SmallVectorImpl<llvm::MDNode * > & Metadata,llvm::SmallPtrSet<Module *,16> & Visited)22750b57cec5SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
22760b57cec5SDimitry Andric                                     SmallVectorImpl<llvm::MDNode *> &Metadata,
22770b57cec5SDimitry Andric                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
22780b57cec5SDimitry Andric   // Import this module's parent.
22790b57cec5SDimitry Andric   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
22800b57cec5SDimitry Andric     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
22810b57cec5SDimitry Andric   }
22820b57cec5SDimitry Andric 
22830b57cec5SDimitry Andric   // Import this module's dependencies.
22840b57cec5SDimitry Andric   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
22850b57cec5SDimitry Andric     if (Visited.insert(Mod->Imports[I - 1]).second)
22860b57cec5SDimitry Andric       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
22870b57cec5SDimitry Andric   }
22880b57cec5SDimitry Andric 
22890b57cec5SDimitry Andric   // Add linker options to link against the libraries/frameworks
22900b57cec5SDimitry Andric   // described by this module.
22910b57cec5SDimitry Andric   llvm::LLVMContext &Context = CGM.getLLVMContext();
22920b57cec5SDimitry Andric   bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
22930b57cec5SDimitry Andric 
22940b57cec5SDimitry Andric   // For modules that use export_as for linking, use that module
22950b57cec5SDimitry Andric   // name instead.
22960b57cec5SDimitry Andric   if (Mod->UseExportAsModuleLinkName)
22970b57cec5SDimitry Andric     return;
22980b57cec5SDimitry Andric 
22990b57cec5SDimitry Andric   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
23000b57cec5SDimitry Andric     // Link against a framework.  Frameworks are currently Darwin only, so we
23010b57cec5SDimitry Andric     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
23020b57cec5SDimitry Andric     if (Mod->LinkLibraries[I-1].IsFramework) {
23030b57cec5SDimitry Andric       llvm::Metadata *Args[2] = {
23040b57cec5SDimitry Andric           llvm::MDString::get(Context, "-framework"),
23050b57cec5SDimitry Andric           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
23060b57cec5SDimitry Andric 
23070b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
23080b57cec5SDimitry Andric       continue;
23090b57cec5SDimitry Andric     }
23100b57cec5SDimitry Andric 
23110b57cec5SDimitry Andric     // Link against a library.
23120b57cec5SDimitry Andric     if (IsELF) {
23130b57cec5SDimitry Andric       llvm::Metadata *Args[2] = {
23140b57cec5SDimitry Andric           llvm::MDString::get(Context, "lib"),
23150b57cec5SDimitry Andric           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library),
23160b57cec5SDimitry Andric       };
23170b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
23180b57cec5SDimitry Andric     } else {
23190b57cec5SDimitry Andric       llvm::SmallString<24> Opt;
23200b57cec5SDimitry Andric       CGM.getTargetCodeGenInfo().getDependentLibraryOption(
23210b57cec5SDimitry Andric           Mod->LinkLibraries[I - 1].Library, Opt);
23220b57cec5SDimitry Andric       auto *OptString = llvm::MDString::get(Context, Opt);
23230b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, OptString));
23240b57cec5SDimitry Andric     }
23250b57cec5SDimitry Andric   }
23260b57cec5SDimitry Andric }
23270b57cec5SDimitry Andric 
EmitModuleLinkOptions()23280b57cec5SDimitry Andric void CodeGenModule::EmitModuleLinkOptions() {
23290b57cec5SDimitry Andric   // Collect the set of all of the modules we want to visit to emit link
23300b57cec5SDimitry Andric   // options, which is essentially the imported modules and all of their
23310b57cec5SDimitry Andric   // non-explicit child modules.
23320b57cec5SDimitry Andric   llvm::SetVector<clang::Module *> LinkModules;
23330b57cec5SDimitry Andric   llvm::SmallPtrSet<clang::Module *, 16> Visited;
23340b57cec5SDimitry Andric   SmallVector<clang::Module *, 16> Stack;
23350b57cec5SDimitry Andric 
23360b57cec5SDimitry Andric   // Seed the stack with imported modules.
23370b57cec5SDimitry Andric   for (Module *M : ImportedModules) {
23380b57cec5SDimitry Andric     // Do not add any link flags when an implementation TU of a module imports
23390b57cec5SDimitry Andric     // a header of that same module.
23400b57cec5SDimitry Andric     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
23410b57cec5SDimitry Andric         !getLangOpts().isCompilingModule())
23420b57cec5SDimitry Andric       continue;
23430b57cec5SDimitry Andric     if (Visited.insert(M).second)
23440b57cec5SDimitry Andric       Stack.push_back(M);
23450b57cec5SDimitry Andric   }
23460b57cec5SDimitry Andric 
23470b57cec5SDimitry Andric   // Find all of the modules to import, making a little effort to prune
23480b57cec5SDimitry Andric   // non-leaf modules.
23490b57cec5SDimitry Andric   while (!Stack.empty()) {
23500b57cec5SDimitry Andric     clang::Module *Mod = Stack.pop_back_val();
23510b57cec5SDimitry Andric 
23520b57cec5SDimitry Andric     bool AnyChildren = false;
23530b57cec5SDimitry Andric 
23540b57cec5SDimitry Andric     // Visit the submodules of this module.
23550b57cec5SDimitry Andric     for (const auto &SM : Mod->submodules()) {
23560b57cec5SDimitry Andric       // Skip explicit children; they need to be explicitly imported to be
23570b57cec5SDimitry Andric       // linked against.
23580b57cec5SDimitry Andric       if (SM->IsExplicit)
23590b57cec5SDimitry Andric         continue;
23600b57cec5SDimitry Andric 
23610b57cec5SDimitry Andric       if (Visited.insert(SM).second) {
23620b57cec5SDimitry Andric         Stack.push_back(SM);
23630b57cec5SDimitry Andric         AnyChildren = true;
23640b57cec5SDimitry Andric       }
23650b57cec5SDimitry Andric     }
23660b57cec5SDimitry Andric 
23670b57cec5SDimitry Andric     // We didn't find any children, so add this module to the list of
23680b57cec5SDimitry Andric     // modules to link against.
23690b57cec5SDimitry Andric     if (!AnyChildren) {
23700b57cec5SDimitry Andric       LinkModules.insert(Mod);
23710b57cec5SDimitry Andric     }
23720b57cec5SDimitry Andric   }
23730b57cec5SDimitry Andric 
23740b57cec5SDimitry Andric   // Add link options for all of the imported modules in reverse topological
23750b57cec5SDimitry Andric   // order.  We don't do anything to try to order import link flags with respect
23760b57cec5SDimitry Andric   // to linker options inserted by things like #pragma comment().
23770b57cec5SDimitry Andric   SmallVector<llvm::MDNode *, 16> MetadataArgs;
23780b57cec5SDimitry Andric   Visited.clear();
23790b57cec5SDimitry Andric   for (Module *M : LinkModules)
23800b57cec5SDimitry Andric     if (Visited.insert(M).second)
23810b57cec5SDimitry Andric       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
23820b57cec5SDimitry Andric   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
23830b57cec5SDimitry Andric   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
23840b57cec5SDimitry Andric 
23850b57cec5SDimitry Andric   // Add the linker options metadata flag.
23860b57cec5SDimitry Andric   auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
23870b57cec5SDimitry Andric   for (auto *MD : LinkerOptionsMetadata)
23880b57cec5SDimitry Andric     NMD->addOperand(MD);
23890b57cec5SDimitry Andric }
23900b57cec5SDimitry Andric 
EmitDeferred()23910b57cec5SDimitry Andric void CodeGenModule::EmitDeferred() {
23920b57cec5SDimitry Andric   // Emit deferred declare target declarations.
23930b57cec5SDimitry Andric   if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
23940b57cec5SDimitry Andric     getOpenMPRuntime().emitDeferredTargetDecls();
23950b57cec5SDimitry Andric 
23960b57cec5SDimitry Andric   // Emit code for any potentially referenced deferred decls.  Since a
23970b57cec5SDimitry Andric   // previously unused static decl may become used during the generation of code
23980b57cec5SDimitry Andric   // for a static function, iterate until no changes are made.
23990b57cec5SDimitry Andric 
24000b57cec5SDimitry Andric   if (!DeferredVTables.empty()) {
24010b57cec5SDimitry Andric     EmitDeferredVTables();
24020b57cec5SDimitry Andric 
24030b57cec5SDimitry Andric     // Emitting a vtable doesn't directly cause more vtables to
24040b57cec5SDimitry Andric     // become deferred, although it can cause functions to be
24050b57cec5SDimitry Andric     // emitted that then need those vtables.
24060b57cec5SDimitry Andric     assert(DeferredVTables.empty());
24070b57cec5SDimitry Andric   }
24080b57cec5SDimitry Andric 
2409af732203SDimitry Andric   // Emit CUDA/HIP static device variables referenced by host code only.
24105f7ddb14SDimitry Andric   // Note we should not clear CUDADeviceVarODRUsedByHost since it is still
24115f7ddb14SDimitry Andric   // needed for further handling.
24125f7ddb14SDimitry Andric   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
24135f7ddb14SDimitry Andric     for (const auto *V : getContext().CUDADeviceVarODRUsedByHost)
2414af732203SDimitry Andric       DeferredDeclsToEmit.push_back(V);
2415af732203SDimitry Andric 
24160b57cec5SDimitry Andric   // Stop if we're out of both deferred vtables and deferred declarations.
24170b57cec5SDimitry Andric   if (DeferredDeclsToEmit.empty())
24180b57cec5SDimitry Andric     return;
24190b57cec5SDimitry Andric 
24200b57cec5SDimitry Andric   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
24210b57cec5SDimitry Andric   // work, it will not interfere with this.
24220b57cec5SDimitry Andric   std::vector<GlobalDecl> CurDeclsToEmit;
24230b57cec5SDimitry Andric   CurDeclsToEmit.swap(DeferredDeclsToEmit);
24240b57cec5SDimitry Andric 
24250b57cec5SDimitry Andric   for (GlobalDecl &D : CurDeclsToEmit) {
24260b57cec5SDimitry Andric     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
24270b57cec5SDimitry Andric     // to get GlobalValue with exactly the type we need, not something that
24280b57cec5SDimitry Andric     // might had been created for another decl with the same mangled name but
24290b57cec5SDimitry Andric     // different type.
24300b57cec5SDimitry Andric     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
24310b57cec5SDimitry Andric         GetAddrOfGlobal(D, ForDefinition));
24320b57cec5SDimitry Andric 
24330b57cec5SDimitry Andric     // In case of different address spaces, we may still get a cast, even with
24340b57cec5SDimitry Andric     // IsForDefinition equal to true. Query mangled names table to get
24350b57cec5SDimitry Andric     // GlobalValue.
24360b57cec5SDimitry Andric     if (!GV)
24370b57cec5SDimitry Andric       GV = GetGlobalValue(getMangledName(D));
24380b57cec5SDimitry Andric 
24390b57cec5SDimitry Andric     // Make sure GetGlobalValue returned non-null.
24400b57cec5SDimitry Andric     assert(GV);
24410b57cec5SDimitry Andric 
24420b57cec5SDimitry Andric     // Check to see if we've already emitted this.  This is necessary
24430b57cec5SDimitry Andric     // for a couple of reasons: first, decls can end up in the
24440b57cec5SDimitry Andric     // deferred-decls queue multiple times, and second, decls can end
24450b57cec5SDimitry Andric     // up with definitions in unusual ways (e.g. by an extern inline
24460b57cec5SDimitry Andric     // function acquiring a strong function redefinition).  Just
24470b57cec5SDimitry Andric     // ignore these cases.
24480b57cec5SDimitry Andric     if (!GV->isDeclaration())
24490b57cec5SDimitry Andric       continue;
24500b57cec5SDimitry Andric 
2451a7dea167SDimitry Andric     // If this is OpenMP, check if it is legal to emit this global normally.
2452a7dea167SDimitry Andric     if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
2453a7dea167SDimitry Andric       continue;
2454a7dea167SDimitry Andric 
24550b57cec5SDimitry Andric     // Otherwise, emit the definition and move on to the next one.
24560b57cec5SDimitry Andric     EmitGlobalDefinition(D, GV);
24570b57cec5SDimitry Andric 
24580b57cec5SDimitry Andric     // If we found out that we need to emit more decls, do that recursively.
24590b57cec5SDimitry Andric     // This has the advantage that the decls are emitted in a DFS and related
24600b57cec5SDimitry Andric     // ones are close together, which is convenient for testing.
24610b57cec5SDimitry Andric     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
24620b57cec5SDimitry Andric       EmitDeferred();
24630b57cec5SDimitry Andric       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
24640b57cec5SDimitry Andric     }
24650b57cec5SDimitry Andric   }
24660b57cec5SDimitry Andric }
24670b57cec5SDimitry Andric 
EmitVTablesOpportunistically()24680b57cec5SDimitry Andric void CodeGenModule::EmitVTablesOpportunistically() {
24690b57cec5SDimitry Andric   // Try to emit external vtables as available_externally if they have emitted
24700b57cec5SDimitry Andric   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
24710b57cec5SDimitry Andric   // is not allowed to create new references to things that need to be emitted
24720b57cec5SDimitry Andric   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
24730b57cec5SDimitry Andric 
24740b57cec5SDimitry Andric   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
24750b57cec5SDimitry Andric          && "Only emit opportunistic vtables with optimizations");
24760b57cec5SDimitry Andric 
24770b57cec5SDimitry Andric   for (const CXXRecordDecl *RD : OpportunisticVTables) {
24780b57cec5SDimitry Andric     assert(getVTables().isVTableExternal(RD) &&
24790b57cec5SDimitry Andric            "This queue should only contain external vtables");
24800b57cec5SDimitry Andric     if (getCXXABI().canSpeculativelyEmitVTable(RD))
24810b57cec5SDimitry Andric       VTables.GenerateClassData(RD);
24820b57cec5SDimitry Andric   }
24830b57cec5SDimitry Andric   OpportunisticVTables.clear();
24840b57cec5SDimitry Andric }
24850b57cec5SDimitry Andric 
EmitGlobalAnnotations()24860b57cec5SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() {
24870b57cec5SDimitry Andric   if (Annotations.empty())
24880b57cec5SDimitry Andric     return;
24890b57cec5SDimitry Andric 
24900b57cec5SDimitry Andric   // Create a new global variable for the ConstantStruct in the Module.
24910b57cec5SDimitry Andric   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
24920b57cec5SDimitry Andric     Annotations[0]->getType(), Annotations.size()), Annotations);
24930b57cec5SDimitry Andric   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
24940b57cec5SDimitry Andric                                       llvm::GlobalValue::AppendingLinkage,
24950b57cec5SDimitry Andric                                       Array, "llvm.global.annotations");
24960b57cec5SDimitry Andric   gv->setSection(AnnotationSection);
24970b57cec5SDimitry Andric }
24980b57cec5SDimitry Andric 
EmitAnnotationString(StringRef Str)24990b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
25000b57cec5SDimitry Andric   llvm::Constant *&AStr = AnnotationStrings[Str];
25010b57cec5SDimitry Andric   if (AStr)
25020b57cec5SDimitry Andric     return AStr;
25030b57cec5SDimitry Andric 
25040b57cec5SDimitry Andric   // Not found yet, create a new global.
25050b57cec5SDimitry Andric   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
25060b57cec5SDimitry Andric   auto *gv =
25070b57cec5SDimitry Andric       new llvm::GlobalVariable(getModule(), s->getType(), true,
25080b57cec5SDimitry Andric                                llvm::GlobalValue::PrivateLinkage, s, ".str");
25090b57cec5SDimitry Andric   gv->setSection(AnnotationSection);
25100b57cec5SDimitry Andric   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
25110b57cec5SDimitry Andric   AStr = gv;
25120b57cec5SDimitry Andric   return gv;
25130b57cec5SDimitry Andric }
25140b57cec5SDimitry Andric 
EmitAnnotationUnit(SourceLocation Loc)25150b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
25160b57cec5SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
25170b57cec5SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
25180b57cec5SDimitry Andric   if (PLoc.isValid())
25190b57cec5SDimitry Andric     return EmitAnnotationString(PLoc.getFilename());
25200b57cec5SDimitry Andric   return EmitAnnotationString(SM.getBufferName(Loc));
25210b57cec5SDimitry Andric }
25220b57cec5SDimitry Andric 
EmitAnnotationLineNo(SourceLocation L)25230b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
25240b57cec5SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
25250b57cec5SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(L);
25260b57cec5SDimitry Andric   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
25270b57cec5SDimitry Andric     SM.getExpansionLineNumber(L);
25280b57cec5SDimitry Andric   return llvm::ConstantInt::get(Int32Ty, LineNo);
25290b57cec5SDimitry Andric }
25300b57cec5SDimitry Andric 
EmitAnnotationArgs(const AnnotateAttr * Attr)2531af732203SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
2532af732203SDimitry Andric   ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()};
2533af732203SDimitry Andric   if (Exprs.empty())
2534af732203SDimitry Andric     return llvm::ConstantPointerNull::get(Int8PtrTy);
2535af732203SDimitry Andric 
2536af732203SDimitry Andric   llvm::FoldingSetNodeID ID;
2537af732203SDimitry Andric   for (Expr *E : Exprs) {
2538af732203SDimitry Andric     ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult());
2539af732203SDimitry Andric   }
2540af732203SDimitry Andric   llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
2541af732203SDimitry Andric   if (Lookup)
2542af732203SDimitry Andric     return Lookup;
2543af732203SDimitry Andric 
2544af732203SDimitry Andric   llvm::SmallVector<llvm::Constant *, 4> LLVMArgs;
2545af732203SDimitry Andric   LLVMArgs.reserve(Exprs.size());
2546af732203SDimitry Andric   ConstantEmitter ConstEmiter(*this);
2547af732203SDimitry Andric   llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) {
2548af732203SDimitry Andric     const auto *CE = cast<clang::ConstantExpr>(E);
2549af732203SDimitry Andric     return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
2550af732203SDimitry Andric                                     CE->getType());
2551af732203SDimitry Andric   });
2552af732203SDimitry Andric   auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
2553af732203SDimitry Andric   auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true,
2554af732203SDimitry Andric                                       llvm::GlobalValue::PrivateLinkage, Struct,
2555af732203SDimitry Andric                                       ".args");
2556af732203SDimitry Andric   GV->setSection(AnnotationSection);
2557af732203SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2558af732203SDimitry Andric   auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, Int8PtrTy);
2559af732203SDimitry Andric 
2560af732203SDimitry Andric   Lookup = Bitcasted;
2561af732203SDimitry Andric   return Bitcasted;
2562af732203SDimitry Andric }
2563af732203SDimitry Andric 
EmitAnnotateAttr(llvm::GlobalValue * GV,const AnnotateAttr * AA,SourceLocation L)25640b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
25650b57cec5SDimitry Andric                                                 const AnnotateAttr *AA,
25660b57cec5SDimitry Andric                                                 SourceLocation L) {
25670b57cec5SDimitry Andric   // Get the globals for file name, annotation, and the line number.
25680b57cec5SDimitry Andric   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
25690b57cec5SDimitry Andric                  *UnitGV = EmitAnnotationUnit(L),
2570af732203SDimitry Andric                  *LineNoCst = EmitAnnotationLineNo(L),
2571af732203SDimitry Andric                  *Args = EmitAnnotationArgs(AA);
25720b57cec5SDimitry Andric 
2573480093f4SDimitry Andric   llvm::Constant *ASZeroGV = GV;
2574480093f4SDimitry Andric   if (GV->getAddressSpace() != 0) {
2575480093f4SDimitry Andric     ASZeroGV = llvm::ConstantExpr::getAddrSpaceCast(
2576480093f4SDimitry Andric                    GV, GV->getValueType()->getPointerTo(0));
2577480093f4SDimitry Andric   }
2578480093f4SDimitry Andric 
25790b57cec5SDimitry Andric   // Create the ConstantStruct for the global annotation.
2580af732203SDimitry Andric   llvm::Constant *Fields[] = {
2581480093f4SDimitry Andric       llvm::ConstantExpr::getBitCast(ASZeroGV, Int8PtrTy),
25820b57cec5SDimitry Andric       llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
25830b57cec5SDimitry Andric       llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
2584af732203SDimitry Andric       LineNoCst,
2585af732203SDimitry Andric       Args,
25860b57cec5SDimitry Andric   };
25870b57cec5SDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
25880b57cec5SDimitry Andric }
25890b57cec5SDimitry Andric 
AddGlobalAnnotations(const ValueDecl * D,llvm::GlobalValue * GV)25900b57cec5SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
25910b57cec5SDimitry Andric                                          llvm::GlobalValue *GV) {
25920b57cec5SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
25930b57cec5SDimitry Andric   // Get the struct elements for these annotations.
25940b57cec5SDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
25950b57cec5SDimitry Andric     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
25960b57cec5SDimitry Andric }
25970b57cec5SDimitry Andric 
isInNoSanitizeList(SanitizerMask Kind,llvm::Function * Fn,SourceLocation Loc) const25985f7ddb14SDimitry Andric bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
25990b57cec5SDimitry Andric                                        SourceLocation Loc) const {
26005f7ddb14SDimitry Andric   const auto &NoSanitizeL = getContext().getNoSanitizeList();
26015f7ddb14SDimitry Andric   // NoSanitize by function name.
26025f7ddb14SDimitry Andric   if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
26030b57cec5SDimitry Andric     return true;
26045f7ddb14SDimitry Andric   // NoSanitize by location.
26050b57cec5SDimitry Andric   if (Loc.isValid())
26065f7ddb14SDimitry Andric     return NoSanitizeL.containsLocation(Kind, Loc);
26070b57cec5SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
26080b57cec5SDimitry Andric   // it's located in the main file.
26090b57cec5SDimitry Andric   auto &SM = Context.getSourceManager();
26100b57cec5SDimitry Andric   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
26115f7ddb14SDimitry Andric     return NoSanitizeL.containsFile(Kind, MainFile->getName());
26120b57cec5SDimitry Andric   }
26130b57cec5SDimitry Andric   return false;
26140b57cec5SDimitry Andric }
26150b57cec5SDimitry Andric 
isInNoSanitizeList(llvm::GlobalVariable * GV,SourceLocation Loc,QualType Ty,StringRef Category) const26165f7ddb14SDimitry Andric bool CodeGenModule::isInNoSanitizeList(llvm::GlobalVariable *GV,
26170b57cec5SDimitry Andric                                        SourceLocation Loc, QualType Ty,
26180b57cec5SDimitry Andric                                        StringRef Category) const {
26195f7ddb14SDimitry Andric   // For now globals can be ignored only in ASan and KASan.
26200b57cec5SDimitry Andric   const SanitizerMask EnabledAsanMask =
26210b57cec5SDimitry Andric       LangOpts.Sanitize.Mask &
26220b57cec5SDimitry Andric       (SanitizerKind::Address | SanitizerKind::KernelAddress |
26230b57cec5SDimitry Andric        SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress |
26240b57cec5SDimitry Andric        SanitizerKind::MemTag);
26250b57cec5SDimitry Andric   if (!EnabledAsanMask)
26260b57cec5SDimitry Andric     return false;
26275f7ddb14SDimitry Andric   const auto &NoSanitizeL = getContext().getNoSanitizeList();
26285f7ddb14SDimitry Andric   if (NoSanitizeL.containsGlobal(EnabledAsanMask, GV->getName(), Category))
26290b57cec5SDimitry Andric     return true;
26305f7ddb14SDimitry Andric   if (NoSanitizeL.containsLocation(EnabledAsanMask, Loc, Category))
26310b57cec5SDimitry Andric     return true;
26320b57cec5SDimitry Andric   // Check global type.
26330b57cec5SDimitry Andric   if (!Ty.isNull()) {
26340b57cec5SDimitry Andric     // Drill down the array types: if global variable of a fixed type is
26355f7ddb14SDimitry Andric     // not sanitized, we also don't instrument arrays of them.
26360b57cec5SDimitry Andric     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
26370b57cec5SDimitry Andric       Ty = AT->getElementType();
26380b57cec5SDimitry Andric     Ty = Ty.getCanonicalType().getUnqualifiedType();
26395f7ddb14SDimitry Andric     // Only record types (classes, structs etc.) are ignored.
26400b57cec5SDimitry Andric     if (Ty->isRecordType()) {
26410b57cec5SDimitry Andric       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
26425f7ddb14SDimitry Andric       if (NoSanitizeL.containsType(EnabledAsanMask, TypeStr, Category))
26430b57cec5SDimitry Andric         return true;
26440b57cec5SDimitry Andric     }
26450b57cec5SDimitry Andric   }
26460b57cec5SDimitry Andric   return false;
26470b57cec5SDimitry Andric }
26480b57cec5SDimitry Andric 
imbueXRayAttrs(llvm::Function * Fn,SourceLocation Loc,StringRef Category) const26490b57cec5SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
26500b57cec5SDimitry Andric                                    StringRef Category) const {
26510b57cec5SDimitry Andric   const auto &XRayFilter = getContext().getXRayFilter();
26520b57cec5SDimitry Andric   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
26530b57cec5SDimitry Andric   auto Attr = ImbueAttr::NONE;
26540b57cec5SDimitry Andric   if (Loc.isValid())
26550b57cec5SDimitry Andric     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
26560b57cec5SDimitry Andric   if (Attr == ImbueAttr::NONE)
26570b57cec5SDimitry Andric     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
26580b57cec5SDimitry Andric   switch (Attr) {
26590b57cec5SDimitry Andric   case ImbueAttr::NONE:
26600b57cec5SDimitry Andric     return false;
26610b57cec5SDimitry Andric   case ImbueAttr::ALWAYS:
26620b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
26630b57cec5SDimitry Andric     break;
26640b57cec5SDimitry Andric   case ImbueAttr::ALWAYS_ARG1:
26650b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
26660b57cec5SDimitry Andric     Fn->addFnAttr("xray-log-args", "1");
26670b57cec5SDimitry Andric     break;
26680b57cec5SDimitry Andric   case ImbueAttr::NEVER:
26690b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-never");
26700b57cec5SDimitry Andric     break;
26710b57cec5SDimitry Andric   }
26720b57cec5SDimitry Andric   return true;
26730b57cec5SDimitry Andric }
26740b57cec5SDimitry Andric 
isProfileInstrExcluded(llvm::Function * Fn,SourceLocation Loc) const2675af732203SDimitry Andric bool CodeGenModule::isProfileInstrExcluded(llvm::Function *Fn,
2676af732203SDimitry Andric                                            SourceLocation Loc) const {
2677af732203SDimitry Andric   const auto &ProfileList = getContext().getProfileList();
2678af732203SDimitry Andric   // If the profile list is empty, then instrument everything.
2679af732203SDimitry Andric   if (ProfileList.isEmpty())
2680af732203SDimitry Andric     return false;
2681af732203SDimitry Andric   CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
2682af732203SDimitry Andric   // First, check the function name.
2683af732203SDimitry Andric   Optional<bool> V = ProfileList.isFunctionExcluded(Fn->getName(), Kind);
2684af732203SDimitry Andric   if (V.hasValue())
2685af732203SDimitry Andric     return *V;
2686af732203SDimitry Andric   // Next, check the source location.
2687af732203SDimitry Andric   if (Loc.isValid()) {
2688af732203SDimitry Andric     Optional<bool> V = ProfileList.isLocationExcluded(Loc, Kind);
2689af732203SDimitry Andric     if (V.hasValue())
2690af732203SDimitry Andric       return *V;
2691af732203SDimitry Andric   }
2692af732203SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
2693af732203SDimitry Andric   // it's located in the main file.
2694af732203SDimitry Andric   auto &SM = Context.getSourceManager();
2695af732203SDimitry Andric   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
2696af732203SDimitry Andric     Optional<bool> V = ProfileList.isFileExcluded(MainFile->getName(), Kind);
2697af732203SDimitry Andric     if (V.hasValue())
2698af732203SDimitry Andric       return *V;
2699af732203SDimitry Andric   }
2700af732203SDimitry Andric   return ProfileList.getDefault();
2701af732203SDimitry Andric }
2702af732203SDimitry Andric 
MustBeEmitted(const ValueDecl * Global)27030b57cec5SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
27040b57cec5SDimitry Andric   // Never defer when EmitAllDecls is specified.
27050b57cec5SDimitry Andric   if (LangOpts.EmitAllDecls)
27060b57cec5SDimitry Andric     return true;
27070b57cec5SDimitry Andric 
27080b57cec5SDimitry Andric   if (CodeGenOpts.KeepStaticConsts) {
27090b57cec5SDimitry Andric     const auto *VD = dyn_cast<VarDecl>(Global);
27100b57cec5SDimitry Andric     if (VD && VD->getType().isConstQualified() &&
27110b57cec5SDimitry Andric         VD->getStorageDuration() == SD_Static)
27120b57cec5SDimitry Andric       return true;
27130b57cec5SDimitry Andric   }
27140b57cec5SDimitry Andric 
27150b57cec5SDimitry Andric   return getContext().DeclMustBeEmitted(Global);
27160b57cec5SDimitry Andric }
27170b57cec5SDimitry Andric 
MayBeEmittedEagerly(const ValueDecl * Global)27180b57cec5SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
27195f7ddb14SDimitry Andric   // In OpenMP 5.0 variables and function may be marked as
27205f7ddb14SDimitry Andric   // device_type(host/nohost) and we should not emit them eagerly unless we sure
27215f7ddb14SDimitry Andric   // that they must be emitted on the host/device. To be sure we need to have
27225f7ddb14SDimitry Andric   // seen a declare target with an explicit mentioning of the function, we know
27235f7ddb14SDimitry Andric   // we have if the level of the declare target attribute is -1. Note that we
27245f7ddb14SDimitry Andric   // check somewhere else if we should emit this at all.
27255f7ddb14SDimitry Andric   if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
27265f7ddb14SDimitry Andric     llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
27275f7ddb14SDimitry Andric         OMPDeclareTargetDeclAttr::getActiveAttr(Global);
27285f7ddb14SDimitry Andric     if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1)
27295f7ddb14SDimitry Andric       return false;
27305f7ddb14SDimitry Andric   }
27315f7ddb14SDimitry Andric 
2732a7dea167SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
27330b57cec5SDimitry Andric     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
27340b57cec5SDimitry Andric       // Implicit template instantiations may change linkage if they are later
27350b57cec5SDimitry Andric       // explicitly instantiated, so they should not be emitted eagerly.
27360b57cec5SDimitry Andric       return false;
2737a7dea167SDimitry Andric   }
27380b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(Global))
27390b57cec5SDimitry Andric     if (Context.getInlineVariableDefinitionKind(VD) ==
27400b57cec5SDimitry Andric         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
27410b57cec5SDimitry Andric       // A definition of an inline constexpr static data member may change
27420b57cec5SDimitry Andric       // linkage later if it's redeclared outside the class.
27430b57cec5SDimitry Andric       return false;
27440b57cec5SDimitry Andric   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
27450b57cec5SDimitry Andric   // codegen for global variables, because they may be marked as threadprivate.
27460b57cec5SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
27470b57cec5SDimitry Andric       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
27480b57cec5SDimitry Andric       !isTypeConstant(Global->getType(), false) &&
27490b57cec5SDimitry Andric       !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
27500b57cec5SDimitry Andric     return false;
27510b57cec5SDimitry Andric 
27520b57cec5SDimitry Andric   return true;
27530b57cec5SDimitry Andric }
27540b57cec5SDimitry Andric 
GetAddrOfMSGuidDecl(const MSGuidDecl * GD)27555ffd83dbSDimitry Andric ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
27565ffd83dbSDimitry Andric   StringRef Name = getMangledName(GD);
27570b57cec5SDimitry Andric 
27580b57cec5SDimitry Andric   // The UUID descriptor should be pointer aligned.
27590b57cec5SDimitry Andric   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
27600b57cec5SDimitry Andric 
27610b57cec5SDimitry Andric   // Look for an existing global.
27620b57cec5SDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
27630b57cec5SDimitry Andric     return ConstantAddress(GV, Alignment);
27640b57cec5SDimitry Andric 
27655ffd83dbSDimitry Andric   ConstantEmitter Emitter(*this);
27665ffd83dbSDimitry Andric   llvm::Constant *Init;
27675ffd83dbSDimitry Andric 
27685ffd83dbSDimitry Andric   APValue &V = GD->getAsAPValue();
27695ffd83dbSDimitry Andric   if (!V.isAbsent()) {
27705ffd83dbSDimitry Andric     // If possible, emit the APValue version of the initializer. In particular,
27715ffd83dbSDimitry Andric     // this gets the type of the constant right.
27725ffd83dbSDimitry Andric     Init = Emitter.emitForInitializer(
27735ffd83dbSDimitry Andric         GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
27745ffd83dbSDimitry Andric   } else {
27755ffd83dbSDimitry Andric     // As a fallback, directly construct the constant.
27765ffd83dbSDimitry Andric     // FIXME: This may get padding wrong under esoteric struct layout rules.
27775ffd83dbSDimitry Andric     // MSVC appears to create a complete type 'struct __s_GUID' that it
27785ffd83dbSDimitry Andric     // presumably uses to represent these constants.
27795ffd83dbSDimitry Andric     MSGuidDecl::Parts Parts = GD->getParts();
27805ffd83dbSDimitry Andric     llvm::Constant *Fields[4] = {
27815ffd83dbSDimitry Andric         llvm::ConstantInt::get(Int32Ty, Parts.Part1),
27825ffd83dbSDimitry Andric         llvm::ConstantInt::get(Int16Ty, Parts.Part2),
27835ffd83dbSDimitry Andric         llvm::ConstantInt::get(Int16Ty, Parts.Part3),
27845ffd83dbSDimitry Andric         llvm::ConstantDataArray::getRaw(
27855ffd83dbSDimitry Andric             StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
27865ffd83dbSDimitry Andric             Int8Ty)};
27875ffd83dbSDimitry Andric     Init = llvm::ConstantStruct::getAnon(Fields);
27885ffd83dbSDimitry Andric   }
27890b57cec5SDimitry Andric 
27900b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
27910b57cec5SDimitry Andric       getModule(), Init->getType(),
27920b57cec5SDimitry Andric       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
27930b57cec5SDimitry Andric   if (supportsCOMDAT())
27940b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
27950b57cec5SDimitry Andric   setDSOLocal(GV);
27965ffd83dbSDimitry Andric 
27975ffd83dbSDimitry Andric   llvm::Constant *Addr = GV;
27985ffd83dbSDimitry Andric   if (!V.isAbsent()) {
27995ffd83dbSDimitry Andric     Emitter.finalize(GV);
28005ffd83dbSDimitry Andric   } else {
28015ffd83dbSDimitry Andric     llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
28025ffd83dbSDimitry Andric     Addr = llvm::ConstantExpr::getBitCast(
28035ffd83dbSDimitry Andric         GV, Ty->getPointerTo(GV->getAddressSpace()));
28045ffd83dbSDimitry Andric   }
28055ffd83dbSDimitry Andric   return ConstantAddress(Addr, Alignment);
28060b57cec5SDimitry Andric }
28070b57cec5SDimitry Andric 
GetAddrOfTemplateParamObject(const TemplateParamObjectDecl * TPO)2808af732203SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject(
2809af732203SDimitry Andric     const TemplateParamObjectDecl *TPO) {
2810af732203SDimitry Andric   StringRef Name = getMangledName(TPO);
2811af732203SDimitry Andric   CharUnits Alignment = getNaturalTypeAlignment(TPO->getType());
2812af732203SDimitry Andric 
2813af732203SDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
2814af732203SDimitry Andric     return ConstantAddress(GV, Alignment);
2815af732203SDimitry Andric 
2816af732203SDimitry Andric   ConstantEmitter Emitter(*this);
2817af732203SDimitry Andric   llvm::Constant *Init = Emitter.emitForInitializer(
2818af732203SDimitry Andric         TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType());
2819af732203SDimitry Andric 
2820af732203SDimitry Andric   if (!Init) {
2821af732203SDimitry Andric     ErrorUnsupported(TPO, "template parameter object");
2822af732203SDimitry Andric     return ConstantAddress::invalid();
2823af732203SDimitry Andric   }
2824af732203SDimitry Andric 
2825af732203SDimitry Andric   auto *GV = new llvm::GlobalVariable(
2826af732203SDimitry Andric       getModule(), Init->getType(),
2827af732203SDimitry Andric       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2828af732203SDimitry Andric   if (supportsCOMDAT())
2829af732203SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2830af732203SDimitry Andric   Emitter.finalize(GV);
2831af732203SDimitry Andric 
2832af732203SDimitry Andric   return ConstantAddress(GV, Alignment);
2833af732203SDimitry Andric }
2834af732203SDimitry Andric 
GetWeakRefReference(const ValueDecl * VD)28350b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
28360b57cec5SDimitry Andric   const AliasAttr *AA = VD->getAttr<AliasAttr>();
28370b57cec5SDimitry Andric   assert(AA && "No alias?");
28380b57cec5SDimitry Andric 
28390b57cec5SDimitry Andric   CharUnits Alignment = getContext().getDeclAlign(VD);
28400b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
28410b57cec5SDimitry Andric 
28420b57cec5SDimitry Andric   // See if there is already something with the target's name in the module.
28430b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
28440b57cec5SDimitry Andric   if (Entry) {
28450b57cec5SDimitry Andric     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
28460b57cec5SDimitry Andric     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
28470b57cec5SDimitry Andric     return ConstantAddress(Ptr, Alignment);
28480b57cec5SDimitry Andric   }
28490b57cec5SDimitry Andric 
28500b57cec5SDimitry Andric   llvm::Constant *Aliasee;
28510b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(DeclTy))
28520b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
28530b57cec5SDimitry Andric                                       GlobalDecl(cast<FunctionDecl>(VD)),
28540b57cec5SDimitry Andric                                       /*ForVTable=*/false);
28550b57cec5SDimitry Andric   else
28565f7ddb14SDimitry Andric     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, 0, nullptr);
28570b57cec5SDimitry Andric 
28580b57cec5SDimitry Andric   auto *F = cast<llvm::GlobalValue>(Aliasee);
28590b57cec5SDimitry Andric   F->setLinkage(llvm::Function::ExternalWeakLinkage);
28600b57cec5SDimitry Andric   WeakRefReferences.insert(F);
28610b57cec5SDimitry Andric 
28620b57cec5SDimitry Andric   return ConstantAddress(Aliasee, Alignment);
28630b57cec5SDimitry Andric }
28640b57cec5SDimitry Andric 
EmitGlobal(GlobalDecl GD)28650b57cec5SDimitry Andric void CodeGenModule::EmitGlobal(GlobalDecl GD) {
28660b57cec5SDimitry Andric   const auto *Global = cast<ValueDecl>(GD.getDecl());
28670b57cec5SDimitry Andric 
28680b57cec5SDimitry Andric   // Weak references don't produce any output by themselves.
28690b57cec5SDimitry Andric   if (Global->hasAttr<WeakRefAttr>())
28700b57cec5SDimitry Andric     return;
28710b57cec5SDimitry Andric 
28720b57cec5SDimitry Andric   // If this is an alias definition (which otherwise looks like a declaration)
28730b57cec5SDimitry Andric   // emit it now.
28740b57cec5SDimitry Andric   if (Global->hasAttr<AliasAttr>())
28750b57cec5SDimitry Andric     return EmitAliasDefinition(GD);
28760b57cec5SDimitry Andric 
28770b57cec5SDimitry Andric   // IFunc like an alias whose value is resolved at runtime by calling resolver.
28780b57cec5SDimitry Andric   if (Global->hasAttr<IFuncAttr>())
28790b57cec5SDimitry Andric     return emitIFuncDefinition(GD);
28800b57cec5SDimitry Andric 
28810b57cec5SDimitry Andric   // If this is a cpu_dispatch multiversion function, emit the resolver.
28820b57cec5SDimitry Andric   if (Global->hasAttr<CPUDispatchAttr>())
28830b57cec5SDimitry Andric     return emitCPUDispatchDefinition(GD);
28840b57cec5SDimitry Andric 
28850b57cec5SDimitry Andric   // If this is CUDA, be selective about which declarations we emit.
28860b57cec5SDimitry Andric   if (LangOpts.CUDA) {
28870b57cec5SDimitry Andric     if (LangOpts.CUDAIsDevice) {
28880b57cec5SDimitry Andric       if (!Global->hasAttr<CUDADeviceAttr>() &&
28890b57cec5SDimitry Andric           !Global->hasAttr<CUDAGlobalAttr>() &&
28900b57cec5SDimitry Andric           !Global->hasAttr<CUDAConstantAttr>() &&
28910b57cec5SDimitry Andric           !Global->hasAttr<CUDASharedAttr>() &&
28925ffd83dbSDimitry Andric           !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
28935ffd83dbSDimitry Andric           !Global->getType()->isCUDADeviceBuiltinTextureType())
28940b57cec5SDimitry Andric         return;
28950b57cec5SDimitry Andric     } else {
28960b57cec5SDimitry Andric       // We need to emit host-side 'shadows' for all global
28970b57cec5SDimitry Andric       // device-side variables because the CUDA runtime needs their
28980b57cec5SDimitry Andric       // size and host-side address in order to provide access to
28990b57cec5SDimitry Andric       // their device-side incarnations.
29000b57cec5SDimitry Andric 
29010b57cec5SDimitry Andric       // So device-only functions are the only things we skip.
29020b57cec5SDimitry Andric       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
29030b57cec5SDimitry Andric           Global->hasAttr<CUDADeviceAttr>())
29040b57cec5SDimitry Andric         return;
29050b57cec5SDimitry Andric 
29060b57cec5SDimitry Andric       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
29070b57cec5SDimitry Andric              "Expected Variable or Function");
29080b57cec5SDimitry Andric     }
29090b57cec5SDimitry Andric   }
29100b57cec5SDimitry Andric 
29110b57cec5SDimitry Andric   if (LangOpts.OpenMP) {
2912a7dea167SDimitry Andric     // If this is OpenMP, check if it is legal to emit this global normally.
29130b57cec5SDimitry Andric     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
29140b57cec5SDimitry Andric       return;
29150b57cec5SDimitry Andric     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
29160b57cec5SDimitry Andric       if (MustBeEmitted(Global))
29170b57cec5SDimitry Andric         EmitOMPDeclareReduction(DRD);
29180b57cec5SDimitry Andric       return;
29190b57cec5SDimitry Andric     } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
29200b57cec5SDimitry Andric       if (MustBeEmitted(Global))
29210b57cec5SDimitry Andric         EmitOMPDeclareMapper(DMD);
29220b57cec5SDimitry Andric       return;
29230b57cec5SDimitry Andric     }
29240b57cec5SDimitry Andric   }
29250b57cec5SDimitry Andric 
29260b57cec5SDimitry Andric   // Ignore declarations, they will be emitted on their first use.
29270b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
29280b57cec5SDimitry Andric     // Forward declarations are emitted lazily on first use.
29290b57cec5SDimitry Andric     if (!FD->doesThisDeclarationHaveABody()) {
29300b57cec5SDimitry Andric       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
29310b57cec5SDimitry Andric         return;
29320b57cec5SDimitry Andric 
29330b57cec5SDimitry Andric       StringRef MangledName = getMangledName(GD);
29340b57cec5SDimitry Andric 
29350b57cec5SDimitry Andric       // Compute the function info and LLVM type.
29360b57cec5SDimitry Andric       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
29370b57cec5SDimitry Andric       llvm::Type *Ty = getTypes().GetFunctionType(FI);
29380b57cec5SDimitry Andric 
29390b57cec5SDimitry Andric       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
29400b57cec5SDimitry Andric                               /*DontDefer=*/false);
29410b57cec5SDimitry Andric       return;
29420b57cec5SDimitry Andric     }
29430b57cec5SDimitry Andric   } else {
29440b57cec5SDimitry Andric     const auto *VD = cast<VarDecl>(Global);
29450b57cec5SDimitry Andric     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
29460b57cec5SDimitry Andric     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
29470b57cec5SDimitry Andric         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
29480b57cec5SDimitry Andric       if (LangOpts.OpenMP) {
29490b57cec5SDimitry Andric         // Emit declaration of the must-be-emitted declare target variable.
29500b57cec5SDimitry Andric         if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
29510b57cec5SDimitry Andric                 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
29520b57cec5SDimitry Andric           bool UnifiedMemoryEnabled =
29530b57cec5SDimitry Andric               getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
29540b57cec5SDimitry Andric           if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
29550b57cec5SDimitry Andric               !UnifiedMemoryEnabled) {
29560b57cec5SDimitry Andric             (void)GetAddrOfGlobalVar(VD);
29570b57cec5SDimitry Andric           } else {
29580b57cec5SDimitry Andric             assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
29590b57cec5SDimitry Andric                     (*Res == OMPDeclareTargetDeclAttr::MT_To &&
29600b57cec5SDimitry Andric                      UnifiedMemoryEnabled)) &&
29610b57cec5SDimitry Andric                    "Link clause or to clause with unified memory expected.");
29620b57cec5SDimitry Andric             (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
29630b57cec5SDimitry Andric           }
29640b57cec5SDimitry Andric 
29650b57cec5SDimitry Andric           return;
29660b57cec5SDimitry Andric         }
29670b57cec5SDimitry Andric       }
29680b57cec5SDimitry Andric       // If this declaration may have caused an inline variable definition to
29690b57cec5SDimitry Andric       // change linkage, make sure that it's emitted.
29700b57cec5SDimitry Andric       if (Context.getInlineVariableDefinitionKind(VD) ==
29710b57cec5SDimitry Andric           ASTContext::InlineVariableDefinitionKind::Strong)
29720b57cec5SDimitry Andric         GetAddrOfGlobalVar(VD);
29730b57cec5SDimitry Andric       return;
29740b57cec5SDimitry Andric     }
29750b57cec5SDimitry Andric   }
29760b57cec5SDimitry Andric 
29770b57cec5SDimitry Andric   // Defer code generation to first use when possible, e.g. if this is an inline
29780b57cec5SDimitry Andric   // function. If the global must always be emitted, do it eagerly if possible
29790b57cec5SDimitry Andric   // to benefit from cache locality.
29800b57cec5SDimitry Andric   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
29810b57cec5SDimitry Andric     // Emit the definition if it can't be deferred.
29820b57cec5SDimitry Andric     EmitGlobalDefinition(GD);
29830b57cec5SDimitry Andric     return;
29840b57cec5SDimitry Andric   }
29850b57cec5SDimitry Andric 
29860b57cec5SDimitry Andric   // If we're deferring emission of a C++ variable with an
29870b57cec5SDimitry Andric   // initializer, remember the order in which it appeared in the file.
29880b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
29890b57cec5SDimitry Andric       cast<VarDecl>(Global)->hasInit()) {
29900b57cec5SDimitry Andric     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
29910b57cec5SDimitry Andric     CXXGlobalInits.push_back(nullptr);
29920b57cec5SDimitry Andric   }
29930b57cec5SDimitry Andric 
29940b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
29950b57cec5SDimitry Andric   if (GetGlobalValue(MangledName) != nullptr) {
29960b57cec5SDimitry Andric     // The value has already been used and should therefore be emitted.
29970b57cec5SDimitry Andric     addDeferredDeclToEmit(GD);
29980b57cec5SDimitry Andric   } else if (MustBeEmitted(Global)) {
29990b57cec5SDimitry Andric     // The value must be emitted, but cannot be emitted eagerly.
30000b57cec5SDimitry Andric     assert(!MayBeEmittedEagerly(Global));
30010b57cec5SDimitry Andric     addDeferredDeclToEmit(GD);
30020b57cec5SDimitry Andric   } else {
30030b57cec5SDimitry Andric     // Otherwise, remember that we saw a deferred decl with this name.  The
30040b57cec5SDimitry Andric     // first use of the mangled name will cause it to move into
30050b57cec5SDimitry Andric     // DeferredDeclsToEmit.
30060b57cec5SDimitry Andric     DeferredDecls[MangledName] = GD;
30070b57cec5SDimitry Andric   }
30080b57cec5SDimitry Andric }
30090b57cec5SDimitry Andric 
30100b57cec5SDimitry Andric // Check if T is a class type with a destructor that's not dllimport.
HasNonDllImportDtor(QualType T)30110b57cec5SDimitry Andric static bool HasNonDllImportDtor(QualType T) {
30120b57cec5SDimitry Andric   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
30130b57cec5SDimitry Andric     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
30140b57cec5SDimitry Andric       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
30150b57cec5SDimitry Andric         return true;
30160b57cec5SDimitry Andric 
30170b57cec5SDimitry Andric   return false;
30180b57cec5SDimitry Andric }
30190b57cec5SDimitry Andric 
30200b57cec5SDimitry Andric namespace {
30210b57cec5SDimitry Andric   struct FunctionIsDirectlyRecursive
30220b57cec5SDimitry Andric       : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
30230b57cec5SDimitry Andric     const StringRef Name;
30240b57cec5SDimitry Andric     const Builtin::Context &BI;
FunctionIsDirectlyRecursive__anondad8672d0811::FunctionIsDirectlyRecursive30250b57cec5SDimitry Andric     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
30260b57cec5SDimitry Andric         : Name(N), BI(C) {}
30270b57cec5SDimitry Andric 
VisitCallExpr__anondad8672d0811::FunctionIsDirectlyRecursive30280b57cec5SDimitry Andric     bool VisitCallExpr(const CallExpr *E) {
30290b57cec5SDimitry Andric       const FunctionDecl *FD = E->getDirectCallee();
30300b57cec5SDimitry Andric       if (!FD)
30310b57cec5SDimitry Andric         return false;
30320b57cec5SDimitry Andric       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
30330b57cec5SDimitry Andric       if (Attr && Name == Attr->getLabel())
30340b57cec5SDimitry Andric         return true;
30350b57cec5SDimitry Andric       unsigned BuiltinID = FD->getBuiltinID();
30360b57cec5SDimitry Andric       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
30370b57cec5SDimitry Andric         return false;
30380b57cec5SDimitry Andric       StringRef BuiltinName = BI.getName(BuiltinID);
30390b57cec5SDimitry Andric       if (BuiltinName.startswith("__builtin_") &&
30400b57cec5SDimitry Andric           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
30410b57cec5SDimitry Andric         return true;
30420b57cec5SDimitry Andric       }
30430b57cec5SDimitry Andric       return false;
30440b57cec5SDimitry Andric     }
30450b57cec5SDimitry Andric 
VisitStmt__anondad8672d0811::FunctionIsDirectlyRecursive30460b57cec5SDimitry Andric     bool VisitStmt(const Stmt *S) {
30470b57cec5SDimitry Andric       for (const Stmt *Child : S->children())
30480b57cec5SDimitry Andric         if (Child && this->Visit(Child))
30490b57cec5SDimitry Andric           return true;
30500b57cec5SDimitry Andric       return false;
30510b57cec5SDimitry Andric     }
30520b57cec5SDimitry Andric   };
30530b57cec5SDimitry Andric 
30540b57cec5SDimitry Andric   // Make sure we're not referencing non-imported vars or functions.
30550b57cec5SDimitry Andric   struct DLLImportFunctionVisitor
30560b57cec5SDimitry Andric       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
30570b57cec5SDimitry Andric     bool SafeToInline = true;
30580b57cec5SDimitry Andric 
shouldVisitImplicitCode__anondad8672d0811::DLLImportFunctionVisitor30590b57cec5SDimitry Andric     bool shouldVisitImplicitCode() const { return true; }
30600b57cec5SDimitry Andric 
VisitVarDecl__anondad8672d0811::DLLImportFunctionVisitor30610b57cec5SDimitry Andric     bool VisitVarDecl(VarDecl *VD) {
30620b57cec5SDimitry Andric       if (VD->getTLSKind()) {
30630b57cec5SDimitry Andric         // A thread-local variable cannot be imported.
30640b57cec5SDimitry Andric         SafeToInline = false;
30650b57cec5SDimitry Andric         return SafeToInline;
30660b57cec5SDimitry Andric       }
30670b57cec5SDimitry Andric 
30680b57cec5SDimitry Andric       // A variable definition might imply a destructor call.
30690b57cec5SDimitry Andric       if (VD->isThisDeclarationADefinition())
30700b57cec5SDimitry Andric         SafeToInline = !HasNonDllImportDtor(VD->getType());
30710b57cec5SDimitry Andric 
30720b57cec5SDimitry Andric       return SafeToInline;
30730b57cec5SDimitry Andric     }
30740b57cec5SDimitry Andric 
VisitCXXBindTemporaryExpr__anondad8672d0811::DLLImportFunctionVisitor30750b57cec5SDimitry Andric     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
30760b57cec5SDimitry Andric       if (const auto *D = E->getTemporary()->getDestructor())
30770b57cec5SDimitry Andric         SafeToInline = D->hasAttr<DLLImportAttr>();
30780b57cec5SDimitry Andric       return SafeToInline;
30790b57cec5SDimitry Andric     }
30800b57cec5SDimitry Andric 
VisitDeclRefExpr__anondad8672d0811::DLLImportFunctionVisitor30810b57cec5SDimitry Andric     bool VisitDeclRefExpr(DeclRefExpr *E) {
30820b57cec5SDimitry Andric       ValueDecl *VD = E->getDecl();
30830b57cec5SDimitry Andric       if (isa<FunctionDecl>(VD))
30840b57cec5SDimitry Andric         SafeToInline = VD->hasAttr<DLLImportAttr>();
30850b57cec5SDimitry Andric       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
30860b57cec5SDimitry Andric         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
30870b57cec5SDimitry Andric       return SafeToInline;
30880b57cec5SDimitry Andric     }
30890b57cec5SDimitry Andric 
VisitCXXConstructExpr__anondad8672d0811::DLLImportFunctionVisitor30900b57cec5SDimitry Andric     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
30910b57cec5SDimitry Andric       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
30920b57cec5SDimitry Andric       return SafeToInline;
30930b57cec5SDimitry Andric     }
30940b57cec5SDimitry Andric 
VisitCXXMemberCallExpr__anondad8672d0811::DLLImportFunctionVisitor30950b57cec5SDimitry Andric     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
30960b57cec5SDimitry Andric       CXXMethodDecl *M = E->getMethodDecl();
30970b57cec5SDimitry Andric       if (!M) {
30980b57cec5SDimitry Andric         // Call through a pointer to member function. This is safe to inline.
30990b57cec5SDimitry Andric         SafeToInline = true;
31000b57cec5SDimitry Andric       } else {
31010b57cec5SDimitry Andric         SafeToInline = M->hasAttr<DLLImportAttr>();
31020b57cec5SDimitry Andric       }
31030b57cec5SDimitry Andric       return SafeToInline;
31040b57cec5SDimitry Andric     }
31050b57cec5SDimitry Andric 
VisitCXXDeleteExpr__anondad8672d0811::DLLImportFunctionVisitor31060b57cec5SDimitry Andric     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
31070b57cec5SDimitry Andric       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
31080b57cec5SDimitry Andric       return SafeToInline;
31090b57cec5SDimitry Andric     }
31100b57cec5SDimitry Andric 
VisitCXXNewExpr__anondad8672d0811::DLLImportFunctionVisitor31110b57cec5SDimitry Andric     bool VisitCXXNewExpr(CXXNewExpr *E) {
31120b57cec5SDimitry Andric       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
31130b57cec5SDimitry Andric       return SafeToInline;
31140b57cec5SDimitry Andric     }
31150b57cec5SDimitry Andric   };
31160b57cec5SDimitry Andric }
31170b57cec5SDimitry Andric 
31180b57cec5SDimitry Andric // isTriviallyRecursive - Check if this function calls another
31190b57cec5SDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin,
31200b57cec5SDimitry Andric // ends up pointing to itself.
31210b57cec5SDimitry Andric bool
isTriviallyRecursive(const FunctionDecl * FD)31220b57cec5SDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
31230b57cec5SDimitry Andric   StringRef Name;
31240b57cec5SDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
31250b57cec5SDimitry Andric     // asm labels are a special kind of mangling we have to support.
31260b57cec5SDimitry Andric     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
31270b57cec5SDimitry Andric     if (!Attr)
31280b57cec5SDimitry Andric       return false;
31290b57cec5SDimitry Andric     Name = Attr->getLabel();
31300b57cec5SDimitry Andric   } else {
31310b57cec5SDimitry Andric     Name = FD->getName();
31320b57cec5SDimitry Andric   }
31330b57cec5SDimitry Andric 
31340b57cec5SDimitry Andric   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
31350b57cec5SDimitry Andric   const Stmt *Body = FD->getBody();
31360b57cec5SDimitry Andric   return Body ? Walker.Visit(Body) : false;
31370b57cec5SDimitry Andric }
31380b57cec5SDimitry Andric 
shouldEmitFunction(GlobalDecl GD)31390b57cec5SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
31400b57cec5SDimitry Andric   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
31410b57cec5SDimitry Andric     return true;
31420b57cec5SDimitry Andric   const auto *F = cast<FunctionDecl>(GD.getDecl());
31430b57cec5SDimitry Andric   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
31440b57cec5SDimitry Andric     return false;
31450b57cec5SDimitry Andric 
31465f7ddb14SDimitry Andric   if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
31470b57cec5SDimitry Andric     // Check whether it would be safe to inline this dllimport function.
31480b57cec5SDimitry Andric     DLLImportFunctionVisitor Visitor;
31490b57cec5SDimitry Andric     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
31500b57cec5SDimitry Andric     if (!Visitor.SafeToInline)
31510b57cec5SDimitry Andric       return false;
31520b57cec5SDimitry Andric 
31530b57cec5SDimitry Andric     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
31540b57cec5SDimitry Andric       // Implicit destructor invocations aren't captured in the AST, so the
31550b57cec5SDimitry Andric       // check above can't see them. Check for them manually here.
31560b57cec5SDimitry Andric       for (const Decl *Member : Dtor->getParent()->decls())
31570b57cec5SDimitry Andric         if (isa<FieldDecl>(Member))
31580b57cec5SDimitry Andric           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
31590b57cec5SDimitry Andric             return false;
31600b57cec5SDimitry Andric       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
31610b57cec5SDimitry Andric         if (HasNonDllImportDtor(B.getType()))
31620b57cec5SDimitry Andric           return false;
31630b57cec5SDimitry Andric     }
31640b57cec5SDimitry Andric   }
31650b57cec5SDimitry Andric 
31660b57cec5SDimitry Andric   // PR9614. Avoid cases where the source code is lying to us. An available
31670b57cec5SDimitry Andric   // externally function should have an equivalent function somewhere else,
31685ffd83dbSDimitry Andric   // but a function that calls itself through asm label/`__builtin_` trickery is
31695ffd83dbSDimitry Andric   // clearly not equivalent to the real implementation.
31700b57cec5SDimitry Andric   // This happens in glibc's btowc and in some configure checks.
31710b57cec5SDimitry Andric   return !isTriviallyRecursive(F);
31720b57cec5SDimitry Andric }
31730b57cec5SDimitry Andric 
shouldOpportunisticallyEmitVTables()31740b57cec5SDimitry Andric bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
31750b57cec5SDimitry Andric   return CodeGenOpts.OptimizationLevel > 0;
31760b57cec5SDimitry Andric }
31770b57cec5SDimitry Andric 
EmitMultiVersionFunctionDefinition(GlobalDecl GD,llvm::GlobalValue * GV)31780b57cec5SDimitry Andric void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
31790b57cec5SDimitry Andric                                                        llvm::GlobalValue *GV) {
31800b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
31810b57cec5SDimitry Andric 
31820b57cec5SDimitry Andric   if (FD->isCPUSpecificMultiVersion()) {
31830b57cec5SDimitry Andric     auto *Spec = FD->getAttr<CPUSpecificAttr>();
31840b57cec5SDimitry Andric     for (unsigned I = 0; I < Spec->cpus_size(); ++I)
31850b57cec5SDimitry Andric       EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
31860b57cec5SDimitry Andric     // Requires multiple emits.
31870b57cec5SDimitry Andric   } else
31880b57cec5SDimitry Andric     EmitGlobalFunctionDefinition(GD, GV);
31890b57cec5SDimitry Andric }
31900b57cec5SDimitry Andric 
EmitGlobalDefinition(GlobalDecl GD,llvm::GlobalValue * GV)31910b57cec5SDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
31920b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
31930b57cec5SDimitry Andric 
31940b57cec5SDimitry Andric   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
31950b57cec5SDimitry Andric                                  Context.getSourceManager(),
31960b57cec5SDimitry Andric                                  "Generating code for declaration");
31970b57cec5SDimitry Andric 
31980b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
31990b57cec5SDimitry Andric     // At -O0, don't generate IR for functions with available_externally
32000b57cec5SDimitry Andric     // linkage.
32010b57cec5SDimitry Andric     if (!shouldEmitFunction(GD))
32020b57cec5SDimitry Andric       return;
32030b57cec5SDimitry Andric 
32040b57cec5SDimitry Andric     llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
32050b57cec5SDimitry Andric       std::string Name;
32060b57cec5SDimitry Andric       llvm::raw_string_ostream OS(Name);
32070b57cec5SDimitry Andric       FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
32080b57cec5SDimitry Andric                                /*Qualified=*/true);
32090b57cec5SDimitry Andric       return Name;
32100b57cec5SDimitry Andric     });
32110b57cec5SDimitry Andric 
32120b57cec5SDimitry Andric     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
32130b57cec5SDimitry Andric       // Make sure to emit the definition(s) before we emit the thunks.
32140b57cec5SDimitry Andric       // This is necessary for the generation of certain thunks.
32150b57cec5SDimitry Andric       if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
32160b57cec5SDimitry Andric         ABI->emitCXXStructor(GD);
32170b57cec5SDimitry Andric       else if (FD->isMultiVersion())
32180b57cec5SDimitry Andric         EmitMultiVersionFunctionDefinition(GD, GV);
32190b57cec5SDimitry Andric       else
32200b57cec5SDimitry Andric         EmitGlobalFunctionDefinition(GD, GV);
32210b57cec5SDimitry Andric 
32220b57cec5SDimitry Andric       if (Method->isVirtual())
32230b57cec5SDimitry Andric         getVTables().EmitThunks(GD);
32240b57cec5SDimitry Andric 
32250b57cec5SDimitry Andric       return;
32260b57cec5SDimitry Andric     }
32270b57cec5SDimitry Andric 
32280b57cec5SDimitry Andric     if (FD->isMultiVersion())
32290b57cec5SDimitry Andric       return EmitMultiVersionFunctionDefinition(GD, GV);
32300b57cec5SDimitry Andric     return EmitGlobalFunctionDefinition(GD, GV);
32310b57cec5SDimitry Andric   }
32320b57cec5SDimitry Andric 
32330b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
32340b57cec5SDimitry Andric     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
32350b57cec5SDimitry Andric 
32360b57cec5SDimitry Andric   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
32370b57cec5SDimitry Andric }
32380b57cec5SDimitry Andric 
32390b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
32400b57cec5SDimitry Andric                                                       llvm::Function *NewFn);
32410b57cec5SDimitry Andric 
32420b57cec5SDimitry Andric static unsigned
TargetMVPriority(const TargetInfo & TI,const CodeGenFunction::MultiVersionResolverOption & RO)32430b57cec5SDimitry Andric TargetMVPriority(const TargetInfo &TI,
32440b57cec5SDimitry Andric                  const CodeGenFunction::MultiVersionResolverOption &RO) {
32450b57cec5SDimitry Andric   unsigned Priority = 0;
32460b57cec5SDimitry Andric   for (StringRef Feat : RO.Conditions.Features)
32470b57cec5SDimitry Andric     Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
32480b57cec5SDimitry Andric 
32490b57cec5SDimitry Andric   if (!RO.Conditions.Architecture.empty())
32500b57cec5SDimitry Andric     Priority = std::max(
32510b57cec5SDimitry Andric         Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
32520b57cec5SDimitry Andric   return Priority;
32530b57cec5SDimitry Andric }
32540b57cec5SDimitry Andric 
emitMultiVersionFunctions()32550b57cec5SDimitry Andric void CodeGenModule::emitMultiVersionFunctions() {
32565f7ddb14SDimitry Andric   std::vector<GlobalDecl> MVFuncsToEmit;
32575f7ddb14SDimitry Andric   MultiVersionFuncs.swap(MVFuncsToEmit);
32585f7ddb14SDimitry Andric   for (GlobalDecl GD : MVFuncsToEmit) {
32590b57cec5SDimitry Andric     SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
32600b57cec5SDimitry Andric     const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
32610b57cec5SDimitry Andric     getContext().forEachMultiversionedFunctionVersion(
32620b57cec5SDimitry Andric         FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
32630b57cec5SDimitry Andric           GlobalDecl CurGD{
32640b57cec5SDimitry Andric               (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
32650b57cec5SDimitry Andric           StringRef MangledName = getMangledName(CurGD);
32660b57cec5SDimitry Andric           llvm::Constant *Func = GetGlobalValue(MangledName);
32670b57cec5SDimitry Andric           if (!Func) {
32680b57cec5SDimitry Andric             if (CurFD->isDefined()) {
32690b57cec5SDimitry Andric               EmitGlobalFunctionDefinition(CurGD, nullptr);
32700b57cec5SDimitry Andric               Func = GetGlobalValue(MangledName);
32710b57cec5SDimitry Andric             } else {
32720b57cec5SDimitry Andric               const CGFunctionInfo &FI =
32730b57cec5SDimitry Andric                   getTypes().arrangeGlobalDeclaration(GD);
32740b57cec5SDimitry Andric               llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
32750b57cec5SDimitry Andric               Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
32760b57cec5SDimitry Andric                                        /*DontDefer=*/false, ForDefinition);
32770b57cec5SDimitry Andric             }
32780b57cec5SDimitry Andric             assert(Func && "This should have just been created");
32790b57cec5SDimitry Andric           }
32800b57cec5SDimitry Andric 
32810b57cec5SDimitry Andric           const auto *TA = CurFD->getAttr<TargetAttr>();
32820b57cec5SDimitry Andric           llvm::SmallVector<StringRef, 8> Feats;
32830b57cec5SDimitry Andric           TA->getAddedFeatures(Feats);
32840b57cec5SDimitry Andric 
32850b57cec5SDimitry Andric           Options.emplace_back(cast<llvm::Function>(Func),
32860b57cec5SDimitry Andric                                TA->getArchitecture(), Feats);
32870b57cec5SDimitry Andric         });
32880b57cec5SDimitry Andric 
32890b57cec5SDimitry Andric     llvm::Function *ResolverFunc;
32900b57cec5SDimitry Andric     const TargetInfo &TI = getTarget();
32910b57cec5SDimitry Andric 
3292a7dea167SDimitry Andric     if (TI.supportsIFunc() || FD->isTargetMultiVersion()) {
32930b57cec5SDimitry Andric       ResolverFunc = cast<llvm::Function>(
32940b57cec5SDimitry Andric           GetGlobalValue((getMangledName(GD) + ".resolver").str()));
3295a7dea167SDimitry Andric       ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
3296a7dea167SDimitry Andric     } else {
32970b57cec5SDimitry Andric       ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
3298a7dea167SDimitry Andric     }
32990b57cec5SDimitry Andric 
33000b57cec5SDimitry Andric     if (supportsCOMDAT())
33010b57cec5SDimitry Andric       ResolverFunc->setComdat(
33020b57cec5SDimitry Andric           getModule().getOrInsertComdat(ResolverFunc->getName()));
33030b57cec5SDimitry Andric 
33040b57cec5SDimitry Andric     llvm::stable_sort(
33050b57cec5SDimitry Andric         Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
33060b57cec5SDimitry Andric                        const CodeGenFunction::MultiVersionResolverOption &RHS) {
33070b57cec5SDimitry Andric           return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
33080b57cec5SDimitry Andric         });
33090b57cec5SDimitry Andric     CodeGenFunction CGF(*this);
33100b57cec5SDimitry Andric     CGF.EmitMultiVersionResolver(ResolverFunc, Options);
33110b57cec5SDimitry Andric   }
33125f7ddb14SDimitry Andric 
33135f7ddb14SDimitry Andric   // Ensure that any additions to the deferred decls list caused by emitting a
33145f7ddb14SDimitry Andric   // variant are emitted.  This can happen when the variant itself is inline and
33155f7ddb14SDimitry Andric   // calls a function without linkage.
33165f7ddb14SDimitry Andric   if (!MVFuncsToEmit.empty())
33175f7ddb14SDimitry Andric     EmitDeferred();
33185f7ddb14SDimitry Andric 
33195f7ddb14SDimitry Andric   // Ensure that any additions to the multiversion funcs list from either the
33205f7ddb14SDimitry Andric   // deferred decls or the multiversion functions themselves are emitted.
33215f7ddb14SDimitry Andric   if (!MultiVersionFuncs.empty())
33225f7ddb14SDimitry Andric     emitMultiVersionFunctions();
33230b57cec5SDimitry Andric }
33240b57cec5SDimitry Andric 
emitCPUDispatchDefinition(GlobalDecl GD)33250b57cec5SDimitry Andric void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
33260b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
33270b57cec5SDimitry Andric   assert(FD && "Not a FunctionDecl?");
33280b57cec5SDimitry Andric   const auto *DD = FD->getAttr<CPUDispatchAttr>();
33290b57cec5SDimitry Andric   assert(DD && "Not a cpu_dispatch Function?");
33300b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
33310b57cec5SDimitry Andric 
33320b57cec5SDimitry Andric   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
33330b57cec5SDimitry Andric     const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
33340b57cec5SDimitry Andric     DeclTy = getTypes().GetFunctionType(FInfo);
33350b57cec5SDimitry Andric   }
33360b57cec5SDimitry Andric 
33370b57cec5SDimitry Andric   StringRef ResolverName = getMangledName(GD);
33380b57cec5SDimitry Andric 
33390b57cec5SDimitry Andric   llvm::Type *ResolverType;
33400b57cec5SDimitry Andric   GlobalDecl ResolverGD;
33410b57cec5SDimitry Andric   if (getTarget().supportsIFunc())
33420b57cec5SDimitry Andric     ResolverType = llvm::FunctionType::get(
33430b57cec5SDimitry Andric         llvm::PointerType::get(DeclTy,
33440b57cec5SDimitry Andric                                Context.getTargetAddressSpace(FD->getType())),
33450b57cec5SDimitry Andric         false);
33460b57cec5SDimitry Andric   else {
33470b57cec5SDimitry Andric     ResolverType = DeclTy;
33480b57cec5SDimitry Andric     ResolverGD = GD;
33490b57cec5SDimitry Andric   }
33500b57cec5SDimitry Andric 
33510b57cec5SDimitry Andric   auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
33520b57cec5SDimitry Andric       ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
3353a7dea167SDimitry Andric   ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
3354a7dea167SDimitry Andric   if (supportsCOMDAT())
3355a7dea167SDimitry Andric     ResolverFunc->setComdat(
3356a7dea167SDimitry Andric         getModule().getOrInsertComdat(ResolverFunc->getName()));
33570b57cec5SDimitry Andric 
33580b57cec5SDimitry Andric   SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
33590b57cec5SDimitry Andric   const TargetInfo &Target = getTarget();
33600b57cec5SDimitry Andric   unsigned Index = 0;
33610b57cec5SDimitry Andric   for (const IdentifierInfo *II : DD->cpus()) {
33620b57cec5SDimitry Andric     // Get the name of the target function so we can look it up/create it.
33630b57cec5SDimitry Andric     std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
33640b57cec5SDimitry Andric                               getCPUSpecificMangling(*this, II->getName());
33650b57cec5SDimitry Andric 
33660b57cec5SDimitry Andric     llvm::Constant *Func = GetGlobalValue(MangledName);
33670b57cec5SDimitry Andric 
33680b57cec5SDimitry Andric     if (!Func) {
33690b57cec5SDimitry Andric       GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
33700b57cec5SDimitry Andric       if (ExistingDecl.getDecl() &&
33710b57cec5SDimitry Andric           ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
33720b57cec5SDimitry Andric         EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
33730b57cec5SDimitry Andric         Func = GetGlobalValue(MangledName);
33740b57cec5SDimitry Andric       } else {
33750b57cec5SDimitry Andric         if (!ExistingDecl.getDecl())
33760b57cec5SDimitry Andric           ExistingDecl = GD.getWithMultiVersionIndex(Index);
33770b57cec5SDimitry Andric 
33780b57cec5SDimitry Andric       Func = GetOrCreateLLVMFunction(
33790b57cec5SDimitry Andric           MangledName, DeclTy, ExistingDecl,
33800b57cec5SDimitry Andric           /*ForVTable=*/false, /*DontDefer=*/true,
33810b57cec5SDimitry Andric           /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
33820b57cec5SDimitry Andric       }
33830b57cec5SDimitry Andric     }
33840b57cec5SDimitry Andric 
33850b57cec5SDimitry Andric     llvm::SmallVector<StringRef, 32> Features;
33860b57cec5SDimitry Andric     Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
33870b57cec5SDimitry Andric     llvm::transform(Features, Features.begin(),
33880b57cec5SDimitry Andric                     [](StringRef Str) { return Str.substr(1); });
33890b57cec5SDimitry Andric     Features.erase(std::remove_if(
33900b57cec5SDimitry Andric         Features.begin(), Features.end(), [&Target](StringRef Feat) {
33910b57cec5SDimitry Andric           return !Target.validateCpuSupports(Feat);
33920b57cec5SDimitry Andric         }), Features.end());
33930b57cec5SDimitry Andric     Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
33940b57cec5SDimitry Andric     ++Index;
33950b57cec5SDimitry Andric   }
33960b57cec5SDimitry Andric 
33975f7ddb14SDimitry Andric   llvm::stable_sort(
33980b57cec5SDimitry Andric       Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
33990b57cec5SDimitry Andric                   const CodeGenFunction::MultiVersionResolverOption &RHS) {
34000b57cec5SDimitry Andric         return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
34010b57cec5SDimitry Andric                CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
34020b57cec5SDimitry Andric       });
34030b57cec5SDimitry Andric 
34040b57cec5SDimitry Andric   // If the list contains multiple 'default' versions, such as when it contains
34050b57cec5SDimitry Andric   // 'pentium' and 'generic', don't emit the call to the generic one (since we
34060b57cec5SDimitry Andric   // always run on at least a 'pentium'). We do this by deleting the 'least
34070b57cec5SDimitry Andric   // advanced' (read, lowest mangling letter).
34080b57cec5SDimitry Andric   while (Options.size() > 1 &&
34090b57cec5SDimitry Andric          CodeGenFunction::GetX86CpuSupportsMask(
34100b57cec5SDimitry Andric              (Options.end() - 2)->Conditions.Features) == 0) {
34110b57cec5SDimitry Andric     StringRef LHSName = (Options.end() - 2)->Function->getName();
34120b57cec5SDimitry Andric     StringRef RHSName = (Options.end() - 1)->Function->getName();
34130b57cec5SDimitry Andric     if (LHSName.compare(RHSName) < 0)
34140b57cec5SDimitry Andric       Options.erase(Options.end() - 2);
34150b57cec5SDimitry Andric     else
34160b57cec5SDimitry Andric       Options.erase(Options.end() - 1);
34170b57cec5SDimitry Andric   }
34180b57cec5SDimitry Andric 
34190b57cec5SDimitry Andric   CodeGenFunction CGF(*this);
34200b57cec5SDimitry Andric   CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3421a7dea167SDimitry Andric 
3422a7dea167SDimitry Andric   if (getTarget().supportsIFunc()) {
3423a7dea167SDimitry Andric     std::string AliasName = getMangledNameImpl(
3424a7dea167SDimitry Andric         *this, GD, FD, /*OmitMultiVersionMangling=*/true);
3425a7dea167SDimitry Andric     llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
3426a7dea167SDimitry Andric     if (!AliasFunc) {
3427a7dea167SDimitry Andric       auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction(
3428a7dea167SDimitry Andric           AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true,
3429a7dea167SDimitry Andric           /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition));
3430a7dea167SDimitry Andric       auto *GA = llvm::GlobalAlias::create(
3431a7dea167SDimitry Andric          DeclTy, 0, getFunctionLinkage(GD), AliasName, IFunc, &getModule());
3432a7dea167SDimitry Andric       GA->setLinkage(llvm::Function::WeakODRLinkage);
3433a7dea167SDimitry Andric       SetCommonAttributes(GD, GA);
3434a7dea167SDimitry Andric     }
3435a7dea167SDimitry Andric   }
34360b57cec5SDimitry Andric }
34370b57cec5SDimitry Andric 
34380b57cec5SDimitry Andric /// If a dispatcher for the specified mangled name is not in the module, create
34390b57cec5SDimitry Andric /// and return an llvm Function with the specified type.
GetOrCreateMultiVersionResolver(GlobalDecl GD,llvm::Type * DeclTy,const FunctionDecl * FD)34400b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
34410b57cec5SDimitry Andric     GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
34420b57cec5SDimitry Andric   std::string MangledName =
34430b57cec5SDimitry Andric       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
34440b57cec5SDimitry Andric 
34450b57cec5SDimitry Andric   // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
34460b57cec5SDimitry Andric   // a separate resolver).
34470b57cec5SDimitry Andric   std::string ResolverName = MangledName;
34480b57cec5SDimitry Andric   if (getTarget().supportsIFunc())
34490b57cec5SDimitry Andric     ResolverName += ".ifunc";
34500b57cec5SDimitry Andric   else if (FD->isTargetMultiVersion())
34510b57cec5SDimitry Andric     ResolverName += ".resolver";
34520b57cec5SDimitry Andric 
34530b57cec5SDimitry Andric   // If this already exists, just return that one.
34540b57cec5SDimitry Andric   if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
34550b57cec5SDimitry Andric     return ResolverGV;
34560b57cec5SDimitry Andric 
34570b57cec5SDimitry Andric   // Since this is the first time we've created this IFunc, make sure
34580b57cec5SDimitry Andric   // that we put this multiversioned function into the list to be
34590b57cec5SDimitry Andric   // replaced later if necessary (target multiversioning only).
34600b57cec5SDimitry Andric   if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
34610b57cec5SDimitry Andric     MultiVersionFuncs.push_back(GD);
34620b57cec5SDimitry Andric 
34630b57cec5SDimitry Andric   if (getTarget().supportsIFunc()) {
34640b57cec5SDimitry Andric     llvm::Type *ResolverType = llvm::FunctionType::get(
34650b57cec5SDimitry Andric         llvm::PointerType::get(
34660b57cec5SDimitry Andric             DeclTy, getContext().getTargetAddressSpace(FD->getType())),
34670b57cec5SDimitry Andric         false);
34680b57cec5SDimitry Andric     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
34690b57cec5SDimitry Andric         MangledName + ".resolver", ResolverType, GlobalDecl{},
34700b57cec5SDimitry Andric         /*ForVTable=*/false);
34710b57cec5SDimitry Andric     llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
3472a7dea167SDimitry Andric         DeclTy, 0, llvm::Function::WeakODRLinkage, "", Resolver, &getModule());
34730b57cec5SDimitry Andric     GIF->setName(ResolverName);
34740b57cec5SDimitry Andric     SetCommonAttributes(FD, GIF);
34750b57cec5SDimitry Andric 
34760b57cec5SDimitry Andric     return GIF;
34770b57cec5SDimitry Andric   }
34780b57cec5SDimitry Andric 
34790b57cec5SDimitry Andric   llvm::Constant *Resolver = GetOrCreateLLVMFunction(
34800b57cec5SDimitry Andric       ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
34810b57cec5SDimitry Andric   assert(isa<llvm::GlobalValue>(Resolver) &&
34820b57cec5SDimitry Andric          "Resolver should be created for the first time");
34830b57cec5SDimitry Andric   SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
34840b57cec5SDimitry Andric   return Resolver;
34850b57cec5SDimitry Andric }
34860b57cec5SDimitry Andric 
34870b57cec5SDimitry Andric /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
34880b57cec5SDimitry Andric /// module, create and return an llvm Function with the specified type. If there
34890b57cec5SDimitry Andric /// is something in the module with the specified name, return it potentially
34900b57cec5SDimitry Andric /// bitcasted to the right type.
34910b57cec5SDimitry Andric ///
34920b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this.  This is used
34930b57cec5SDimitry Andric /// to set the attributes on the function when it is first created.
GetOrCreateLLVMFunction(StringRef MangledName,llvm::Type * Ty,GlobalDecl GD,bool ForVTable,bool DontDefer,bool IsThunk,llvm::AttributeList ExtraAttrs,ForDefinition_t IsForDefinition)34940b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
34950b57cec5SDimitry Andric     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
34960b57cec5SDimitry Andric     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
34970b57cec5SDimitry Andric     ForDefinition_t IsForDefinition) {
34980b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
34990b57cec5SDimitry Andric 
35000b57cec5SDimitry Andric   // Any attempts to use a MultiVersion function should result in retrieving
35010b57cec5SDimitry Andric   // the iFunc instead. Name Mangling will handle the rest of the changes.
35020b57cec5SDimitry Andric   if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
35030b57cec5SDimitry Andric     // For the device mark the function as one that should be emitted.
35040b57cec5SDimitry Andric     if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
35050b57cec5SDimitry Andric         !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
35060b57cec5SDimitry Andric         !DontDefer && !IsForDefinition) {
35070b57cec5SDimitry Andric       if (const FunctionDecl *FDDef = FD->getDefinition()) {
35080b57cec5SDimitry Andric         GlobalDecl GDDef;
35090b57cec5SDimitry Andric         if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
35100b57cec5SDimitry Andric           GDDef = GlobalDecl(CD, GD.getCtorType());
35110b57cec5SDimitry Andric         else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
35120b57cec5SDimitry Andric           GDDef = GlobalDecl(DD, GD.getDtorType());
35130b57cec5SDimitry Andric         else
35140b57cec5SDimitry Andric           GDDef = GlobalDecl(FDDef);
35150b57cec5SDimitry Andric         EmitGlobal(GDDef);
35160b57cec5SDimitry Andric       }
35170b57cec5SDimitry Andric     }
35180b57cec5SDimitry Andric 
35190b57cec5SDimitry Andric     if (FD->isMultiVersion()) {
35205ffd83dbSDimitry Andric       if (FD->hasAttr<TargetAttr>())
35210b57cec5SDimitry Andric         UpdateMultiVersionNames(GD, FD);
35220b57cec5SDimitry Andric       if (!IsForDefinition)
35230b57cec5SDimitry Andric         return GetOrCreateMultiVersionResolver(GD, Ty, FD);
35240b57cec5SDimitry Andric     }
35250b57cec5SDimitry Andric   }
35260b57cec5SDimitry Andric 
35270b57cec5SDimitry Andric   // Lookup the entry, lazily creating it if necessary.
35280b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
35290b57cec5SDimitry Andric   if (Entry) {
35300b57cec5SDimitry Andric     if (WeakRefReferences.erase(Entry)) {
35310b57cec5SDimitry Andric       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
35320b57cec5SDimitry Andric       if (FD && !FD->hasAttr<WeakAttr>())
35330b57cec5SDimitry Andric         Entry->setLinkage(llvm::Function::ExternalLinkage);
35340b57cec5SDimitry Andric     }
35350b57cec5SDimitry Andric 
35360b57cec5SDimitry Andric     // Handle dropped DLL attributes.
35370b57cec5SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
35380b57cec5SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
35390b57cec5SDimitry Andric       setDSOLocal(Entry);
35400b57cec5SDimitry Andric     }
35410b57cec5SDimitry Andric 
35420b57cec5SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
35430b57cec5SDimitry Andric     // error.
35440b57cec5SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
35450b57cec5SDimitry Andric       GlobalDecl OtherGD;
35460b57cec5SDimitry Andric       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
35470b57cec5SDimitry Andric       // to make sure that we issue an error only once.
35480b57cec5SDimitry Andric       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
35490b57cec5SDimitry Andric           (GD.getCanonicalDecl().getDecl() !=
35500b57cec5SDimitry Andric            OtherGD.getCanonicalDecl().getDecl()) &&
35510b57cec5SDimitry Andric           DiagnosedConflictingDefinitions.insert(GD).second) {
35520b57cec5SDimitry Andric         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
35530b57cec5SDimitry Andric             << MangledName;
35540b57cec5SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
35550b57cec5SDimitry Andric                           diag::note_previous_definition);
35560b57cec5SDimitry Andric       }
35570b57cec5SDimitry Andric     }
35580b57cec5SDimitry Andric 
35590b57cec5SDimitry Andric     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
35605ffd83dbSDimitry Andric         (Entry->getValueType() == Ty)) {
35610b57cec5SDimitry Andric       return Entry;
35620b57cec5SDimitry Andric     }
35630b57cec5SDimitry Andric 
35640b57cec5SDimitry Andric     // Make sure the result is of the correct type.
35650b57cec5SDimitry Andric     // (If function is requested for a definition, we always need to create a new
35660b57cec5SDimitry Andric     // function, not just return a bitcast.)
35670b57cec5SDimitry Andric     if (!IsForDefinition)
35680b57cec5SDimitry Andric       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
35690b57cec5SDimitry Andric   }
35700b57cec5SDimitry Andric 
35710b57cec5SDimitry Andric   // This function doesn't have a complete type (for example, the return
35720b57cec5SDimitry Andric   // type is an incomplete struct). Use a fake type instead, and make
35730b57cec5SDimitry Andric   // sure not to try to set attributes.
35740b57cec5SDimitry Andric   bool IsIncompleteFunction = false;
35750b57cec5SDimitry Andric 
35760b57cec5SDimitry Andric   llvm::FunctionType *FTy;
35770b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(Ty)) {
35780b57cec5SDimitry Andric     FTy = cast<llvm::FunctionType>(Ty);
35790b57cec5SDimitry Andric   } else {
35800b57cec5SDimitry Andric     FTy = llvm::FunctionType::get(VoidTy, false);
35810b57cec5SDimitry Andric     IsIncompleteFunction = true;
35820b57cec5SDimitry Andric   }
35830b57cec5SDimitry Andric 
35840b57cec5SDimitry Andric   llvm::Function *F =
35850b57cec5SDimitry Andric       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
35860b57cec5SDimitry Andric                              Entry ? StringRef() : MangledName, &getModule());
35870b57cec5SDimitry Andric 
35880b57cec5SDimitry Andric   // If we already created a function with the same mangled name (but different
35890b57cec5SDimitry Andric   // type) before, take its name and add it to the list of functions to be
35900b57cec5SDimitry Andric   // replaced with F at the end of CodeGen.
35910b57cec5SDimitry Andric   //
35920b57cec5SDimitry Andric   // This happens if there is a prototype for a function (e.g. "int f()") and
35930b57cec5SDimitry Andric   // then a definition of a different type (e.g. "int f(int x)").
35940b57cec5SDimitry Andric   if (Entry) {
35950b57cec5SDimitry Andric     F->takeName(Entry);
35960b57cec5SDimitry Andric 
35970b57cec5SDimitry Andric     // This might be an implementation of a function without a prototype, in
35980b57cec5SDimitry Andric     // which case, try to do special replacement of calls which match the new
35990b57cec5SDimitry Andric     // prototype.  The really key thing here is that we also potentially drop
36000b57cec5SDimitry Andric     // arguments from the call site so as to make a direct call, which makes the
36010b57cec5SDimitry Andric     // inliner happier and suppresses a number of optimizer warnings (!) about
36020b57cec5SDimitry Andric     // dropping arguments.
36030b57cec5SDimitry Andric     if (!Entry->use_empty()) {
36040b57cec5SDimitry Andric       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
36050b57cec5SDimitry Andric       Entry->removeDeadConstantUsers();
36060b57cec5SDimitry Andric     }
36070b57cec5SDimitry Andric 
36080b57cec5SDimitry Andric     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
36095ffd83dbSDimitry Andric         F, Entry->getValueType()->getPointerTo());
36100b57cec5SDimitry Andric     addGlobalValReplacement(Entry, BC);
36110b57cec5SDimitry Andric   }
36120b57cec5SDimitry Andric 
36130b57cec5SDimitry Andric   assert(F->getName() == MangledName && "name was uniqued!");
36140b57cec5SDimitry Andric   if (D)
36150b57cec5SDimitry Andric     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
36160b57cec5SDimitry Andric   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
36170b57cec5SDimitry Andric     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
36180b57cec5SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
36190b57cec5SDimitry Andric   }
36200b57cec5SDimitry Andric 
36210b57cec5SDimitry Andric   if (!DontDefer) {
36220b57cec5SDimitry Andric     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
36230b57cec5SDimitry Andric     // each other bottoming out with the base dtor.  Therefore we emit non-base
36240b57cec5SDimitry Andric     // dtors on usage, even if there is no dtor definition in the TU.
36250b57cec5SDimitry Andric     if (D && isa<CXXDestructorDecl>(D) &&
36260b57cec5SDimitry Andric         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
36270b57cec5SDimitry Andric                                            GD.getDtorType()))
36280b57cec5SDimitry Andric       addDeferredDeclToEmit(GD);
36290b57cec5SDimitry Andric 
36300b57cec5SDimitry Andric     // This is the first use or definition of a mangled name.  If there is a
36310b57cec5SDimitry Andric     // deferred decl with this name, remember that we need to emit it at the end
36320b57cec5SDimitry Andric     // of the file.
36330b57cec5SDimitry Andric     auto DDI = DeferredDecls.find(MangledName);
36340b57cec5SDimitry Andric     if (DDI != DeferredDecls.end()) {
36350b57cec5SDimitry Andric       // Move the potentially referenced deferred decl to the
36360b57cec5SDimitry Andric       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
36370b57cec5SDimitry Andric       // don't need it anymore).
36380b57cec5SDimitry Andric       addDeferredDeclToEmit(DDI->second);
36390b57cec5SDimitry Andric       DeferredDecls.erase(DDI);
36400b57cec5SDimitry Andric 
36410b57cec5SDimitry Andric       // Otherwise, there are cases we have to worry about where we're
36420b57cec5SDimitry Andric       // using a declaration for which we must emit a definition but where
36430b57cec5SDimitry Andric       // we might not find a top-level definition:
36440b57cec5SDimitry Andric       //   - member functions defined inline in their classes
36450b57cec5SDimitry Andric       //   - friend functions defined inline in some class
36460b57cec5SDimitry Andric       //   - special member functions with implicit definitions
36470b57cec5SDimitry Andric       // If we ever change our AST traversal to walk into class methods,
36480b57cec5SDimitry Andric       // this will be unnecessary.
36490b57cec5SDimitry Andric       //
36500b57cec5SDimitry Andric       // We also don't emit a definition for a function if it's going to be an
36510b57cec5SDimitry Andric       // entry in a vtable, unless it's already marked as used.
36520b57cec5SDimitry Andric     } else if (getLangOpts().CPlusPlus && D) {
36530b57cec5SDimitry Andric       // Look for a declaration that's lexically in a record.
36540b57cec5SDimitry Andric       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
36550b57cec5SDimitry Andric            FD = FD->getPreviousDecl()) {
36560b57cec5SDimitry Andric         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
36570b57cec5SDimitry Andric           if (FD->doesThisDeclarationHaveABody()) {
36580b57cec5SDimitry Andric             addDeferredDeclToEmit(GD.getWithDecl(FD));
36590b57cec5SDimitry Andric             break;
36600b57cec5SDimitry Andric           }
36610b57cec5SDimitry Andric         }
36620b57cec5SDimitry Andric       }
36630b57cec5SDimitry Andric     }
36640b57cec5SDimitry Andric   }
36650b57cec5SDimitry Andric 
36660b57cec5SDimitry Andric   // Make sure the result is of the requested type.
36670b57cec5SDimitry Andric   if (!IsIncompleteFunction) {
36685ffd83dbSDimitry Andric     assert(F->getFunctionType() == Ty);
36690b57cec5SDimitry Andric     return F;
36700b57cec5SDimitry Andric   }
36710b57cec5SDimitry Andric 
36720b57cec5SDimitry Andric   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
36730b57cec5SDimitry Andric   return llvm::ConstantExpr::getBitCast(F, PTy);
36740b57cec5SDimitry Andric }
36750b57cec5SDimitry Andric 
36760b57cec5SDimitry Andric /// GetAddrOfFunction - Return the address of the given function.  If Ty is
36770b57cec5SDimitry Andric /// non-null, then this function will use the specified type if it has to
36780b57cec5SDimitry Andric /// create it (this occurs when we see a definition of the function).
GetAddrOfFunction(GlobalDecl GD,llvm::Type * Ty,bool ForVTable,bool DontDefer,ForDefinition_t IsForDefinition)36790b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
36800b57cec5SDimitry Andric                                                  llvm::Type *Ty,
36810b57cec5SDimitry Andric                                                  bool ForVTable,
36820b57cec5SDimitry Andric                                                  bool DontDefer,
36830b57cec5SDimitry Andric                                               ForDefinition_t IsForDefinition) {
36845ffd83dbSDimitry Andric   assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() &&
36855ffd83dbSDimitry Andric          "consteval function should never be emitted");
36860b57cec5SDimitry Andric   // If there was no specific requested type, just convert it now.
36870b57cec5SDimitry Andric   if (!Ty) {
36880b57cec5SDimitry Andric     const auto *FD = cast<FunctionDecl>(GD.getDecl());
36890b57cec5SDimitry Andric     Ty = getTypes().ConvertType(FD->getType());
36900b57cec5SDimitry Andric   }
36910b57cec5SDimitry Andric 
36920b57cec5SDimitry Andric   // Devirtualized destructor calls may come through here instead of via
36930b57cec5SDimitry Andric   // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
36940b57cec5SDimitry Andric   // of the complete destructor when necessary.
36950b57cec5SDimitry Andric   if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
36960b57cec5SDimitry Andric     if (getTarget().getCXXABI().isMicrosoft() &&
36970b57cec5SDimitry Andric         GD.getDtorType() == Dtor_Complete &&
36980b57cec5SDimitry Andric         DD->getParent()->getNumVBases() == 0)
36990b57cec5SDimitry Andric       GD = GlobalDecl(DD, Dtor_Base);
37000b57cec5SDimitry Andric   }
37010b57cec5SDimitry Andric 
37020b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
37035f7ddb14SDimitry Andric   auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
37040b57cec5SDimitry Andric                                     /*IsThunk=*/false, llvm::AttributeList(),
37050b57cec5SDimitry Andric                                     IsForDefinition);
37065f7ddb14SDimitry Andric   // Returns kernel handle for HIP kernel stub function.
37075f7ddb14SDimitry Andric   if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
37085f7ddb14SDimitry Andric       cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) {
37095f7ddb14SDimitry Andric     auto *Handle = getCUDARuntime().getKernelHandle(
37105f7ddb14SDimitry Andric         cast<llvm::Function>(F->stripPointerCasts()), GD);
37115f7ddb14SDimitry Andric     if (IsForDefinition)
37125f7ddb14SDimitry Andric       return F;
37135f7ddb14SDimitry Andric     return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo());
37145f7ddb14SDimitry Andric   }
37155f7ddb14SDimitry Andric   return F;
37160b57cec5SDimitry Andric }
37170b57cec5SDimitry Andric 
37180b57cec5SDimitry Andric static const FunctionDecl *
GetRuntimeFunctionDecl(ASTContext & C,StringRef Name)37190b57cec5SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
37200b57cec5SDimitry Andric   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
37210b57cec5SDimitry Andric   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
37220b57cec5SDimitry Andric 
37230b57cec5SDimitry Andric   IdentifierInfo &CII = C.Idents.get(Name);
37245f7ddb14SDimitry Andric   for (const auto *Result : DC->lookup(&CII))
37255f7ddb14SDimitry Andric     if (const auto *FD = dyn_cast<FunctionDecl>(Result))
37260b57cec5SDimitry Andric       return FD;
37270b57cec5SDimitry Andric 
37280b57cec5SDimitry Andric   if (!C.getLangOpts().CPlusPlus)
37290b57cec5SDimitry Andric     return nullptr;
37300b57cec5SDimitry Andric 
37310b57cec5SDimitry Andric   // Demangle the premangled name from getTerminateFn()
37320b57cec5SDimitry Andric   IdentifierInfo &CXXII =
37330b57cec5SDimitry Andric       (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
37340b57cec5SDimitry Andric           ? C.Idents.get("terminate")
37350b57cec5SDimitry Andric           : C.Idents.get(Name);
37360b57cec5SDimitry Andric 
37370b57cec5SDimitry Andric   for (const auto &N : {"__cxxabiv1", "std"}) {
37380b57cec5SDimitry Andric     IdentifierInfo &NS = C.Idents.get(N);
37395f7ddb14SDimitry Andric     for (const auto *Result : DC->lookup(&NS)) {
37405f7ddb14SDimitry Andric       const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
37415f7ddb14SDimitry Andric       if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
37425f7ddb14SDimitry Andric         for (const auto *Result : LSD->lookup(&NS))
37430b57cec5SDimitry Andric           if ((ND = dyn_cast<NamespaceDecl>(Result)))
37440b57cec5SDimitry Andric             break;
37450b57cec5SDimitry Andric 
37460b57cec5SDimitry Andric       if (ND)
37475f7ddb14SDimitry Andric         for (const auto *Result : ND->lookup(&CXXII))
37480b57cec5SDimitry Andric           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
37490b57cec5SDimitry Andric             return FD;
37500b57cec5SDimitry Andric     }
37510b57cec5SDimitry Andric   }
37520b57cec5SDimitry Andric 
37530b57cec5SDimitry Andric   return nullptr;
37540b57cec5SDimitry Andric }
37550b57cec5SDimitry Andric 
37560b57cec5SDimitry Andric /// CreateRuntimeFunction - Create a new runtime function with the specified
37570b57cec5SDimitry Andric /// type and name.
37580b57cec5SDimitry Andric llvm::FunctionCallee
CreateRuntimeFunction(llvm::FunctionType * FTy,StringRef Name,llvm::AttributeList ExtraAttrs,bool Local,bool AssumeConvergent)37590b57cec5SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
3760480093f4SDimitry Andric                                      llvm::AttributeList ExtraAttrs, bool Local,
3761480093f4SDimitry Andric                                      bool AssumeConvergent) {
3762480093f4SDimitry Andric   if (AssumeConvergent) {
3763480093f4SDimitry Andric     ExtraAttrs =
3764480093f4SDimitry Andric         ExtraAttrs.addAttribute(VMContext, llvm::AttributeList::FunctionIndex,
3765480093f4SDimitry Andric                                 llvm::Attribute::Convergent);
3766480093f4SDimitry Andric   }
3767480093f4SDimitry Andric 
37680b57cec5SDimitry Andric   llvm::Constant *C =
37690b57cec5SDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
37700b57cec5SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false,
37710b57cec5SDimitry Andric                               ExtraAttrs);
37720b57cec5SDimitry Andric 
37730b57cec5SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C)) {
37740b57cec5SDimitry Andric     if (F->empty()) {
37750b57cec5SDimitry Andric       F->setCallingConv(getRuntimeCC());
37760b57cec5SDimitry Andric 
37770b57cec5SDimitry Andric       // In Windows Itanium environments, try to mark runtime functions
37780b57cec5SDimitry Andric       // dllimport. For Mingw and MSVC, don't. We don't really know if the user
37790b57cec5SDimitry Andric       // will link their standard library statically or dynamically. Marking
37800b57cec5SDimitry Andric       // functions imported when they are not imported can cause linker errors
37810b57cec5SDimitry Andric       // and warnings.
37820b57cec5SDimitry Andric       if (!Local && getTriple().isWindowsItaniumEnvironment() &&
37830b57cec5SDimitry Andric           !getCodeGenOpts().LTOVisibilityPublicStd) {
37840b57cec5SDimitry Andric         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
37850b57cec5SDimitry Andric         if (!FD || FD->hasAttr<DLLImportAttr>()) {
37860b57cec5SDimitry Andric           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
37870b57cec5SDimitry Andric           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
37880b57cec5SDimitry Andric         }
37890b57cec5SDimitry Andric       }
37900b57cec5SDimitry Andric       setDSOLocal(F);
37910b57cec5SDimitry Andric     }
37920b57cec5SDimitry Andric   }
37930b57cec5SDimitry Andric 
37940b57cec5SDimitry Andric   return {FTy, C};
37950b57cec5SDimitry Andric }
37960b57cec5SDimitry Andric 
37970b57cec5SDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted
37980b57cec5SDimitry Andric /// as a constant.
37990b57cec5SDimitry Andric ///
38000b57cec5SDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs
38010b57cec5SDimitry Andric /// will not be considered. The caller will need to verify that the object is
38020b57cec5SDimitry Andric /// not written to during its construction.
isTypeConstant(QualType Ty,bool ExcludeCtor)38030b57cec5SDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
38040b57cec5SDimitry Andric   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
38050b57cec5SDimitry Andric     return false;
38060b57cec5SDimitry Andric 
38070b57cec5SDimitry Andric   if (Context.getLangOpts().CPlusPlus) {
38080b57cec5SDimitry Andric     if (const CXXRecordDecl *Record
38090b57cec5SDimitry Andric           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
38100b57cec5SDimitry Andric       return ExcludeCtor && !Record->hasMutableFields() &&
38110b57cec5SDimitry Andric              Record->hasTrivialDestructor();
38120b57cec5SDimitry Andric   }
38130b57cec5SDimitry Andric 
38140b57cec5SDimitry Andric   return true;
38150b57cec5SDimitry Andric }
38160b57cec5SDimitry Andric 
38170b57cec5SDimitry Andric /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
38185f7ddb14SDimitry Andric /// create and return an llvm GlobalVariable with the specified type and address
38195f7ddb14SDimitry Andric /// space. If there is something in the module with the specified name, return
38205f7ddb14SDimitry Andric /// it potentially bitcasted to the right type.
38210b57cec5SDimitry Andric ///
38220b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this.  This is used
38230b57cec5SDimitry Andric /// to set the attributes on the global when it is first created.
38240b57cec5SDimitry Andric ///
38250b57cec5SDimitry Andric /// If IsForDefinition is true, it is guaranteed that an actual global with
38260b57cec5SDimitry Andric /// type Ty will be returned, not conversion of a variable with the same
38270b57cec5SDimitry Andric /// mangled name but some other type.
38280b57cec5SDimitry Andric llvm::Constant *
GetOrCreateLLVMGlobal(StringRef MangledName,llvm::Type * Ty,unsigned AddrSpace,const VarDecl * D,ForDefinition_t IsForDefinition)38295f7ddb14SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty,
38305f7ddb14SDimitry Andric                                      unsigned AddrSpace, const VarDecl *D,
38310b57cec5SDimitry Andric                                      ForDefinition_t IsForDefinition) {
38320b57cec5SDimitry Andric   // Lookup the entry, lazily creating it if necessary.
38330b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
38340b57cec5SDimitry Andric   if (Entry) {
38350b57cec5SDimitry Andric     if (WeakRefReferences.erase(Entry)) {
38360b57cec5SDimitry Andric       if (D && !D->hasAttr<WeakAttr>())
38370b57cec5SDimitry Andric         Entry->setLinkage(llvm::Function::ExternalLinkage);
38380b57cec5SDimitry Andric     }
38390b57cec5SDimitry Andric 
38400b57cec5SDimitry Andric     // Handle dropped DLL attributes.
38410b57cec5SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
38420b57cec5SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
38430b57cec5SDimitry Andric 
38440b57cec5SDimitry Andric     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
38450b57cec5SDimitry Andric       getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
38460b57cec5SDimitry Andric 
38475f7ddb14SDimitry Andric     if (Entry->getValueType() == Ty && Entry->getAddressSpace() == AddrSpace)
38480b57cec5SDimitry Andric       return Entry;
38490b57cec5SDimitry Andric 
38500b57cec5SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
38510b57cec5SDimitry Andric     // error.
38520b57cec5SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
38530b57cec5SDimitry Andric       GlobalDecl OtherGD;
38540b57cec5SDimitry Andric       const VarDecl *OtherD;
38550b57cec5SDimitry Andric 
38560b57cec5SDimitry Andric       // Check that D is not yet in DiagnosedConflictingDefinitions is required
38570b57cec5SDimitry Andric       // to make sure that we issue an error only once.
38580b57cec5SDimitry Andric       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
38590b57cec5SDimitry Andric           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
38600b57cec5SDimitry Andric           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
38610b57cec5SDimitry Andric           OtherD->hasInit() &&
38620b57cec5SDimitry Andric           DiagnosedConflictingDefinitions.insert(D).second) {
38630b57cec5SDimitry Andric         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
38640b57cec5SDimitry Andric             << MangledName;
38650b57cec5SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
38660b57cec5SDimitry Andric                           diag::note_previous_definition);
38670b57cec5SDimitry Andric       }
38680b57cec5SDimitry Andric     }
38690b57cec5SDimitry Andric 
38700b57cec5SDimitry Andric     // Make sure the result is of the correct type.
38715f7ddb14SDimitry Andric     if (Entry->getType()->getAddressSpace() != AddrSpace) {
38725f7ddb14SDimitry Andric       return llvm::ConstantExpr::getAddrSpaceCast(Entry,
38735f7ddb14SDimitry Andric                                                   Ty->getPointerTo(AddrSpace));
38745f7ddb14SDimitry Andric     }
38750b57cec5SDimitry Andric 
38760b57cec5SDimitry Andric     // (If global is requested for a definition, we always need to create a new
38770b57cec5SDimitry Andric     // global, not just return a bitcast.)
38780b57cec5SDimitry Andric     if (!IsForDefinition)
38795f7ddb14SDimitry Andric       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(AddrSpace));
38800b57cec5SDimitry Andric   }
38810b57cec5SDimitry Andric 
38825f7ddb14SDimitry Andric   auto DAddrSpace = GetGlobalVarAddressSpace(D);
38835f7ddb14SDimitry Andric   auto TargetAddrSpace = getContext().getTargetAddressSpace(DAddrSpace);
38840b57cec5SDimitry Andric 
38850b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
38865f7ddb14SDimitry Andric       getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr,
38875f7ddb14SDimitry Andric       MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal,
38885f7ddb14SDimitry Andric       TargetAddrSpace);
38890b57cec5SDimitry Andric 
38900b57cec5SDimitry Andric   // If we already created a global with the same mangled name (but different
38910b57cec5SDimitry Andric   // type) before, take its name and remove it from its parent.
38920b57cec5SDimitry Andric   if (Entry) {
38930b57cec5SDimitry Andric     GV->takeName(Entry);
38940b57cec5SDimitry Andric 
38950b57cec5SDimitry Andric     if (!Entry->use_empty()) {
38960b57cec5SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
38970b57cec5SDimitry Andric           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
38980b57cec5SDimitry Andric       Entry->replaceAllUsesWith(NewPtrForOldDecl);
38990b57cec5SDimitry Andric     }
39000b57cec5SDimitry Andric 
39010b57cec5SDimitry Andric     Entry->eraseFromParent();
39020b57cec5SDimitry Andric   }
39030b57cec5SDimitry Andric 
39040b57cec5SDimitry Andric   // This is the first use or definition of a mangled name.  If there is a
39050b57cec5SDimitry Andric   // deferred decl with this name, remember that we need to emit it at the end
39060b57cec5SDimitry Andric   // of the file.
39070b57cec5SDimitry Andric   auto DDI = DeferredDecls.find(MangledName);
39080b57cec5SDimitry Andric   if (DDI != DeferredDecls.end()) {
39090b57cec5SDimitry Andric     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
39100b57cec5SDimitry Andric     // list, and remove it from DeferredDecls (since we don't need it anymore).
39110b57cec5SDimitry Andric     addDeferredDeclToEmit(DDI->second);
39120b57cec5SDimitry Andric     DeferredDecls.erase(DDI);
39130b57cec5SDimitry Andric   }
39140b57cec5SDimitry Andric 
39150b57cec5SDimitry Andric   // Handle things which are present even on external declarations.
39160b57cec5SDimitry Andric   if (D) {
39170b57cec5SDimitry Andric     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
39180b57cec5SDimitry Andric       getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
39190b57cec5SDimitry Andric 
39200b57cec5SDimitry Andric     // FIXME: This code is overly simple and should be merged with other global
39210b57cec5SDimitry Andric     // handling.
39220b57cec5SDimitry Andric     GV->setConstant(isTypeConstant(D->getType(), false));
39230b57cec5SDimitry Andric 
3924a7dea167SDimitry Andric     GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
39250b57cec5SDimitry Andric 
39260b57cec5SDimitry Andric     setLinkageForGV(GV, D);
39270b57cec5SDimitry Andric 
39280b57cec5SDimitry Andric     if (D->getTLSKind()) {
39290b57cec5SDimitry Andric       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
39300b57cec5SDimitry Andric         CXXThreadLocals.push_back(D);
39310b57cec5SDimitry Andric       setTLSMode(GV, *D);
39320b57cec5SDimitry Andric     }
39330b57cec5SDimitry Andric 
39340b57cec5SDimitry Andric     setGVProperties(GV, D);
39350b57cec5SDimitry Andric 
39360b57cec5SDimitry Andric     // If required by the ABI, treat declarations of static data members with
39370b57cec5SDimitry Andric     // inline initializers as definitions.
39380b57cec5SDimitry Andric     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
39390b57cec5SDimitry Andric       EmitGlobalVarDefinition(D);
39400b57cec5SDimitry Andric     }
39410b57cec5SDimitry Andric 
39420b57cec5SDimitry Andric     // Emit section information for extern variables.
39430b57cec5SDimitry Andric     if (D->hasExternalStorage()) {
39440b57cec5SDimitry Andric       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
39450b57cec5SDimitry Andric         GV->setSection(SA->getName());
39460b57cec5SDimitry Andric     }
39470b57cec5SDimitry Andric 
39480b57cec5SDimitry Andric     // Handle XCore specific ABI requirements.
39490b57cec5SDimitry Andric     if (getTriple().getArch() == llvm::Triple::xcore &&
39500b57cec5SDimitry Andric         D->getLanguageLinkage() == CLanguageLinkage &&
39510b57cec5SDimitry Andric         D->getType().isConstant(Context) &&
39520b57cec5SDimitry Andric         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
39530b57cec5SDimitry Andric       GV->setSection(".cp.rodata");
39540b57cec5SDimitry Andric 
39550b57cec5SDimitry Andric     // Check if we a have a const declaration with an initializer, we may be
39560b57cec5SDimitry Andric     // able to emit it as available_externally to expose it's value to the
39570b57cec5SDimitry Andric     // optimizer.
39580b57cec5SDimitry Andric     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
39590b57cec5SDimitry Andric         D->getType().isConstQualified() && !GV->hasInitializer() &&
39600b57cec5SDimitry Andric         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
39610b57cec5SDimitry Andric       const auto *Record =
39620b57cec5SDimitry Andric           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
39630b57cec5SDimitry Andric       bool HasMutableFields = Record && Record->hasMutableFields();
39640b57cec5SDimitry Andric       if (!HasMutableFields) {
39650b57cec5SDimitry Andric         const VarDecl *InitDecl;
39660b57cec5SDimitry Andric         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
39670b57cec5SDimitry Andric         if (InitExpr) {
39680b57cec5SDimitry Andric           ConstantEmitter emitter(*this);
39690b57cec5SDimitry Andric           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
39700b57cec5SDimitry Andric           if (Init) {
39710b57cec5SDimitry Andric             auto *InitType = Init->getType();
39725ffd83dbSDimitry Andric             if (GV->getValueType() != InitType) {
39730b57cec5SDimitry Andric               // The type of the initializer does not match the definition.
39740b57cec5SDimitry Andric               // This happens when an initializer has a different type from
39750b57cec5SDimitry Andric               // the type of the global (because of padding at the end of a
39760b57cec5SDimitry Andric               // structure for instance).
39770b57cec5SDimitry Andric               GV->setName(StringRef());
39780b57cec5SDimitry Andric               // Make a new global with the correct type, this is now guaranteed
39790b57cec5SDimitry Andric               // to work.
39800b57cec5SDimitry Andric               auto *NewGV = cast<llvm::GlobalVariable>(
3981a7dea167SDimitry Andric                   GetAddrOfGlobalVar(D, InitType, IsForDefinition)
3982a7dea167SDimitry Andric                       ->stripPointerCasts());
39830b57cec5SDimitry Andric 
39840b57cec5SDimitry Andric               // Erase the old global, since it is no longer used.
39850b57cec5SDimitry Andric               GV->eraseFromParent();
39860b57cec5SDimitry Andric               GV = NewGV;
39870b57cec5SDimitry Andric             } else {
39880b57cec5SDimitry Andric               GV->setInitializer(Init);
39890b57cec5SDimitry Andric               GV->setConstant(true);
39900b57cec5SDimitry Andric               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
39910b57cec5SDimitry Andric             }
39920b57cec5SDimitry Andric             emitter.finalize(GV);
39930b57cec5SDimitry Andric           }
39940b57cec5SDimitry Andric         }
39950b57cec5SDimitry Andric       }
39960b57cec5SDimitry Andric     }
39970b57cec5SDimitry Andric   }
39980b57cec5SDimitry Andric 
39995f7ddb14SDimitry Andric   if (GV->isDeclaration()) {
4000480093f4SDimitry Andric     getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
40015f7ddb14SDimitry Andric     // External HIP managed variables needed to be recorded for transformation
40025f7ddb14SDimitry Andric     // in both device and host compilations.
40035f7ddb14SDimitry Andric     if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() &&
40045f7ddb14SDimitry Andric         D->hasExternalStorage())
40055f7ddb14SDimitry Andric       getCUDARuntime().handleVarRegistration(D, *GV);
40065f7ddb14SDimitry Andric   }
4007480093f4SDimitry Andric 
40080b57cec5SDimitry Andric   LangAS ExpectedAS =
40090b57cec5SDimitry Andric       D ? D->getType().getAddressSpace()
40100b57cec5SDimitry Andric         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
40115f7ddb14SDimitry Andric   assert(getContext().getTargetAddressSpace(ExpectedAS) == AddrSpace);
40125f7ddb14SDimitry Andric   if (DAddrSpace != ExpectedAS) {
40135f7ddb14SDimitry Andric     return getTargetCodeGenInfo().performAddrSpaceCast(
40145f7ddb14SDimitry Andric         *this, GV, DAddrSpace, ExpectedAS, Ty->getPointerTo(AddrSpace));
40155f7ddb14SDimitry Andric   }
40160b57cec5SDimitry Andric 
40170b57cec5SDimitry Andric   return GV;
40180b57cec5SDimitry Andric }
40190b57cec5SDimitry Andric 
40200b57cec5SDimitry Andric llvm::Constant *
GetAddrOfGlobal(GlobalDecl GD,ForDefinition_t IsForDefinition)40215ffd83dbSDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
40220b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
40235ffd83dbSDimitry Andric 
40240b57cec5SDimitry Andric   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
40250b57cec5SDimitry Andric     return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
40260b57cec5SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
40275ffd83dbSDimitry Andric 
40285ffd83dbSDimitry Andric   if (isa<CXXMethodDecl>(D)) {
40295ffd83dbSDimitry Andric     auto FInfo =
40305ffd83dbSDimitry Andric         &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
40310b57cec5SDimitry Andric     auto Ty = getTypes().GetFunctionType(*FInfo);
40320b57cec5SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
40330b57cec5SDimitry Andric                              IsForDefinition);
40345ffd83dbSDimitry Andric   }
40355ffd83dbSDimitry Andric 
40365ffd83dbSDimitry Andric   if (isa<FunctionDecl>(D)) {
40370b57cec5SDimitry Andric     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
40380b57cec5SDimitry Andric     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
40390b57cec5SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
40400b57cec5SDimitry Andric                              IsForDefinition);
40415ffd83dbSDimitry Andric   }
40425ffd83dbSDimitry Andric 
40435ffd83dbSDimitry Andric   return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
40440b57cec5SDimitry Andric }
40450b57cec5SDimitry Andric 
CreateOrReplaceCXXRuntimeVariable(StringRef Name,llvm::Type * Ty,llvm::GlobalValue::LinkageTypes Linkage,unsigned Alignment)40460b57cec5SDimitry Andric llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
40470b57cec5SDimitry Andric     StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
40480b57cec5SDimitry Andric     unsigned Alignment) {
40490b57cec5SDimitry Andric   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
40500b57cec5SDimitry Andric   llvm::GlobalVariable *OldGV = nullptr;
40510b57cec5SDimitry Andric 
40520b57cec5SDimitry Andric   if (GV) {
40530b57cec5SDimitry Andric     // Check if the variable has the right type.
40545ffd83dbSDimitry Andric     if (GV->getValueType() == Ty)
40550b57cec5SDimitry Andric       return GV;
40560b57cec5SDimitry Andric 
40570b57cec5SDimitry Andric     // Because C++ name mangling, the only way we can end up with an already
40580b57cec5SDimitry Andric     // existing global with the same name is if it has been declared extern "C".
40590b57cec5SDimitry Andric     assert(GV->isDeclaration() && "Declaration has wrong type!");
40600b57cec5SDimitry Andric     OldGV = GV;
40610b57cec5SDimitry Andric   }
40620b57cec5SDimitry Andric 
40630b57cec5SDimitry Andric   // Create a new variable.
40640b57cec5SDimitry Andric   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
40650b57cec5SDimitry Andric                                 Linkage, nullptr, Name);
40660b57cec5SDimitry Andric 
40670b57cec5SDimitry Andric   if (OldGV) {
40680b57cec5SDimitry Andric     // Replace occurrences of the old variable if needed.
40690b57cec5SDimitry Andric     GV->takeName(OldGV);
40700b57cec5SDimitry Andric 
40710b57cec5SDimitry Andric     if (!OldGV->use_empty()) {
40720b57cec5SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
40730b57cec5SDimitry Andric       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
40740b57cec5SDimitry Andric       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
40750b57cec5SDimitry Andric     }
40760b57cec5SDimitry Andric 
40770b57cec5SDimitry Andric     OldGV->eraseFromParent();
40780b57cec5SDimitry Andric   }
40790b57cec5SDimitry Andric 
40800b57cec5SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker() &&
40810b57cec5SDimitry Andric       !GV->hasAvailableExternallyLinkage())
40820b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
40830b57cec5SDimitry Andric 
4084a7dea167SDimitry Andric   GV->setAlignment(llvm::MaybeAlign(Alignment));
40850b57cec5SDimitry Andric 
40860b57cec5SDimitry Andric   return GV;
40870b57cec5SDimitry Andric }
40880b57cec5SDimitry Andric 
40890b57cec5SDimitry Andric /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
40900b57cec5SDimitry Andric /// given global variable.  If Ty is non-null and if the global doesn't exist,
40910b57cec5SDimitry Andric /// then it will be created with the specified type instead of whatever the
40920b57cec5SDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guaranteed
40930b57cec5SDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a
40940b57cec5SDimitry Andric /// variable with the same mangled name but some other type.
GetAddrOfGlobalVar(const VarDecl * D,llvm::Type * Ty,ForDefinition_t IsForDefinition)40950b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
40960b57cec5SDimitry Andric                                                   llvm::Type *Ty,
40970b57cec5SDimitry Andric                                            ForDefinition_t IsForDefinition) {
40980b57cec5SDimitry Andric   assert(D->hasGlobalStorage() && "Not a global variable");
40990b57cec5SDimitry Andric   QualType ASTTy = D->getType();
41000b57cec5SDimitry Andric   if (!Ty)
41010b57cec5SDimitry Andric     Ty = getTypes().ConvertTypeForMem(ASTTy);
41020b57cec5SDimitry Andric 
41030b57cec5SDimitry Andric   StringRef MangledName = getMangledName(D);
41045f7ddb14SDimitry Andric   return GetOrCreateLLVMGlobal(MangledName, Ty,
41055f7ddb14SDimitry Andric                                getContext().getTargetAddressSpace(ASTTy), D,
41065f7ddb14SDimitry Andric                                IsForDefinition);
41070b57cec5SDimitry Andric }
41080b57cec5SDimitry Andric 
41090b57cec5SDimitry Andric /// CreateRuntimeVariable - Create a new runtime global variable with the
41100b57cec5SDimitry Andric /// specified type and name.
41110b57cec5SDimitry Andric llvm::Constant *
CreateRuntimeVariable(llvm::Type * Ty,StringRef Name)41120b57cec5SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
41130b57cec5SDimitry Andric                                      StringRef Name) {
41145f7ddb14SDimitry Andric   auto AddrSpace =
41150b57cec5SDimitry Andric       getContext().getLangOpts().OpenCL
41165f7ddb14SDimitry Andric           ? getContext().getTargetAddressSpace(LangAS::opencl_global)
41175f7ddb14SDimitry Andric           : 0;
41185f7ddb14SDimitry Andric   auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr);
41190b57cec5SDimitry Andric   setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
41200b57cec5SDimitry Andric   return Ret;
41210b57cec5SDimitry Andric }
41220b57cec5SDimitry Andric 
EmitTentativeDefinition(const VarDecl * D)41230b57cec5SDimitry Andric void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
41240b57cec5SDimitry Andric   assert(!D->getInit() && "Cannot emit definite definitions here!");
41250b57cec5SDimitry Andric 
41260b57cec5SDimitry Andric   StringRef MangledName = getMangledName(D);
41270b57cec5SDimitry Andric   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
41280b57cec5SDimitry Andric 
41290b57cec5SDimitry Andric   // We already have a definition, not declaration, with the same mangled name.
41300b57cec5SDimitry Andric   // Emitting of declaration is not required (and actually overwrites emitted
41310b57cec5SDimitry Andric   // definition).
41320b57cec5SDimitry Andric   if (GV && !GV->isDeclaration())
41330b57cec5SDimitry Andric     return;
41340b57cec5SDimitry Andric 
41350b57cec5SDimitry Andric   // If we have not seen a reference to this variable yet, place it into the
41360b57cec5SDimitry Andric   // deferred declarations table to be emitted if needed later.
41370b57cec5SDimitry Andric   if (!MustBeEmitted(D) && !GV) {
41380b57cec5SDimitry Andric       DeferredDecls[MangledName] = D;
41390b57cec5SDimitry Andric       return;
41400b57cec5SDimitry Andric   }
41410b57cec5SDimitry Andric 
41420b57cec5SDimitry Andric   // The tentative definition is the only definition.
41430b57cec5SDimitry Andric   EmitGlobalVarDefinition(D);
41440b57cec5SDimitry Andric }
41450b57cec5SDimitry Andric 
EmitExternalDeclaration(const VarDecl * D)4146480093f4SDimitry Andric void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
4147480093f4SDimitry Andric   EmitExternalVarDeclaration(D);
4148480093f4SDimitry Andric }
4149480093f4SDimitry Andric 
GetTargetTypeStoreSize(llvm::Type * Ty) const41500b57cec5SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
41510b57cec5SDimitry Andric   return Context.toCharUnitsFromBits(
41520b57cec5SDimitry Andric       getDataLayout().getTypeStoreSizeInBits(Ty));
41530b57cec5SDimitry Andric }
41540b57cec5SDimitry Andric 
GetGlobalVarAddressSpace(const VarDecl * D)41550b57cec5SDimitry Andric LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
41560b57cec5SDimitry Andric   LangAS AddrSpace = LangAS::Default;
41570b57cec5SDimitry Andric   if (LangOpts.OpenCL) {
41580b57cec5SDimitry Andric     AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
41590b57cec5SDimitry Andric     assert(AddrSpace == LangAS::opencl_global ||
4160af732203SDimitry Andric            AddrSpace == LangAS::opencl_global_device ||
4161af732203SDimitry Andric            AddrSpace == LangAS::opencl_global_host ||
41620b57cec5SDimitry Andric            AddrSpace == LangAS::opencl_constant ||
41630b57cec5SDimitry Andric            AddrSpace == LangAS::opencl_local ||
41640b57cec5SDimitry Andric            AddrSpace >= LangAS::FirstTargetAddressSpace);
41650b57cec5SDimitry Andric     return AddrSpace;
41660b57cec5SDimitry Andric   }
41670b57cec5SDimitry Andric 
41685f7ddb14SDimitry Andric   if (LangOpts.SYCLIsDevice &&
41695f7ddb14SDimitry Andric       (!D || D->getType().getAddressSpace() == LangAS::Default))
41705f7ddb14SDimitry Andric     return LangAS::sycl_global;
41715f7ddb14SDimitry Andric 
41720b57cec5SDimitry Andric   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
41730b57cec5SDimitry Andric     if (D && D->hasAttr<CUDAConstantAttr>())
41740b57cec5SDimitry Andric       return LangAS::cuda_constant;
41750b57cec5SDimitry Andric     else if (D && D->hasAttr<CUDASharedAttr>())
41760b57cec5SDimitry Andric       return LangAS::cuda_shared;
41770b57cec5SDimitry Andric     else if (D && D->hasAttr<CUDADeviceAttr>())
41780b57cec5SDimitry Andric       return LangAS::cuda_device;
41790b57cec5SDimitry Andric     else if (D && D->getType().isConstQualified())
41800b57cec5SDimitry Andric       return LangAS::cuda_constant;
41810b57cec5SDimitry Andric     else
41820b57cec5SDimitry Andric       return LangAS::cuda_device;
41830b57cec5SDimitry Andric   }
41840b57cec5SDimitry Andric 
41850b57cec5SDimitry Andric   if (LangOpts.OpenMP) {
41860b57cec5SDimitry Andric     LangAS AS;
41870b57cec5SDimitry Andric     if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
41880b57cec5SDimitry Andric       return AS;
41890b57cec5SDimitry Andric   }
41900b57cec5SDimitry Andric   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
41910b57cec5SDimitry Andric }
41920b57cec5SDimitry Andric 
GetGlobalConstantAddressSpace() const41935f7ddb14SDimitry Andric LangAS CodeGenModule::GetGlobalConstantAddressSpace() const {
41940b57cec5SDimitry Andric   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
41950b57cec5SDimitry Andric   if (LangOpts.OpenCL)
41960b57cec5SDimitry Andric     return LangAS::opencl_constant;
41975f7ddb14SDimitry Andric   if (LangOpts.SYCLIsDevice)
41985f7ddb14SDimitry Andric     return LangAS::sycl_global;
41990b57cec5SDimitry Andric   if (auto AS = getTarget().getConstantAddressSpace())
42000b57cec5SDimitry Andric     return AS.getValue();
42010b57cec5SDimitry Andric   return LangAS::Default;
42020b57cec5SDimitry Andric }
42030b57cec5SDimitry Andric 
42040b57cec5SDimitry Andric // In address space agnostic languages, string literals are in default address
42050b57cec5SDimitry Andric // space in AST. However, certain targets (e.g. amdgcn) request them to be
42060b57cec5SDimitry Andric // emitted in constant address space in LLVM IR. To be consistent with other
42070b57cec5SDimitry Andric // parts of AST, string literal global variables in constant address space
42080b57cec5SDimitry Andric // need to be casted to default address space before being put into address
42090b57cec5SDimitry Andric // map and referenced by other part of CodeGen.
42100b57cec5SDimitry Andric // In OpenCL, string literals are in constant address space in AST, therefore
42110b57cec5SDimitry Andric // they should not be casted to default address space.
42120b57cec5SDimitry Andric static llvm::Constant *
castStringLiteralToDefaultAddressSpace(CodeGenModule & CGM,llvm::GlobalVariable * GV)42130b57cec5SDimitry Andric castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
42140b57cec5SDimitry Andric                                        llvm::GlobalVariable *GV) {
42150b57cec5SDimitry Andric   llvm::Constant *Cast = GV;
42160b57cec5SDimitry Andric   if (!CGM.getLangOpts().OpenCL) {
42175f7ddb14SDimitry Andric     auto AS = CGM.GetGlobalConstantAddressSpace();
42180b57cec5SDimitry Andric     if (AS != LangAS::Default)
42190b57cec5SDimitry Andric       Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
42205f7ddb14SDimitry Andric           CGM, GV, AS, LangAS::Default,
42210b57cec5SDimitry Andric           GV->getValueType()->getPointerTo(
42220b57cec5SDimitry Andric               CGM.getContext().getTargetAddressSpace(LangAS::Default)));
42230b57cec5SDimitry Andric   }
42240b57cec5SDimitry Andric   return Cast;
42250b57cec5SDimitry Andric }
42260b57cec5SDimitry Andric 
42270b57cec5SDimitry Andric template<typename SomeDecl>
MaybeHandleStaticInExternC(const SomeDecl * D,llvm::GlobalValue * GV)42280b57cec5SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
42290b57cec5SDimitry Andric                                                llvm::GlobalValue *GV) {
42300b57cec5SDimitry Andric   if (!getLangOpts().CPlusPlus)
42310b57cec5SDimitry Andric     return;
42320b57cec5SDimitry Andric 
42330b57cec5SDimitry Andric   // Must have 'used' attribute, or else inline assembly can't rely on
42340b57cec5SDimitry Andric   // the name existing.
42350b57cec5SDimitry Andric   if (!D->template hasAttr<UsedAttr>())
42360b57cec5SDimitry Andric     return;
42370b57cec5SDimitry Andric 
42380b57cec5SDimitry Andric   // Must have internal linkage and an ordinary name.
42390b57cec5SDimitry Andric   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
42400b57cec5SDimitry Andric     return;
42410b57cec5SDimitry Andric 
42420b57cec5SDimitry Andric   // Must be in an extern "C" context. Entities declared directly within
42430b57cec5SDimitry Andric   // a record are not extern "C" even if the record is in such a context.
42440b57cec5SDimitry Andric   const SomeDecl *First = D->getFirstDecl();
42450b57cec5SDimitry Andric   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
42460b57cec5SDimitry Andric     return;
42470b57cec5SDimitry Andric 
42480b57cec5SDimitry Andric   // OK, this is an internal linkage entity inside an extern "C" linkage
42490b57cec5SDimitry Andric   // specification. Make a note of that so we can give it the "expected"
42500b57cec5SDimitry Andric   // mangled name if nothing else is using that name.
42510b57cec5SDimitry Andric   std::pair<StaticExternCMap::iterator, bool> R =
42520b57cec5SDimitry Andric       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
42530b57cec5SDimitry Andric 
42540b57cec5SDimitry Andric   // If we have multiple internal linkage entities with the same name
42550b57cec5SDimitry Andric   // in extern "C" regions, none of them gets that name.
42560b57cec5SDimitry Andric   if (!R.second)
42570b57cec5SDimitry Andric     R.first->second = nullptr;
42580b57cec5SDimitry Andric }
42590b57cec5SDimitry Andric 
shouldBeInCOMDAT(CodeGenModule & CGM,const Decl & D)42600b57cec5SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
42610b57cec5SDimitry Andric   if (!CGM.supportsCOMDAT())
42620b57cec5SDimitry Andric     return false;
42630b57cec5SDimitry Andric 
42640b57cec5SDimitry Andric   // Do not set COMDAT attribute for CUDA/HIP stub functions to prevent
42650b57cec5SDimitry Andric   // them being "merged" by the COMDAT Folding linker optimization.
42660b57cec5SDimitry Andric   if (D.hasAttr<CUDAGlobalAttr>())
42670b57cec5SDimitry Andric     return false;
42680b57cec5SDimitry Andric 
42690b57cec5SDimitry Andric   if (D.hasAttr<SelectAnyAttr>())
42700b57cec5SDimitry Andric     return true;
42710b57cec5SDimitry Andric 
42720b57cec5SDimitry Andric   GVALinkage Linkage;
42730b57cec5SDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(&D))
42740b57cec5SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
42750b57cec5SDimitry Andric   else
42760b57cec5SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
42770b57cec5SDimitry Andric 
42780b57cec5SDimitry Andric   switch (Linkage) {
42790b57cec5SDimitry Andric   case GVA_Internal:
42800b57cec5SDimitry Andric   case GVA_AvailableExternally:
42810b57cec5SDimitry Andric   case GVA_StrongExternal:
42820b57cec5SDimitry Andric     return false;
42830b57cec5SDimitry Andric   case GVA_DiscardableODR:
42840b57cec5SDimitry Andric   case GVA_StrongODR:
42850b57cec5SDimitry Andric     return true;
42860b57cec5SDimitry Andric   }
42870b57cec5SDimitry Andric   llvm_unreachable("No such linkage");
42880b57cec5SDimitry Andric }
42890b57cec5SDimitry Andric 
maybeSetTrivialComdat(const Decl & D,llvm::GlobalObject & GO)42900b57cec5SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
42910b57cec5SDimitry Andric                                           llvm::GlobalObject &GO) {
42920b57cec5SDimitry Andric   if (!shouldBeInCOMDAT(*this, D))
42930b57cec5SDimitry Andric     return;
42940b57cec5SDimitry Andric   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
42950b57cec5SDimitry Andric }
42960b57cec5SDimitry Andric 
42970b57cec5SDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition.
EmitGlobalVarDefinition(const VarDecl * D,bool IsTentative)42980b57cec5SDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
42990b57cec5SDimitry Andric                                             bool IsTentative) {
43000b57cec5SDimitry Andric   // OpenCL global variables of sampler type are translated to function calls,
43010b57cec5SDimitry Andric   // therefore no need to be translated.
43020b57cec5SDimitry Andric   QualType ASTTy = D->getType();
43030b57cec5SDimitry Andric   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
43040b57cec5SDimitry Andric     return;
43050b57cec5SDimitry Andric 
43060b57cec5SDimitry Andric   // If this is OpenMP device, check if it is legal to emit this global
43070b57cec5SDimitry Andric   // normally.
43080b57cec5SDimitry Andric   if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
43090b57cec5SDimitry Andric       OpenMPRuntime->emitTargetGlobalVariable(D))
43100b57cec5SDimitry Andric     return;
43110b57cec5SDimitry Andric 
43125f7ddb14SDimitry Andric   llvm::TrackingVH<llvm::Constant> Init;
43130b57cec5SDimitry Andric   bool NeedsGlobalCtor = false;
4314a7dea167SDimitry Andric   bool NeedsGlobalDtor =
4315a7dea167SDimitry Andric       D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
43160b57cec5SDimitry Andric 
43170b57cec5SDimitry Andric   const VarDecl *InitDecl;
43180b57cec5SDimitry Andric   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
43190b57cec5SDimitry Andric 
43200b57cec5SDimitry Andric   Optional<ConstantEmitter> emitter;
43210b57cec5SDimitry Andric 
43220b57cec5SDimitry Andric   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
43230b57cec5SDimitry Andric   // as part of their declaration."  Sema has already checked for
43240b57cec5SDimitry Andric   // error cases, so we just need to set Init to UndefValue.
43250b57cec5SDimitry Andric   bool IsCUDASharedVar =
43260b57cec5SDimitry Andric       getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
43270b57cec5SDimitry Andric   // Shadows of initialized device-side global variables are also left
43280b57cec5SDimitry Andric   // undefined.
43295f7ddb14SDimitry Andric   // Managed Variables should be initialized on both host side and device side.
43300b57cec5SDimitry Andric   bool IsCUDAShadowVar =
4331af732203SDimitry Andric       !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
43320b57cec5SDimitry Andric       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
43330b57cec5SDimitry Andric        D->hasAttr<CUDASharedAttr>());
43345ffd83dbSDimitry Andric   bool IsCUDADeviceShadowVar =
43355f7ddb14SDimitry Andric       getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
43365ffd83dbSDimitry Andric       (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
43375f7ddb14SDimitry Andric        D->getType()->isCUDADeviceBuiltinTextureType());
43380b57cec5SDimitry Andric   if (getLangOpts().CUDA &&
43395ffd83dbSDimitry Andric       (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
43405f7ddb14SDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
43415ffd83dbSDimitry Andric   else if (D->hasAttr<LoaderUninitializedAttr>())
43425f7ddb14SDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
43430b57cec5SDimitry Andric   else if (!InitExpr) {
43440b57cec5SDimitry Andric     // This is a tentative definition; tentative definitions are
43450b57cec5SDimitry Andric     // implicitly initialized with { 0 }.
43460b57cec5SDimitry Andric     //
43470b57cec5SDimitry Andric     // Note that tentative definitions are only emitted at the end of
43480b57cec5SDimitry Andric     // a translation unit, so they should never have incomplete
43490b57cec5SDimitry Andric     // type. In addition, EmitTentativeDefinition makes sure that we
43500b57cec5SDimitry Andric     // never attempt to emit a tentative definition if a real one
43510b57cec5SDimitry Andric     // exists. A use may still exists, however, so we still may need
43520b57cec5SDimitry Andric     // to do a RAUW.
43530b57cec5SDimitry Andric     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
43540b57cec5SDimitry Andric     Init = EmitNullConstant(D->getType());
43550b57cec5SDimitry Andric   } else {
43560b57cec5SDimitry Andric     initializedGlobalDecl = GlobalDecl(D);
43570b57cec5SDimitry Andric     emitter.emplace(*this);
43585f7ddb14SDimitry Andric     llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl);
43595f7ddb14SDimitry Andric     if (!Initializer) {
43600b57cec5SDimitry Andric       QualType T = InitExpr->getType();
43610b57cec5SDimitry Andric       if (D->getType()->isReferenceType())
43620b57cec5SDimitry Andric         T = D->getType();
43630b57cec5SDimitry Andric 
43640b57cec5SDimitry Andric       if (getLangOpts().CPlusPlus) {
43650b57cec5SDimitry Andric         Init = EmitNullConstant(T);
43660b57cec5SDimitry Andric         NeedsGlobalCtor = true;
43670b57cec5SDimitry Andric       } else {
43680b57cec5SDimitry Andric         ErrorUnsupported(D, "static initializer");
43690b57cec5SDimitry Andric         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
43700b57cec5SDimitry Andric       }
43710b57cec5SDimitry Andric     } else {
43725f7ddb14SDimitry Andric       Init = Initializer;
43730b57cec5SDimitry Andric       // We don't need an initializer, so remove the entry for the delayed
43740b57cec5SDimitry Andric       // initializer position (just in case this entry was delayed) if we
43750b57cec5SDimitry Andric       // also don't need to register a destructor.
43760b57cec5SDimitry Andric       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
43770b57cec5SDimitry Andric         DelayedCXXInitPosition.erase(D);
43780b57cec5SDimitry Andric     }
43790b57cec5SDimitry Andric   }
43800b57cec5SDimitry Andric 
43810b57cec5SDimitry Andric   llvm::Type* InitType = Init->getType();
43820b57cec5SDimitry Andric   llvm::Constant *Entry =
43830b57cec5SDimitry Andric       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
43840b57cec5SDimitry Andric 
4385a7dea167SDimitry Andric   // Strip off pointer casts if we got them.
4386a7dea167SDimitry Andric   Entry = Entry->stripPointerCasts();
43870b57cec5SDimitry Andric 
43880b57cec5SDimitry Andric   // Entry is now either a Function or GlobalVariable.
43890b57cec5SDimitry Andric   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
43900b57cec5SDimitry Andric 
43910b57cec5SDimitry Andric   // We have a definition after a declaration with the wrong type.
43920b57cec5SDimitry Andric   // We must make a new GlobalVariable* and update everything that used OldGV
43930b57cec5SDimitry Andric   // (a declaration or tentative definition) with the new GlobalVariable*
43940b57cec5SDimitry Andric   // (which will be a definition).
43950b57cec5SDimitry Andric   //
43960b57cec5SDimitry Andric   // This happens if there is a prototype for a global (e.g.
43970b57cec5SDimitry Andric   // "extern int x[];") and then a definition of a different type (e.g.
43980b57cec5SDimitry Andric   // "int x[10];"). This also happens when an initializer has a different type
43990b57cec5SDimitry Andric   // from the type of the global (this happens with unions).
44005ffd83dbSDimitry Andric   if (!GV || GV->getValueType() != InitType ||
44010b57cec5SDimitry Andric       GV->getType()->getAddressSpace() !=
44020b57cec5SDimitry Andric           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
44030b57cec5SDimitry Andric 
44040b57cec5SDimitry Andric     // Move the old entry aside so that we'll create a new one.
44050b57cec5SDimitry Andric     Entry->setName(StringRef());
44060b57cec5SDimitry Andric 
44070b57cec5SDimitry Andric     // Make a new global with the correct type, this is now guaranteed to work.
44080b57cec5SDimitry Andric     GV = cast<llvm::GlobalVariable>(
4409a7dea167SDimitry Andric         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
4410a7dea167SDimitry Andric             ->stripPointerCasts());
44110b57cec5SDimitry Andric 
44120b57cec5SDimitry Andric     // Replace all uses of the old global with the new global
44130b57cec5SDimitry Andric     llvm::Constant *NewPtrForOldDecl =
44145f7ddb14SDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
44155f7ddb14SDimitry Andric                                                              Entry->getType());
44160b57cec5SDimitry Andric     Entry->replaceAllUsesWith(NewPtrForOldDecl);
44170b57cec5SDimitry Andric 
44180b57cec5SDimitry Andric     // Erase the old global, since it is no longer used.
44190b57cec5SDimitry Andric     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
44200b57cec5SDimitry Andric   }
44210b57cec5SDimitry Andric 
44220b57cec5SDimitry Andric   MaybeHandleStaticInExternC(D, GV);
44230b57cec5SDimitry Andric 
44240b57cec5SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
44250b57cec5SDimitry Andric     AddGlobalAnnotations(D, GV);
44260b57cec5SDimitry Andric 
44270b57cec5SDimitry Andric   // Set the llvm linkage type as appropriate.
44280b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
44290b57cec5SDimitry Andric       getLLVMLinkageVarDefinition(D, GV->isConstant());
44300b57cec5SDimitry Andric 
44310b57cec5SDimitry Andric   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
44320b57cec5SDimitry Andric   // the device. [...]"
44330b57cec5SDimitry Andric   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
44340b57cec5SDimitry Andric   // __device__, declares a variable that: [...]
44350b57cec5SDimitry Andric   // Is accessible from all the threads within the grid and from the host
44360b57cec5SDimitry Andric   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
44370b57cec5SDimitry Andric   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
44380b57cec5SDimitry Andric   if (GV && LangOpts.CUDA) {
44390b57cec5SDimitry Andric     if (LangOpts.CUDAIsDevice) {
44400b57cec5SDimitry Andric       if (Linkage != llvm::GlobalValue::InternalLinkage &&
44410b57cec5SDimitry Andric           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()))
44420b57cec5SDimitry Andric         GV->setExternallyInitialized(true);
44430b57cec5SDimitry Andric     } else {
44445f7ddb14SDimitry Andric       getCUDARuntime().internalizeDeviceSideVar(D, Linkage);
44455ffd83dbSDimitry Andric     }
44465f7ddb14SDimitry Andric     getCUDARuntime().handleVarRegistration(D, *GV);
44470b57cec5SDimitry Andric   }
44480b57cec5SDimitry Andric 
44490b57cec5SDimitry Andric   GV->setInitializer(Init);
44505ffd83dbSDimitry Andric   if (emitter)
44515ffd83dbSDimitry Andric     emitter->finalize(GV);
44520b57cec5SDimitry Andric 
44530b57cec5SDimitry Andric   // If it is safe to mark the global 'constant', do so now.
44540b57cec5SDimitry Andric   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
44550b57cec5SDimitry Andric                   isTypeConstant(D->getType(), true));
44560b57cec5SDimitry Andric 
44570b57cec5SDimitry Andric   // If it is in a read-only section, mark it 'constant'.
44580b57cec5SDimitry Andric   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
44590b57cec5SDimitry Andric     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
44600b57cec5SDimitry Andric     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
44610b57cec5SDimitry Andric       GV->setConstant(true);
44620b57cec5SDimitry Andric   }
44630b57cec5SDimitry Andric 
4464a7dea167SDimitry Andric   GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
44650b57cec5SDimitry Andric 
44665ffd83dbSDimitry Andric   // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
44675ffd83dbSDimitry Andric   // function is only defined alongside the variable, not also alongside
44685ffd83dbSDimitry Andric   // callers. Normally, all accesses to a thread_local go through the
44695ffd83dbSDimitry Andric   // thread-wrapper in order to ensure initialization has occurred, underlying
44705ffd83dbSDimitry Andric   // variable will never be used other than the thread-wrapper, so it can be
44715ffd83dbSDimitry Andric   // converted to internal linkage.
44725ffd83dbSDimitry Andric   //
44735ffd83dbSDimitry Andric   // However, if the variable has the 'constinit' attribute, it _can_ be
44745ffd83dbSDimitry Andric   // referenced directly, without calling the thread-wrapper, so the linkage
44755ffd83dbSDimitry Andric   // must not be changed.
44765ffd83dbSDimitry Andric   //
44775ffd83dbSDimitry Andric   // Additionally, if the variable isn't plain external linkage, e.g. if it's
44785ffd83dbSDimitry Andric   // weak or linkonce, the de-duplication semantics are important to preserve,
44795ffd83dbSDimitry Andric   // so we don't change the linkage.
44805ffd83dbSDimitry Andric   if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
44815ffd83dbSDimitry Andric       Linkage == llvm::GlobalValue::ExternalLinkage &&
44820b57cec5SDimitry Andric       Context.getTargetInfo().getTriple().isOSDarwin() &&
44835ffd83dbSDimitry Andric       !D->hasAttr<ConstInitAttr>())
44840b57cec5SDimitry Andric     Linkage = llvm::GlobalValue::InternalLinkage;
44850b57cec5SDimitry Andric 
44860b57cec5SDimitry Andric   GV->setLinkage(Linkage);
44870b57cec5SDimitry Andric   if (D->hasAttr<DLLImportAttr>())
44880b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
44890b57cec5SDimitry Andric   else if (D->hasAttr<DLLExportAttr>())
44900b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
44910b57cec5SDimitry Andric   else
44920b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
44930b57cec5SDimitry Andric 
44940b57cec5SDimitry Andric   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
44950b57cec5SDimitry Andric     // common vars aren't constant even if declared const.
44960b57cec5SDimitry Andric     GV->setConstant(false);
44970b57cec5SDimitry Andric     // Tentative definition of global variables may be initialized with
44980b57cec5SDimitry Andric     // non-zero null pointers. In this case they should have weak linkage
44990b57cec5SDimitry Andric     // since common linkage must have zero initializer and must not have
45000b57cec5SDimitry Andric     // explicit section therefore cannot have non-zero initial value.
45010b57cec5SDimitry Andric     if (!GV->getInitializer()->isNullValue())
45020b57cec5SDimitry Andric       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
45030b57cec5SDimitry Andric   }
45040b57cec5SDimitry Andric 
45050b57cec5SDimitry Andric   setNonAliasAttributes(D, GV);
45060b57cec5SDimitry Andric 
45070b57cec5SDimitry Andric   if (D->getTLSKind() && !GV->isThreadLocal()) {
45080b57cec5SDimitry Andric     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
45090b57cec5SDimitry Andric       CXXThreadLocals.push_back(D);
45100b57cec5SDimitry Andric     setTLSMode(GV, *D);
45110b57cec5SDimitry Andric   }
45120b57cec5SDimitry Andric 
45130b57cec5SDimitry Andric   maybeSetTrivialComdat(*D, *GV);
45140b57cec5SDimitry Andric 
45150b57cec5SDimitry Andric   // Emit the initializer function if necessary.
45160b57cec5SDimitry Andric   if (NeedsGlobalCtor || NeedsGlobalDtor)
45170b57cec5SDimitry Andric     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
45180b57cec5SDimitry Andric 
45190b57cec5SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
45200b57cec5SDimitry Andric 
45210b57cec5SDimitry Andric   // Emit global variable debug information.
45220b57cec5SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
4523480093f4SDimitry Andric     if (getCodeGenOpts().hasReducedDebugInfo())
45240b57cec5SDimitry Andric       DI->EmitGlobalVariable(GV, D);
45250b57cec5SDimitry Andric }
45260b57cec5SDimitry Andric 
EmitExternalVarDeclaration(const VarDecl * D)4527480093f4SDimitry Andric void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
4528480093f4SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
4529480093f4SDimitry Andric     if (getCodeGenOpts().hasReducedDebugInfo()) {
4530480093f4SDimitry Andric       QualType ASTTy = D->getType();
4531480093f4SDimitry Andric       llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
45325f7ddb14SDimitry Andric       llvm::Constant *GV = GetOrCreateLLVMGlobal(
45335f7ddb14SDimitry Andric           D->getName(), Ty, getContext().getTargetAddressSpace(ASTTy), D);
4534480093f4SDimitry Andric       DI->EmitExternalVariable(
4535480093f4SDimitry Andric           cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
4536480093f4SDimitry Andric     }
4537480093f4SDimitry Andric }
4538480093f4SDimitry Andric 
isVarDeclStrongDefinition(const ASTContext & Context,CodeGenModule & CGM,const VarDecl * D,bool NoCommon)45390b57cec5SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context,
45400b57cec5SDimitry Andric                                       CodeGenModule &CGM, const VarDecl *D,
45410b57cec5SDimitry Andric                                       bool NoCommon) {
45420b57cec5SDimitry Andric   // Don't give variables common linkage if -fno-common was specified unless it
45430b57cec5SDimitry Andric   // was overridden by a NoCommon attribute.
45440b57cec5SDimitry Andric   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
45450b57cec5SDimitry Andric     return true;
45460b57cec5SDimitry Andric 
45470b57cec5SDimitry Andric   // C11 6.9.2/2:
45480b57cec5SDimitry Andric   //   A declaration of an identifier for an object that has file scope without
45490b57cec5SDimitry Andric   //   an initializer, and without a storage-class specifier or with the
45500b57cec5SDimitry Andric   //   storage-class specifier static, constitutes a tentative definition.
45510b57cec5SDimitry Andric   if (D->getInit() || D->hasExternalStorage())
45520b57cec5SDimitry Andric     return true;
45530b57cec5SDimitry Andric 
45540b57cec5SDimitry Andric   // A variable cannot be both common and exist in a section.
45550b57cec5SDimitry Andric   if (D->hasAttr<SectionAttr>())
45560b57cec5SDimitry Andric     return true;
45570b57cec5SDimitry Andric 
45580b57cec5SDimitry Andric   // A variable cannot be both common and exist in a section.
45590b57cec5SDimitry Andric   // We don't try to determine which is the right section in the front-end.
45600b57cec5SDimitry Andric   // If no specialized section name is applicable, it will resort to default.
45610b57cec5SDimitry Andric   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
45620b57cec5SDimitry Andric       D->hasAttr<PragmaClangDataSectionAttr>() ||
4563a7dea167SDimitry Andric       D->hasAttr<PragmaClangRelroSectionAttr>() ||
45640b57cec5SDimitry Andric       D->hasAttr<PragmaClangRodataSectionAttr>())
45650b57cec5SDimitry Andric     return true;
45660b57cec5SDimitry Andric 
45670b57cec5SDimitry Andric   // Thread local vars aren't considered common linkage.
45680b57cec5SDimitry Andric   if (D->getTLSKind())
45690b57cec5SDimitry Andric     return true;
45700b57cec5SDimitry Andric 
45710b57cec5SDimitry Andric   // Tentative definitions marked with WeakImportAttr are true definitions.
45720b57cec5SDimitry Andric   if (D->hasAttr<WeakImportAttr>())
45730b57cec5SDimitry Andric     return true;
45740b57cec5SDimitry Andric 
45750b57cec5SDimitry Andric   // A variable cannot be both common and exist in a comdat.
45760b57cec5SDimitry Andric   if (shouldBeInCOMDAT(CGM, *D))
45770b57cec5SDimitry Andric     return true;
45780b57cec5SDimitry Andric 
45790b57cec5SDimitry Andric   // Declarations with a required alignment do not have common linkage in MSVC
45800b57cec5SDimitry Andric   // mode.
45810b57cec5SDimitry Andric   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
45820b57cec5SDimitry Andric     if (D->hasAttr<AlignedAttr>())
45830b57cec5SDimitry Andric       return true;
45840b57cec5SDimitry Andric     QualType VarType = D->getType();
45850b57cec5SDimitry Andric     if (Context.isAlignmentRequired(VarType))
45860b57cec5SDimitry Andric       return true;
45870b57cec5SDimitry Andric 
45880b57cec5SDimitry Andric     if (const auto *RT = VarType->getAs<RecordType>()) {
45890b57cec5SDimitry Andric       const RecordDecl *RD = RT->getDecl();
45900b57cec5SDimitry Andric       for (const FieldDecl *FD : RD->fields()) {
45910b57cec5SDimitry Andric         if (FD->isBitField())
45920b57cec5SDimitry Andric           continue;
45930b57cec5SDimitry Andric         if (FD->hasAttr<AlignedAttr>())
45940b57cec5SDimitry Andric           return true;
45950b57cec5SDimitry Andric         if (Context.isAlignmentRequired(FD->getType()))
45960b57cec5SDimitry Andric           return true;
45970b57cec5SDimitry Andric       }
45980b57cec5SDimitry Andric     }
45990b57cec5SDimitry Andric   }
46000b57cec5SDimitry Andric 
46010b57cec5SDimitry Andric   // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
46020b57cec5SDimitry Andric   // common symbols, so symbols with greater alignment requirements cannot be
46030b57cec5SDimitry Andric   // common.
46040b57cec5SDimitry Andric   // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
46050b57cec5SDimitry Andric   // alignments for common symbols via the aligncomm directive, so this
46060b57cec5SDimitry Andric   // restriction only applies to MSVC environments.
46070b57cec5SDimitry Andric   if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
46080b57cec5SDimitry Andric       Context.getTypeAlignIfKnown(D->getType()) >
46090b57cec5SDimitry Andric           Context.toBits(CharUnits::fromQuantity(32)))
46100b57cec5SDimitry Andric     return true;
46110b57cec5SDimitry Andric 
46120b57cec5SDimitry Andric   return false;
46130b57cec5SDimitry Andric }
46140b57cec5SDimitry Andric 
getLLVMLinkageForDeclarator(const DeclaratorDecl * D,GVALinkage Linkage,bool IsConstantVariable)46150b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
46160b57cec5SDimitry Andric     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
46170b57cec5SDimitry Andric   if (Linkage == GVA_Internal)
46180b57cec5SDimitry Andric     return llvm::Function::InternalLinkage;
46190b57cec5SDimitry Andric 
46200b57cec5SDimitry Andric   if (D->hasAttr<WeakAttr>()) {
46210b57cec5SDimitry Andric     if (IsConstantVariable)
46220b57cec5SDimitry Andric       return llvm::GlobalVariable::WeakODRLinkage;
46230b57cec5SDimitry Andric     else
46240b57cec5SDimitry Andric       return llvm::GlobalVariable::WeakAnyLinkage;
46250b57cec5SDimitry Andric   }
46260b57cec5SDimitry Andric 
46270b57cec5SDimitry Andric   if (const auto *FD = D->getAsFunction())
46280b57cec5SDimitry Andric     if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
46290b57cec5SDimitry Andric       return llvm::GlobalVariable::LinkOnceAnyLinkage;
46300b57cec5SDimitry Andric 
46310b57cec5SDimitry Andric   // We are guaranteed to have a strong definition somewhere else,
46320b57cec5SDimitry Andric   // so we can use available_externally linkage.
46330b57cec5SDimitry Andric   if (Linkage == GVA_AvailableExternally)
46340b57cec5SDimitry Andric     return llvm::GlobalValue::AvailableExternallyLinkage;
46350b57cec5SDimitry Andric 
46360b57cec5SDimitry Andric   // Note that Apple's kernel linker doesn't support symbol
46370b57cec5SDimitry Andric   // coalescing, so we need to avoid linkonce and weak linkages there.
46380b57cec5SDimitry Andric   // Normally, this means we just map to internal, but for explicit
46390b57cec5SDimitry Andric   // instantiations we'll map to external.
46400b57cec5SDimitry Andric 
46410b57cec5SDimitry Andric   // In C++, the compiler has to emit a definition in every translation unit
46420b57cec5SDimitry Andric   // that references the function.  We should use linkonce_odr because
46430b57cec5SDimitry Andric   // a) if all references in this translation unit are optimized away, we
46440b57cec5SDimitry Andric   // don't need to codegen it.  b) if the function persists, it needs to be
46450b57cec5SDimitry Andric   // merged with other definitions. c) C++ has the ODR, so we know the
46460b57cec5SDimitry Andric   // definition is dependable.
46470b57cec5SDimitry Andric   if (Linkage == GVA_DiscardableODR)
46480b57cec5SDimitry Andric     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
46490b57cec5SDimitry Andric                                             : llvm::Function::InternalLinkage;
46500b57cec5SDimitry Andric 
46510b57cec5SDimitry Andric   // An explicit instantiation of a template has weak linkage, since
46520b57cec5SDimitry Andric   // explicit instantiations can occur in multiple translation units
46530b57cec5SDimitry Andric   // and must all be equivalent. However, we are not allowed to
46540b57cec5SDimitry Andric   // throw away these explicit instantiations.
46550b57cec5SDimitry Andric   //
4656af732203SDimitry Andric   // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
46570b57cec5SDimitry Andric   // so say that CUDA templates are either external (for kernels) or internal.
4658af732203SDimitry Andric   // This lets llvm perform aggressive inter-procedural optimizations. For
4659af732203SDimitry Andric   // -fgpu-rdc case, device function calls across multiple TU's are allowed,
4660af732203SDimitry Andric   // therefore we need to follow the normal linkage paradigm.
46610b57cec5SDimitry Andric   if (Linkage == GVA_StrongODR) {
4662af732203SDimitry Andric     if (getLangOpts().AppleKext)
46630b57cec5SDimitry Andric       return llvm::Function::ExternalLinkage;
4664af732203SDimitry Andric     if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
4665af732203SDimitry Andric         !getLangOpts().GPURelocatableDeviceCode)
46660b57cec5SDimitry Andric       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
46670b57cec5SDimitry Andric                                           : llvm::Function::InternalLinkage;
46680b57cec5SDimitry Andric     return llvm::Function::WeakODRLinkage;
46690b57cec5SDimitry Andric   }
46700b57cec5SDimitry Andric 
46710b57cec5SDimitry Andric   // C++ doesn't have tentative definitions and thus cannot have common
46720b57cec5SDimitry Andric   // linkage.
46730b57cec5SDimitry Andric   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
46740b57cec5SDimitry Andric       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
46750b57cec5SDimitry Andric                                  CodeGenOpts.NoCommon))
46760b57cec5SDimitry Andric     return llvm::GlobalVariable::CommonLinkage;
46770b57cec5SDimitry Andric 
46780b57cec5SDimitry Andric   // selectany symbols are externally visible, so use weak instead of
46790b57cec5SDimitry Andric   // linkonce.  MSVC optimizes away references to const selectany globals, so
46800b57cec5SDimitry Andric   // all definitions should be the same and ODR linkage should be used.
46810b57cec5SDimitry Andric   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
46820b57cec5SDimitry Andric   if (D->hasAttr<SelectAnyAttr>())
46830b57cec5SDimitry Andric     return llvm::GlobalVariable::WeakODRLinkage;
46840b57cec5SDimitry Andric 
46850b57cec5SDimitry Andric   // Otherwise, we have strong external linkage.
46860b57cec5SDimitry Andric   assert(Linkage == GVA_StrongExternal);
46870b57cec5SDimitry Andric   return llvm::GlobalVariable::ExternalLinkage;
46880b57cec5SDimitry Andric }
46890b57cec5SDimitry Andric 
getLLVMLinkageVarDefinition(const VarDecl * VD,bool IsConstant)46900b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
46910b57cec5SDimitry Andric     const VarDecl *VD, bool IsConstant) {
46920b57cec5SDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
46930b57cec5SDimitry Andric   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
46940b57cec5SDimitry Andric }
46950b57cec5SDimitry Andric 
46960b57cec5SDimitry Andric /// Replace the uses of a function that was declared with a non-proto type.
46970b57cec5SDimitry Andric /// We want to silently drop extra arguments from call sites
replaceUsesOfNonProtoConstant(llvm::Constant * old,llvm::Function * newFn)46980b57cec5SDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
46990b57cec5SDimitry Andric                                           llvm::Function *newFn) {
47000b57cec5SDimitry Andric   // Fast path.
47010b57cec5SDimitry Andric   if (old->use_empty()) return;
47020b57cec5SDimitry Andric 
47030b57cec5SDimitry Andric   llvm::Type *newRetTy = newFn->getReturnType();
47040b57cec5SDimitry Andric   SmallVector<llvm::Value*, 4> newArgs;
47050b57cec5SDimitry Andric 
47060b57cec5SDimitry Andric   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
47070b57cec5SDimitry Andric          ui != ue; ) {
47080b57cec5SDimitry Andric     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
47090b57cec5SDimitry Andric     llvm::User *user = use->getUser();
47100b57cec5SDimitry Andric 
47110b57cec5SDimitry Andric     // Recognize and replace uses of bitcasts.  Most calls to
47120b57cec5SDimitry Andric     // unprototyped functions will use bitcasts.
47130b57cec5SDimitry Andric     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
47140b57cec5SDimitry Andric       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
47150b57cec5SDimitry Andric         replaceUsesOfNonProtoConstant(bitcast, newFn);
47160b57cec5SDimitry Andric       continue;
47170b57cec5SDimitry Andric     }
47180b57cec5SDimitry Andric 
47190b57cec5SDimitry Andric     // Recognize calls to the function.
47200b57cec5SDimitry Andric     llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
47210b57cec5SDimitry Andric     if (!callSite) continue;
47220b57cec5SDimitry Andric     if (!callSite->isCallee(&*use))
47230b57cec5SDimitry Andric       continue;
47240b57cec5SDimitry Andric 
47250b57cec5SDimitry Andric     // If the return types don't match exactly, then we can't
47260b57cec5SDimitry Andric     // transform this call unless it's dead.
47270b57cec5SDimitry Andric     if (callSite->getType() != newRetTy && !callSite->use_empty())
47280b57cec5SDimitry Andric       continue;
47290b57cec5SDimitry Andric 
47300b57cec5SDimitry Andric     // Get the call site's attribute list.
47310b57cec5SDimitry Andric     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
47320b57cec5SDimitry Andric     llvm::AttributeList oldAttrs = callSite->getAttributes();
47330b57cec5SDimitry Andric 
47340b57cec5SDimitry Andric     // If the function was passed too few arguments, don't transform.
47350b57cec5SDimitry Andric     unsigned newNumArgs = newFn->arg_size();
47360b57cec5SDimitry Andric     if (callSite->arg_size() < newNumArgs)
47370b57cec5SDimitry Andric       continue;
47380b57cec5SDimitry Andric 
47390b57cec5SDimitry Andric     // If extra arguments were passed, we silently drop them.
47400b57cec5SDimitry Andric     // If any of the types mismatch, we don't transform.
47410b57cec5SDimitry Andric     unsigned argNo = 0;
47420b57cec5SDimitry Andric     bool dontTransform = false;
47430b57cec5SDimitry Andric     for (llvm::Argument &A : newFn->args()) {
47440b57cec5SDimitry Andric       if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
47450b57cec5SDimitry Andric         dontTransform = true;
47460b57cec5SDimitry Andric         break;
47470b57cec5SDimitry Andric       }
47480b57cec5SDimitry Andric 
47490b57cec5SDimitry Andric       // Add any parameter attributes.
47500b57cec5SDimitry Andric       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
47510b57cec5SDimitry Andric       argNo++;
47520b57cec5SDimitry Andric     }
47530b57cec5SDimitry Andric     if (dontTransform)
47540b57cec5SDimitry Andric       continue;
47550b57cec5SDimitry Andric 
47560b57cec5SDimitry Andric     // Okay, we can transform this.  Create the new call instruction and copy
47570b57cec5SDimitry Andric     // over the required information.
47580b57cec5SDimitry Andric     newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
47590b57cec5SDimitry Andric 
47600b57cec5SDimitry Andric     // Copy over any operand bundles.
47615f7ddb14SDimitry Andric     SmallVector<llvm::OperandBundleDef, 1> newBundles;
47620b57cec5SDimitry Andric     callSite->getOperandBundlesAsDefs(newBundles);
47630b57cec5SDimitry Andric 
47640b57cec5SDimitry Andric     llvm::CallBase *newCall;
47650b57cec5SDimitry Andric     if (dyn_cast<llvm::CallInst>(callSite)) {
47660b57cec5SDimitry Andric       newCall =
47670b57cec5SDimitry Andric           llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
47680b57cec5SDimitry Andric     } else {
47690b57cec5SDimitry Andric       auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
47700b57cec5SDimitry Andric       newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
47710b57cec5SDimitry Andric                                          oldInvoke->getUnwindDest(), newArgs,
47720b57cec5SDimitry Andric                                          newBundles, "", callSite);
47730b57cec5SDimitry Andric     }
47740b57cec5SDimitry Andric     newArgs.clear(); // for the next iteration
47750b57cec5SDimitry Andric 
47760b57cec5SDimitry Andric     if (!newCall->getType()->isVoidTy())
47770b57cec5SDimitry Andric       newCall->takeName(callSite);
47780b57cec5SDimitry Andric     newCall->setAttributes(llvm::AttributeList::get(
47790b57cec5SDimitry Andric         newFn->getContext(), oldAttrs.getFnAttributes(),
47800b57cec5SDimitry Andric         oldAttrs.getRetAttributes(), newArgAttrs));
47810b57cec5SDimitry Andric     newCall->setCallingConv(callSite->getCallingConv());
47820b57cec5SDimitry Andric 
47830b57cec5SDimitry Andric     // Finally, remove the old call, replacing any uses with the new one.
47840b57cec5SDimitry Andric     if (!callSite->use_empty())
47850b57cec5SDimitry Andric       callSite->replaceAllUsesWith(newCall);
47860b57cec5SDimitry Andric 
47870b57cec5SDimitry Andric     // Copy debug location attached to CI.
47880b57cec5SDimitry Andric     if (callSite->getDebugLoc())
47890b57cec5SDimitry Andric       newCall->setDebugLoc(callSite->getDebugLoc());
47900b57cec5SDimitry Andric 
47910b57cec5SDimitry Andric     callSite->eraseFromParent();
47920b57cec5SDimitry Andric   }
47930b57cec5SDimitry Andric }
47940b57cec5SDimitry Andric 
47950b57cec5SDimitry Andric /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
47960b57cec5SDimitry Andric /// implement a function with no prototype, e.g. "int foo() {}".  If there are
47970b57cec5SDimitry Andric /// existing call uses of the old function in the module, this adjusts them to
47980b57cec5SDimitry Andric /// call the new function directly.
47990b57cec5SDimitry Andric ///
48000b57cec5SDimitry Andric /// This is not just a cleanup: the always_inline pass requires direct calls to
48010b57cec5SDimitry Andric /// functions to be able to inline them.  If there is a bitcast in the way, it
48020b57cec5SDimitry Andric /// won't inline them.  Instcombine normally deletes these calls, but it isn't
48030b57cec5SDimitry Andric /// run at -O0.
ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue * Old,llvm::Function * NewFn)48040b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
48050b57cec5SDimitry Andric                                                       llvm::Function *NewFn) {
48060b57cec5SDimitry Andric   // If we're redefining a global as a function, don't transform it.
48070b57cec5SDimitry Andric   if (!isa<llvm::Function>(Old)) return;
48080b57cec5SDimitry Andric 
48090b57cec5SDimitry Andric   replaceUsesOfNonProtoConstant(Old, NewFn);
48100b57cec5SDimitry Andric }
48110b57cec5SDimitry Andric 
HandleCXXStaticMemberVarInstantiation(VarDecl * VD)48120b57cec5SDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
48130b57cec5SDimitry Andric   auto DK = VD->isThisDeclarationADefinition();
48140b57cec5SDimitry Andric   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
48150b57cec5SDimitry Andric     return;
48160b57cec5SDimitry Andric 
48170b57cec5SDimitry Andric   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
48180b57cec5SDimitry Andric   // If we have a definition, this might be a deferred decl. If the
48190b57cec5SDimitry Andric   // instantiation is explicit, make sure we emit it at the end.
48200b57cec5SDimitry Andric   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
48210b57cec5SDimitry Andric     GetAddrOfGlobalVar(VD);
48220b57cec5SDimitry Andric 
48230b57cec5SDimitry Andric   EmitTopLevelDecl(VD);
48240b57cec5SDimitry Andric }
48250b57cec5SDimitry Andric 
EmitGlobalFunctionDefinition(GlobalDecl GD,llvm::GlobalValue * GV)48260b57cec5SDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
48270b57cec5SDimitry Andric                                                  llvm::GlobalValue *GV) {
48280b57cec5SDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
48290b57cec5SDimitry Andric 
48300b57cec5SDimitry Andric   // Compute the function info and LLVM type.
48310b57cec5SDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
48320b57cec5SDimitry Andric   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
48330b57cec5SDimitry Andric 
48340b57cec5SDimitry Andric   // Get or create the prototype for the function.
48355ffd83dbSDimitry Andric   if (!GV || (GV->getValueType() != Ty))
48360b57cec5SDimitry Andric     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
48370b57cec5SDimitry Andric                                                    /*DontDefer=*/true,
48380b57cec5SDimitry Andric                                                    ForDefinition));
48390b57cec5SDimitry Andric 
48400b57cec5SDimitry Andric   // Already emitted.
48410b57cec5SDimitry Andric   if (!GV->isDeclaration())
48420b57cec5SDimitry Andric     return;
48430b57cec5SDimitry Andric 
48440b57cec5SDimitry Andric   // We need to set linkage and visibility on the function before
48450b57cec5SDimitry Andric   // generating code for it because various parts of IR generation
48460b57cec5SDimitry Andric   // want to propagate this information down (e.g. to local static
48470b57cec5SDimitry Andric   // declarations).
48480b57cec5SDimitry Andric   auto *Fn = cast<llvm::Function>(GV);
48490b57cec5SDimitry Andric   setFunctionLinkage(GD, Fn);
48500b57cec5SDimitry Andric 
48510b57cec5SDimitry Andric   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
48520b57cec5SDimitry Andric   setGVProperties(Fn, GD);
48530b57cec5SDimitry Andric 
48540b57cec5SDimitry Andric   MaybeHandleStaticInExternC(D, Fn);
48550b57cec5SDimitry Andric 
48560b57cec5SDimitry Andric   maybeSetTrivialComdat(*D, *Fn);
48570b57cec5SDimitry Andric 
4858af732203SDimitry Andric   // Set CodeGen attributes that represent floating point environment.
4859af732203SDimitry Andric   setLLVMFunctionFEnvAttributes(D, Fn);
4860af732203SDimitry Andric 
48615ffd83dbSDimitry Andric   CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
48620b57cec5SDimitry Andric 
48630b57cec5SDimitry Andric   setNonAliasAttributes(GD, Fn);
48640b57cec5SDimitry Andric   SetLLVMFunctionAttributesForDefinition(D, Fn);
48650b57cec5SDimitry Andric 
48660b57cec5SDimitry Andric   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
48670b57cec5SDimitry Andric     AddGlobalCtor(Fn, CA->getPriority());
48680b57cec5SDimitry Andric   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
4869af732203SDimitry Andric     AddGlobalDtor(Fn, DA->getPriority(), true);
48700b57cec5SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
48710b57cec5SDimitry Andric     AddGlobalAnnotations(D, Fn);
48720b57cec5SDimitry Andric }
48730b57cec5SDimitry Andric 
EmitAliasDefinition(GlobalDecl GD)48740b57cec5SDimitry Andric void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
48750b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
48760b57cec5SDimitry Andric   const AliasAttr *AA = D->getAttr<AliasAttr>();
48770b57cec5SDimitry Andric   assert(AA && "Not an alias?");
48780b57cec5SDimitry Andric 
48790b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
48800b57cec5SDimitry Andric 
48810b57cec5SDimitry Andric   if (AA->getAliasee() == MangledName) {
48820b57cec5SDimitry Andric     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
48830b57cec5SDimitry Andric     return;
48840b57cec5SDimitry Andric   }
48850b57cec5SDimitry Andric 
48860b57cec5SDimitry Andric   // If there is a definition in the module, then it wins over the alias.
48870b57cec5SDimitry Andric   // This is dubious, but allow it to be safe.  Just ignore the alias.
48880b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
48890b57cec5SDimitry Andric   if (Entry && !Entry->isDeclaration())
48900b57cec5SDimitry Andric     return;
48910b57cec5SDimitry Andric 
48920b57cec5SDimitry Andric   Aliases.push_back(GD);
48930b57cec5SDimitry Andric 
48940b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
48950b57cec5SDimitry Andric 
48960b57cec5SDimitry Andric   // Create a reference to the named value.  This ensures that it is emitted
48970b57cec5SDimitry Andric   // if a deferred decl.
48980b57cec5SDimitry Andric   llvm::Constant *Aliasee;
48990b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
49000b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(DeclTy)) {
49010b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
49020b57cec5SDimitry Andric                                       /*ForVTable=*/false);
49030b57cec5SDimitry Andric     LT = getFunctionLinkage(GD);
49040b57cec5SDimitry Andric   } else {
49055f7ddb14SDimitry Andric     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, 0,
49060b57cec5SDimitry Andric                                     /*D=*/nullptr);
4907af732203SDimitry Andric     if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl()))
4908af732203SDimitry Andric       LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified());
4909af732203SDimitry Andric     else
4910af732203SDimitry Andric       LT = getFunctionLinkage(GD);
49110b57cec5SDimitry Andric   }
49120b57cec5SDimitry Andric 
49130b57cec5SDimitry Andric   // Create the new alias itself, but don't set a name yet.
49145ffd83dbSDimitry Andric   unsigned AS = Aliasee->getType()->getPointerAddressSpace();
49150b57cec5SDimitry Andric   auto *GA =
49165ffd83dbSDimitry Andric       llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
49170b57cec5SDimitry Andric 
49180b57cec5SDimitry Andric   if (Entry) {
49190b57cec5SDimitry Andric     if (GA->getAliasee() == Entry) {
49200b57cec5SDimitry Andric       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
49210b57cec5SDimitry Andric       return;
49220b57cec5SDimitry Andric     }
49230b57cec5SDimitry Andric 
49240b57cec5SDimitry Andric     assert(Entry->isDeclaration());
49250b57cec5SDimitry Andric 
49260b57cec5SDimitry Andric     // If there is a declaration in the module, then we had an extern followed
49270b57cec5SDimitry Andric     // by the alias, as in:
49280b57cec5SDimitry Andric     //   extern int test6();
49290b57cec5SDimitry Andric     //   ...
49300b57cec5SDimitry Andric     //   int test6() __attribute__((alias("test7")));
49310b57cec5SDimitry Andric     //
49320b57cec5SDimitry Andric     // Remove it and replace uses of it with the alias.
49330b57cec5SDimitry Andric     GA->takeName(Entry);
49340b57cec5SDimitry Andric 
49350b57cec5SDimitry Andric     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
49360b57cec5SDimitry Andric                                                           Entry->getType()));
49370b57cec5SDimitry Andric     Entry->eraseFromParent();
49380b57cec5SDimitry Andric   } else {
49390b57cec5SDimitry Andric     GA->setName(MangledName);
49400b57cec5SDimitry Andric   }
49410b57cec5SDimitry Andric 
49420b57cec5SDimitry Andric   // Set attributes which are particular to an alias; this is a
49430b57cec5SDimitry Andric   // specialization of the attributes which may be set on a global
49440b57cec5SDimitry Andric   // variable/function.
49450b57cec5SDimitry Andric   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
49460b57cec5SDimitry Andric       D->isWeakImported()) {
49470b57cec5SDimitry Andric     GA->setLinkage(llvm::Function::WeakAnyLinkage);
49480b57cec5SDimitry Andric   }
49490b57cec5SDimitry Andric 
49500b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
49510b57cec5SDimitry Andric     if (VD->getTLSKind())
49520b57cec5SDimitry Andric       setTLSMode(GA, *VD);
49530b57cec5SDimitry Andric 
49540b57cec5SDimitry Andric   SetCommonAttributes(GD, GA);
49550b57cec5SDimitry Andric }
49560b57cec5SDimitry Andric 
emitIFuncDefinition(GlobalDecl GD)49570b57cec5SDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
49580b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
49590b57cec5SDimitry Andric   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
49600b57cec5SDimitry Andric   assert(IFA && "Not an ifunc?");
49610b57cec5SDimitry Andric 
49620b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
49630b57cec5SDimitry Andric 
49640b57cec5SDimitry Andric   if (IFA->getResolver() == MangledName) {
49650b57cec5SDimitry Andric     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
49660b57cec5SDimitry Andric     return;
49670b57cec5SDimitry Andric   }
49680b57cec5SDimitry Andric 
49690b57cec5SDimitry Andric   // Report an error if some definition overrides ifunc.
49700b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
49710b57cec5SDimitry Andric   if (Entry && !Entry->isDeclaration()) {
49720b57cec5SDimitry Andric     GlobalDecl OtherGD;
49730b57cec5SDimitry Andric     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
49740b57cec5SDimitry Andric         DiagnosedConflictingDefinitions.insert(GD).second) {
49750b57cec5SDimitry Andric       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
49760b57cec5SDimitry Andric           << MangledName;
49770b57cec5SDimitry Andric       Diags.Report(OtherGD.getDecl()->getLocation(),
49780b57cec5SDimitry Andric                    diag::note_previous_definition);
49790b57cec5SDimitry Andric     }
49800b57cec5SDimitry Andric     return;
49810b57cec5SDimitry Andric   }
49820b57cec5SDimitry Andric 
49830b57cec5SDimitry Andric   Aliases.push_back(GD);
49840b57cec5SDimitry Andric 
49850b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
49860b57cec5SDimitry Andric   llvm::Constant *Resolver =
49870b57cec5SDimitry Andric       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
49880b57cec5SDimitry Andric                               /*ForVTable=*/false);
49890b57cec5SDimitry Andric   llvm::GlobalIFunc *GIF =
49900b57cec5SDimitry Andric       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
49910b57cec5SDimitry Andric                                 "", Resolver, &getModule());
49920b57cec5SDimitry Andric   if (Entry) {
49930b57cec5SDimitry Andric     if (GIF->getResolver() == Entry) {
49940b57cec5SDimitry Andric       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
49950b57cec5SDimitry Andric       return;
49960b57cec5SDimitry Andric     }
49970b57cec5SDimitry Andric     assert(Entry->isDeclaration());
49980b57cec5SDimitry Andric 
49990b57cec5SDimitry Andric     // If there is a declaration in the module, then we had an extern followed
50000b57cec5SDimitry Andric     // by the ifunc, as in:
50010b57cec5SDimitry Andric     //   extern int test();
50020b57cec5SDimitry Andric     //   ...
50030b57cec5SDimitry Andric     //   int test() __attribute__((ifunc("resolver")));
50040b57cec5SDimitry Andric     //
50050b57cec5SDimitry Andric     // Remove it and replace uses of it with the ifunc.
50060b57cec5SDimitry Andric     GIF->takeName(Entry);
50070b57cec5SDimitry Andric 
50080b57cec5SDimitry Andric     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
50090b57cec5SDimitry Andric                                                           Entry->getType()));
50100b57cec5SDimitry Andric     Entry->eraseFromParent();
50110b57cec5SDimitry Andric   } else
50120b57cec5SDimitry Andric     GIF->setName(MangledName);
50130b57cec5SDimitry Andric 
50140b57cec5SDimitry Andric   SetCommonAttributes(GD, GIF);
50150b57cec5SDimitry Andric }
50160b57cec5SDimitry Andric 
getIntrinsic(unsigned IID,ArrayRef<llvm::Type * > Tys)50170b57cec5SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
50180b57cec5SDimitry Andric                                             ArrayRef<llvm::Type*> Tys) {
50190b57cec5SDimitry Andric   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
50200b57cec5SDimitry Andric                                          Tys);
50210b57cec5SDimitry Andric }
50220b57cec5SDimitry Andric 
50230b57cec5SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> &
GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable * > & Map,const StringLiteral * Literal,bool TargetIsLSB,bool & IsUTF16,unsigned & StringLength)50240b57cec5SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
50250b57cec5SDimitry Andric                          const StringLiteral *Literal, bool TargetIsLSB,
50260b57cec5SDimitry Andric                          bool &IsUTF16, unsigned &StringLength) {
50270b57cec5SDimitry Andric   StringRef String = Literal->getString();
50280b57cec5SDimitry Andric   unsigned NumBytes = String.size();
50290b57cec5SDimitry Andric 
50300b57cec5SDimitry Andric   // Check for simple case.
50310b57cec5SDimitry Andric   if (!Literal->containsNonAsciiOrNull()) {
50320b57cec5SDimitry Andric     StringLength = NumBytes;
50330b57cec5SDimitry Andric     return *Map.insert(std::make_pair(String, nullptr)).first;
50340b57cec5SDimitry Andric   }
50350b57cec5SDimitry Andric 
50360b57cec5SDimitry Andric   // Otherwise, convert the UTF8 literals into a string of shorts.
50370b57cec5SDimitry Andric   IsUTF16 = true;
50380b57cec5SDimitry Andric 
50390b57cec5SDimitry Andric   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
50400b57cec5SDimitry Andric   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
50410b57cec5SDimitry Andric   llvm::UTF16 *ToPtr = &ToBuf[0];
50420b57cec5SDimitry Andric 
50430b57cec5SDimitry Andric   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
50440b57cec5SDimitry Andric                                  ToPtr + NumBytes, llvm::strictConversion);
50450b57cec5SDimitry Andric 
50460b57cec5SDimitry Andric   // ConvertUTF8toUTF16 returns the length in ToPtr.
50470b57cec5SDimitry Andric   StringLength = ToPtr - &ToBuf[0];
50480b57cec5SDimitry Andric 
50490b57cec5SDimitry Andric   // Add an explicit null.
50500b57cec5SDimitry Andric   *ToPtr = 0;
50510b57cec5SDimitry Andric   return *Map.insert(std::make_pair(
50520b57cec5SDimitry Andric                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
50530b57cec5SDimitry Andric                                    (StringLength + 1) * 2),
50540b57cec5SDimitry Andric                          nullptr)).first;
50550b57cec5SDimitry Andric }
50560b57cec5SDimitry Andric 
50570b57cec5SDimitry Andric ConstantAddress
GetAddrOfConstantCFString(const StringLiteral * Literal)50580b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
50590b57cec5SDimitry Andric   unsigned StringLength = 0;
50600b57cec5SDimitry Andric   bool isUTF16 = false;
50610b57cec5SDimitry Andric   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
50620b57cec5SDimitry Andric       GetConstantCFStringEntry(CFConstantStringMap, Literal,
50630b57cec5SDimitry Andric                                getDataLayout().isLittleEndian(), isUTF16,
50640b57cec5SDimitry Andric                                StringLength);
50650b57cec5SDimitry Andric 
50660b57cec5SDimitry Andric   if (auto *C = Entry.second)
50670b57cec5SDimitry Andric     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
50680b57cec5SDimitry Andric 
50690b57cec5SDimitry Andric   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
50700b57cec5SDimitry Andric   llvm::Constant *Zeros[] = { Zero, Zero };
50710b57cec5SDimitry Andric 
50720b57cec5SDimitry Andric   const ASTContext &Context = getContext();
50730b57cec5SDimitry Andric   const llvm::Triple &Triple = getTriple();
50740b57cec5SDimitry Andric 
50750b57cec5SDimitry Andric   const auto CFRuntime = getLangOpts().CFRuntime;
50760b57cec5SDimitry Andric   const bool IsSwiftABI =
50770b57cec5SDimitry Andric       static_cast<unsigned>(CFRuntime) >=
50780b57cec5SDimitry Andric       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
50790b57cec5SDimitry Andric   const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
50800b57cec5SDimitry Andric 
50810b57cec5SDimitry Andric   // If we don't already have it, get __CFConstantStringClassReference.
50820b57cec5SDimitry Andric   if (!CFConstantStringClassRef) {
50830b57cec5SDimitry Andric     const char *CFConstantStringClassName = "__CFConstantStringClassReference";
50840b57cec5SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
50850b57cec5SDimitry Andric     Ty = llvm::ArrayType::get(Ty, 0);
50860b57cec5SDimitry Andric 
50870b57cec5SDimitry Andric     switch (CFRuntime) {
50880b57cec5SDimitry Andric     default: break;
50890b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
50900b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift5_0:
50910b57cec5SDimitry Andric       CFConstantStringClassName =
50920b57cec5SDimitry Andric           Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
50930b57cec5SDimitry Andric                               : "$s10Foundation19_NSCFConstantStringCN";
50940b57cec5SDimitry Andric       Ty = IntPtrTy;
50950b57cec5SDimitry Andric       break;
50960b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift4_2:
50970b57cec5SDimitry Andric       CFConstantStringClassName =
50980b57cec5SDimitry Andric           Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
50990b57cec5SDimitry Andric                               : "$S10Foundation19_NSCFConstantStringCN";
51000b57cec5SDimitry Andric       Ty = IntPtrTy;
51010b57cec5SDimitry Andric       break;
51020b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift4_1:
51030b57cec5SDimitry Andric       CFConstantStringClassName =
51040b57cec5SDimitry Andric           Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
51050b57cec5SDimitry Andric                               : "__T010Foundation19_NSCFConstantStringCN";
51060b57cec5SDimitry Andric       Ty = IntPtrTy;
51070b57cec5SDimitry Andric       break;
51080b57cec5SDimitry Andric     }
51090b57cec5SDimitry Andric 
51100b57cec5SDimitry Andric     llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
51110b57cec5SDimitry Andric 
51120b57cec5SDimitry Andric     if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
51130b57cec5SDimitry Andric       llvm::GlobalValue *GV = nullptr;
51140b57cec5SDimitry Andric 
51150b57cec5SDimitry Andric       if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
51160b57cec5SDimitry Andric         IdentifierInfo &II = Context.Idents.get(GV->getName());
51170b57cec5SDimitry Andric         TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
51180b57cec5SDimitry Andric         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
51190b57cec5SDimitry Andric 
51200b57cec5SDimitry Andric         const VarDecl *VD = nullptr;
51215f7ddb14SDimitry Andric         for (const auto *Result : DC->lookup(&II))
51220b57cec5SDimitry Andric           if ((VD = dyn_cast<VarDecl>(Result)))
51230b57cec5SDimitry Andric             break;
51240b57cec5SDimitry Andric 
51250b57cec5SDimitry Andric         if (Triple.isOSBinFormatELF()) {
51260b57cec5SDimitry Andric           if (!VD)
51270b57cec5SDimitry Andric             GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
51280b57cec5SDimitry Andric         } else {
51290b57cec5SDimitry Andric           GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
51300b57cec5SDimitry Andric           if (!VD || !VD->hasAttr<DLLExportAttr>())
51310b57cec5SDimitry Andric             GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
51320b57cec5SDimitry Andric           else
51330b57cec5SDimitry Andric             GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
51340b57cec5SDimitry Andric         }
51350b57cec5SDimitry Andric 
51360b57cec5SDimitry Andric         setDSOLocal(GV);
51370b57cec5SDimitry Andric       }
51380b57cec5SDimitry Andric     }
51390b57cec5SDimitry Andric 
51400b57cec5SDimitry Andric     // Decay array -> ptr
51410b57cec5SDimitry Andric     CFConstantStringClassRef =
51420b57cec5SDimitry Andric         IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
51430b57cec5SDimitry Andric                    : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
51440b57cec5SDimitry Andric   }
51450b57cec5SDimitry Andric 
51460b57cec5SDimitry Andric   QualType CFTy = Context.getCFConstantStringType();
51470b57cec5SDimitry Andric 
51480b57cec5SDimitry Andric   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
51490b57cec5SDimitry Andric 
51500b57cec5SDimitry Andric   ConstantInitBuilder Builder(*this);
51510b57cec5SDimitry Andric   auto Fields = Builder.beginStruct(STy);
51520b57cec5SDimitry Andric 
51530b57cec5SDimitry Andric   // Class pointer.
51540b57cec5SDimitry Andric   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
51550b57cec5SDimitry Andric 
51560b57cec5SDimitry Andric   // Flags.
51570b57cec5SDimitry Andric   if (IsSwiftABI) {
51580b57cec5SDimitry Andric     Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
51590b57cec5SDimitry Andric     Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
51600b57cec5SDimitry Andric   } else {
51610b57cec5SDimitry Andric     Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
51620b57cec5SDimitry Andric   }
51630b57cec5SDimitry Andric 
51640b57cec5SDimitry Andric   // String pointer.
51650b57cec5SDimitry Andric   llvm::Constant *C = nullptr;
51660b57cec5SDimitry Andric   if (isUTF16) {
51670b57cec5SDimitry Andric     auto Arr = llvm::makeArrayRef(
51680b57cec5SDimitry Andric         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
51690b57cec5SDimitry Andric         Entry.first().size() / 2);
51700b57cec5SDimitry Andric     C = llvm::ConstantDataArray::get(VMContext, Arr);
51710b57cec5SDimitry Andric   } else {
51720b57cec5SDimitry Andric     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
51730b57cec5SDimitry Andric   }
51740b57cec5SDimitry Andric 
51750b57cec5SDimitry Andric   // Note: -fwritable-strings doesn't make the backing store strings of
51760b57cec5SDimitry Andric   // CFStrings writable. (See <rdar://problem/10657500>)
51770b57cec5SDimitry Andric   auto *GV =
51780b57cec5SDimitry Andric       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
51790b57cec5SDimitry Andric                                llvm::GlobalValue::PrivateLinkage, C, ".str");
51800b57cec5SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
51810b57cec5SDimitry Andric   // Don't enforce the target's minimum global alignment, since the only use
51820b57cec5SDimitry Andric   // of the string is via this class initializer.
51830b57cec5SDimitry Andric   CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
51840b57cec5SDimitry Andric                             : Context.getTypeAlignInChars(Context.CharTy);
5185a7dea167SDimitry Andric   GV->setAlignment(Align.getAsAlign());
51860b57cec5SDimitry Andric 
51870b57cec5SDimitry Andric   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
51880b57cec5SDimitry Andric   // Without it LLVM can merge the string with a non unnamed_addr one during
51890b57cec5SDimitry Andric   // LTO.  Doing that changes the section it ends in, which surprises ld64.
51900b57cec5SDimitry Andric   if (Triple.isOSBinFormatMachO())
51910b57cec5SDimitry Andric     GV->setSection(isUTF16 ? "__TEXT,__ustring"
51920b57cec5SDimitry Andric                            : "__TEXT,__cstring,cstring_literals");
51930b57cec5SDimitry Andric   // Make sure the literal ends up in .rodata to allow for safe ICF and for
51940b57cec5SDimitry Andric   // the static linker to adjust permissions to read-only later on.
51950b57cec5SDimitry Andric   else if (Triple.isOSBinFormatELF())
51960b57cec5SDimitry Andric     GV->setSection(".rodata");
51970b57cec5SDimitry Andric 
51980b57cec5SDimitry Andric   // String.
51990b57cec5SDimitry Andric   llvm::Constant *Str =
52000b57cec5SDimitry Andric       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
52010b57cec5SDimitry Andric 
52020b57cec5SDimitry Andric   if (isUTF16)
52030b57cec5SDimitry Andric     // Cast the UTF16 string to the correct type.
52040b57cec5SDimitry Andric     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
52050b57cec5SDimitry Andric   Fields.add(Str);
52060b57cec5SDimitry Andric 
52070b57cec5SDimitry Andric   // String length.
52080b57cec5SDimitry Andric   llvm::IntegerType *LengthTy =
52090b57cec5SDimitry Andric       llvm::IntegerType::get(getModule().getContext(),
52100b57cec5SDimitry Andric                              Context.getTargetInfo().getLongWidth());
52110b57cec5SDimitry Andric   if (IsSwiftABI) {
52120b57cec5SDimitry Andric     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
52130b57cec5SDimitry Andric         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
52140b57cec5SDimitry Andric       LengthTy = Int32Ty;
52150b57cec5SDimitry Andric     else
52160b57cec5SDimitry Andric       LengthTy = IntPtrTy;
52170b57cec5SDimitry Andric   }
52180b57cec5SDimitry Andric   Fields.addInt(LengthTy, StringLength);
52190b57cec5SDimitry Andric 
5220a7dea167SDimitry Andric   // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
5221a7dea167SDimitry Andric   // properly aligned on 32-bit platforms.
5222a7dea167SDimitry Andric   CharUnits Alignment =
5223a7dea167SDimitry Andric       IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
52240b57cec5SDimitry Andric 
52250b57cec5SDimitry Andric   // The struct.
52260b57cec5SDimitry Andric   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
52270b57cec5SDimitry Andric                                     /*isConstant=*/false,
52280b57cec5SDimitry Andric                                     llvm::GlobalVariable::PrivateLinkage);
52290b57cec5SDimitry Andric   GV->addAttribute("objc_arc_inert");
52300b57cec5SDimitry Andric   switch (Triple.getObjectFormat()) {
52310b57cec5SDimitry Andric   case llvm::Triple::UnknownObjectFormat:
52320b57cec5SDimitry Andric     llvm_unreachable("unknown file format");
5233af732203SDimitry Andric   case llvm::Triple::GOFF:
5234af732203SDimitry Andric     llvm_unreachable("GOFF is not yet implemented");
52350b57cec5SDimitry Andric   case llvm::Triple::XCOFF:
52360b57cec5SDimitry Andric     llvm_unreachable("XCOFF is not yet implemented");
52370b57cec5SDimitry Andric   case llvm::Triple::COFF:
52380b57cec5SDimitry Andric   case llvm::Triple::ELF:
52390b57cec5SDimitry Andric   case llvm::Triple::Wasm:
52400b57cec5SDimitry Andric     GV->setSection("cfstring");
52410b57cec5SDimitry Andric     break;
52420b57cec5SDimitry Andric   case llvm::Triple::MachO:
52430b57cec5SDimitry Andric     GV->setSection("__DATA,__cfstring");
52440b57cec5SDimitry Andric     break;
52450b57cec5SDimitry Andric   }
52460b57cec5SDimitry Andric   Entry.second = GV;
52470b57cec5SDimitry Andric 
52480b57cec5SDimitry Andric   return ConstantAddress(GV, Alignment);
52490b57cec5SDimitry Andric }
52500b57cec5SDimitry Andric 
getExpressionLocationsEnabled() const52510b57cec5SDimitry Andric bool CodeGenModule::getExpressionLocationsEnabled() const {
52520b57cec5SDimitry Andric   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
52530b57cec5SDimitry Andric }
52540b57cec5SDimitry Andric 
getObjCFastEnumerationStateType()52550b57cec5SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() {
52560b57cec5SDimitry Andric   if (ObjCFastEnumerationStateType.isNull()) {
52570b57cec5SDimitry Andric     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
52580b57cec5SDimitry Andric     D->startDefinition();
52590b57cec5SDimitry Andric 
52600b57cec5SDimitry Andric     QualType FieldTypes[] = {
52610b57cec5SDimitry Andric       Context.UnsignedLongTy,
52620b57cec5SDimitry Andric       Context.getPointerType(Context.getObjCIdType()),
52630b57cec5SDimitry Andric       Context.getPointerType(Context.UnsignedLongTy),
52640b57cec5SDimitry Andric       Context.getConstantArrayType(Context.UnsignedLongTy,
5265a7dea167SDimitry Andric                            llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
52660b57cec5SDimitry Andric     };
52670b57cec5SDimitry Andric 
52680b57cec5SDimitry Andric     for (size_t i = 0; i < 4; ++i) {
52690b57cec5SDimitry Andric       FieldDecl *Field = FieldDecl::Create(Context,
52700b57cec5SDimitry Andric                                            D,
52710b57cec5SDimitry Andric                                            SourceLocation(),
52720b57cec5SDimitry Andric                                            SourceLocation(), nullptr,
52730b57cec5SDimitry Andric                                            FieldTypes[i], /*TInfo=*/nullptr,
52740b57cec5SDimitry Andric                                            /*BitWidth=*/nullptr,
52750b57cec5SDimitry Andric                                            /*Mutable=*/false,
52760b57cec5SDimitry Andric                                            ICIS_NoInit);
52770b57cec5SDimitry Andric       Field->setAccess(AS_public);
52780b57cec5SDimitry Andric       D->addDecl(Field);
52790b57cec5SDimitry Andric     }
52800b57cec5SDimitry Andric 
52810b57cec5SDimitry Andric     D->completeDefinition();
52820b57cec5SDimitry Andric     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
52830b57cec5SDimitry Andric   }
52840b57cec5SDimitry Andric 
52850b57cec5SDimitry Andric   return ObjCFastEnumerationStateType;
52860b57cec5SDimitry Andric }
52870b57cec5SDimitry Andric 
52880b57cec5SDimitry Andric llvm::Constant *
GetConstantArrayFromStringLiteral(const StringLiteral * E)52890b57cec5SDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
52900b57cec5SDimitry Andric   assert(!E->getType()->isPointerType() && "Strings are always arrays");
52910b57cec5SDimitry Andric 
52920b57cec5SDimitry Andric   // Don't emit it as the address of the string, emit the string data itself
52930b57cec5SDimitry Andric   // as an inline array.
52940b57cec5SDimitry Andric   if (E->getCharByteWidth() == 1) {
52950b57cec5SDimitry Andric     SmallString<64> Str(E->getString());
52960b57cec5SDimitry Andric 
52970b57cec5SDimitry Andric     // Resize the string to the right size, which is indicated by its type.
52980b57cec5SDimitry Andric     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
52990b57cec5SDimitry Andric     Str.resize(CAT->getSize().getZExtValue());
53000b57cec5SDimitry Andric     return llvm::ConstantDataArray::getString(VMContext, Str, false);
53010b57cec5SDimitry Andric   }
53020b57cec5SDimitry Andric 
53030b57cec5SDimitry Andric   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
53040b57cec5SDimitry Andric   llvm::Type *ElemTy = AType->getElementType();
53050b57cec5SDimitry Andric   unsigned NumElements = AType->getNumElements();
53060b57cec5SDimitry Andric 
53070b57cec5SDimitry Andric   // Wide strings have either 2-byte or 4-byte elements.
53080b57cec5SDimitry Andric   if (ElemTy->getPrimitiveSizeInBits() == 16) {
53090b57cec5SDimitry Andric     SmallVector<uint16_t, 32> Elements;
53100b57cec5SDimitry Andric     Elements.reserve(NumElements);
53110b57cec5SDimitry Andric 
53120b57cec5SDimitry Andric     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
53130b57cec5SDimitry Andric       Elements.push_back(E->getCodeUnit(i));
53140b57cec5SDimitry Andric     Elements.resize(NumElements);
53150b57cec5SDimitry Andric     return llvm::ConstantDataArray::get(VMContext, Elements);
53160b57cec5SDimitry Andric   }
53170b57cec5SDimitry Andric 
53180b57cec5SDimitry Andric   assert(ElemTy->getPrimitiveSizeInBits() == 32);
53190b57cec5SDimitry Andric   SmallVector<uint32_t, 32> Elements;
53200b57cec5SDimitry Andric   Elements.reserve(NumElements);
53210b57cec5SDimitry Andric 
53220b57cec5SDimitry Andric   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
53230b57cec5SDimitry Andric     Elements.push_back(E->getCodeUnit(i));
53240b57cec5SDimitry Andric   Elements.resize(NumElements);
53250b57cec5SDimitry Andric   return llvm::ConstantDataArray::get(VMContext, Elements);
53260b57cec5SDimitry Andric }
53270b57cec5SDimitry Andric 
53280b57cec5SDimitry Andric static llvm::GlobalVariable *
GenerateStringLiteral(llvm::Constant * C,llvm::GlobalValue::LinkageTypes LT,CodeGenModule & CGM,StringRef GlobalName,CharUnits Alignment)53290b57cec5SDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
53300b57cec5SDimitry Andric                       CodeGenModule &CGM, StringRef GlobalName,
53310b57cec5SDimitry Andric                       CharUnits Alignment) {
53320b57cec5SDimitry Andric   unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
53335f7ddb14SDimitry Andric       CGM.GetGlobalConstantAddressSpace());
53340b57cec5SDimitry Andric 
53350b57cec5SDimitry Andric   llvm::Module &M = CGM.getModule();
53360b57cec5SDimitry Andric   // Create a global variable for this string
53370b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
53380b57cec5SDimitry Andric       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
53390b57cec5SDimitry Andric       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
5340a7dea167SDimitry Andric   GV->setAlignment(Alignment.getAsAlign());
53410b57cec5SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
53420b57cec5SDimitry Andric   if (GV->isWeakForLinker()) {
53430b57cec5SDimitry Andric     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
53440b57cec5SDimitry Andric     GV->setComdat(M.getOrInsertComdat(GV->getName()));
53450b57cec5SDimitry Andric   }
53460b57cec5SDimitry Andric   CGM.setDSOLocal(GV);
53470b57cec5SDimitry Andric 
53480b57cec5SDimitry Andric   return GV;
53490b57cec5SDimitry Andric }
53500b57cec5SDimitry Andric 
53510b57cec5SDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
53520b57cec5SDimitry Andric /// constant array for the given string literal.
53530b57cec5SDimitry Andric ConstantAddress
GetAddrOfConstantStringFromLiteral(const StringLiteral * S,StringRef Name)53540b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
53550b57cec5SDimitry Andric                                                   StringRef Name) {
53560b57cec5SDimitry Andric   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
53570b57cec5SDimitry Andric 
53580b57cec5SDimitry Andric   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
53590b57cec5SDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
53600b57cec5SDimitry Andric   if (!LangOpts.WritableStrings) {
53610b57cec5SDimitry Andric     Entry = &ConstantStringMap[C];
53620b57cec5SDimitry Andric     if (auto GV = *Entry) {
53630b57cec5SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
5364a7dea167SDimitry Andric         GV->setAlignment(Alignment.getAsAlign());
53650b57cec5SDimitry Andric       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
53660b57cec5SDimitry Andric                              Alignment);
53670b57cec5SDimitry Andric     }
53680b57cec5SDimitry Andric   }
53690b57cec5SDimitry Andric 
53700b57cec5SDimitry Andric   SmallString<256> MangledNameBuffer;
53710b57cec5SDimitry Andric   StringRef GlobalVariableName;
53720b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
53730b57cec5SDimitry Andric 
53740b57cec5SDimitry Andric   // Mangle the string literal if that's how the ABI merges duplicate strings.
53750b57cec5SDimitry Andric   // Don't do it if they are writable, since we don't want writes in one TU to
53760b57cec5SDimitry Andric   // affect strings in another.
53770b57cec5SDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
53780b57cec5SDimitry Andric       !LangOpts.WritableStrings) {
53790b57cec5SDimitry Andric     llvm::raw_svector_ostream Out(MangledNameBuffer);
53800b57cec5SDimitry Andric     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
53810b57cec5SDimitry Andric     LT = llvm::GlobalValue::LinkOnceODRLinkage;
53820b57cec5SDimitry Andric     GlobalVariableName = MangledNameBuffer;
53830b57cec5SDimitry Andric   } else {
53840b57cec5SDimitry Andric     LT = llvm::GlobalValue::PrivateLinkage;
53850b57cec5SDimitry Andric     GlobalVariableName = Name;
53860b57cec5SDimitry Andric   }
53870b57cec5SDimitry Andric 
53880b57cec5SDimitry Andric   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
53890b57cec5SDimitry Andric   if (Entry)
53900b57cec5SDimitry Andric     *Entry = GV;
53910b57cec5SDimitry Andric 
53920b57cec5SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
53930b57cec5SDimitry Andric                                   QualType());
53940b57cec5SDimitry Andric 
53950b57cec5SDimitry Andric   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
53960b57cec5SDimitry Andric                          Alignment);
53970b57cec5SDimitry Andric }
53980b57cec5SDimitry Andric 
53990b57cec5SDimitry Andric /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
54000b57cec5SDimitry Andric /// array for the given ObjCEncodeExpr node.
54010b57cec5SDimitry Andric ConstantAddress
GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr * E)54020b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
54030b57cec5SDimitry Andric   std::string Str;
54040b57cec5SDimitry Andric   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
54050b57cec5SDimitry Andric 
54060b57cec5SDimitry Andric   return GetAddrOfConstantCString(Str);
54070b57cec5SDimitry Andric }
54080b57cec5SDimitry Andric 
54090b57cec5SDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing
54100b57cec5SDimitry Andric /// the literal and a terminating '\0' character.
54110b57cec5SDimitry Andric /// The result has pointer to array type.
GetAddrOfConstantCString(const std::string & Str,const char * GlobalName)54120b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString(
54130b57cec5SDimitry Andric     const std::string &Str, const char *GlobalName) {
54140b57cec5SDimitry Andric   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
54150b57cec5SDimitry Andric   CharUnits Alignment =
54160b57cec5SDimitry Andric     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
54170b57cec5SDimitry Andric 
54180b57cec5SDimitry Andric   llvm::Constant *C =
54190b57cec5SDimitry Andric       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
54200b57cec5SDimitry Andric 
54210b57cec5SDimitry Andric   // Don't share any string literals if strings aren't constant.
54220b57cec5SDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
54230b57cec5SDimitry Andric   if (!LangOpts.WritableStrings) {
54240b57cec5SDimitry Andric     Entry = &ConstantStringMap[C];
54250b57cec5SDimitry Andric     if (auto GV = *Entry) {
54260b57cec5SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
5427a7dea167SDimitry Andric         GV->setAlignment(Alignment.getAsAlign());
54280b57cec5SDimitry Andric       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
54290b57cec5SDimitry Andric                              Alignment);
54300b57cec5SDimitry Andric     }
54310b57cec5SDimitry Andric   }
54320b57cec5SDimitry Andric 
54330b57cec5SDimitry Andric   // Get the default prefix if a name wasn't specified.
54340b57cec5SDimitry Andric   if (!GlobalName)
54350b57cec5SDimitry Andric     GlobalName = ".str";
54360b57cec5SDimitry Andric   // Create a global variable for this.
54370b57cec5SDimitry Andric   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
54380b57cec5SDimitry Andric                                   GlobalName, Alignment);
54390b57cec5SDimitry Andric   if (Entry)
54400b57cec5SDimitry Andric     *Entry = GV;
54410b57cec5SDimitry Andric 
54420b57cec5SDimitry Andric   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
54430b57cec5SDimitry Andric                          Alignment);
54440b57cec5SDimitry Andric }
54450b57cec5SDimitry Andric 
GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr * E,const Expr * Init)54460b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
54470b57cec5SDimitry Andric     const MaterializeTemporaryExpr *E, const Expr *Init) {
54480b57cec5SDimitry Andric   assert((E->getStorageDuration() == SD_Static ||
54490b57cec5SDimitry Andric           E->getStorageDuration() == SD_Thread) && "not a global temporary");
54500b57cec5SDimitry Andric   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
54510b57cec5SDimitry Andric 
54520b57cec5SDimitry Andric   // If we're not materializing a subobject of the temporary, keep the
54530b57cec5SDimitry Andric   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
54540b57cec5SDimitry Andric   QualType MaterializedType = Init->getType();
5455480093f4SDimitry Andric   if (Init == E->getSubExpr())
54560b57cec5SDimitry Andric     MaterializedType = E->getType();
54570b57cec5SDimitry Andric 
54580b57cec5SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
54590b57cec5SDimitry Andric 
54605f7ddb14SDimitry Andric   auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr});
54615f7ddb14SDimitry Andric   if (!InsertResult.second) {
54625f7ddb14SDimitry Andric     // We've seen this before: either we already created it or we're in the
54635f7ddb14SDimitry Andric     // process of doing so.
54645f7ddb14SDimitry Andric     if (!InsertResult.first->second) {
54655f7ddb14SDimitry Andric       // We recursively re-entered this function, probably during emission of
54665f7ddb14SDimitry Andric       // the initializer. Create a placeholder. We'll clean this up in the
54675f7ddb14SDimitry Andric       // outer call, at the end of this function.
54685f7ddb14SDimitry Andric       llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType);
54695f7ddb14SDimitry Andric       InsertResult.first->second = new llvm::GlobalVariable(
54705f7ddb14SDimitry Andric           getModule(), Type, false, llvm::GlobalVariable::InternalLinkage,
54715f7ddb14SDimitry Andric           nullptr);
54725f7ddb14SDimitry Andric     }
54735f7ddb14SDimitry Andric     return ConstantAddress(InsertResult.first->second, Align);
54745f7ddb14SDimitry Andric   }
54750b57cec5SDimitry Andric 
54760b57cec5SDimitry Andric   // FIXME: If an externally-visible declaration extends multiple temporaries,
54770b57cec5SDimitry Andric   // we need to give each temporary the same name in every translation unit (and
54780b57cec5SDimitry Andric   // we also need to make the temporaries externally-visible).
54790b57cec5SDimitry Andric   SmallString<256> Name;
54800b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Name);
54810b57cec5SDimitry Andric   getCXXABI().getMangleContext().mangleReferenceTemporary(
54820b57cec5SDimitry Andric       VD, E->getManglingNumber(), Out);
54830b57cec5SDimitry Andric 
54840b57cec5SDimitry Andric   APValue *Value = nullptr;
5485a7dea167SDimitry Andric   if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
5486a7dea167SDimitry Andric     // If the initializer of the extending declaration is a constant
5487a7dea167SDimitry Andric     // initializer, we should have a cached constant initializer for this
5488a7dea167SDimitry Andric     // temporary. Note that this might have a different value from the value
5489a7dea167SDimitry Andric     // computed by evaluating the initializer if the surrounding constant
5490a7dea167SDimitry Andric     // expression modifies the temporary.
5491480093f4SDimitry Andric     Value = E->getOrCreateValue(false);
54920b57cec5SDimitry Andric   }
54930b57cec5SDimitry Andric 
54940b57cec5SDimitry Andric   // Try evaluating it now, it might have a constant initializer.
54950b57cec5SDimitry Andric   Expr::EvalResult EvalResult;
54960b57cec5SDimitry Andric   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
54970b57cec5SDimitry Andric       !EvalResult.hasSideEffects())
54980b57cec5SDimitry Andric     Value = &EvalResult.Val;
54990b57cec5SDimitry Andric 
55000b57cec5SDimitry Andric   LangAS AddrSpace =
55010b57cec5SDimitry Andric       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
55020b57cec5SDimitry Andric 
55030b57cec5SDimitry Andric   Optional<ConstantEmitter> emitter;
55040b57cec5SDimitry Andric   llvm::Constant *InitialValue = nullptr;
55050b57cec5SDimitry Andric   bool Constant = false;
55060b57cec5SDimitry Andric   llvm::Type *Type;
55070b57cec5SDimitry Andric   if (Value) {
55080b57cec5SDimitry Andric     // The temporary has a constant initializer, use it.
55090b57cec5SDimitry Andric     emitter.emplace(*this);
55100b57cec5SDimitry Andric     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
55110b57cec5SDimitry Andric                                                MaterializedType);
55120b57cec5SDimitry Andric     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
55130b57cec5SDimitry Andric     Type = InitialValue->getType();
55140b57cec5SDimitry Andric   } else {
55150b57cec5SDimitry Andric     // No initializer, the initialization will be provided when we
55160b57cec5SDimitry Andric     // initialize the declaration which performed lifetime extension.
55170b57cec5SDimitry Andric     Type = getTypes().ConvertTypeForMem(MaterializedType);
55180b57cec5SDimitry Andric   }
55190b57cec5SDimitry Andric 
55200b57cec5SDimitry Andric   // Create a global variable for this lifetime-extended temporary.
55210b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
55220b57cec5SDimitry Andric       getLLVMLinkageVarDefinition(VD, Constant);
55230b57cec5SDimitry Andric   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
55240b57cec5SDimitry Andric     const VarDecl *InitVD;
55250b57cec5SDimitry Andric     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
55260b57cec5SDimitry Andric         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
55270b57cec5SDimitry Andric       // Temporaries defined inside a class get linkonce_odr linkage because the
55280b57cec5SDimitry Andric       // class can be defined in multiple translation units.
55290b57cec5SDimitry Andric       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
55300b57cec5SDimitry Andric     } else {
55310b57cec5SDimitry Andric       // There is no need for this temporary to have external linkage if the
55320b57cec5SDimitry Andric       // VarDecl has external linkage.
55330b57cec5SDimitry Andric       Linkage = llvm::GlobalVariable::InternalLinkage;
55340b57cec5SDimitry Andric     }
55350b57cec5SDimitry Andric   }
55360b57cec5SDimitry Andric   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
55370b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
55380b57cec5SDimitry Andric       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
55390b57cec5SDimitry Andric       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
55400b57cec5SDimitry Andric   if (emitter) emitter->finalize(GV);
55410b57cec5SDimitry Andric   setGVProperties(GV, VD);
5542a7dea167SDimitry Andric   GV->setAlignment(Align.getAsAlign());
55430b57cec5SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker())
55440b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
55450b57cec5SDimitry Andric   if (VD->getTLSKind())
55460b57cec5SDimitry Andric     setTLSMode(GV, *VD);
55470b57cec5SDimitry Andric   llvm::Constant *CV = GV;
55480b57cec5SDimitry Andric   if (AddrSpace != LangAS::Default)
55490b57cec5SDimitry Andric     CV = getTargetCodeGenInfo().performAddrSpaceCast(
55500b57cec5SDimitry Andric         *this, GV, AddrSpace, LangAS::Default,
55510b57cec5SDimitry Andric         Type->getPointerTo(
55520b57cec5SDimitry Andric             getContext().getTargetAddressSpace(LangAS::Default)));
55535f7ddb14SDimitry Andric 
55545f7ddb14SDimitry Andric   // Update the map with the new temporary. If we created a placeholder above,
55555f7ddb14SDimitry Andric   // replace it with the new global now.
55565f7ddb14SDimitry Andric   llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
55575f7ddb14SDimitry Andric   if (Entry) {
55585f7ddb14SDimitry Andric     Entry->replaceAllUsesWith(
55595f7ddb14SDimitry Andric         llvm::ConstantExpr::getBitCast(CV, Entry->getType()));
55605f7ddb14SDimitry Andric     llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
55615f7ddb14SDimitry Andric   }
55625f7ddb14SDimitry Andric   Entry = CV;
55635f7ddb14SDimitry Andric 
55640b57cec5SDimitry Andric   return ConstantAddress(CV, Align);
55650b57cec5SDimitry Andric }
55660b57cec5SDimitry Andric 
55670b57cec5SDimitry Andric /// EmitObjCPropertyImplementations - Emit information for synthesized
55680b57cec5SDimitry Andric /// properties for an implementation.
EmitObjCPropertyImplementations(const ObjCImplementationDecl * D)55690b57cec5SDimitry Andric void CodeGenModule::EmitObjCPropertyImplementations(const
55700b57cec5SDimitry Andric                                                     ObjCImplementationDecl *D) {
55710b57cec5SDimitry Andric   for (const auto *PID : D->property_impls()) {
55720b57cec5SDimitry Andric     // Dynamic is just for type-checking.
55730b57cec5SDimitry Andric     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
55740b57cec5SDimitry Andric       ObjCPropertyDecl *PD = PID->getPropertyDecl();
55750b57cec5SDimitry Andric 
55760b57cec5SDimitry Andric       // Determine which methods need to be implemented, some may have
55770b57cec5SDimitry Andric       // been overridden. Note that ::isPropertyAccessor is not the method
55780b57cec5SDimitry Andric       // we want, that just indicates if the decl came from a
55790b57cec5SDimitry Andric       // property. What we want to know is if the method is defined in
55800b57cec5SDimitry Andric       // this implementation.
5581480093f4SDimitry Andric       auto *Getter = PID->getGetterMethodDecl();
5582480093f4SDimitry Andric       if (!Getter || Getter->isSynthesizedAccessorStub())
55830b57cec5SDimitry Andric         CodeGenFunction(*this).GenerateObjCGetter(
55840b57cec5SDimitry Andric             const_cast<ObjCImplementationDecl *>(D), PID);
5585480093f4SDimitry Andric       auto *Setter = PID->getSetterMethodDecl();
5586480093f4SDimitry Andric       if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
55870b57cec5SDimitry Andric         CodeGenFunction(*this).GenerateObjCSetter(
55880b57cec5SDimitry Andric                                  const_cast<ObjCImplementationDecl *>(D), PID);
55890b57cec5SDimitry Andric     }
55900b57cec5SDimitry Andric   }
55910b57cec5SDimitry Andric }
55920b57cec5SDimitry Andric 
needsDestructMethod(ObjCImplementationDecl * impl)55930b57cec5SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) {
55940b57cec5SDimitry Andric   const ObjCInterfaceDecl *iface = impl->getClassInterface();
55950b57cec5SDimitry Andric   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
55960b57cec5SDimitry Andric        ivar; ivar = ivar->getNextIvar())
55970b57cec5SDimitry Andric     if (ivar->getType().isDestructedType())
55980b57cec5SDimitry Andric       return true;
55990b57cec5SDimitry Andric 
56000b57cec5SDimitry Andric   return false;
56010b57cec5SDimitry Andric }
56020b57cec5SDimitry Andric 
AllTrivialInitializers(CodeGenModule & CGM,ObjCImplementationDecl * D)56030b57cec5SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM,
56040b57cec5SDimitry Andric                                    ObjCImplementationDecl *D) {
56050b57cec5SDimitry Andric   CodeGenFunction CGF(CGM);
56060b57cec5SDimitry Andric   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
56070b57cec5SDimitry Andric        E = D->init_end(); B != E; ++B) {
56080b57cec5SDimitry Andric     CXXCtorInitializer *CtorInitExp = *B;
56090b57cec5SDimitry Andric     Expr *Init = CtorInitExp->getInit();
56100b57cec5SDimitry Andric     if (!CGF.isTrivialInitializer(Init))
56110b57cec5SDimitry Andric       return false;
56120b57cec5SDimitry Andric   }
56130b57cec5SDimitry Andric   return true;
56140b57cec5SDimitry Andric }
56150b57cec5SDimitry Andric 
56160b57cec5SDimitry Andric /// EmitObjCIvarInitializations - Emit information for ivar initialization
56170b57cec5SDimitry Andric /// for an implementation.
EmitObjCIvarInitializations(ObjCImplementationDecl * D)56180b57cec5SDimitry Andric void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
56190b57cec5SDimitry Andric   // We might need a .cxx_destruct even if we don't have any ivar initializers.
56200b57cec5SDimitry Andric   if (needsDestructMethod(D)) {
56210b57cec5SDimitry Andric     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
56220b57cec5SDimitry Andric     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5623480093f4SDimitry Andric     ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
5624480093f4SDimitry Andric         getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5625480093f4SDimitry Andric         getContext().VoidTy, nullptr, D,
56260b57cec5SDimitry Andric         /*isInstance=*/true, /*isVariadic=*/false,
5627480093f4SDimitry Andric         /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5628480093f4SDimitry Andric         /*isImplicitlyDeclared=*/true,
56290b57cec5SDimitry Andric         /*isDefined=*/false, ObjCMethodDecl::Required);
56300b57cec5SDimitry Andric     D->addInstanceMethod(DTORMethod);
56310b57cec5SDimitry Andric     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
56320b57cec5SDimitry Andric     D->setHasDestructors(true);
56330b57cec5SDimitry Andric   }
56340b57cec5SDimitry Andric 
56350b57cec5SDimitry Andric   // If the implementation doesn't have any ivar initializers, we don't need
56360b57cec5SDimitry Andric   // a .cxx_construct.
56370b57cec5SDimitry Andric   if (D->getNumIvarInitializers() == 0 ||
56380b57cec5SDimitry Andric       AllTrivialInitializers(*this, D))
56390b57cec5SDimitry Andric     return;
56400b57cec5SDimitry Andric 
56410b57cec5SDimitry Andric   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
56420b57cec5SDimitry Andric   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
56430b57cec5SDimitry Andric   // The constructor returns 'self'.
5644480093f4SDimitry Andric   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
5645480093f4SDimitry Andric       getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5646480093f4SDimitry Andric       getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
56470b57cec5SDimitry Andric       /*isVariadic=*/false,
5648480093f4SDimitry Andric       /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
56490b57cec5SDimitry Andric       /*isImplicitlyDeclared=*/true,
5650480093f4SDimitry Andric       /*isDefined=*/false, ObjCMethodDecl::Required);
56510b57cec5SDimitry Andric   D->addInstanceMethod(CTORMethod);
56520b57cec5SDimitry Andric   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
56530b57cec5SDimitry Andric   D->setHasNonZeroConstructors(true);
56540b57cec5SDimitry Andric }
56550b57cec5SDimitry Andric 
56560b57cec5SDimitry Andric // EmitLinkageSpec - Emit all declarations in a linkage spec.
EmitLinkageSpec(const LinkageSpecDecl * LSD)56570b57cec5SDimitry Andric void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
56580b57cec5SDimitry Andric   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
5659480093f4SDimitry Andric       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
56600b57cec5SDimitry Andric     ErrorUnsupported(LSD, "linkage spec");
56610b57cec5SDimitry Andric     return;
56620b57cec5SDimitry Andric   }
56630b57cec5SDimitry Andric 
56640b57cec5SDimitry Andric   EmitDeclContext(LSD);
56650b57cec5SDimitry Andric }
56660b57cec5SDimitry Andric 
EmitDeclContext(const DeclContext * DC)56670b57cec5SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
56680b57cec5SDimitry Andric   for (auto *I : DC->decls()) {
56690b57cec5SDimitry Andric     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
56700b57cec5SDimitry Andric     // are themselves considered "top-level", so EmitTopLevelDecl on an
56710b57cec5SDimitry Andric     // ObjCImplDecl does not recursively visit them. We need to do that in
56720b57cec5SDimitry Andric     // case they're nested inside another construct (LinkageSpecDecl /
56730b57cec5SDimitry Andric     // ExportDecl) that does stop them from being considered "top-level".
56740b57cec5SDimitry Andric     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
56750b57cec5SDimitry Andric       for (auto *M : OID->methods())
56760b57cec5SDimitry Andric         EmitTopLevelDecl(M);
56770b57cec5SDimitry Andric     }
56780b57cec5SDimitry Andric 
56790b57cec5SDimitry Andric     EmitTopLevelDecl(I);
56800b57cec5SDimitry Andric   }
56810b57cec5SDimitry Andric }
56820b57cec5SDimitry Andric 
56830b57cec5SDimitry Andric /// EmitTopLevelDecl - Emit code for a single top level declaration.
EmitTopLevelDecl(Decl * D)56840b57cec5SDimitry Andric void CodeGenModule::EmitTopLevelDecl(Decl *D) {
56850b57cec5SDimitry Andric   // Ignore dependent declarations.
56860b57cec5SDimitry Andric   if (D->isTemplated())
56870b57cec5SDimitry Andric     return;
56880b57cec5SDimitry Andric 
56895ffd83dbSDimitry Andric   // Consteval function shouldn't be emitted.
56905ffd83dbSDimitry Andric   if (auto *FD = dyn_cast<FunctionDecl>(D))
56915ffd83dbSDimitry Andric     if (FD->isConsteval())
56925ffd83dbSDimitry Andric       return;
56935ffd83dbSDimitry Andric 
56940b57cec5SDimitry Andric   switch (D->getKind()) {
56950b57cec5SDimitry Andric   case Decl::CXXConversion:
56960b57cec5SDimitry Andric   case Decl::CXXMethod:
56970b57cec5SDimitry Andric   case Decl::Function:
56980b57cec5SDimitry Andric     EmitGlobal(cast<FunctionDecl>(D));
56990b57cec5SDimitry Andric     // Always provide some coverage mapping
57000b57cec5SDimitry Andric     // even for the functions that aren't emitted.
57010b57cec5SDimitry Andric     AddDeferredUnusedCoverageMapping(D);
57020b57cec5SDimitry Andric     break;
57030b57cec5SDimitry Andric 
57040b57cec5SDimitry Andric   case Decl::CXXDeductionGuide:
57050b57cec5SDimitry Andric     // Function-like, but does not result in code emission.
57060b57cec5SDimitry Andric     break;
57070b57cec5SDimitry Andric 
57080b57cec5SDimitry Andric   case Decl::Var:
57090b57cec5SDimitry Andric   case Decl::Decomposition:
57100b57cec5SDimitry Andric   case Decl::VarTemplateSpecialization:
57110b57cec5SDimitry Andric     EmitGlobal(cast<VarDecl>(D));
57120b57cec5SDimitry Andric     if (auto *DD = dyn_cast<DecompositionDecl>(D))
57130b57cec5SDimitry Andric       for (auto *B : DD->bindings())
57140b57cec5SDimitry Andric         if (auto *HD = B->getHoldingVar())
57150b57cec5SDimitry Andric           EmitGlobal(HD);
57160b57cec5SDimitry Andric     break;
57170b57cec5SDimitry Andric 
57180b57cec5SDimitry Andric   // Indirect fields from global anonymous structs and unions can be
57190b57cec5SDimitry Andric   // ignored; only the actual variable requires IR gen support.
57200b57cec5SDimitry Andric   case Decl::IndirectField:
57210b57cec5SDimitry Andric     break;
57220b57cec5SDimitry Andric 
57230b57cec5SDimitry Andric   // C++ Decls
57240b57cec5SDimitry Andric   case Decl::Namespace:
57250b57cec5SDimitry Andric     EmitDeclContext(cast<NamespaceDecl>(D));
57260b57cec5SDimitry Andric     break;
57270b57cec5SDimitry Andric   case Decl::ClassTemplateSpecialization: {
57280b57cec5SDimitry Andric     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
57295ffd83dbSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
57305ffd83dbSDimitry Andric       if (Spec->getSpecializationKind() ==
57315ffd83dbSDimitry Andric               TSK_ExplicitInstantiationDefinition &&
57320b57cec5SDimitry Andric           Spec->hasDefinition())
57335ffd83dbSDimitry Andric         DI->completeTemplateDefinition(*Spec);
57340b57cec5SDimitry Andric   } LLVM_FALLTHROUGH;
5735af732203SDimitry Andric   case Decl::CXXRecord: {
5736af732203SDimitry Andric     CXXRecordDecl *CRD = cast<CXXRecordDecl>(D);
5737af732203SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo()) {
5738af732203SDimitry Andric       if (CRD->hasDefinition())
5739af732203SDimitry Andric         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
57400b57cec5SDimitry Andric       if (auto *ES = D->getASTContext().getExternalSource())
57410b57cec5SDimitry Andric         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
5742af732203SDimitry Andric           DI->completeUnusedClass(*CRD);
5743af732203SDimitry Andric     }
57440b57cec5SDimitry Andric     // Emit any static data members, they may be definitions.
5745af732203SDimitry Andric     for (auto *I : CRD->decls())
57460b57cec5SDimitry Andric       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
57470b57cec5SDimitry Andric         EmitTopLevelDecl(I);
57480b57cec5SDimitry Andric     break;
5749af732203SDimitry Andric   }
57500b57cec5SDimitry Andric     // No code generation needed.
57510b57cec5SDimitry Andric   case Decl::UsingShadow:
57520b57cec5SDimitry Andric   case Decl::ClassTemplate:
57530b57cec5SDimitry Andric   case Decl::VarTemplate:
57540b57cec5SDimitry Andric   case Decl::Concept:
57550b57cec5SDimitry Andric   case Decl::VarTemplatePartialSpecialization:
57560b57cec5SDimitry Andric   case Decl::FunctionTemplate:
57570b57cec5SDimitry Andric   case Decl::TypeAliasTemplate:
57580b57cec5SDimitry Andric   case Decl::Block:
57590b57cec5SDimitry Andric   case Decl::Empty:
57600b57cec5SDimitry Andric   case Decl::Binding:
57610b57cec5SDimitry Andric     break;
57620b57cec5SDimitry Andric   case Decl::Using:          // using X; [C++]
57630b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
57640b57cec5SDimitry Andric         DI->EmitUsingDecl(cast<UsingDecl>(*D));
57655ffd83dbSDimitry Andric     break;
57665f7ddb14SDimitry Andric   case Decl::UsingEnum: // using enum X; [C++]
57675f7ddb14SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
57685f7ddb14SDimitry Andric       DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D));
57695f7ddb14SDimitry Andric     break;
57700b57cec5SDimitry Andric   case Decl::NamespaceAlias:
57710b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
57720b57cec5SDimitry Andric         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
57735ffd83dbSDimitry Andric     break;
57740b57cec5SDimitry Andric   case Decl::UsingDirective: // using namespace X; [C++]
57750b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
57760b57cec5SDimitry Andric       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
57775ffd83dbSDimitry Andric     break;
57780b57cec5SDimitry Andric   case Decl::CXXConstructor:
57790b57cec5SDimitry Andric     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
57800b57cec5SDimitry Andric     break;
57810b57cec5SDimitry Andric   case Decl::CXXDestructor:
57820b57cec5SDimitry Andric     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
57830b57cec5SDimitry Andric     break;
57840b57cec5SDimitry Andric 
57850b57cec5SDimitry Andric   case Decl::StaticAssert:
57860b57cec5SDimitry Andric     // Nothing to do.
57870b57cec5SDimitry Andric     break;
57880b57cec5SDimitry Andric 
57890b57cec5SDimitry Andric   // Objective-C Decls
57900b57cec5SDimitry Andric 
57910b57cec5SDimitry Andric   // Forward declarations, no (immediate) code generation.
57920b57cec5SDimitry Andric   case Decl::ObjCInterface:
57930b57cec5SDimitry Andric   case Decl::ObjCCategory:
57940b57cec5SDimitry Andric     break;
57950b57cec5SDimitry Andric 
57960b57cec5SDimitry Andric   case Decl::ObjCProtocol: {
57970b57cec5SDimitry Andric     auto *Proto = cast<ObjCProtocolDecl>(D);
57980b57cec5SDimitry Andric     if (Proto->isThisDeclarationADefinition())
57990b57cec5SDimitry Andric       ObjCRuntime->GenerateProtocol(Proto);
58000b57cec5SDimitry Andric     break;
58010b57cec5SDimitry Andric   }
58020b57cec5SDimitry Andric 
58030b57cec5SDimitry Andric   case Decl::ObjCCategoryImpl:
58040b57cec5SDimitry Andric     // Categories have properties but don't support synthesize so we
58050b57cec5SDimitry Andric     // can ignore them here.
58060b57cec5SDimitry Andric     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
58070b57cec5SDimitry Andric     break;
58080b57cec5SDimitry Andric 
58090b57cec5SDimitry Andric   case Decl::ObjCImplementation: {
58100b57cec5SDimitry Andric     auto *OMD = cast<ObjCImplementationDecl>(D);
58110b57cec5SDimitry Andric     EmitObjCPropertyImplementations(OMD);
58120b57cec5SDimitry Andric     EmitObjCIvarInitializations(OMD);
58130b57cec5SDimitry Andric     ObjCRuntime->GenerateClass(OMD);
58140b57cec5SDimitry Andric     // Emit global variable debug information.
58150b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
5816480093f4SDimitry Andric       if (getCodeGenOpts().hasReducedDebugInfo())
58170b57cec5SDimitry Andric         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
58180b57cec5SDimitry Andric             OMD->getClassInterface()), OMD->getLocation());
58190b57cec5SDimitry Andric     break;
58200b57cec5SDimitry Andric   }
58210b57cec5SDimitry Andric   case Decl::ObjCMethod: {
58220b57cec5SDimitry Andric     auto *OMD = cast<ObjCMethodDecl>(D);
58230b57cec5SDimitry Andric     // If this is not a prototype, emit the body.
58240b57cec5SDimitry Andric     if (OMD->getBody())
58250b57cec5SDimitry Andric       CodeGenFunction(*this).GenerateObjCMethod(OMD);
58260b57cec5SDimitry Andric     break;
58270b57cec5SDimitry Andric   }
58280b57cec5SDimitry Andric   case Decl::ObjCCompatibleAlias:
58290b57cec5SDimitry Andric     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
58300b57cec5SDimitry Andric     break;
58310b57cec5SDimitry Andric 
58320b57cec5SDimitry Andric   case Decl::PragmaComment: {
58330b57cec5SDimitry Andric     const auto *PCD = cast<PragmaCommentDecl>(D);
58340b57cec5SDimitry Andric     switch (PCD->getCommentKind()) {
58350b57cec5SDimitry Andric     case PCK_Unknown:
58360b57cec5SDimitry Andric       llvm_unreachable("unexpected pragma comment kind");
58370b57cec5SDimitry Andric     case PCK_Linker:
58380b57cec5SDimitry Andric       AppendLinkerOptions(PCD->getArg());
58390b57cec5SDimitry Andric       break;
58400b57cec5SDimitry Andric     case PCK_Lib:
58410b57cec5SDimitry Andric         AddDependentLib(PCD->getArg());
58420b57cec5SDimitry Andric       break;
58430b57cec5SDimitry Andric     case PCK_Compiler:
58440b57cec5SDimitry Andric     case PCK_ExeStr:
58450b57cec5SDimitry Andric     case PCK_User:
58460b57cec5SDimitry Andric       break; // We ignore all of these.
58470b57cec5SDimitry Andric     }
58480b57cec5SDimitry Andric     break;
58490b57cec5SDimitry Andric   }
58500b57cec5SDimitry Andric 
58510b57cec5SDimitry Andric   case Decl::PragmaDetectMismatch: {
58520b57cec5SDimitry Andric     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
58530b57cec5SDimitry Andric     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
58540b57cec5SDimitry Andric     break;
58550b57cec5SDimitry Andric   }
58560b57cec5SDimitry Andric 
58570b57cec5SDimitry Andric   case Decl::LinkageSpec:
58580b57cec5SDimitry Andric     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
58590b57cec5SDimitry Andric     break;
58600b57cec5SDimitry Andric 
58610b57cec5SDimitry Andric   case Decl::FileScopeAsm: {
58620b57cec5SDimitry Andric     // File-scope asm is ignored during device-side CUDA compilation.
58630b57cec5SDimitry Andric     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
58640b57cec5SDimitry Andric       break;
58650b57cec5SDimitry Andric     // File-scope asm is ignored during device-side OpenMP compilation.
58660b57cec5SDimitry Andric     if (LangOpts.OpenMPIsDevice)
58670b57cec5SDimitry Andric       break;
58685f7ddb14SDimitry Andric     // File-scope asm is ignored during device-side SYCL compilation.
58695f7ddb14SDimitry Andric     if (LangOpts.SYCLIsDevice)
58705f7ddb14SDimitry Andric       break;
58710b57cec5SDimitry Andric     auto *AD = cast<FileScopeAsmDecl>(D);
58720b57cec5SDimitry Andric     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
58730b57cec5SDimitry Andric     break;
58740b57cec5SDimitry Andric   }
58750b57cec5SDimitry Andric 
58760b57cec5SDimitry Andric   case Decl::Import: {
58770b57cec5SDimitry Andric     auto *Import = cast<ImportDecl>(D);
58780b57cec5SDimitry Andric 
58790b57cec5SDimitry Andric     // If we've already imported this module, we're done.
58800b57cec5SDimitry Andric     if (!ImportedModules.insert(Import->getImportedModule()))
58810b57cec5SDimitry Andric       break;
58820b57cec5SDimitry Andric 
58830b57cec5SDimitry Andric     // Emit debug information for direct imports.
58840b57cec5SDimitry Andric     if (!Import->getImportedOwningModule()) {
58850b57cec5SDimitry Andric       if (CGDebugInfo *DI = getModuleDebugInfo())
58860b57cec5SDimitry Andric         DI->EmitImportDecl(*Import);
58870b57cec5SDimitry Andric     }
58880b57cec5SDimitry Andric 
58890b57cec5SDimitry Andric     // Find all of the submodules and emit the module initializers.
58900b57cec5SDimitry Andric     llvm::SmallPtrSet<clang::Module *, 16> Visited;
58910b57cec5SDimitry Andric     SmallVector<clang::Module *, 16> Stack;
58920b57cec5SDimitry Andric     Visited.insert(Import->getImportedModule());
58930b57cec5SDimitry Andric     Stack.push_back(Import->getImportedModule());
58940b57cec5SDimitry Andric 
58950b57cec5SDimitry Andric     while (!Stack.empty()) {
58960b57cec5SDimitry Andric       clang::Module *Mod = Stack.pop_back_val();
58970b57cec5SDimitry Andric       if (!EmittedModuleInitializers.insert(Mod).second)
58980b57cec5SDimitry Andric         continue;
58990b57cec5SDimitry Andric 
59000b57cec5SDimitry Andric       for (auto *D : Context.getModuleInitializers(Mod))
59010b57cec5SDimitry Andric         EmitTopLevelDecl(D);
59020b57cec5SDimitry Andric 
59030b57cec5SDimitry Andric       // Visit the submodules of this module.
59040b57cec5SDimitry Andric       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
59050b57cec5SDimitry Andric                                              SubEnd = Mod->submodule_end();
59060b57cec5SDimitry Andric            Sub != SubEnd; ++Sub) {
59070b57cec5SDimitry Andric         // Skip explicit children; they need to be explicitly imported to emit
59080b57cec5SDimitry Andric         // the initializers.
59090b57cec5SDimitry Andric         if ((*Sub)->IsExplicit)
59100b57cec5SDimitry Andric           continue;
59110b57cec5SDimitry Andric 
59120b57cec5SDimitry Andric         if (Visited.insert(*Sub).second)
59130b57cec5SDimitry Andric           Stack.push_back(*Sub);
59140b57cec5SDimitry Andric       }
59150b57cec5SDimitry Andric     }
59160b57cec5SDimitry Andric     break;
59170b57cec5SDimitry Andric   }
59180b57cec5SDimitry Andric 
59190b57cec5SDimitry Andric   case Decl::Export:
59200b57cec5SDimitry Andric     EmitDeclContext(cast<ExportDecl>(D));
59210b57cec5SDimitry Andric     break;
59220b57cec5SDimitry Andric 
59230b57cec5SDimitry Andric   case Decl::OMPThreadPrivate:
59240b57cec5SDimitry Andric     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
59250b57cec5SDimitry Andric     break;
59260b57cec5SDimitry Andric 
59270b57cec5SDimitry Andric   case Decl::OMPAllocate:
59285f7ddb14SDimitry Andric     EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D));
59290b57cec5SDimitry Andric     break;
59300b57cec5SDimitry Andric 
59310b57cec5SDimitry Andric   case Decl::OMPDeclareReduction:
59320b57cec5SDimitry Andric     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
59330b57cec5SDimitry Andric     break;
59340b57cec5SDimitry Andric 
59350b57cec5SDimitry Andric   case Decl::OMPDeclareMapper:
59360b57cec5SDimitry Andric     EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
59370b57cec5SDimitry Andric     break;
59380b57cec5SDimitry Andric 
59390b57cec5SDimitry Andric   case Decl::OMPRequires:
59400b57cec5SDimitry Andric     EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
59410b57cec5SDimitry Andric     break;
59420b57cec5SDimitry Andric 
5943af732203SDimitry Andric   case Decl::Typedef:
5944af732203SDimitry Andric   case Decl::TypeAlias: // using foo = bar; [C++11]
5945af732203SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
5946af732203SDimitry Andric       DI->EmitAndRetainType(
5947af732203SDimitry Andric           getContext().getTypedefType(cast<TypedefNameDecl>(D)));
5948af732203SDimitry Andric     break;
5949af732203SDimitry Andric 
5950af732203SDimitry Andric   case Decl::Record:
5951af732203SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
5952af732203SDimitry Andric       if (cast<RecordDecl>(D)->getDefinition())
5953af732203SDimitry Andric         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
5954af732203SDimitry Andric     break;
5955af732203SDimitry Andric 
5956af732203SDimitry Andric   case Decl::Enum:
5957af732203SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
5958af732203SDimitry Andric       if (cast<EnumDecl>(D)->getDefinition())
5959af732203SDimitry Andric         DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D)));
5960af732203SDimitry Andric     break;
5961af732203SDimitry Andric 
59620b57cec5SDimitry Andric   default:
59630b57cec5SDimitry Andric     // Make sure we handled everything we should, every other kind is a
59640b57cec5SDimitry Andric     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
59650b57cec5SDimitry Andric     // function. Need to recode Decl::Kind to do that easily.
59660b57cec5SDimitry Andric     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
59670b57cec5SDimitry Andric     break;
59680b57cec5SDimitry Andric   }
59690b57cec5SDimitry Andric }
59700b57cec5SDimitry Andric 
AddDeferredUnusedCoverageMapping(Decl * D)59710b57cec5SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
59720b57cec5SDimitry Andric   // Do we need to generate coverage mapping?
59730b57cec5SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
59740b57cec5SDimitry Andric     return;
59750b57cec5SDimitry Andric   switch (D->getKind()) {
59760b57cec5SDimitry Andric   case Decl::CXXConversion:
59770b57cec5SDimitry Andric   case Decl::CXXMethod:
59780b57cec5SDimitry Andric   case Decl::Function:
59790b57cec5SDimitry Andric   case Decl::ObjCMethod:
59800b57cec5SDimitry Andric   case Decl::CXXConstructor:
59810b57cec5SDimitry Andric   case Decl::CXXDestructor: {
59820b57cec5SDimitry Andric     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
59835ffd83dbSDimitry Andric       break;
59840b57cec5SDimitry Andric     SourceManager &SM = getContext().getSourceManager();
59850b57cec5SDimitry Andric     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
59865ffd83dbSDimitry Andric       break;
59870b57cec5SDimitry Andric     auto I = DeferredEmptyCoverageMappingDecls.find(D);
59880b57cec5SDimitry Andric     if (I == DeferredEmptyCoverageMappingDecls.end())
59890b57cec5SDimitry Andric       DeferredEmptyCoverageMappingDecls[D] = true;
59900b57cec5SDimitry Andric     break;
59910b57cec5SDimitry Andric   }
59920b57cec5SDimitry Andric   default:
59930b57cec5SDimitry Andric     break;
59940b57cec5SDimitry Andric   };
59950b57cec5SDimitry Andric }
59960b57cec5SDimitry Andric 
ClearUnusedCoverageMapping(const Decl * D)59970b57cec5SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
59980b57cec5SDimitry Andric   // Do we need to generate coverage mapping?
59990b57cec5SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
60000b57cec5SDimitry Andric     return;
60010b57cec5SDimitry Andric   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
60020b57cec5SDimitry Andric     if (Fn->isTemplateInstantiation())
60030b57cec5SDimitry Andric       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
60040b57cec5SDimitry Andric   }
60050b57cec5SDimitry Andric   auto I = DeferredEmptyCoverageMappingDecls.find(D);
60060b57cec5SDimitry Andric   if (I == DeferredEmptyCoverageMappingDecls.end())
60070b57cec5SDimitry Andric     DeferredEmptyCoverageMappingDecls[D] = false;
60080b57cec5SDimitry Andric   else
60090b57cec5SDimitry Andric     I->second = false;
60100b57cec5SDimitry Andric }
60110b57cec5SDimitry Andric 
EmitDeferredUnusedCoverageMappings()60120b57cec5SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
60130b57cec5SDimitry Andric   // We call takeVector() here to avoid use-after-free.
60140b57cec5SDimitry Andric   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
60150b57cec5SDimitry Andric   // we deserialize function bodies to emit coverage info for them, and that
60160b57cec5SDimitry Andric   // deserializes more declarations. How should we handle that case?
60170b57cec5SDimitry Andric   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
60180b57cec5SDimitry Andric     if (!Entry.second)
60190b57cec5SDimitry Andric       continue;
60200b57cec5SDimitry Andric     const Decl *D = Entry.first;
60210b57cec5SDimitry Andric     switch (D->getKind()) {
60220b57cec5SDimitry Andric     case Decl::CXXConversion:
60230b57cec5SDimitry Andric     case Decl::CXXMethod:
60240b57cec5SDimitry Andric     case Decl::Function:
60250b57cec5SDimitry Andric     case Decl::ObjCMethod: {
60260b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
60270b57cec5SDimitry Andric       GlobalDecl GD(cast<FunctionDecl>(D));
60280b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
60290b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
60300b57cec5SDimitry Andric       break;
60310b57cec5SDimitry Andric     }
60320b57cec5SDimitry Andric     case Decl::CXXConstructor: {
60330b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
60340b57cec5SDimitry Andric       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
60350b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
60360b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
60370b57cec5SDimitry Andric       break;
60380b57cec5SDimitry Andric     }
60390b57cec5SDimitry Andric     case Decl::CXXDestructor: {
60400b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
60410b57cec5SDimitry Andric       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
60420b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
60430b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
60440b57cec5SDimitry Andric       break;
60450b57cec5SDimitry Andric     }
60460b57cec5SDimitry Andric     default:
60470b57cec5SDimitry Andric       break;
60480b57cec5SDimitry Andric     };
60490b57cec5SDimitry Andric   }
60500b57cec5SDimitry Andric }
60510b57cec5SDimitry Andric 
EmitMainVoidAlias()60525ffd83dbSDimitry Andric void CodeGenModule::EmitMainVoidAlias() {
60535ffd83dbSDimitry Andric   // In order to transition away from "__original_main" gracefully, emit an
60545ffd83dbSDimitry Andric   // alias for "main" in the no-argument case so that libc can detect when
60555ffd83dbSDimitry Andric   // new-style no-argument main is in used.
60565ffd83dbSDimitry Andric   if (llvm::Function *F = getModule().getFunction("main")) {
60575ffd83dbSDimitry Andric     if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
60585ffd83dbSDimitry Andric         F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth()))
60595ffd83dbSDimitry Andric       addUsedGlobal(llvm::GlobalAlias::create("__main_void", F));
60605ffd83dbSDimitry Andric   }
60615ffd83dbSDimitry Andric }
60625ffd83dbSDimitry Andric 
60630b57cec5SDimitry Andric /// Turns the given pointer into a constant.
GetPointerConstant(llvm::LLVMContext & Context,const void * Ptr)60640b57cec5SDimitry Andric static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
60650b57cec5SDimitry Andric                                           const void *Ptr) {
60660b57cec5SDimitry Andric   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
60670b57cec5SDimitry Andric   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
60680b57cec5SDimitry Andric   return llvm::ConstantInt::get(i64, PtrInt);
60690b57cec5SDimitry Andric }
60700b57cec5SDimitry Andric 
EmitGlobalDeclMetadata(CodeGenModule & CGM,llvm::NamedMDNode * & GlobalMetadata,GlobalDecl D,llvm::GlobalValue * Addr)60710b57cec5SDimitry Andric static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
60720b57cec5SDimitry Andric                                    llvm::NamedMDNode *&GlobalMetadata,
60730b57cec5SDimitry Andric                                    GlobalDecl D,
60740b57cec5SDimitry Andric                                    llvm::GlobalValue *Addr) {
60750b57cec5SDimitry Andric   if (!GlobalMetadata)
60760b57cec5SDimitry Andric     GlobalMetadata =
60770b57cec5SDimitry Andric       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
60780b57cec5SDimitry Andric 
60790b57cec5SDimitry Andric   // TODO: should we report variant information for ctors/dtors?
60800b57cec5SDimitry Andric   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
60810b57cec5SDimitry Andric                            llvm::ConstantAsMetadata::get(GetPointerConstant(
60820b57cec5SDimitry Andric                                CGM.getLLVMContext(), D.getDecl()))};
60830b57cec5SDimitry Andric   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
60840b57cec5SDimitry Andric }
60850b57cec5SDimitry Andric 
60860b57cec5SDimitry Andric /// For each function which is declared within an extern "C" region and marked
60870b57cec5SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled
60880b57cec5SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer
60890b57cec5SDimitry Andric /// to such functions with an unmangled name from inline assembly within the
60900b57cec5SDimitry Andric /// same translation unit.
EmitStaticExternCAliases()60910b57cec5SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() {
60920b57cec5SDimitry Andric   if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
60930b57cec5SDimitry Andric     return;
60940b57cec5SDimitry Andric   for (auto &I : StaticExternCValues) {
60950b57cec5SDimitry Andric     IdentifierInfo *Name = I.first;
60960b57cec5SDimitry Andric     llvm::GlobalValue *Val = I.second;
60970b57cec5SDimitry Andric     if (Val && !getModule().getNamedValue(Name->getName()))
60985f7ddb14SDimitry Andric       addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
60990b57cec5SDimitry Andric   }
61000b57cec5SDimitry Andric }
61010b57cec5SDimitry Andric 
lookupRepresentativeDecl(StringRef MangledName,GlobalDecl & Result) const61020b57cec5SDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
61030b57cec5SDimitry Andric                                              GlobalDecl &Result) const {
61040b57cec5SDimitry Andric   auto Res = Manglings.find(MangledName);
61050b57cec5SDimitry Andric   if (Res == Manglings.end())
61060b57cec5SDimitry Andric     return false;
61070b57cec5SDimitry Andric   Result = Res->getValue();
61080b57cec5SDimitry Andric   return true;
61090b57cec5SDimitry Andric }
61100b57cec5SDimitry Andric 
61110b57cec5SDimitry Andric /// Emits metadata nodes associating all the global values in the
61120b57cec5SDimitry Andric /// current module with the Decls they came from.  This is useful for
61130b57cec5SDimitry Andric /// projects using IR gen as a subroutine.
61140b57cec5SDimitry Andric ///
61150b57cec5SDimitry Andric /// Since there's currently no way to associate an MDNode directly
61160b57cec5SDimitry Andric /// with an llvm::GlobalValue, we create a global named metadata
61170b57cec5SDimitry Andric /// with the name 'clang.global.decl.ptrs'.
EmitDeclMetadata()61180b57cec5SDimitry Andric void CodeGenModule::EmitDeclMetadata() {
61190b57cec5SDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
61200b57cec5SDimitry Andric 
61210b57cec5SDimitry Andric   for (auto &I : MangledDeclNames) {
61220b57cec5SDimitry Andric     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
61230b57cec5SDimitry Andric     // Some mangled names don't necessarily have an associated GlobalValue
61240b57cec5SDimitry Andric     // in this module, e.g. if we mangled it for DebugInfo.
61250b57cec5SDimitry Andric     if (Addr)
61260b57cec5SDimitry Andric       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
61270b57cec5SDimitry Andric   }
61280b57cec5SDimitry Andric }
61290b57cec5SDimitry Andric 
61300b57cec5SDimitry Andric /// Emits metadata nodes for all the local variables in the current
61310b57cec5SDimitry Andric /// function.
EmitDeclMetadata()61320b57cec5SDimitry Andric void CodeGenFunction::EmitDeclMetadata() {
61330b57cec5SDimitry Andric   if (LocalDeclMap.empty()) return;
61340b57cec5SDimitry Andric 
61350b57cec5SDimitry Andric   llvm::LLVMContext &Context = getLLVMContext();
61360b57cec5SDimitry Andric 
61370b57cec5SDimitry Andric   // Find the unique metadata ID for this name.
61380b57cec5SDimitry Andric   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
61390b57cec5SDimitry Andric 
61400b57cec5SDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
61410b57cec5SDimitry Andric 
61420b57cec5SDimitry Andric   for (auto &I : LocalDeclMap) {
61430b57cec5SDimitry Andric     const Decl *D = I.first;
61440b57cec5SDimitry Andric     llvm::Value *Addr = I.second.getPointer();
61450b57cec5SDimitry Andric     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
61460b57cec5SDimitry Andric       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
61470b57cec5SDimitry Andric       Alloca->setMetadata(
61480b57cec5SDimitry Andric           DeclPtrKind, llvm::MDNode::get(
61490b57cec5SDimitry Andric                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
61500b57cec5SDimitry Andric     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
61510b57cec5SDimitry Andric       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
61520b57cec5SDimitry Andric       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
61530b57cec5SDimitry Andric     }
61540b57cec5SDimitry Andric   }
61550b57cec5SDimitry Andric }
61560b57cec5SDimitry Andric 
EmitVersionIdentMetadata()61570b57cec5SDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() {
61580b57cec5SDimitry Andric   llvm::NamedMDNode *IdentMetadata =
61590b57cec5SDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.ident");
61600b57cec5SDimitry Andric   std::string Version = getClangFullVersion();
61610b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
61620b57cec5SDimitry Andric 
61630b57cec5SDimitry Andric   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
61640b57cec5SDimitry Andric   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
61650b57cec5SDimitry Andric }
61660b57cec5SDimitry Andric 
EmitCommandLineMetadata()61670b57cec5SDimitry Andric void CodeGenModule::EmitCommandLineMetadata() {
61680b57cec5SDimitry Andric   llvm::NamedMDNode *CommandLineMetadata =
61690b57cec5SDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.commandline");
61700b57cec5SDimitry Andric   std::string CommandLine = getCodeGenOpts().RecordCommandLine;
61710b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
61720b57cec5SDimitry Andric 
61730b57cec5SDimitry Andric   llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
61740b57cec5SDimitry Andric   CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
61750b57cec5SDimitry Andric }
61760b57cec5SDimitry Andric 
EmitCoverageFile()61770b57cec5SDimitry Andric void CodeGenModule::EmitCoverageFile() {
61780b57cec5SDimitry Andric   if (getCodeGenOpts().CoverageDataFile.empty() &&
61790b57cec5SDimitry Andric       getCodeGenOpts().CoverageNotesFile.empty())
61800b57cec5SDimitry Andric     return;
61810b57cec5SDimitry Andric 
61820b57cec5SDimitry Andric   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
61830b57cec5SDimitry Andric   if (!CUNode)
61840b57cec5SDimitry Andric     return;
61850b57cec5SDimitry Andric 
61860b57cec5SDimitry Andric   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
61870b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
61880b57cec5SDimitry Andric   auto *CoverageDataFile =
61890b57cec5SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
61900b57cec5SDimitry Andric   auto *CoverageNotesFile =
61910b57cec5SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
61920b57cec5SDimitry Andric   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
61930b57cec5SDimitry Andric     llvm::MDNode *CU = CUNode->getOperand(i);
61940b57cec5SDimitry Andric     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
61950b57cec5SDimitry Andric     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
61960b57cec5SDimitry Andric   }
61970b57cec5SDimitry Andric }
61980b57cec5SDimitry Andric 
GetAddrOfRTTIDescriptor(QualType Ty,bool ForEH)61990b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
62000b57cec5SDimitry Andric                                                        bool ForEH) {
62010b57cec5SDimitry Andric   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
62020b57cec5SDimitry Andric   // FIXME: should we even be calling this method if RTTI is disabled
62030b57cec5SDimitry Andric   // and it's not for EH?
62045ffd83dbSDimitry Andric   if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice ||
62055ffd83dbSDimitry Andric       (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
62065ffd83dbSDimitry Andric        getTriple().isNVPTX()))
62070b57cec5SDimitry Andric     return llvm::Constant::getNullValue(Int8PtrTy);
62080b57cec5SDimitry Andric 
62090b57cec5SDimitry Andric   if (ForEH && Ty->isObjCObjectPointerType() &&
62100b57cec5SDimitry Andric       LangOpts.ObjCRuntime.isGNUFamily())
62110b57cec5SDimitry Andric     return ObjCRuntime->GetEHType(Ty);
62120b57cec5SDimitry Andric 
62130b57cec5SDimitry Andric   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
62140b57cec5SDimitry Andric }
62150b57cec5SDimitry Andric 
EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl * D)62160b57cec5SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
62170b57cec5SDimitry Andric   // Do not emit threadprivates in simd-only mode.
62180b57cec5SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
62190b57cec5SDimitry Andric     return;
62200b57cec5SDimitry Andric   for (auto RefExpr : D->varlists()) {
62210b57cec5SDimitry Andric     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
62220b57cec5SDimitry Andric     bool PerformInit =
62230b57cec5SDimitry Andric         VD->getAnyInitializer() &&
62240b57cec5SDimitry Andric         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
62250b57cec5SDimitry Andric                                                         /*ForRef=*/false);
62260b57cec5SDimitry Andric 
62270b57cec5SDimitry Andric     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
62280b57cec5SDimitry Andric     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
62290b57cec5SDimitry Andric             VD, Addr, RefExpr->getBeginLoc(), PerformInit))
62300b57cec5SDimitry Andric       CXXGlobalInits.push_back(InitFunction);
62310b57cec5SDimitry Andric   }
62320b57cec5SDimitry Andric }
62330b57cec5SDimitry Andric 
62340b57cec5SDimitry Andric llvm::Metadata *
CreateMetadataIdentifierImpl(QualType T,MetadataTypeMap & Map,StringRef Suffix)62350b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
62360b57cec5SDimitry Andric                                             StringRef Suffix) {
62370b57cec5SDimitry Andric   llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
62380b57cec5SDimitry Andric   if (InternalId)
62390b57cec5SDimitry Andric     return InternalId;
62400b57cec5SDimitry Andric 
62410b57cec5SDimitry Andric   if (isExternallyVisible(T->getLinkage())) {
62420b57cec5SDimitry Andric     std::string OutName;
62430b57cec5SDimitry Andric     llvm::raw_string_ostream Out(OutName);
62440b57cec5SDimitry Andric     getCXXABI().getMangleContext().mangleTypeName(T, Out);
62450b57cec5SDimitry Andric     Out << Suffix;
62460b57cec5SDimitry Andric 
62470b57cec5SDimitry Andric     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
62480b57cec5SDimitry Andric   } else {
62490b57cec5SDimitry Andric     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
62500b57cec5SDimitry Andric                                            llvm::ArrayRef<llvm::Metadata *>());
62510b57cec5SDimitry Andric   }
62520b57cec5SDimitry Andric 
62530b57cec5SDimitry Andric   return InternalId;
62540b57cec5SDimitry Andric }
62550b57cec5SDimitry Andric 
CreateMetadataIdentifierForType(QualType T)62560b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
62570b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
62580b57cec5SDimitry Andric }
62590b57cec5SDimitry Andric 
62600b57cec5SDimitry Andric llvm::Metadata *
CreateMetadataIdentifierForVirtualMemPtrType(QualType T)62610b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
62620b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
62630b57cec5SDimitry Andric }
62640b57cec5SDimitry Andric 
62650b57cec5SDimitry Andric // Generalize pointer types to a void pointer with the qualifiers of the
62660b57cec5SDimitry Andric // originally pointed-to type, e.g. 'const char *' and 'char * const *'
62670b57cec5SDimitry Andric // generalize to 'const void *' while 'char *' and 'const char **' generalize to
62680b57cec5SDimitry Andric // 'void *'.
GeneralizeType(ASTContext & Ctx,QualType Ty)62690b57cec5SDimitry Andric static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
62700b57cec5SDimitry Andric   if (!Ty->isPointerType())
62710b57cec5SDimitry Andric     return Ty;
62720b57cec5SDimitry Andric 
62730b57cec5SDimitry Andric   return Ctx.getPointerType(
62740b57cec5SDimitry Andric       QualType(Ctx.VoidTy).withCVRQualifiers(
62750b57cec5SDimitry Andric           Ty->getPointeeType().getCVRQualifiers()));
62760b57cec5SDimitry Andric }
62770b57cec5SDimitry Andric 
62780b57cec5SDimitry Andric // Apply type generalization to a FunctionType's return and argument types
GeneralizeFunctionType(ASTContext & Ctx,QualType Ty)62790b57cec5SDimitry Andric static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
62800b57cec5SDimitry Andric   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
62810b57cec5SDimitry Andric     SmallVector<QualType, 8> GeneralizedParams;
62820b57cec5SDimitry Andric     for (auto &Param : FnType->param_types())
62830b57cec5SDimitry Andric       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
62840b57cec5SDimitry Andric 
62850b57cec5SDimitry Andric     return Ctx.getFunctionType(
62860b57cec5SDimitry Andric         GeneralizeType(Ctx, FnType->getReturnType()),
62870b57cec5SDimitry Andric         GeneralizedParams, FnType->getExtProtoInfo());
62880b57cec5SDimitry Andric   }
62890b57cec5SDimitry Andric 
62900b57cec5SDimitry Andric   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
62910b57cec5SDimitry Andric     return Ctx.getFunctionNoProtoType(
62920b57cec5SDimitry Andric         GeneralizeType(Ctx, FnType->getReturnType()));
62930b57cec5SDimitry Andric 
62940b57cec5SDimitry Andric   llvm_unreachable("Encountered unknown FunctionType");
62950b57cec5SDimitry Andric }
62960b57cec5SDimitry Andric 
CreateMetadataIdentifierGeneralized(QualType T)62970b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
62980b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
62990b57cec5SDimitry Andric                                       GeneralizedMetadataIdMap, ".generalized");
63000b57cec5SDimitry Andric }
63010b57cec5SDimitry Andric 
63020b57cec5SDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier.
NeedAllVtablesTypeId() const63030b57cec5SDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const {
63040b57cec5SDimitry Andric   // Returns true if at least one of vtable-based CFI checkers is enabled and
63050b57cec5SDimitry Andric   // is not in the trapping mode.
63060b57cec5SDimitry Andric   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
63070b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
63080b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
63090b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
63100b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
63110b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
63120b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
63130b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
63140b57cec5SDimitry Andric }
63150b57cec5SDimitry Andric 
AddVTableTypeMetadata(llvm::GlobalVariable * VTable,CharUnits Offset,const CXXRecordDecl * RD)63160b57cec5SDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
63170b57cec5SDimitry Andric                                           CharUnits Offset,
63180b57cec5SDimitry Andric                                           const CXXRecordDecl *RD) {
63190b57cec5SDimitry Andric   llvm::Metadata *MD =
63200b57cec5SDimitry Andric       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
63210b57cec5SDimitry Andric   VTable->addTypeMetadata(Offset.getQuantity(), MD);
63220b57cec5SDimitry Andric 
63230b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
63240b57cec5SDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
63250b57cec5SDimitry Andric       VTable->addTypeMetadata(Offset.getQuantity(),
63260b57cec5SDimitry Andric                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
63270b57cec5SDimitry Andric 
63280b57cec5SDimitry Andric   if (NeedAllVtablesTypeId()) {
63290b57cec5SDimitry Andric     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
63300b57cec5SDimitry Andric     VTable->addTypeMetadata(Offset.getQuantity(), MD);
63310b57cec5SDimitry Andric   }
63320b57cec5SDimitry Andric }
63330b57cec5SDimitry Andric 
getSanStats()63340b57cec5SDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
63350b57cec5SDimitry Andric   if (!SanStats)
6336a7dea167SDimitry Andric     SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
63370b57cec5SDimitry Andric 
63380b57cec5SDimitry Andric   return *SanStats;
63390b57cec5SDimitry Andric }
6340af732203SDimitry Andric 
63410b57cec5SDimitry Andric llvm::Value *
createOpenCLIntToSamplerConversion(const Expr * E,CodeGenFunction & CGF)63420b57cec5SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
63430b57cec5SDimitry Andric                                                   CodeGenFunction &CGF) {
63440b57cec5SDimitry Andric   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
6345af732203SDimitry Andric   auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
6346af732203SDimitry Andric   auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
63475f7ddb14SDimitry Andric   auto *Call = CGF.EmitRuntimeCall(
6348af732203SDimitry Andric       CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C});
6349af732203SDimitry Andric   return Call;
63500b57cec5SDimitry Andric }
63515ffd83dbSDimitry Andric 
getNaturalPointeeTypeAlignment(QualType T,LValueBaseInfo * BaseInfo,TBAAAccessInfo * TBAAInfo)63525ffd83dbSDimitry Andric CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
63535ffd83dbSDimitry Andric     QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
63545ffd83dbSDimitry Andric   return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
63555ffd83dbSDimitry Andric                                  /* forPointeeType= */ true);
63565ffd83dbSDimitry Andric }
63575ffd83dbSDimitry Andric 
getNaturalTypeAlignment(QualType T,LValueBaseInfo * BaseInfo,TBAAAccessInfo * TBAAInfo,bool forPointeeType)63585ffd83dbSDimitry Andric CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
63595ffd83dbSDimitry Andric                                                  LValueBaseInfo *BaseInfo,
63605ffd83dbSDimitry Andric                                                  TBAAAccessInfo *TBAAInfo,
63615ffd83dbSDimitry Andric                                                  bool forPointeeType) {
63625ffd83dbSDimitry Andric   if (TBAAInfo)
63635ffd83dbSDimitry Andric     *TBAAInfo = getTBAAAccessInfo(T);
63645ffd83dbSDimitry Andric 
63655ffd83dbSDimitry Andric   // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
63665ffd83dbSDimitry Andric   // that doesn't return the information we need to compute BaseInfo.
63675ffd83dbSDimitry Andric 
63685ffd83dbSDimitry Andric   // Honor alignment typedef attributes even on incomplete types.
63695ffd83dbSDimitry Andric   // We also honor them straight for C++ class types, even as pointees;
63705ffd83dbSDimitry Andric   // there's an expressivity gap here.
63715ffd83dbSDimitry Andric   if (auto TT = T->getAs<TypedefType>()) {
63725ffd83dbSDimitry Andric     if (auto Align = TT->getDecl()->getMaxAlignment()) {
63735ffd83dbSDimitry Andric       if (BaseInfo)
63745ffd83dbSDimitry Andric         *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
63755ffd83dbSDimitry Andric       return getContext().toCharUnitsFromBits(Align);
63765ffd83dbSDimitry Andric     }
63775ffd83dbSDimitry Andric   }
63785ffd83dbSDimitry Andric 
63795ffd83dbSDimitry Andric   bool AlignForArray = T->isArrayType();
63805ffd83dbSDimitry Andric 
63815ffd83dbSDimitry Andric   // Analyze the base element type, so we don't get confused by incomplete
63825ffd83dbSDimitry Andric   // array types.
63835ffd83dbSDimitry Andric   T = getContext().getBaseElementType(T);
63845ffd83dbSDimitry Andric 
63855ffd83dbSDimitry Andric   if (T->isIncompleteType()) {
63865ffd83dbSDimitry Andric     // We could try to replicate the logic from
63875ffd83dbSDimitry Andric     // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
63885ffd83dbSDimitry Andric     // type is incomplete, so it's impossible to test. We could try to reuse
63895ffd83dbSDimitry Andric     // getTypeAlignIfKnown, but that doesn't return the information we need
63905ffd83dbSDimitry Andric     // to set BaseInfo.  So just ignore the possibility that the alignment is
63915ffd83dbSDimitry Andric     // greater than one.
63925ffd83dbSDimitry Andric     if (BaseInfo)
63935ffd83dbSDimitry Andric       *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
63945ffd83dbSDimitry Andric     return CharUnits::One();
63955ffd83dbSDimitry Andric   }
63965ffd83dbSDimitry Andric 
63975ffd83dbSDimitry Andric   if (BaseInfo)
63985ffd83dbSDimitry Andric     *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
63995ffd83dbSDimitry Andric 
64005ffd83dbSDimitry Andric   CharUnits Alignment;
6401af732203SDimitry Andric   const CXXRecordDecl *RD;
6402af732203SDimitry Andric   if (T.getQualifiers().hasUnaligned()) {
6403af732203SDimitry Andric     Alignment = CharUnits::One();
6404af732203SDimitry Andric   } else if (forPointeeType && !AlignForArray &&
6405af732203SDimitry Andric              (RD = T->getAsCXXRecordDecl())) {
64065ffd83dbSDimitry Andric     // For C++ class pointees, we don't know whether we're pointing at a
64075ffd83dbSDimitry Andric     // base or a complete object, so we generally need to use the
64085ffd83dbSDimitry Andric     // non-virtual alignment.
64095ffd83dbSDimitry Andric     Alignment = getClassPointerAlignment(RD);
64105ffd83dbSDimitry Andric   } else {
64115ffd83dbSDimitry Andric     Alignment = getContext().getTypeAlignInChars(T);
64125ffd83dbSDimitry Andric   }
64135ffd83dbSDimitry Andric 
64145ffd83dbSDimitry Andric   // Cap to the global maximum type alignment unless the alignment
64155ffd83dbSDimitry Andric   // was somehow explicit on the type.
64165ffd83dbSDimitry Andric   if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
64175ffd83dbSDimitry Andric     if (Alignment.getQuantity() > MaxAlign &&
64185ffd83dbSDimitry Andric         !getContext().isAlignmentRequired(T))
64195ffd83dbSDimitry Andric       Alignment = CharUnits::fromQuantity(MaxAlign);
64205ffd83dbSDimitry Andric   }
64215ffd83dbSDimitry Andric   return Alignment;
64225ffd83dbSDimitry Andric }
64235ffd83dbSDimitry Andric 
stopAutoInit()64245ffd83dbSDimitry Andric bool CodeGenModule::stopAutoInit() {
64255ffd83dbSDimitry Andric   unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
64265ffd83dbSDimitry Andric   if (StopAfter) {
64275ffd83dbSDimitry Andric     // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
64285ffd83dbSDimitry Andric     // used
64295ffd83dbSDimitry Andric     if (NumAutoVarInit >= StopAfter) {
64305ffd83dbSDimitry Andric       return true;
64315ffd83dbSDimitry Andric     }
64325ffd83dbSDimitry Andric     if (!NumAutoVarInit) {
64335ffd83dbSDimitry Andric       unsigned DiagID = getDiags().getCustomDiagID(
64345ffd83dbSDimitry Andric           DiagnosticsEngine::Warning,
64355ffd83dbSDimitry Andric           "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
64365ffd83dbSDimitry Andric           "number of times ftrivial-auto-var-init=%1 gets applied.");
64375ffd83dbSDimitry Andric       getDiags().Report(DiagID)
64385ffd83dbSDimitry Andric           << StopAfter
64395ffd83dbSDimitry Andric           << (getContext().getLangOpts().getTrivialAutoVarInit() ==
64405ffd83dbSDimitry Andric                       LangOptions::TrivialAutoVarInitKind::Zero
64415ffd83dbSDimitry Andric                   ? "zero"
64425ffd83dbSDimitry Andric                   : "pattern");
64435ffd83dbSDimitry Andric     }
64445ffd83dbSDimitry Andric     ++NumAutoVarInit;
64455ffd83dbSDimitry Andric   }
64465ffd83dbSDimitry Andric   return false;
64475ffd83dbSDimitry Andric }
64485f7ddb14SDimitry Andric 
printPostfixForExternalizedStaticVar(llvm::raw_ostream & OS) const64495f7ddb14SDimitry Andric void CodeGenModule::printPostfixForExternalizedStaticVar(
64505f7ddb14SDimitry Andric     llvm::raw_ostream &OS) const {
64515f7ddb14SDimitry Andric   OS << ".static." << getContext().getCUIDHash();
64525f7ddb14SDimitry Andric }
6453