52#include "llvm/ADT/STLExtras.h"
53#include "llvm/ADT/StringExtras.h"
54#include "llvm/ADT/StringSwitch.h"
55#include "llvm/Analysis/TargetLibraryInfo.h"
56#include "llvm/BinaryFormat/ELF.h"
57#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
58#include "llvm/IR/AttributeMask.h"
59#include "llvm/IR/CallingConv.h"
60#include "llvm/IR/DataLayout.h"
61#include "llvm/IR/Intrinsics.h"
62#include "llvm/IR/LLVMContext.h"
63#include "llvm/IR/Module.h"
64#include "llvm/IR/ProfileSummary.h"
65#include "llvm/ProfileData/InstrProfReader.h"
66#include "llvm/ProfileData/SampleProf.h"
67#include "llvm/Support/CRC.h"
68#include "llvm/Support/CodeGen.h"
69#include "llvm/Support/CommandLine.h"
70#include "llvm/Support/ConvertUTF.h"
71#include "llvm/Support/ErrorHandling.h"
72#include "llvm/Support/TimeProfiler.h"
73#include "llvm/Support/xxhash.h"
74#include "llvm/TargetParser/RISCVISAInfo.h"
75#include "llvm/TargetParser/Triple.h"
76#include "llvm/TargetParser/X86TargetParser.h"
77#include "llvm/Transforms/Utils/BuildLibCalls.h"
81using namespace CodeGen;
84 "limited-coverage-experimental", llvm::cl::Hidden,
85 llvm::cl::desc(
"Emit limited coverage mapping information (experimental)"));
91 case TargetCXXABI::AppleARM64:
92 case TargetCXXABI::Fuchsia:
93 case TargetCXXABI::GenericAArch64:
94 case TargetCXXABI::GenericARM:
95 case TargetCXXABI::iOS:
96 case TargetCXXABI::WatchOS:
97 case TargetCXXABI::GenericMIPS:
98 case TargetCXXABI::GenericItanium:
99 case TargetCXXABI::WebAssembly:
100 case TargetCXXABI::XL:
102 case TargetCXXABI::Microsoft:
106 llvm_unreachable(
"invalid C++ ABI kind");
109static std::unique_ptr<TargetCodeGenInfo>
115 switch (Triple.getArch()) {
119 case llvm::Triple::m68k:
121 case llvm::Triple::mips:
122 case llvm::Triple::mipsel:
123 if (Triple.getOS() == llvm::Triple::NaCl)
127 case llvm::Triple::mips64:
128 case llvm::Triple::mips64el:
131 case llvm::Triple::avr: {
135 unsigned NPR =
Target.getABI() ==
"avrtiny" ? 6 : 18;
136 unsigned NRR =
Target.getABI() ==
"avrtiny" ? 4 : 8;
140 case llvm::Triple::aarch64:
141 case llvm::Triple::aarch64_32:
142 case llvm::Triple::aarch64_be: {
144 if (
Target.getABI() ==
"darwinpcs")
145 Kind = AArch64ABIKind::DarwinPCS;
146 else if (Triple.isOSWindows())
148 else if (
Target.getABI() ==
"aapcs-soft")
149 Kind = AArch64ABIKind::AAPCSSoft;
150 else if (
Target.getABI() ==
"pauthtest")
151 Kind = AArch64ABIKind::PAuthTest;
156 case llvm::Triple::wasm32:
157 case llvm::Triple::wasm64: {
159 if (
Target.getABI() ==
"experimental-mv")
160 Kind = WebAssemblyABIKind::ExperimentalMV;
164 case llvm::Triple::arm:
165 case llvm::Triple::armeb:
166 case llvm::Triple::thumb:
167 case llvm::Triple::thumbeb: {
168 if (Triple.getOS() == llvm::Triple::Win32)
172 StringRef ABIStr =
Target.getABI();
173 if (ABIStr ==
"apcs-gnu")
174 Kind = ARMABIKind::APCS;
175 else if (ABIStr ==
"aapcs16")
176 Kind = ARMABIKind::AAPCS16_VFP;
177 else if (CodeGenOpts.
FloatABI ==
"hard" ||
179 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
180 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
181 Triple.getEnvironment() == llvm::Triple::EABIHF)))
182 Kind = ARMABIKind::AAPCS_VFP;
187 case llvm::Triple::ppc: {
188 if (Triple.isOSAIX())
195 case llvm::Triple::ppcle: {
196 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
199 case llvm::Triple::ppc64:
200 if (Triple.isOSAIX())
203 if (Triple.isOSBinFormatELF()) {
205 if (
Target.getABI() ==
"elfv2")
206 Kind = PPC64_SVR4_ABIKind::ELFv2;
207 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
212 case llvm::Triple::ppc64le: {
213 assert(Triple.isOSBinFormatELF() &&
"PPC64 LE non-ELF not supported!");
215 if (
Target.getABI() ==
"elfv1")
216 Kind = PPC64_SVR4_ABIKind::ELFv1;
217 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
222 case llvm::Triple::nvptx:
223 case llvm::Triple::nvptx64:
226 case llvm::Triple::msp430:
229 case llvm::Triple::riscv32:
230 case llvm::Triple::riscv64: {
231 StringRef ABIStr =
Target.getABI();
232 unsigned XLen =
Target.getPointerWidth(LangAS::Default);
233 unsigned ABIFLen = 0;
234 if (ABIStr.ends_with(
"f"))
236 else if (ABIStr.ends_with(
"d"))
238 bool EABI = ABIStr.ends_with(
"e");
242 case llvm::Triple::systemz: {
243 bool SoftFloat = CodeGenOpts.
FloatABI ==
"soft";
244 bool HasVector = !SoftFloat &&
Target.getABI() ==
"vector";
248 case llvm::Triple::tce:
249 case llvm::Triple::tcele:
252 case llvm::Triple::x86: {
253 bool IsDarwinVectorABI = Triple.isOSDarwin();
254 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
256 if (Triple.getOS() == llvm::Triple::Win32) {
258 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
259 CodeGenOpts.NumRegisterParameters);
262 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
263 CodeGenOpts.NumRegisterParameters, CodeGenOpts.
FloatABI ==
"soft");
266 case llvm::Triple::x86_64: {
267 StringRef ABI =
Target.getABI();
268 X86AVXABILevel AVXLevel = (ABI ==
"avx512" ? X86AVXABILevel::AVX512
269 : ABI ==
"avx" ? X86AVXABILevel::AVX
270 : X86AVXABILevel::None);
272 switch (Triple.getOS()) {
273 case llvm::Triple::Win32:
279 case llvm::Triple::hexagon:
281 case llvm::Triple::lanai:
283 case llvm::Triple::r600:
285 case llvm::Triple::amdgcn:
287 case llvm::Triple::sparc:
289 case llvm::Triple::sparcv9:
291 case llvm::Triple::xcore:
293 case llvm::Triple::arc:
295 case llvm::Triple::spir:
296 case llvm::Triple::spir64:
298 case llvm::Triple::spirv32:
299 case llvm::Triple::spirv64:
301 case llvm::Triple::ve:
303 case llvm::Triple::csky: {
304 bool IsSoftFloat = !
Target.hasFeature(
"hard-float-abi");
306 Target.hasFeature(
"fpuv2_df") ||
Target.hasFeature(
"fpuv3_df");
311 case llvm::Triple::bpfeb:
312 case llvm::Triple::bpfel:
314 case llvm::Triple::loongarch32:
315 case llvm::Triple::loongarch64: {
316 StringRef ABIStr =
Target.getABI();
317 unsigned ABIFRLen = 0;
318 if (ABIStr.ends_with(
"f"))
320 else if (ABIStr.ends_with(
"d"))
323 CGM,
Target.getPointerWidth(LangAS::Default), ABIFRLen);
329 if (!TheTargetCodeGenInfo)
331 return *TheTargetCodeGenInfo;
341 : Context(
C), LangOpts(
C.getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
342 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
344 VMContext(M.getContext()), VTables(*this),
349 llvm::LLVMContext &LLVMContext = M.getContext();
350 VoidTy = llvm::Type::getVoidTy(LLVMContext);
351 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
352 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
353 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
354 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
355 HalfTy = llvm::Type::getHalfTy(LLVMContext);
356 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
357 FloatTy = llvm::Type::getFloatTy(LLVMContext);
358 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
364 C.toCharUnitsFromBits(
C.getTargetInfo().getMaxPointerWidth()).getQuantity();
366 C.toCharUnitsFromBits(
C.getTargetInfo().getIntAlign()).getQuantity();
368 llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getCharWidth());
369 IntTy = llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getIntWidth());
370 IntPtrTy = llvm::IntegerType::get(LLVMContext,
371 C.getTargetInfo().getMaxPointerWidth());
372 Int8PtrTy = llvm::PointerType::get(LLVMContext,
374 const llvm::DataLayout &DL = M.getDataLayout();
376 llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
378 llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
395 createOpenCLRuntime();
397 createOpenMPRuntime();
404 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread) ||
405 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
411 if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
416 Block.GlobalUniqueCount = 0;
418 if (
C.getLangOpts().ObjC)
422 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
429 PGOReader = std::move(ReaderOrErr.get());
434 if (CodeGenOpts.CoverageMapping)
438 if (CodeGenOpts.UniqueInternalLinkageNames &&
439 !
getModule().getSourceFileName().empty()) {
443 if (
Path.rfind(Entry.first, 0) != std::string::npos) {
444 Path = Entry.second +
Path.substr(Entry.first.size());
447 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(
Path);
452 getModule().addModuleFlag(llvm::Module::Error,
"NumRegisterParameters",
453 CodeGenOpts.NumRegisterParameters);
458void CodeGenModule::createObjCRuntime() {
475 llvm_unreachable(
"bad runtime kind");
478void CodeGenModule::createOpenCLRuntime() {
482void CodeGenModule::createOpenMPRuntime() {
486 case llvm::Triple::nvptx:
487 case llvm::Triple::nvptx64:
488 case llvm::Triple::amdgcn:
490 "OpenMP AMDGPU/NVPTX is only prepared to deal with device code.");
494 if (LangOpts.OpenMPSimd)
502void CodeGenModule::createCUDARuntime() {
506void CodeGenModule::createHLSLRuntime() {
511 Replacements[Name] =
C;
514void CodeGenModule::applyReplacements() {
515 for (
auto &I : Replacements) {
516 StringRef MangledName = I.first;
517 llvm::Constant *Replacement = I.second;
521 auto *OldF = cast<llvm::Function>(Entry);
522 auto *NewF = dyn_cast<llvm::Function>(Replacement);
524 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
525 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
527 auto *CE = cast<llvm::ConstantExpr>(Replacement);
528 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
529 CE->getOpcode() == llvm::Instruction::GetElementPtr);
530 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
535 OldF->replaceAllUsesWith(Replacement);
537 NewF->removeFromParent();
538 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
541 OldF->eraseFromParent();
546 GlobalValReplacements.push_back(std::make_pair(GV,
C));
549void CodeGenModule::applyGlobalValReplacements() {
550 for (
auto &I : GlobalValReplacements) {
551 llvm::GlobalValue *GV = I.first;
552 llvm::Constant *
C = I.second;
554 GV->replaceAllUsesWith(
C);
555 GV->eraseFromParent();
562 const llvm::Constant *
C;
563 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
564 C = GA->getAliasee();
565 else if (
auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
566 C = GI->getResolver();
570 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(
C->stripPointerCasts());
574 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
583 bool IsIFunc,
const llvm::GlobalValue *Alias,
const llvm::GlobalValue *&GV,
584 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
588 Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
592 if (GV->hasCommonLinkage()) {
594 if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
595 Diags.
Report(Location, diag::err_alias_to_common);
600 if (GV->isDeclaration()) {
601 Diags.
Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
602 Diags.
Report(Location, diag::note_alias_requires_mangled_name)
603 << IsIFunc << IsIFunc;
606 for (
const auto &[
Decl, Name] : MangledDeclNames) {
607 if (
const auto *ND = dyn_cast<NamedDecl>(
Decl.getDecl())) {
608 if (ND->getName() == GV->getName()) {
609 Diags.
Report(Location, diag::note_alias_mangled_name_alternative)
613 (Twine(IsIFunc ?
"ifunc" :
"alias") +
"(\"" + Name +
"\")")
623 const auto *F = dyn_cast<llvm::Function>(GV);
625 Diags.
Report(Location, diag::err_alias_to_undefined)
626 << IsIFunc << IsIFunc;
630 llvm::FunctionType *FTy = F->getFunctionType();
631 if (!FTy->getReturnType()->isPointerTy()) {
632 Diags.
Report(Location, diag::err_ifunc_resolver_return);
646 if (GVar->hasAttribute(
"toc-data")) {
647 auto GVId = GVar->getName();
650 Diags.
Report(Location, diag::warn_toc_unsupported_type)
651 << GVId <<
"the variable has an alias";
653 llvm::AttributeSet CurrAttributes = GVar->getAttributes();
654 llvm::AttributeSet NewAttributes =
655 CurrAttributes.removeAttribute(GVar->getContext(),
"toc-data");
656 GVar->setAttributes(NewAttributes);
660void CodeGenModule::checkAliases() {
667 const auto *
D = cast<ValueDecl>(GD.getDecl());
670 bool IsIFunc =
D->
hasAttr<IFuncAttr>();
672 Location = A->getLocation();
673 Range = A->getRange();
675 llvm_unreachable(
"Not an alias or ifunc?");
679 const llvm::GlobalValue *GV =
nullptr;
681 MangledDeclNames,
Range)) {
687 if (
const llvm::GlobalVariable *GVar =
688 dyn_cast<const llvm::GlobalVariable>(GV))
692 llvm::Constant *Aliasee =
693 IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver()
694 : cast<llvm::GlobalAlias>(Alias)->getAliasee();
696 llvm::GlobalValue *AliaseeGV;
697 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
698 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
700 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
702 if (
const SectionAttr *SA =
D->
getAttr<SectionAttr>()) {
703 StringRef AliasSection = SA->getName();
704 if (AliasSection != AliaseeGV->getSection())
705 Diags.
Report(SA->getLocation(), diag::warn_alias_with_section)
706 << AliasSection << IsIFunc << IsIFunc;
714 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
715 if (GA->isInterposable()) {
716 Diags.
Report(Location, diag::warn_alias_to_weak_alias)
717 << GV->getName() << GA->getName() << IsIFunc;
718 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
719 GA->getAliasee(), Alias->getType());
722 cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee);
724 cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee);
730 cast<llvm::Function>(Aliasee)->addFnAttr(
731 llvm::Attribute::DisableSanitizerInstrumentation);
739 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
740 Alias->eraseFromParent();
745 DeferredDeclsToEmit.clear();
746 EmittedDeferredDecls.clear();
747 DeferredAnnotations.clear();
749 OpenMPRuntime->clear();
753 StringRef MainFile) {
756 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
757 if (MainFile.empty())
758 MainFile =
"<stdin>";
759 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
762 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
765 Diags.
Report(diag::warn_profile_data_missing) << Visited << Missing;
769static std::optional<llvm::GlobalValue::VisibilityTypes>
776 return llvm::GlobalValue::DefaultVisibility;
778 return llvm::GlobalValue::HiddenVisibility;
780 return llvm::GlobalValue::ProtectedVisibility;
782 llvm_unreachable(
"unknown option value!");
786 std::optional<llvm::GlobalValue::VisibilityTypes>
V) {
795 GV.setDSOLocal(
false);
796 GV.setVisibility(*
V);
801 if (!LO.VisibilityFromDLLStorageClass)
804 std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
807 std::optional<llvm::GlobalValue::VisibilityTypes>
808 NoDLLStorageClassVisibility =
811 std::optional<llvm::GlobalValue::VisibilityTypes>
812 ExternDeclDLLImportVisibility =
815 std::optional<llvm::GlobalValue::VisibilityTypes>
816 ExternDeclNoDLLStorageClassVisibility =
819 for (llvm::GlobalValue &GV : M.global_values()) {
820 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
823 if (GV.isDeclarationForLinker())
825 llvm::GlobalValue::DLLImportStorageClass
826 ? ExternDeclDLLImportVisibility
827 : ExternDeclNoDLLStorageClassVisibility);
830 llvm::GlobalValue::DLLExportStorageClass
831 ? DLLExportVisibility
832 : NoDLLStorageClassVisibility);
834 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
839 const llvm::Triple &Triple,
841 if (Triple.isAMDGPU() || Triple.isNVPTX())
843 return LangOpts.getStackProtector() == Mode;
849 EmitModuleInitializers(Primary);
851 DeferredDecls.insert(EmittedDeferredDecls.begin(),
852 EmittedDeferredDecls.end());
853 EmittedDeferredDecls.clear();
854 EmitVTablesOpportunistically();
855 applyGlobalValReplacements();
857 emitMultiVersionFunctions();
860 GlobalTopLevelStmtBlockInFlight.first) {
862 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->
getEndLoc());
863 GlobalTopLevelStmtBlockInFlight = {
nullptr,
nullptr};
869 EmitCXXModuleInitFunc(Primary);
871 EmitCXXGlobalInitFunc();
872 EmitCXXGlobalCleanUpFunc();
873 registerGlobalDtorsWithAtExit();
874 EmitCXXThreadLocalInitFunc();
876 if (llvm::Function *ObjCInitFunction =
ObjCRuntime->ModuleInitFunction())
879 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
883 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
884 OpenMPRuntime->clear();
888 PGOReader->getSummary(
false).getMD(VMContext),
889 llvm::ProfileSummary::PSK_Instr);
896 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
897 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
899 EmitStaticExternCAliases();
905 CoverageMapping->emit();
906 if (CodeGenOpts.SanitizeCfiCrossDso) {
912 emitAtAvailableLinkGuard();
920 if (
getTarget().getTargetOpts().CodeObjectVersion !=
921 llvm::CodeObjectVersionKind::COV_None) {
922 getModule().addModuleFlag(llvm::Module::Error,
923 "amdhsa_code_object_version",
924 getTarget().getTargetOpts().CodeObjectVersion);
929 auto *MDStr = llvm::MDString::get(
934 getModule().addModuleFlag(llvm::Module::Error,
"amdgpu_printf_kind",
947 if (
auto *FD = dyn_cast<FunctionDecl>(
D))
951 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
955 llvm::ArrayType *ATy = llvm::ArrayType::get(
Int8PtrTy, UsedArray.size());
957 auto *GV =
new llvm::GlobalVariable(
958 getModule(), ATy,
false, llvm::GlobalValue::InternalLinkage,
959 llvm::ConstantArray::get(ATy, UsedArray),
"__clang_gpu_used_external");
962 if (LangOpts.HIP && !
getLangOpts().OffloadingNewDriver) {
965 auto *GV =
new llvm::GlobalVariable(
967 llvm::Constant::getNullValue(
Int8Ty),
975 if (CodeGenOpts.Autolink &&
976 (Context.
getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
977 EmitModuleLinkOptions();
992 if (!ELFDependentLibraries.empty() && !Context.
getLangOpts().CUDAIsDevice) {
993 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.dependent-libraries");
994 for (
auto *MD : ELFDependentLibraries)
998 if (CodeGenOpts.DwarfVersion) {
999 getModule().addModuleFlag(llvm::Module::Max,
"Dwarf Version",
1000 CodeGenOpts.DwarfVersion);
1003 if (CodeGenOpts.Dwarf64)
1004 getModule().addModuleFlag(llvm::Module::Max,
"DWARF64", 1);
1008 getModule().setSemanticInterposition(
true);
1010 if (CodeGenOpts.EmitCodeView) {
1012 getModule().addModuleFlag(llvm::Module::Warning,
"CodeView", 1);
1014 if (CodeGenOpts.CodeViewGHash) {
1015 getModule().addModuleFlag(llvm::Module::Warning,
"CodeViewGHash", 1);
1017 if (CodeGenOpts.ControlFlowGuard) {
1019 getModule().addModuleFlag(llvm::Module::Warning,
"cfguard", 2);
1020 }
else if (CodeGenOpts.ControlFlowGuardNoChecks) {
1022 getModule().addModuleFlag(llvm::Module::Warning,
"cfguard", 1);
1024 if (CodeGenOpts.EHContGuard) {
1026 getModule().addModuleFlag(llvm::Module::Warning,
"ehcontguard", 1);
1030 getModule().addModuleFlag(llvm::Module::Warning,
"ms-kernel", 1);
1032 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
1037 getModule().addModuleFlag(llvm::Module::Error,
"StrictVTablePointers",1);
1039 llvm::Metadata *Ops[2] = {
1040 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
1041 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1042 llvm::Type::getInt32Ty(VMContext), 1))};
1044 getModule().addModuleFlag(llvm::Module::Require,
1045 "StrictVTablePointersRequirement",
1046 llvm::MDNode::get(VMContext, Ops));
1052 getModule().addModuleFlag(llvm::Module::Warning,
"Debug Info Version",
1053 llvm::DEBUG_METADATA_VERSION);
1058 uint64_t WCharWidth =
1060 getModule().addModuleFlag(llvm::Module::Error,
"wchar_size", WCharWidth);
1063 getModule().addModuleFlag(llvm::Module::Warning,
1064 "zos_product_major_version",
1065 uint32_t(CLANG_VERSION_MAJOR));
1066 getModule().addModuleFlag(llvm::Module::Warning,
1067 "zos_product_minor_version",
1068 uint32_t(CLANG_VERSION_MINOR));
1069 getModule().addModuleFlag(llvm::Module::Warning,
"zos_product_patchlevel",
1070 uint32_t(CLANG_VERSION_PATCHLEVEL));
1072 getModule().addModuleFlag(llvm::Module::Error,
"zos_product_id",
1073 llvm::MDString::get(VMContext, ProductId));
1078 getModule().addModuleFlag(llvm::Module::Error,
"zos_cu_language",
1079 llvm::MDString::get(VMContext, lang_str));
1083 : std::time(
nullptr);
1084 getModule().addModuleFlag(llvm::Module::Max,
"zos_translation_time",
1085 static_cast<uint64_t
>(TT));
1088 getModule().addModuleFlag(llvm::Module::Error,
"zos_le_char_mode",
1089 llvm::MDString::get(VMContext,
"ascii"));
1093 if (
T.isARM() ||
T.isThumb()) {
1095 uint64_t EnumWidth = Context.
getLangOpts().ShortEnums ? 1 : 4;
1096 getModule().addModuleFlag(llvm::Module::Error,
"min_enum_size", EnumWidth);
1100 StringRef ABIStr =
Target.getABI();
1101 llvm::LLVMContext &Ctx = TheModule.getContext();
1102 getModule().addModuleFlag(llvm::Module::Error,
"target-abi",
1103 llvm::MDString::get(Ctx, ABIStr));
1108 const std::vector<std::string> &Features =
1111 llvm::RISCVISAInfo::parseFeatures(
T.isRISCV64() ? 64 : 32, Features);
1112 if (!errorToBool(ParseResult.takeError()))
1114 llvm::Module::AppendUnique,
"riscv-isa",
1116 Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString())));
1119 if (CodeGenOpts.SanitizeCfiCrossDso) {
1121 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
1124 if (CodeGenOpts.WholeProgramVTables) {
1128 getModule().addModuleFlag(llvm::Module::Error,
"Virtual Function Elim",
1129 CodeGenOpts.VirtualFunctionElimination);
1132 if (LangOpts.
Sanitize.
has(SanitizerKind::CFIICall)) {
1133 getModule().addModuleFlag(llvm::Module::Override,
1134 "CFI Canonical Jump Tables",
1135 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1138 if (CodeGenOpts.SanitizeCfiICallNormalizeIntegers) {
1139 getModule().addModuleFlag(llvm::Module::Override,
"cfi-normalize-integers",
1144 getModule().addModuleFlag(llvm::Module::Override,
"kcfi", 1);
1147 if (CodeGenOpts.PatchableFunctionEntryOffset)
1148 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-offset",
1149 CodeGenOpts.PatchableFunctionEntryOffset);
1152 if (CodeGenOpts.CFProtectionReturn &&
1155 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-return",
1159 if (CodeGenOpts.CFProtectionBranch &&
1162 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-branch",
1166 if (CodeGenOpts.FunctionReturnThunks)
1167 getModule().addModuleFlag(llvm::Module::Override,
"function_return_thunk_extern", 1);
1169 if (CodeGenOpts.IndirectBranchCSPrefix)
1170 getModule().addModuleFlag(llvm::Module::Override,
"indirect_branch_cs_prefix", 1);
1182 LangOpts.getSignReturnAddressScope() !=
1184 getModule().addModuleFlag(llvm::Module::Override,
1185 "sign-return-address-buildattr", 1);
1186 if (LangOpts.
Sanitize.
has(SanitizerKind::MemtagStack))
1187 getModule().addModuleFlag(llvm::Module::Override,
1188 "tag-stack-memory-buildattr", 1);
1190 if (
T.isARM() ||
T.isThumb() ||
T.isAArch64()) {
1191 if (LangOpts.BranchTargetEnforcement)
1192 getModule().addModuleFlag(llvm::Module::Min,
"branch-target-enforcement",
1194 if (LangOpts.BranchProtectionPAuthLR)
1195 getModule().addModuleFlag(llvm::Module::Min,
"branch-protection-pauth-lr",
1197 if (LangOpts.GuardedControlStack)
1198 getModule().addModuleFlag(llvm::Module::Min,
"guarded-control-stack", 1);
1200 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address", 1);
1202 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address-all",
1205 getModule().addModuleFlag(llvm::Module::Min,
1206 "sign-return-address-with-bkey", 1);
1210 using namespace llvm::ELF;
1211 uint64_t PAuthABIVersion =
1212 (LangOpts.PointerAuthIntrinsics
1213 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS) |
1214 (LangOpts.PointerAuthCalls
1215 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS) |
1216 (LangOpts.PointerAuthReturns
1217 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS) |
1218 (LangOpts.PointerAuthAuthTraps
1219 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS) |
1220 (LangOpts.PointerAuthVTPtrAddressDiscrimination
1221 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR) |
1222 (LangOpts.PointerAuthVTPtrTypeDiscrimination
1223 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR) |
1224 (LangOpts.PointerAuthInitFini
1225 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI) |
1226 (LangOpts.PointerAuthInitFiniAddressDiscrimination
1227 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC) |
1228 (LangOpts.PointerAuthELFGOT
1229 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT) |
1230 (LangOpts.PointerAuthIndirectGotos
1231 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS) |
1232 (LangOpts.PointerAuthTypeInfoVTPtrDiscrimination
1233 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR) |
1234 (LangOpts.PointerAuthFunctionTypeDiscrimination
1235 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR);
1236 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR ==
1237 AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
1238 "Update when new enum items are defined");
1239 if (PAuthABIVersion != 0) {
1240 getModule().addModuleFlag(llvm::Module::Error,
1241 "aarch64-elf-pauthabi-platform",
1242 AARCH64_PAUTH_PLATFORM_LLVM_LINUX);
1243 getModule().addModuleFlag(llvm::Module::Error,
1244 "aarch64-elf-pauthabi-version",
1250 if (CodeGenOpts.StackClashProtector)
1252 llvm::Module::Override,
"probe-stack",
1253 llvm::MDString::get(TheModule.getContext(),
"inline-asm"));
1255 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
1256 getModule().addModuleFlag(llvm::Module::Min,
"stack-probe-size",
1257 CodeGenOpts.StackProbeSize);
1260 llvm::LLVMContext &Ctx = TheModule.getContext();
1262 llvm::Module::Error,
"MemProfProfileFilename",
1266 if (LangOpts.CUDAIsDevice &&
getTriple().isNVPTX()) {
1270 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
1272 llvm::DenormalMode::IEEE);
1275 if (LangOpts.EHAsynch)
1276 getModule().addModuleFlag(llvm::Module::Warning,
"eh-asynch", 1);
1280 getModule().addModuleFlag(llvm::Module::Max,
"openmp", LangOpts.OpenMP);
1282 getModule().addModuleFlag(llvm::Module::Max,
"openmp-device",
1286 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())) {
1287 EmitOpenCLMetadata();
1295 llvm::Metadata *SPIRVerElts[] = {
1296 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1298 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1299 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
1300 llvm::NamedMDNode *SPIRVerMD =
1301 TheModule.getOrInsertNamedMetadata(
"opencl.spir.version");
1302 llvm::LLVMContext &Ctx = TheModule.getContext();
1303 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
1311 if (uint32_t PLevel = Context.
getLangOpts().PICLevel) {
1312 assert(PLevel < 3 &&
"Invalid PIC Level");
1313 getModule().setPICLevel(
static_cast<llvm::PICLevel::Level
>(PLevel));
1315 getModule().setPIELevel(
static_cast<llvm::PIELevel::Level
>(PLevel));
1319 unsigned CM = llvm::StringSwitch<unsigned>(
getCodeGenOpts().CodeModel)
1320 .Case(
"tiny", llvm::CodeModel::Tiny)
1321 .Case(
"small", llvm::CodeModel::Small)
1322 .Case(
"kernel", llvm::CodeModel::Kernel)
1323 .Case(
"medium", llvm::CodeModel::Medium)
1324 .Case(
"large", llvm::CodeModel::Large)
1327 llvm::CodeModel::Model codeModel =
static_cast<llvm::CodeModel::Model
>(CM);
1330 if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
1332 llvm::Triple::x86_64) {
1338 if (CodeGenOpts.NoPLT)
1341 CodeGenOpts.DirectAccessExternalData !=
1342 getModule().getDirectAccessExternalData()) {
1343 getModule().setDirectAccessExternalData(
1344 CodeGenOpts.DirectAccessExternalData);
1346 if (CodeGenOpts.UnwindTables)
1347 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1349 switch (CodeGenOpts.getFramePointer()) {
1354 getModule().setFramePointer(llvm::FramePointerKind::Reserved);
1357 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1360 getModule().setFramePointer(llvm::FramePointerKind::All);
1364 SimplifyPersonality();
1377 EmitVersionIdentMetadata();
1380 EmitCommandLineMetadata();
1388 getModule().setStackProtectorGuardSymbol(
1391 getModule().setStackProtectorGuardOffset(
1396 getModule().addModuleFlag(llvm::Module::Override,
"SkipRaxSetup", 1);
1398 getModule().addModuleFlag(llvm::Module::Override,
"RegCallv4", 1);
1400 if (
getContext().getTargetInfo().getMaxTLSAlign())
1401 getModule().addModuleFlag(llvm::Module::Error,
"MaxTLSAlign",
1402 getContext().getTargetInfo().getMaxTLSAlign());
1420 if (
getTriple().isPPC() && !MustTailCallUndefinedGlobals.empty()) {
1421 for (
auto &I : MustTailCallUndefinedGlobals) {
1422 if (!I.first->isDefined())
1423 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1427 if (!Entry || Entry->isWeakForLinker() ||
1428 Entry->isDeclarationForLinker())
1429 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1435void CodeGenModule::EmitOpenCLMetadata() {
1441 auto EmitVersion = [
this](StringRef MDName,
int Version) {
1442 llvm::Metadata *OCLVerElts[] = {
1443 llvm::ConstantAsMetadata::get(
1444 llvm::ConstantInt::get(
Int32Ty, Version / 100)),
1445 llvm::ConstantAsMetadata::get(
1446 llvm::ConstantInt::get(
Int32Ty, (Version % 100) / 10))};
1447 llvm::NamedMDNode *OCLVerMD = TheModule.getOrInsertNamedMetadata(MDName);
1448 llvm::LLVMContext &Ctx = TheModule.getContext();
1449 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
1452 EmitVersion(
"opencl.ocl.version", CLVersion);
1453 if (LangOpts.OpenCLCPlusPlus) {
1455 EmitVersion(
"opencl.cxx.version", LangOpts.OpenCLCPlusPlusVersion);
1459void CodeGenModule::EmitBackendOptionsMetadata(
1462 getModule().addModuleFlag(llvm::Module::Min,
"SmallDataLimit",
1463 CodeGenOpts.SmallDataLimit);
1480 return TBAA->getTypeInfo(QTy);
1499 return TBAA->getAccessInfo(AccessType);
1506 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
1512 return TBAA->getTBAAStructInfo(QTy);
1518 return TBAA->getBaseTypeInfo(QTy);
1524 return TBAA->getAccessTagInfo(Info);
1531 return TBAA->mergeTBAAInfoForCast(SourceInfo,
TargetInfo);
1539 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
1547 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
1553 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
1558 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
1571 "cannot compile this %0 yet");
1572 std::string Msg =
Type;
1574 << Msg << S->getSourceRange();
1581 "cannot compile this %0 yet");
1582 std::string Msg =
Type;
1593 if (GV->hasLocalLinkage()) {
1594 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1608 Context.
getLangOpts().OpenMPIsTargetDevice && isa<VarDecl>(
D) &&
1609 D->
hasAttr<OMPDeclareTargetDeclAttr>() &&
1610 D->
getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
1611 OMPDeclareTargetDeclAttr::DT_NoHost &&
1613 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1617 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
1621 if (GV->hasDLLExportStorageClass()) {
1624 diag::err_hidden_visibility_dllexport);
1627 diag::err_non_default_visibility_dllimport);
1633 !GV->isDeclarationForLinker())
1638 llvm::GlobalValue *GV) {
1639 if (GV->hasLocalLinkage())
1642 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
1646 if (GV->hasDLLImportStorageClass())
1649 const llvm::Triple &TT = CGM.
getTriple();
1651 if (TT.isWindowsGNUEnvironment()) {
1660 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
1669 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
1677 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
1681 if (!TT.isOSBinFormatELF())
1687 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1693 if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias()))
1695 return !(CGM.
getLangOpts().SemanticInterposition ||
1700 if (!GV->isDeclarationForLinker())
1706 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
1713 if (CGOpts.DirectAccessExternalData) {
1719 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1720 if (!Var->isThreadLocal())
1729 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
1745 const auto *
D = dyn_cast<NamedDecl>(GD.
getDecl());
1747 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(
D)) {
1756 if (
D &&
D->isExternallyVisible()) {
1758 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1759 else if ((
D->
hasAttr<DLLExportAttr>() ||
1761 !GV->isDeclarationForLinker())
1762 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
1786 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
1787 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
1788 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
1789 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
1790 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
1793llvm::GlobalVariable::ThreadLocalMode
1795 switch (CodeGenOpts.getDefaultTLSModel()) {
1797 return llvm::GlobalVariable::GeneralDynamicTLSModel;
1799 return llvm::GlobalVariable::LocalDynamicTLSModel;
1801 return llvm::GlobalVariable::InitialExecTLSModel;
1803 return llvm::GlobalVariable::LocalExecTLSModel;
1805 llvm_unreachable(
"Invalid TLS model!");
1809 assert(
D.getTLSKind() &&
"setting TLS mode on non-TLS var!");
1811 llvm::GlobalValue::ThreadLocalMode TLM;
1815 if (
const TLSModelAttr *
Attr =
D.
getAttr<TLSModelAttr>()) {
1819 GV->setThreadLocalMode(TLM);
1825 return (Twine(
'.') + Twine(
Target.CPUSpecificManglingCharacter(Name))).str();
1829 const CPUSpecificAttr *
Attr,
1851 bool OmitMultiVersionMangling =
false) {
1853 llvm::raw_svector_ostream Out(Buffer);
1862 assert(II &&
"Attempt to mangle unnamed decl.");
1863 const auto *FD = dyn_cast<FunctionDecl>(ND);
1868 Out <<
"__regcall4__" << II->
getName();
1870 Out <<
"__regcall3__" << II->
getName();
1871 }
else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
1873 Out <<
"__device_stub__" << II->
getName();
1889 "Hash computed when not explicitly requested");
1893 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
1894 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
1895 switch (FD->getMultiVersionKind()) {
1899 FD->getAttr<CPUSpecificAttr>(),
1903 auto *
Attr = FD->getAttr<TargetAttr>();
1904 assert(
Attr &&
"Expected TargetAttr to be present "
1905 "for attribute mangling");
1911 auto *
Attr = FD->getAttr<TargetVersionAttr>();
1912 assert(
Attr &&
"Expected TargetVersionAttr to be present "
1913 "for attribute mangling");
1919 auto *
Attr = FD->getAttr<TargetClonesAttr>();
1920 assert(
Attr &&
"Expected TargetClonesAttr to be present "
1921 "for attribute mangling");
1928 llvm_unreachable(
"None multiversion type isn't valid here");
1938 return std::string(Out.str());
1941void CodeGenModule::UpdateMultiVersionNames(
GlobalDecl GD,
1943 StringRef &CurName) {
1950 std::string NonTargetName =
1958 "Other GD should now be a multiversioned function");
1968 if (OtherName != NonTargetName) {
1971 const auto ExistingRecord = Manglings.find(NonTargetName);
1972 if (ExistingRecord != std::end(Manglings))
1973 Manglings.remove(&(*ExistingRecord));
1974 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1979 CurName = OtherNameRef;
1981 Entry->setName(OtherName);
1991 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
2005 auto FoundName = MangledDeclNames.find(CanonicalGD);
2006 if (FoundName != MangledDeclNames.end())
2007 return FoundName->second;
2011 const auto *ND = cast<NamedDecl>(GD.
getDecl());
2023 assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
2034 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
2035 return MangledDeclNames[CanonicalGD] =
Result.first->first();
2044 llvm::raw_svector_ostream Out(Buffer);
2047 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.
getDecl()), Out);
2048 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(
D))
2050 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(
D))
2055 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
2056 return Result.first->first();
2060 auto it = MangledDeclNames.begin();
2061 while (it != MangledDeclNames.end()) {
2062 if (it->second == Name)
2077 llvm::Constant *AssociatedData) {
2085 bool IsDtorAttrFunc) {
2086 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2088 DtorsUsingAtExit[
Priority].push_back(Dtor);
2096void CodeGenModule::EmitCtorList(CtorList &Fns,
const char *GlobalName) {
2097 if (Fns.empty())
return;
2103 llvm::PointerType *PtrTy = llvm::PointerType::get(
2104 getLLVMContext(), TheModule.getDataLayout().getProgramAddressSpace());
2107 llvm::StructType *CtorStructTy = llvm::StructType::get(
Int32Ty, PtrTy, PtrTy);
2111 auto Ctors = Builder.beginArray(CtorStructTy);
2112 for (
const auto &I : Fns) {
2113 auto Ctor = Ctors.beginStruct(CtorStructTy);
2114 Ctor.addInt(
Int32Ty, I.Priority);
2115 if (InitFiniAuthSchema) {
2116 llvm::Constant *StorageAddress =
2118 ? llvm::ConstantExpr::getIntToPtr(
2119 llvm::ConstantInt::get(
2121 llvm::ConstantPtrAuth::AddrDiscriminator_CtorsDtors),
2125 I.Initializer, InitFiniAuthSchema.
getKey(), StorageAddress,
2126 llvm::ConstantInt::get(
2128 Ctor.add(SignedCtorPtr);
2130 Ctor.add(I.Initializer);
2132 if (I.AssociatedData)
2133 Ctor.add(I.AssociatedData);
2135 Ctor.addNullPointer(PtrTy);
2136 Ctor.finishAndAddTo(Ctors);
2139 auto List = Ctors.finishAndCreateGlobal(GlobalName,
getPointerAlign(),
2141 llvm::GlobalValue::AppendingLinkage);
2145 List->setAlignment(std::nullopt);
2150llvm::GlobalValue::LinkageTypes
2152 const auto *
D = cast<FunctionDecl>(GD.
getDecl());
2156 if (
const auto *Dtor = dyn_cast<CXXDestructorDecl>(
D))
2163 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2164 if (!MDS)
return nullptr;
2166 return llvm::ConstantInt::get(
Int64Ty, llvm::MD5Hash(MDS->getString()));
2172 FnType->getReturnType(), FnType->getParamTypes(),
2173 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
2175 std::string OutName;
2176 llvm::raw_string_ostream Out(OutName);
2181 Out <<
".normalized";
2183 return llvm::ConstantInt::get(
Int32Ty,
2184 static_cast<uint32_t
>(llvm::xxHash64(OutName)));
2189 llvm::Function *F,
bool IsThunk) {
2191 llvm::AttributeList PAL;
2194 if (
CallingConv == llvm::CallingConv::X86_VectorCall &&
2200 Error(
Loc,
"__vectorcall calling convention is not currently supported");
2202 F->setAttributes(PAL);
2203 F->setCallingConv(
static_cast<llvm::CallingConv::ID
>(
CallingConv));
2207 std::string ReadOnlyQual(
"__read_only");
2208 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2209 if (ReadOnlyPos != std::string::npos)
2211 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2213 std::string WriteOnlyQual(
"__write_only");
2214 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2215 if (WriteOnlyPos != std::string::npos)
2216 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2218 std::string ReadWriteQual(
"__read_write");
2219 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2220 if (ReadWritePos != std::string::npos)
2221 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2254 assert(((FD && CGF) || (!FD && !CGF)) &&
2255 "Incorrect use - FD and CGF should either be both null or not!");
2281 for (
unsigned i = 0, e = FD->
getNumParams(); i != e; ++i) {
2284 argNames.push_back(llvm::MDString::get(VMContext, parm->
getName()));
2289 std::string typeQuals;
2293 const Decl *PDecl = parm;
2295 PDecl = TD->getDecl();
2296 const OpenCLAccessAttr *A = PDecl->
getAttr<OpenCLAccessAttr>();
2297 if (A && A->isWriteOnly())
2298 accessQuals.push_back(llvm::MDString::get(VMContext,
"write_only"));
2299 else if (A && A->isReadWrite())
2300 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_write"));
2302 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_only"));
2304 accessQuals.push_back(llvm::MDString::get(VMContext,
"none"));
2306 auto getTypeSpelling = [&](
QualType Ty) {
2307 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2309 if (Ty.isCanonical()) {
2310 StringRef typeNameRef = typeName;
2312 if (typeNameRef.consume_front(
"unsigned "))
2313 return std::string(
"u") + typeNameRef.str();
2314 if (typeNameRef.consume_front(
"signed "))
2315 return typeNameRef.str();
2325 addressQuals.push_back(
2326 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(
2330 std::string typeName = getTypeSpelling(pointeeTy) +
"*";
2331 std::string baseTypeName =
2333 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2334 argBaseTypeNames.push_back(
2335 llvm::MDString::get(VMContext, baseTypeName));
2339 typeQuals =
"restrict";
2342 typeQuals += typeQuals.empty() ?
"const" :
" const";
2344 typeQuals += typeQuals.empty() ?
"volatile" :
" volatile";
2346 uint32_t AddrSpc = 0;
2351 addressQuals.push_back(
2352 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(AddrSpc)));
2356 std::string typeName = getTypeSpelling(ty);
2368 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2369 argBaseTypeNames.push_back(
2370 llvm::MDString::get(VMContext, baseTypeName));
2375 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
2379 Fn->setMetadata(
"kernel_arg_addr_space",
2380 llvm::MDNode::get(VMContext, addressQuals));
2381 Fn->setMetadata(
"kernel_arg_access_qual",
2382 llvm::MDNode::get(VMContext, accessQuals));
2383 Fn->setMetadata(
"kernel_arg_type",
2384 llvm::MDNode::get(VMContext, argTypeNames));
2385 Fn->setMetadata(
"kernel_arg_base_type",
2386 llvm::MDNode::get(VMContext, argBaseTypeNames));
2387 Fn->setMetadata(
"kernel_arg_type_qual",
2388 llvm::MDNode::get(VMContext, argTypeQuals));
2392 Fn->setMetadata(
"kernel_arg_name",
2393 llvm::MDNode::get(VMContext, argNames));
2403 if (!LangOpts.Exceptions)
return false;
2406 if (LangOpts.CXXExceptions)
return true;
2409 if (LangOpts.ObjCExceptions) {
2426 !isa<CXXConstructorDecl, CXXDestructorDecl>(MD);
2431 llvm::SetVector<const CXXRecordDecl *> MostBases;
2433 std::function<void (
const CXXRecordDecl *)> CollectMostBases;
2436 MostBases.insert(RD);
2438 CollectMostBases(B.getType()->getAsCXXRecordDecl());
2440 CollectMostBases(RD);
2441 return MostBases.takeVector();
2445 llvm::Function *F) {
2446 llvm::AttrBuilder B(F->getContext());
2448 if ((!
D || !
D->
hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2449 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2451 if (CodeGenOpts.StackClashProtector)
2452 B.addAttribute(
"probe-stack",
"inline-asm");
2454 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
2455 B.addAttribute(
"stack-probe-size",
2456 std::to_string(CodeGenOpts.StackProbeSize));
2459 B.addAttribute(llvm::Attribute::NoUnwind);
2461 if (
D &&
D->
hasAttr<NoStackProtectorAttr>())
2463 else if (
D &&
D->
hasAttr<StrictGuardStackCheckAttr>() &&
2465 B.addAttribute(llvm::Attribute::StackProtectStrong);
2467 B.addAttribute(llvm::Attribute::StackProtect);
2469 B.addAttribute(llvm::Attribute::StackProtectStrong);
2471 B.addAttribute(llvm::Attribute::StackProtectReq);
2477 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2479 B.addAttribute(llvm::Attribute::NoInline);
2487 if (
D->
hasAttr<ArmLocallyStreamingAttr>())
2488 B.addAttribute(
"aarch64_pstate_sm_body");
2491 if (
Attr->isNewZA())
2492 B.addAttribute(
"aarch64_new_za");
2493 if (
Attr->isNewZT0())
2494 B.addAttribute(
"aarch64_new_zt0");
2499 bool ShouldAddOptNone =
2500 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
2502 ShouldAddOptNone &= !
D->
hasAttr<MinSizeAttr>();
2503 ShouldAddOptNone &= !
D->
hasAttr<AlwaysInlineAttr>();
2506 if ((ShouldAddOptNone ||
D->
hasAttr<OptimizeNoneAttr>()) &&
2507 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2508 B.addAttribute(llvm::Attribute::OptimizeNone);
2511 B.addAttribute(llvm::Attribute::NoInline);
2516 B.addAttribute(llvm::Attribute::Naked);
2519 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
2520 F->removeFnAttr(llvm::Attribute::MinSize);
2521 }
else if (
D->
hasAttr<NakedAttr>()) {
2523 B.addAttribute(llvm::Attribute::Naked);
2524 B.addAttribute(llvm::Attribute::NoInline);
2525 }
else if (
D->
hasAttr<NoDuplicateAttr>()) {
2526 B.addAttribute(llvm::Attribute::NoDuplicate);
2527 }
else if (
D->
hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2529 B.addAttribute(llvm::Attribute::NoInline);
2530 }
else if (
D->
hasAttr<AlwaysInlineAttr>() &&
2531 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
2533 B.addAttribute(llvm::Attribute::AlwaysInline);
2537 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
2538 B.addAttribute(llvm::Attribute::NoInline);
2542 if (
auto *FD = dyn_cast<FunctionDecl>(
D)) {
2545 auto CheckRedeclForInline = [](
const FunctionDecl *Redecl) {
2546 return Redecl->isInlineSpecified();
2548 if (any_of(FD->
redecls(), CheckRedeclForInline))
2553 return any_of(Pattern->
redecls(), CheckRedeclForInline);
2555 if (CheckForInline(FD)) {
2556 B.addAttribute(llvm::Attribute::InlineHint);
2557 }
else if (CodeGenOpts.getInlining() ==
2560 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2561 B.addAttribute(llvm::Attribute::NoInline);
2568 if (!
D->
hasAttr<OptimizeNoneAttr>()) {
2570 if (!ShouldAddOptNone)
2571 B.addAttribute(llvm::Attribute::OptimizeForSize);
2572 B.addAttribute(llvm::Attribute::Cold);
2575 B.addAttribute(llvm::Attribute::Hot);
2577 B.addAttribute(llvm::Attribute::MinSize);
2584 F->setAlignment(llvm::Align(alignment));
2587 if (LangOpts.FunctionAlignment)
2588 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
2595 if (isa<CXXMethodDecl>(
D) && F->getPointerAlignment(
getDataLayout()) < 2)
2596 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
2601 if (CodeGenOpts.SanitizeCfiCrossDso &&
2602 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2603 if (
auto *FD = dyn_cast<FunctionDecl>(
D)) {
2614 auto *MD = dyn_cast<CXXMethodDecl>(
D);
2617 llvm::Metadata *
Id =
2620 F->addTypeMetadata(0,
Id);
2627 if (isa_and_nonnull<NamedDecl>(
D))
2630 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2635 if (
const auto *VD = dyn_cast_if_present<VarDecl>(
D);
2637 ((CodeGenOpts.KeepPersistentStorageVariables &&
2638 (VD->getStorageDuration() ==
SD_Static ||
2639 VD->getStorageDuration() ==
SD_Thread)) ||
2640 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
2641 VD->getType().isConstQualified())))
2645bool CodeGenModule::GetCPUAndFeaturesAttributes(
GlobalDecl GD,
2646 llvm::AttrBuilder &Attrs,
2647 bool SetTargetFeatures) {
2653 std::vector<std::string> Features;
2654 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.
getDecl());
2656 const auto *TD = FD ? FD->
getAttr<TargetAttr>() :
nullptr;
2657 const auto *TV = FD ? FD->
getAttr<TargetVersionAttr>() :
nullptr;
2658 assert((!TD || !TV) &&
"both target_version and target specified");
2659 const auto *SD = FD ? FD->
getAttr<CPUSpecificAttr>() :
nullptr;
2660 const auto *TC = FD ? FD->
getAttr<TargetClonesAttr>() :
nullptr;
2661 bool AddedAttr =
false;
2662 if (TD || TV || SD || TC) {
2663 llvm::StringMap<bool> FeatureMap;
2667 for (
const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
2668 Features.push_back((Entry.getValue() ?
"+" :
"-") + Entry.getKey().str());
2676 Target.parseTargetAttr(TD->getFeaturesStr());
2698 if (!TargetCPU.empty()) {
2699 Attrs.addAttribute(
"target-cpu", TargetCPU);
2702 if (!TuneCPU.empty()) {
2703 Attrs.addAttribute(
"tune-cpu", TuneCPU);
2706 if (!Features.empty() && SetTargetFeatures) {
2707 llvm::erase_if(Features, [&](
const std::string& F) {
2710 llvm::sort(Features);
2711 Attrs.addAttribute(
"target-features", llvm::join(Features,
","));
2718void CodeGenModule::setNonAliasAttributes(
GlobalDecl GD,
2719 llvm::GlobalObject *GO) {
2724 if (
auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
2727 if (
auto *SA =
D->
getAttr<PragmaClangBSSSectionAttr>())
2728 GV->addAttribute(
"bss-section", SA->getName());
2729 if (
auto *SA =
D->
getAttr<PragmaClangDataSectionAttr>())
2730 GV->addAttribute(
"data-section", SA->getName());
2731 if (
auto *SA =
D->
getAttr<PragmaClangRodataSectionAttr>())
2732 GV->addAttribute(
"rodata-section", SA->getName());
2733 if (
auto *SA =
D->
getAttr<PragmaClangRelroSectionAttr>())
2734 GV->addAttribute(
"relro-section", SA->getName());
2737 if (
auto *F = dyn_cast<llvm::Function>(GO)) {
2740 if (
auto *SA =
D->
getAttr<PragmaClangTextSectionAttr>())
2742 F->setSection(SA->getName());
2744 llvm::AttrBuilder Attrs(F->getContext());
2745 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
2749 llvm::AttributeMask RemoveAttrs;
2750 RemoveAttrs.addAttribute(
"target-cpu");
2751 RemoveAttrs.addAttribute(
"target-features");
2752 RemoveAttrs.addAttribute(
"tune-cpu");
2753 F->removeFnAttrs(RemoveAttrs);
2754 F->addFnAttrs(Attrs);
2758 if (
const auto *CSA =
D->
getAttr<CodeSegAttr>())
2759 GO->setSection(CSA->getName());
2760 else if (
const auto *SA =
D->
getAttr<SectionAttr>())
2761 GO->setSection(SA->getName());
2774 F->setLinkage(llvm::Function::InternalLinkage);
2776 setNonAliasAttributes(GD, F);
2787 GV->
setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2791 llvm::Function *F) {
2793 if (!LangOpts.
Sanitize.
has(SanitizerKind::CFIICall))
2798 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2802 F->addTypeMetadata(0, MD);
2806 if (CodeGenOpts.SanitizeCfiCrossDso)
2808 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
2812 llvm::LLVMContext &Ctx = F->getContext();
2813 llvm::MDBuilder MDB(Ctx);
2814 F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
2823 return llvm::all_of(Name, [](
const char &
C) {
2824 return llvm::isAlnum(
C) ||
C ==
'_' ||
C ==
'.';
2830 for (
auto &F : M.functions()) {
2832 bool AddressTaken = F.hasAddressTaken();
2833 if (!AddressTaken && F.hasLocalLinkage())
2834 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
2839 if (!AddressTaken || !F.isDeclaration())
2842 const llvm::ConstantInt *
Type;
2843 if (
const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
2844 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
2848 StringRef Name = F.getName();
2852 std::string
Asm = (
".weak __kcfi_typeid_" + Name +
"\n.set __kcfi_typeid_" +
2853 Name +
", " + Twine(
Type->getZExtValue()) +
"\n")
2855 M.appendModuleInlineAsm(
Asm);
2859void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
2860 bool IsIncompleteFunction,
2863 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
2866 F->setAttributes(llvm::Intrinsic::getAttributes(
getLLVMContext(), IID));
2870 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
2872 if (!IsIncompleteFunction)
2879 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
2881 assert(!F->arg_empty() &&
2882 F->arg_begin()->getType()
2883 ->canLosslesslyBitCastTo(F->getReturnType()) &&
2884 "unexpected this return");
2885 F->addParamAttr(0, llvm::Attribute::Returned);
2895 if (!IsIncompleteFunction && F->isDeclaration())
2898 if (
const auto *CSA = FD->
getAttr<CodeSegAttr>())
2899 F->setSection(CSA->getName());
2900 else if (
const auto *SA = FD->
getAttr<SectionAttr>())
2901 F->setSection(SA->getName());
2903 if (
const auto *EA = FD->
getAttr<ErrorAttr>()) {
2905 F->addFnAttr(
"dontcall-error", EA->getUserDiagnostic());
2906 else if (EA->isWarning())
2907 F->addFnAttr(
"dontcall-warn", EA->getUserDiagnostic());
2913 bool HasBody = FD->
hasBody(FDBody);
2915 assert(HasBody &&
"Inline builtin declarations should always have an "
2917 if (shouldEmitFunction(FDBody))
2918 F->addFnAttr(llvm::Attribute::NoBuiltin);
2924 F->addFnAttr(llvm::Attribute::NoBuiltin);
2927 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
2928 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2929 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
2930 if (MD->isVirtual())
2931 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2937 if (!CodeGenOpts.SanitizeCfiCrossDso ||
2938 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
2947 if (CodeGenOpts.InlineMaxStackSize !=
UINT_MAX)
2948 F->addFnAttr(
"inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
2950 if (
const auto *CB = FD->
getAttr<CallbackAttr>()) {
2954 llvm::LLVMContext &Ctx = F->getContext();
2955 llvm::MDBuilder MDB(Ctx);
2959 int CalleeIdx = *CB->encoding_begin();
2960 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
2961 F->addMetadata(llvm::LLVMContext::MD_callback,
2962 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
2963 CalleeIdx, PayloadIndices,
2969 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2970 "Only globals with definition can force usage.");
2971 LLVMUsed.emplace_back(GV);
2975 assert(!GV->isDeclaration() &&
2976 "Only globals with definition can force usage.");
2977 LLVMCompilerUsed.emplace_back(GV);
2981 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2982 "Only globals with definition can force usage.");
2984 LLVMCompilerUsed.emplace_back(GV);
2986 LLVMUsed.emplace_back(GV);
2990 std::vector<llvm::WeakTrackingVH> &List) {
2997 UsedArray.resize(List.size());
2998 for (
unsigned i = 0, e = List.size(); i != e; ++i) {
3000 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3001 cast<llvm::Constant>(&*List[i]), CGM.
Int8PtrTy);
3004 if (UsedArray.empty())
3006 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
3008 auto *GV =
new llvm::GlobalVariable(
3009 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
3010 llvm::ConstantArray::get(ATy, UsedArray), Name);
3012 GV->setSection(
"llvm.metadata");
3015void CodeGenModule::emitLLVMUsed() {
3016 emitUsed(*
this,
"llvm.used", LLVMUsed);
3017 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
3022 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3031 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3037 ELFDependentLibraries.push_back(
3038 llvm::MDNode::get(
C, llvm::MDString::get(
C, Lib)));
3045 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
C, MDOpts));
3060 if (
Visited.insert(Import).second)
3077 if (LL.IsFramework) {
3078 llvm::Metadata *Args[2] = {llvm::MDString::get(Context,
"-framework"),
3079 llvm::MDString::get(Context, LL.Library)};
3081 Metadata.push_back(llvm::MDNode::get(Context, Args));
3087 llvm::Metadata *Args[2] = {
3088 llvm::MDString::get(Context,
"lib"),
3089 llvm::MDString::get(Context, LL.Library),
3091 Metadata.push_back(llvm::MDNode::get(Context, Args));
3095 auto *OptString = llvm::MDString::get(Context, Opt);
3096 Metadata.push_back(llvm::MDNode::get(Context, OptString));
3101void CodeGenModule::EmitModuleInitializers(
clang::Module *Primary) {
3103 "We should only emit module initializers for named modules.");
3109 if (isa<ImportDecl>(
D))
3111 assert(isa<VarDecl>(
D) &&
"GMF initializer decl is not a var?");
3118 if (isa<ImportDecl>(
D))
3126 if (isa<ImportDecl>(
D))
3128 assert(isa<VarDecl>(
D) &&
"PMF initializer decl is not a var?");
3134void CodeGenModule::EmitModuleLinkOptions() {
3138 llvm::SetVector<clang::Module *> LinkModules;
3143 for (
Module *M : ImportedModules) {
3146 if (M->getTopLevelModuleName() ==
getLangOpts().CurrentModule &&
3155 while (!Stack.empty()) {
3158 bool AnyChildren =
false;
3168 Stack.push_back(
SM);
3176 LinkModules.insert(Mod);
3185 for (
Module *M : LinkModules)
3188 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
3189 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
3192 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.linker.options");
3193 for (
auto *MD : LinkerOptionsMetadata)
3194 NMD->addOperand(MD);
3197void CodeGenModule::EmitDeferred() {
3206 if (!DeferredVTables.empty()) {
3207 EmitDeferredVTables();
3212 assert(DeferredVTables.empty());
3219 llvm::append_range(DeferredDeclsToEmit,
3223 if (DeferredDeclsToEmit.empty())
3228 std::vector<GlobalDecl> CurDeclsToEmit;
3229 CurDeclsToEmit.swap(DeferredDeclsToEmit);
3236 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
3254 if (!GV->isDeclaration())
3258 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(
D))
3262 EmitGlobalDefinition(
D, GV);
3267 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
3269 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
3274void CodeGenModule::EmitVTablesOpportunistically() {
3280 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
3281 &&
"Only emit opportunistic vtables with optimizations");
3285 "This queue should only contain external vtables");
3286 if (
getCXXABI().canSpeculativelyEmitVTable(RD))
3289 OpportunisticVTables.clear();
3293 for (
const auto& [MangledName, VD] : DeferredAnnotations) {
3298 DeferredAnnotations.clear();
3300 if (Annotations.empty())
3304 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
3305 Annotations[0]->getType(), Annotations.size()), Annotations);
3306 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
3307 llvm::GlobalValue::AppendingLinkage,
3308 Array,
"llvm.global.annotations");
3313 llvm::Constant *&AStr = AnnotationStrings[Str];
3318 llvm::Constant *
s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
3319 auto *gv =
new llvm::GlobalVariable(
3320 getModule(),
s->getType(),
true, llvm::GlobalValue::PrivateLinkage,
s,
3321 ".str",
nullptr, llvm::GlobalValue::NotThreadLocal,
3324 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3341 SM.getExpansionLineNumber(L);
3342 return llvm::ConstantInt::get(
Int32Ty, LineNo);
3350 llvm::FoldingSetNodeID ID;
3351 for (
Expr *
E : Exprs) {
3352 ID.Add(cast<clang::ConstantExpr>(
E)->getAPValueResult());
3354 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
3359 LLVMArgs.reserve(Exprs.size());
3361 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](
const Expr *
E) {
3362 const auto *CE = cast<clang::ConstantExpr>(
E);
3363 return ConstEmiter.
emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
3366 auto *
Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
3367 auto *GV =
new llvm::GlobalVariable(
getModule(),
Struct->getType(),
true,
3368 llvm::GlobalValue::PrivateLinkage,
Struct,
3371 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3378 const AnnotateAttr *AA,
3386 llvm::Constant *GVInGlobalsAS = GV;
3387 if (GV->getAddressSpace() !=
3389 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
3391 llvm::PointerType::get(
3392 GV->getContext(),
getDataLayout().getDefaultGlobalsAddressSpace()));
3396 llvm::Constant *Fields[] = {
3397 GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
3399 return llvm::ConstantStruct::getAnon(Fields);
3403 llvm::GlobalValue *GV) {
3404 assert(
D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
3414 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
3419 if (NoSanitizeL.containsMainFile(Kind, MainFile.
getName()))
3424 return NoSanitizeL.containsLocation(Kind,
Loc);
3427 return NoSanitizeL.containsFile(Kind, MainFile.
getName());
3431 llvm::GlobalVariable *GV,
3435 if (NoSanitizeL.containsGlobal(Kind, GV->getName(),
Category))
3438 if (NoSanitizeL.containsMainFile(
3439 Kind,
SM.getFileEntryRefForID(
SM.getMainFileID())->getName(),
3442 if (NoSanitizeL.containsLocation(Kind,
Loc,
Category))
3449 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
3450 Ty = AT->getElementType();
3455 if (NoSanitizeL.containsType(Kind, TypeStr,
Category))
3466 auto Attr = ImbueAttr::NONE;
3469 if (
Attr == ImbueAttr::NONE)
3470 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
3472 case ImbueAttr::NONE:
3474 case ImbueAttr::ALWAYS:
3475 Fn->addFnAttr(
"function-instrument",
"xray-always");
3477 case ImbueAttr::ALWAYS_ARG1:
3478 Fn->addFnAttr(
"function-instrument",
"xray-always");
3479 Fn->addFnAttr(
"xray-log-args",
"1");
3481 case ImbueAttr::NEVER:
3482 Fn->addFnAttr(
"function-instrument",
"xray-never");
3506 if (
auto MainFile =
SM.getFileEntryRefForID(
SM.getMainFileID()))
3520 if (NumGroups > 1) {
3521 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
3530 if (LangOpts.EmitAllDecls)
3533 const auto *VD = dyn_cast<VarDecl>(
Global);
3535 ((CodeGenOpts.KeepPersistentStorageVariables &&
3536 (VD->getStorageDuration() ==
SD_Static ||
3537 VD->getStorageDuration() ==
SD_Thread)) ||
3538 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
3539 VD->getType().isConstQualified())))
3552 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
3553 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
3554 OMPDeclareTargetDeclAttr::getActiveAttr(
Global);
3555 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (
unsigned)-1)
3559 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
3568 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
3574 if (CXX20ModuleInits && VD->getOwningModule() &&
3575 !VD->getOwningModule()->isModuleMapModule()) {
3584 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
3587 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
Global))
3600 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
3604 llvm::Constant *
Init;
3607 if (!
V.isAbsent()) {
3618 llvm::Constant *Fields[4] = {
3622 llvm::ConstantDataArray::getRaw(
3623 StringRef(
reinterpret_cast<char *
>(Parts.
Part4And5), 8), 8,
3625 Init = llvm::ConstantStruct::getAnon(Fields);
3628 auto *GV =
new llvm::GlobalVariable(
3630 true, llvm::GlobalValue::LinkOnceODRLinkage,
Init, Name);
3632 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3635 if (!
V.isAbsent()) {
3648 llvm::GlobalVariable **Entry =
nullptr;
3649 Entry = &UnnamedGlobalConstantDeclMap[GCD];
3654 llvm::Constant *
Init;
3658 assert(!
V.isAbsent());
3662 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
3664 llvm::GlobalValue::PrivateLinkage,
Init,
3666 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3680 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
3684 llvm::Constant *
Init =
Emitter.emitForInitializer(
3692 llvm::GlobalValue::LinkageTypes
Linkage =
3694 ? llvm::GlobalValue::LinkOnceODRLinkage
3695 : llvm::GlobalValue::InternalLinkage;
3696 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
3700 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3707 const AliasAttr *AA = VD->
getAttr<AliasAttr>();
3708 assert(AA &&
"No alias?");
3718 llvm::Constant *Aliasee;
3719 if (isa<llvm::FunctionType>(DeclTy))
3720 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
3727 auto *F = cast<llvm::GlobalValue>(Aliasee);
3728 F->setLinkage(llvm::Function::ExternalWeakLinkage);
3729 WeakRefReferences.insert(F);
3738 return A->isImplicit();
3742bool CodeGenModule::shouldEmitCUDAGlobalVar(
const VarDecl *
Global)
const {
3743 assert(LangOpts.CUDA &&
"Should not be called by non-CUDA languages");
3748 return !LangOpts.CUDAIsDevice ||
Global->hasAttr<CUDADeviceAttr>() ||
3749 Global->hasAttr<CUDAConstantAttr>() ||
3750 Global->hasAttr<CUDASharedAttr>() ||
3751 Global->getType()->isCUDADeviceBuiltinSurfaceType() ||
3752 Global->getType()->isCUDADeviceBuiltinTextureType();
3759 if (
Global->hasAttr<WeakRefAttr>())
3764 if (
Global->hasAttr<AliasAttr>())
3765 return EmitAliasDefinition(GD);
3768 if (
Global->hasAttr<IFuncAttr>())
3769 return emitIFuncDefinition(GD);
3772 if (
Global->hasAttr<CPUDispatchAttr>())
3773 return emitCPUDispatchDefinition(GD);
3778 if (LangOpts.CUDA) {
3779 assert((isa<FunctionDecl>(
Global) || isa<VarDecl>(
Global)) &&
3780 "Expected Variable or Function");
3781 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
3782 if (!shouldEmitCUDAGlobalVar(VD))
3784 }
else if (LangOpts.CUDAIsDevice) {
3785 const auto *FD = dyn_cast<FunctionDecl>(
Global);
3786 if ((!
Global->hasAttr<CUDADeviceAttr>() ||
3787 (LangOpts.OffloadImplicitHostDeviceTemplates &&
3788 hasImplicitAttr<CUDAHostAttr>(FD) &&
3789 hasImplicitAttr<CUDADeviceAttr>(FD) && !FD->
isConstexpr() &&
3791 !
getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
3792 !
Global->hasAttr<CUDAGlobalAttr>() &&
3793 !(LangOpts.HIPStdPar && isa<FunctionDecl>(
Global) &&
3794 !
Global->hasAttr<CUDAHostAttr>()))
3797 }
else if (!
Global->hasAttr<CUDAHostAttr>() &&
3798 Global->hasAttr<CUDADeviceAttr>())
3802 if (LangOpts.OpenMP) {
3804 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
3806 if (
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(
Global)) {
3807 if (MustBeEmitted(
Global))
3811 if (
auto *DMD = dyn_cast<OMPDeclareMapperDecl>(
Global)) {
3812 if (MustBeEmitted(
Global))
3819 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
3822 if (FD->
hasAttr<AnnotateAttr>()) {
3825 DeferredAnnotations[MangledName] = FD;
3840 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
3845 const auto *VD = cast<VarDecl>(
Global);
3846 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
3849 if (LangOpts.OpenMP) {
3851 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3852 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
3856 if (VD->hasExternalStorage() &&
3857 Res != OMPDeclareTargetDeclAttr::MT_Link)
3860 bool UnifiedMemoryEnabled =
3862 if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3863 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3864 !UnifiedMemoryEnabled) {
3867 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3868 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3869 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3870 UnifiedMemoryEnabled)) &&
3871 "Link clause or to clause with unified memory expected.");
3890 if (MustBeEmitted(
Global) && MayBeEmittedEagerly(
Global)) {
3892 EmitGlobalDefinition(GD);
3893 addEmittedDeferredDecl(GD);
3900 cast<VarDecl>(
Global)->hasInit()) {
3901 DelayedCXXInitPosition[
Global] = CXXGlobalInits.size();
3902 CXXGlobalInits.push_back(
nullptr);
3908 addDeferredDeclToEmit(GD);
3909 }
else if (MustBeEmitted(
Global)) {
3911 assert(!MayBeEmittedEagerly(
Global));
3912 addDeferredDeclToEmit(GD);
3917 DeferredDecls[MangledName] = GD;
3924 if (
CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
3925 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
3932 struct FunctionIsDirectlyRecursive
3934 const StringRef Name;
3944 if (
Attr && Name ==
Attr->getLabel())
3949 StringRef BuiltinName = BI.
getName(BuiltinID);
3950 if (BuiltinName.starts_with(
"__builtin_") &&
3951 Name == BuiltinName.slice(strlen(
"__builtin_"), StringRef::npos)) {
3957 bool VisitStmt(
const Stmt *S) {
3958 for (
const Stmt *Child : S->children())
3959 if (Child && this->Visit(Child))
3966 struct DLLImportFunctionVisitor
3968 bool SafeToInline =
true;
3970 bool shouldVisitImplicitCode()
const {
return true; }
3972 bool VisitVarDecl(
VarDecl *VD) {
3975 SafeToInline =
false;
3976 return SafeToInline;
3983 return SafeToInline;
3987 if (
const auto *
D =
E->getTemporary()->getDestructor())
3988 SafeToInline =
D->
hasAttr<DLLImportAttr>();
3989 return SafeToInline;
3994 if (isa<FunctionDecl>(VD))
3995 SafeToInline = VD->
hasAttr<DLLImportAttr>();
3996 else if (
VarDecl *
V = dyn_cast<VarDecl>(VD))
3997 SafeToInline = !
V->hasGlobalStorage() ||
V->hasAttr<DLLImportAttr>();
3998 return SafeToInline;
4002 SafeToInline =
E->getConstructor()->hasAttr<DLLImportAttr>();
4003 return SafeToInline;
4010 SafeToInline =
true;
4012 SafeToInline = M->
hasAttr<DLLImportAttr>();
4014 return SafeToInline;
4018 SafeToInline =
E->getOperatorDelete()->hasAttr<DLLImportAttr>();
4019 return SafeToInline;
4023 SafeToInline =
E->getOperatorNew()->hasAttr<DLLImportAttr>();
4024 return SafeToInline;
4033CodeGenModule::isTriviallyRecursive(
const FunctionDecl *FD) {
4035 if (
getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
4040 Name =
Attr->getLabel();
4045 FunctionIsDirectlyRecursive Walker(Name, Context.
BuiltinInfo);
4047 return Body ? Walker.Visit(Body) :
false;
4050bool CodeGenModule::shouldEmitFunction(
GlobalDecl GD) {
4054 const auto *F = cast<FunctionDecl>(GD.
getDecl());
4057 if (F->isInlineBuiltinDeclaration())
4060 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
4065 if (
const Module *M = F->getOwningModule();
4066 M && M->getTopLevelModule()->isNamedModule() &&
4067 getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
4077 if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
4082 if (F->hasAttr<NoInlineAttr>())
4085 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
4087 DLLImportFunctionVisitor Visitor;
4088 Visitor.TraverseFunctionDecl(
const_cast<FunctionDecl*
>(F));
4089 if (!Visitor.SafeToInline)
4095 for (
const Decl *
Member : Dtor->getParent()->decls())
4096 if (isa<FieldDecl>(
Member))
4110 return !isTriviallyRecursive(F);
4113bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
4114 return CodeGenOpts.OptimizationLevel > 0;
4117void CodeGenModule::EmitMultiVersionFunctionDefinition(
GlobalDecl GD,
4118 llvm::GlobalValue *GV) {
4119 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4122 auto *Spec = FD->
getAttr<CPUSpecificAttr>();
4123 for (
unsigned I = 0; I < Spec->cpus_size(); ++I)
4125 }
else if (
auto *TC = FD->
getAttr<TargetClonesAttr>()) {
4126 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I)
4129 TC->isFirstOfVersion(I))
4132 GetOrCreateMultiVersionResolver(GD);
4134 EmitGlobalFunctionDefinition(GD, GV);
4139 AddDeferredMultiVersionResolverToEmit(GD);
4142void CodeGenModule::EmitGlobalDefinition(
GlobalDecl GD, llvm::GlobalValue *GV) {
4143 const auto *
D = cast<ValueDecl>(GD.
getDecl());
4147 "Generating code for declaration");
4149 if (
const auto *FD = dyn_cast<FunctionDecl>(
D)) {
4152 if (!shouldEmitFunction(GD))
4155 llvm::TimeTraceScope TimeScope(
"CodeGen Function", [&]() {
4157 llvm::raw_string_ostream OS(Name);
4163 if (
const auto *Method = dyn_cast<CXXMethodDecl>(
D)) {
4166 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
4167 ABI->emitCXXStructor(GD);
4169 EmitMultiVersionFunctionDefinition(GD, GV);
4171 EmitGlobalFunctionDefinition(GD, GV);
4173 if (Method->isVirtual())
4180 return EmitMultiVersionFunctionDefinition(GD, GV);
4181 return EmitGlobalFunctionDefinition(GD, GV);
4184 if (
const auto *VD = dyn_cast<VarDecl>(
D))
4185 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
4187 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
4191 llvm::Function *NewFn);
4195 const CodeGenFunction::MultiVersionResolverOption &RO) {
4197 unsigned NumFeatures = 0;
4198 for (StringRef Feat : RO.Conditions.Features) {
4203 if (!RO.Conditions.Architecture.empty())
4221 return llvm::GlobalValue::InternalLinkage;
4222 return llvm::GlobalValue::WeakODRLinkage;
4225void CodeGenModule::emitMultiVersionFunctions() {
4226 std::vector<GlobalDecl> MVFuncsToEmit;
4227 MultiVersionFuncs.swap(MVFuncsToEmit);
4229 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4230 assert(FD &&
"Expected a FunctionDecl");
4237 if (
Decl->isDefined()) {
4238 EmitGlobalFunctionDefinition(CurGD,
nullptr);
4246 assert(
Func &&
"This should have just been created");
4248 return cast<llvm::Function>(
Func);
4262 if (
const auto *TA = CurFD->
getAttr<TargetAttr>()) {
4263 TA->getAddedFeatures(Feats);
4264 llvm::Function *Func = createFunction(CurFD);
4265 Options.emplace_back(Func, TA->getArchitecture(), Feats);
4266 }
else if (
const auto *TVA = CurFD->
getAttr<TargetVersionAttr>()) {
4267 if (TVA->isDefaultVersion() && IsDefined)
4268 ShouldEmitResolver = true;
4269 TVA->getFeatures(Feats);
4270 llvm::Function *Func = createFunction(CurFD);
4271 Options.emplace_back(Func,
"", Feats);
4272 }
else if (
const auto *TC = CurFD->
getAttr<TargetClonesAttr>()) {
4274 ShouldEmitResolver = true;
4275 for (unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
4276 if (!TC->isFirstOfVersion(I))
4279 llvm::Function *Func = createFunction(CurFD, I);
4280 StringRef Architecture;
4282 if (getTarget().getTriple().isAArch64())
4283 TC->getFeatures(Feats, I);
4285 StringRef Version = TC->getFeatureStr(I);
4286 if (Version.starts_with(
"arch="))
4287 Architecture = Version.drop_front(sizeof(
"arch=") - 1);
4288 else if (Version !=
"default")
4289 Feats.push_back(Version);
4291 Options.emplace_back(Func, Architecture, Feats);
4294 llvm_unreachable(
"unexpected MultiVersionKind");
4297 if (!ShouldEmitResolver)
4300 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
4301 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
4302 ResolverConstant = IFunc->getResolver();
4306 *
this, GD, FD,
true);
4313 auto *Alias = llvm::GlobalAlias::create(
4315 MangledName +
".ifunc", IFunc, &
getModule());
4320 llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant);
4325 ResolverFunc->setComdat(
4326 getModule().getOrInsertComdat(ResolverFunc->getName()));
4330 Options, [&TI](
const CodeGenFunction::MultiVersionResolverOption &LHS,
4331 const CodeGenFunction::MultiVersionResolverOption &RHS) {
4335 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4341 if (!MVFuncsToEmit.empty())
4346 if (!MultiVersionFuncs.empty())
4347 emitMultiVersionFunctions();
4351 llvm::Constant *New) {
4352 assert(cast<llvm::Function>(Old)->isDeclaration() &&
"Not a declaration");
4354 Old->replaceAllUsesWith(New);
4355 Old->eraseFromParent();
4358void CodeGenModule::emitCPUDispatchDefinition(
GlobalDecl GD) {
4359 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4360 assert(FD &&
"Not a FunctionDecl?");
4362 const auto *DD = FD->
getAttr<CPUDispatchAttr>();
4363 assert(DD &&
"Not a cpu_dispatch Function?");
4369 UpdateMultiVersionNames(GD, FD, ResolverName);
4371 llvm::Type *ResolverType;
4374 ResolverType = llvm::FunctionType::get(
4375 llvm::PointerType::get(DeclTy,
4384 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
4385 ResolverName, ResolverType, ResolverGD,
false));
4388 ResolverFunc->setComdat(
4389 getModule().getOrInsertComdat(ResolverFunc->getName()));
4402 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
4405 EmitGlobalFunctionDefinition(ExistingDecl,
nullptr);
4411 Func = GetOrCreateLLVMFunction(
4412 MangledName, DeclTy, ExistingDecl,
4419 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
4420 llvm::transform(Features, Features.begin(),
4421 [](StringRef Str) { return Str.substr(1); });
4422 llvm::erase_if(Features, [&
Target](StringRef Feat) {
4423 return !
Target.validateCpuSupports(Feat);
4425 Options.emplace_back(cast<llvm::Function>(
Func), StringRef{}, Features);
4430 Options, [](
const CodeGenFunction::MultiVersionResolverOption &LHS,
4431 const CodeGenFunction::MultiVersionResolverOption &RHS) {
4432 return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) >
4433 llvm::X86::getCpuSupportsMask(RHS.Conditions.Features);
4440 while (Options.size() > 1 &&
4441 llvm::all_of(llvm::X86::getCpuSupportsMask(
4442 (Options.end() - 2)->Conditions.Features),
4443 [](
auto X) { return X == 0; })) {
4444 StringRef LHSName = (Options.end() - 2)->
Function->getName();
4445 StringRef RHSName = (Options.end() - 1)->
Function->getName();
4446 if (LHSName.compare(RHSName) < 0)
4447 Options.erase(Options.end() - 2);
4449 Options.erase(Options.end() - 1);
4453 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4457 auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD));
4461 if (!isa<llvm::GlobalIFunc>(IFunc)) {
4462 auto *GI = llvm::GlobalIFunc::create(DeclTy, 0,
Linkage,
"", ResolverFunc,
4469 *
this, GD, FD,
true);
4472 auto *GA = llvm::GlobalAlias::create(DeclTy, 0,
Linkage, AliasName, IFunc,
4480void CodeGenModule::AddDeferredMultiVersionResolverToEmit(
GlobalDecl GD) {
4481 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4482 assert(FD &&
"Not a FunctionDecl?");
4485 std::string MangledName =
4487 if (!DeferredResolversToEmit.insert(MangledName).second)
4490 MultiVersionFuncs.push_back(GD);
4496llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
GlobalDecl GD) {
4497 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4498 assert(FD &&
"Not a FunctionDecl?");
4500 std::string MangledName =
4505 std::string ResolverName = MangledName;
4509 llvm_unreachable(
"unexpected MultiVersionKind::None for resolver");
4513 ResolverName +=
".ifunc";
4520 ResolverName +=
".resolver";
4531 (isa<llvm::GlobalIFunc>(ResolverGV) || !
getTarget().supportsIFunc()))
4540 AddDeferredMultiVersionResolverToEmit(GD);
4545 llvm::Type *ResolverType = llvm::FunctionType::get(
4546 llvm::PointerType::get(DeclTy,
4549 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4550 MangledName +
".resolver", ResolverType,
GlobalDecl{},
4552 llvm::GlobalIFunc *GIF =
4555 GIF->setName(ResolverName);
4562 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4564 assert(isa<llvm::GlobalValue>(Resolver) &&
4565 "Resolver should be created for the first time");
4572bool CodeGenModule::shouldDropDLLAttribute(
const Decl *
D,
4573 const llvm::GlobalValue *GV)
const {
4574 auto SC = GV->getDLLStorageClass();
4575 if (SC == llvm::GlobalValue::DefaultStorageClass)
4578 return (((SC == llvm::GlobalValue::DLLImportStorageClass &&
4579 !MRD->
hasAttr<DLLImportAttr>()) ||
4580 (SC == llvm::GlobalValue::DLLExportStorageClass &&
4581 !MRD->
hasAttr<DLLExportAttr>())) &&
4592llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
4593 StringRef MangledName, llvm::Type *Ty,
GlobalDecl GD,
bool ForVTable,
4594 bool DontDefer,
bool IsThunk, llvm::AttributeList ExtraAttrs,
4598 std::string NameWithoutMultiVersionMangling;
4601 if (
const FunctionDecl *FD = cast_or_null<FunctionDecl>(
D)) {
4603 if (
getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
4604 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->
isDefined() &&
4605 !DontDefer && !IsForDefinition) {
4608 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
4610 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
4619 UpdateMultiVersionNames(GD, FD, MangledName);
4620 if (!IsForDefinition) {
4626 AddDeferredMultiVersionResolverToEmit(GD);
4628 *
this, GD, FD,
true);
4630 return GetOrCreateMultiVersionResolver(GD);
4635 if (!NameWithoutMultiVersionMangling.empty())
4636 MangledName = NameWithoutMultiVersionMangling;
4641 if (WeakRefReferences.erase(Entry)) {
4643 if (FD && !FD->
hasAttr<WeakAttr>())
4644 Entry->setLinkage(llvm::Function::ExternalLinkage);
4648 if (
D && shouldDropDLLAttribute(
D, Entry)) {
4649 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4655 if (IsForDefinition && !Entry->isDeclaration()) {
4662 DiagnosedConflictingDefinitions.insert(GD).second) {
4666 diag::note_previous_definition);
4670 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
4671 (Entry->getValueType() == Ty)) {
4678 if (!IsForDefinition)
4685 bool IsIncompleteFunction =
false;
4687 llvm::FunctionType *FTy;
4688 if (isa<llvm::FunctionType>(Ty)) {
4689 FTy = cast<llvm::FunctionType>(Ty);
4691 FTy = llvm::FunctionType::get(
VoidTy,
false);
4692 IsIncompleteFunction =
true;
4696 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
4697 Entry ? StringRef() : MangledName, &
getModule());
4702 DeferredAnnotations[MangledName] = cast<ValueDecl>(
D);
4719 if (!Entry->use_empty()) {
4721 Entry->removeDeadConstantUsers();
4727 assert(F->getName() == MangledName &&
"name was uniqued!");
4729 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
4730 if (ExtraAttrs.hasFnAttrs()) {
4731 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
4739 if (isa_and_nonnull<CXXDestructorDecl>(
D) &&
4740 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(
D),
4742 addDeferredDeclToEmit(GD);
4747 auto DDI = DeferredDecls.find(MangledName);
4748 if (DDI != DeferredDecls.end()) {
4752 addDeferredDeclToEmit(DDI->second);
4753 DeferredDecls.erase(DDI);
4768 for (
const auto *FD = cast<FunctionDecl>(
D)->getMostRecentDecl(); FD;
4781 if (!IsIncompleteFunction) {
4782 assert(F->getFunctionType() == Ty);
4798 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4805 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(GD.
getDecl())) {
4808 DD->getParent()->getNumVBases() == 0)
4813 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
4814 false, llvm::AttributeList(),
4817 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
4818 cast<FunctionDecl>(GD.
getDecl())->hasAttr<CUDAGlobalAttr>()) {
4820 cast<llvm::Function>(F->stripPointerCasts()), GD);
4821 if (IsForDefinition)
4829 llvm::GlobalValue *F =
4832 return llvm::NoCFIValue::get(F);
4842 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
4845 if (!
C.getLangOpts().CPlusPlus)
4850 (Name ==
"_ZSt9terminatev" || Name ==
"?terminate@@YAXXZ")
4851 ?
C.Idents.get(
"terminate")
4852 :
C.Idents.get(Name);
4854 for (
const auto &N : {
"__cxxabiv1",
"std"}) {
4858 if (
auto *LSD = dyn_cast<LinkageSpecDecl>(
Result))
4859 for (
const auto *
Result : LSD->lookup(&NS))
4860 if ((ND = dyn_cast<NamespaceDecl>(
Result)))
4865 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
4877 llvm::AttributeList ExtraAttrs,
bool Local,
4878 bool AssumeConvergent) {
4879 if (AssumeConvergent) {
4881 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
4885 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
4889 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
4898 if (!Local &&
getTriple().isWindowsItaniumEnvironment() &&
4901 if (!FD || FD->
hasAttr<DLLImportAttr>()) {
4902 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4903 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
4910 markRegisterParameterAttributes(F);
4936 if (WeakRefReferences.erase(Entry)) {
4938 Entry->setLinkage(llvm::Function::ExternalLinkage);
4942 if (
D && shouldDropDLLAttribute(
D, Entry))
4943 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4945 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd &&
D)
4948 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
4953 if (IsForDefinition && !Entry->isDeclaration()) {
4961 (OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
4963 DiagnosedConflictingDefinitions.insert(
D).second) {
4967 diag::note_previous_definition);
4972 if (Entry->getType()->getAddressSpace() != TargetAS)
4973 return llvm::ConstantExpr::getAddrSpaceCast(
4974 Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
4978 if (!IsForDefinition)
4984 auto *GV =
new llvm::GlobalVariable(
4985 getModule(), Ty,
false, llvm::GlobalValue::ExternalLinkage,
nullptr,
4986 MangledName,
nullptr, llvm::GlobalVariable::NotThreadLocal,
4987 getContext().getTargetAddressSpace(DAddrSpace));
4992 GV->takeName(Entry);
4994 if (!Entry->use_empty()) {
4995 Entry->replaceAllUsesWith(GV);
4998 Entry->eraseFromParent();
5004 auto DDI = DeferredDecls.find(MangledName);
5005 if (DDI != DeferredDecls.end()) {
5008 addDeferredDeclToEmit(DDI->second);
5009 DeferredDecls.erase(DDI);
5014 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
5019 GV->setConstant(
D->getType().isConstantStorage(
getContext(),
false,
false));
5021 GV->setAlignment(
getContext().getDeclAlign(
D).getAsAlign());
5025 if (
D->getTLSKind()) {
5027 CXXThreadLocals.push_back(
D);
5035 if (
getContext().isMSStaticDataMemberInlineDefinition(
D)) {
5036 EmitGlobalVarDefinition(
D);
5040 if (
D->hasExternalStorage()) {
5041 if (
const SectionAttr *SA =
D->
getAttr<SectionAttr>())
5042 GV->setSection(SA->getName());
5046 if (
getTriple().getArch() == llvm::Triple::xcore &&
5048 D->getType().isConstant(Context) &&
5050 GV->setSection(
".cp.rodata");
5053 if (
const auto *CMA =
D->
getAttr<CodeModelAttr>())
5054 GV->setCodeModel(CMA->getModel());
5059 if (Context.
getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
5060 D->getType().isConstQualified() && !GV->hasInitializer() &&
5061 !
D->hasDefinition() &&
D->hasInit() && !
D->
hasAttr<DLLImportAttr>()) {
5065 if (!HasMutableFields) {
5067 const Expr *InitExpr =
D->getAnyInitializer(InitDecl);
5072 auto *InitType =
Init->getType();
5073 if (GV->getValueType() != InitType) {
5078 GV->setName(StringRef());
5081 auto *NewGV = cast<llvm::GlobalVariable>(
5083 ->stripPointerCasts());
5086 GV->eraseFromParent();
5089 GV->setInitializer(
Init);
5090 GV->setConstant(
true);
5091 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
5106 D->hasExternalStorage())
5111 SanitizerMD->reportGlobal(GV, *
D);
5114 D ?
D->getType().getAddressSpace()
5116 assert(
getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
5117 if (DAddrSpace != ExpectedAS) {
5119 *
this, GV, DAddrSpace, ExpectedAS,
5130 if (isa<CXXConstructorDecl>(
D) || isa<CXXDestructorDecl>(
D))
5132 false, IsForDefinition);
5134 if (isa<CXXMethodDecl>(
D)) {
5142 if (isa<FunctionDecl>(
D)) {
5153 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes