50#include "llvm/ADT/STLExtras.h"
51#include "llvm/ADT/StringExtras.h"
52#include "llvm/ADT/StringSwitch.h"
53#include "llvm/Analysis/TargetLibraryInfo.h"
54#include "llvm/BinaryFormat/ELF.h"
55#include "llvm/IR/AttributeMask.h"
56#include "llvm/IR/CallingConv.h"
57#include "llvm/IR/DataLayout.h"
58#include "llvm/IR/Intrinsics.h"
59#include "llvm/IR/LLVMContext.h"
60#include "llvm/IR/Module.h"
61#include "llvm/IR/ProfileSummary.h"
62#include "llvm/ProfileData/InstrProfReader.h"
63#include "llvm/ProfileData/SampleProf.h"
64#include "llvm/Support/CRC.h"
65#include "llvm/Support/CodeGen.h"
66#include "llvm/Support/CommandLine.h"
67#include "llvm/Support/ConvertUTF.h"
68#include "llvm/Support/ErrorHandling.h"
69#include "llvm/Support/TimeProfiler.h"
70#include "llvm/Support/xxhash.h"
71#include "llvm/TargetParser/RISCVISAInfo.h"
72#include "llvm/TargetParser/Triple.h"
73#include "llvm/TargetParser/X86TargetParser.h"
74#include "llvm/Transforms/Utils/BuildLibCalls.h"
78using namespace CodeGen;
81 "limited-coverage-experimental", llvm::cl::Hidden,
82 llvm::cl::desc(
"Emit limited coverage mapping information (experimental)"));
88 case TargetCXXABI::AppleARM64:
89 case TargetCXXABI::Fuchsia:
90 case TargetCXXABI::GenericAArch64:
91 case TargetCXXABI::GenericARM:
92 case TargetCXXABI::iOS:
93 case TargetCXXABI::WatchOS:
94 case TargetCXXABI::GenericMIPS:
95 case TargetCXXABI::GenericItanium:
96 case TargetCXXABI::WebAssembly:
97 case TargetCXXABI::XL:
99 case TargetCXXABI::Microsoft:
103 llvm_unreachable(
"invalid C++ ABI kind");
106static std::unique_ptr<TargetCodeGenInfo>
112 switch (Triple.getArch()) {
116 case llvm::Triple::m68k:
118 case llvm::Triple::mips:
119 case llvm::Triple::mipsel:
120 if (Triple.getOS() == llvm::Triple::NaCl)
124 case llvm::Triple::mips64:
125 case llvm::Triple::mips64el:
128 case llvm::Triple::avr: {
132 unsigned NPR =
Target.getABI() ==
"avrtiny" ? 6 : 18;
133 unsigned NRR =
Target.getABI() ==
"avrtiny" ? 4 : 8;
137 case llvm::Triple::aarch64:
138 case llvm::Triple::aarch64_32:
139 case llvm::Triple::aarch64_be: {
141 if (
Target.getABI() ==
"darwinpcs")
142 Kind = AArch64ABIKind::DarwinPCS;
143 else if (Triple.isOSWindows())
145 else if (
Target.getABI() ==
"aapcs-soft")
146 Kind = AArch64ABIKind::AAPCSSoft;
147 else if (
Target.getABI() ==
"pauthtest")
148 Kind = AArch64ABIKind::PAuthTest;
153 case llvm::Triple::wasm32:
154 case llvm::Triple::wasm64: {
156 if (
Target.getABI() ==
"experimental-mv")
157 Kind = WebAssemblyABIKind::ExperimentalMV;
161 case llvm::Triple::arm:
162 case llvm::Triple::armeb:
163 case llvm::Triple::thumb:
164 case llvm::Triple::thumbeb: {
165 if (Triple.getOS() == llvm::Triple::Win32)
169 StringRef ABIStr =
Target.getABI();
170 if (ABIStr ==
"apcs-gnu")
171 Kind = ARMABIKind::APCS;
172 else if (ABIStr ==
"aapcs16")
173 Kind = ARMABIKind::AAPCS16_VFP;
174 else if (CodeGenOpts.
FloatABI ==
"hard" ||
175 (CodeGenOpts.
FloatABI !=
"soft" && Triple.isHardFloatABI()))
176 Kind = ARMABIKind::AAPCS_VFP;
181 case llvm::Triple::ppc: {
182 if (Triple.isOSAIX())
189 case llvm::Triple::ppcle: {
190 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
193 case llvm::Triple::ppc64:
194 if (Triple.isOSAIX())
197 if (Triple.isOSBinFormatELF()) {
199 if (
Target.getABI() ==
"elfv2")
200 Kind = PPC64_SVR4_ABIKind::ELFv2;
201 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
206 case llvm::Triple::ppc64le: {
207 assert(Triple.isOSBinFormatELF() &&
"PPC64 LE non-ELF not supported!");
209 if (
Target.getABI() ==
"elfv1")
210 Kind = PPC64_SVR4_ABIKind::ELFv1;
211 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
216 case llvm::Triple::nvptx:
217 case llvm::Triple::nvptx64:
220 case llvm::Triple::msp430:
223 case llvm::Triple::riscv32:
224 case llvm::Triple::riscv64: {
225 StringRef ABIStr =
Target.getABI();
226 unsigned XLen =
Target.getPointerWidth(LangAS::Default);
227 unsigned ABIFLen = 0;
228 if (ABIStr.ends_with(
"f"))
230 else if (ABIStr.ends_with(
"d"))
232 bool EABI = ABIStr.ends_with(
"e");
236 case llvm::Triple::systemz: {
237 bool SoftFloat = CodeGenOpts.
FloatABI ==
"soft";
238 bool HasVector = !SoftFloat &&
Target.getABI() ==
"vector";
242 case llvm::Triple::tce:
243 case llvm::Triple::tcele:
246 case llvm::Triple::x86: {
247 bool IsDarwinVectorABI = Triple.isOSDarwin();
248 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
250 if (Triple.getOS() == llvm::Triple::Win32) {
252 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
253 CodeGenOpts.NumRegisterParameters);
256 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
257 CodeGenOpts.NumRegisterParameters, CodeGenOpts.
FloatABI ==
"soft");
260 case llvm::Triple::x86_64: {
261 StringRef ABI =
Target.getABI();
262 X86AVXABILevel AVXLevel = (ABI ==
"avx512" ? X86AVXABILevel::AVX512
263 : ABI ==
"avx" ? X86AVXABILevel::AVX
264 : X86AVXABILevel::None);
266 switch (Triple.getOS()) {
267 case llvm::Triple::Win32:
273 case llvm::Triple::hexagon:
275 case llvm::Triple::lanai:
277 case llvm::Triple::r600:
279 case llvm::Triple::amdgcn:
281 case llvm::Triple::sparc:
283 case llvm::Triple::sparcv9:
285 case llvm::Triple::xcore:
287 case llvm::Triple::arc:
289 case llvm::Triple::spir:
290 case llvm::Triple::spir64:
292 case llvm::Triple::spirv32:
293 case llvm::Triple::spirv64:
294 case llvm::Triple::spirv:
296 case llvm::Triple::dxil:
298 case llvm::Triple::ve:
300 case llvm::Triple::csky: {
301 bool IsSoftFloat = !
Target.hasFeature(
"hard-float-abi");
303 Target.hasFeature(
"fpuv2_df") ||
Target.hasFeature(
"fpuv3_df");
308 case llvm::Triple::bpfeb:
309 case llvm::Triple::bpfel:
311 case llvm::Triple::loongarch32:
312 case llvm::Triple::loongarch64: {
313 StringRef ABIStr =
Target.getABI();
314 unsigned ABIFRLen = 0;
315 if (ABIStr.ends_with(
"f"))
317 else if (ABIStr.ends_with(
"d"))
320 CGM,
Target.getPointerWidth(LangAS::Default), ABIFRLen);
326 if (!TheTargetCodeGenInfo)
328 return *TheTargetCodeGenInfo;
338 : Context(
C), LangOpts(
C.getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
339 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
341 VMContext(M.getContext()), VTables(*this), StackHandler(diags),
346 llvm::LLVMContext &LLVMContext = M.getContext();
347 VoidTy = llvm::Type::getVoidTy(LLVMContext);
348 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
349 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
350 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
351 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
352 HalfTy = llvm::Type::getHalfTy(LLVMContext);
353 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
354 FloatTy = llvm::Type::getFloatTy(LLVMContext);
355 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
361 C.toCharUnitsFromBits(
C.getTargetInfo().getMaxPointerWidth()).getQuantity();
363 C.toCharUnitsFromBits(
C.getTargetInfo().getIntAlign()).getQuantity();
365 llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getCharWidth());
366 IntTy = llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getIntWidth());
367 IntPtrTy = llvm::IntegerType::get(LLVMContext,
368 C.getTargetInfo().getMaxPointerWidth());
369 Int8PtrTy = llvm::PointerType::get(LLVMContext,
371 const llvm::DataLayout &DL = M.getDataLayout();
373 llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
375 llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
392 createOpenCLRuntime();
394 createOpenMPRuntime();
401 if (LangOpts.
Sanitize.
hasOneOf(SanitizerKind::Thread | SanitizerKind::Type) ||
402 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
408 if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
413 Block.GlobalUniqueCount = 0;
415 if (
C.getLangOpts().ObjC)
419 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
426 PGOReader = std::move(ReaderOrErr.get());
431 if (CodeGenOpts.CoverageMapping)
435 if (CodeGenOpts.UniqueInternalLinkageNames &&
436 !
getModule().getSourceFileName().empty()) {
440 if (
Path.rfind(Entry.first, 0) != std::string::npos) {
441 Path = Entry.second +
Path.substr(Entry.first.size());
444 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(
Path);
449 getModule().addModuleFlag(llvm::Module::Error,
"NumRegisterParameters",
450 CodeGenOpts.NumRegisterParameters);
455void CodeGenModule::createObjCRuntime() {
472 llvm_unreachable(
"bad runtime kind");
475void CodeGenModule::createOpenCLRuntime() {
479void CodeGenModule::createOpenMPRuntime() {
483 case llvm::Triple::nvptx:
484 case llvm::Triple::nvptx64:
485 case llvm::Triple::amdgcn:
487 "OpenMP AMDGPU/NVPTX is only prepared to deal with device code.");
491 if (LangOpts.OpenMPSimd)
499void CodeGenModule::createCUDARuntime() {
503void CodeGenModule::createHLSLRuntime() {
508 Replacements[Name] =
C;
511void CodeGenModule::applyReplacements() {
512 for (
auto &I : Replacements) {
513 StringRef MangledName = I.first;
514 llvm::Constant *Replacement = I.second;
518 auto *OldF = cast<llvm::Function>(Entry);
519 auto *NewF = dyn_cast<llvm::Function>(Replacement);
521 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
522 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
524 auto *CE = cast<llvm::ConstantExpr>(Replacement);
525 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
526 CE->getOpcode() == llvm::Instruction::GetElementPtr);
527 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
532 OldF->replaceAllUsesWith(Replacement);
534 NewF->removeFromParent();
535 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
538 OldF->eraseFromParent();
543 GlobalValReplacements.push_back(std::make_pair(GV,
C));
546void CodeGenModule::applyGlobalValReplacements() {
547 for (
auto &I : GlobalValReplacements) {
548 llvm::GlobalValue *GV = I.first;
549 llvm::Constant *
C = I.second;
551 GV->replaceAllUsesWith(
C);
552 GV->eraseFromParent();
559 const llvm::Constant *
C;
560 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
561 C = GA->getAliasee();
562 else if (
auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
563 C = GI->getResolver();
567 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(
C->stripPointerCasts());
571 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
580 bool IsIFunc,
const llvm::GlobalValue *Alias,
const llvm::GlobalValue *&GV,
581 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
585 Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
589 if (GV->hasCommonLinkage()) {
591 if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
592 Diags.
Report(Location, diag::err_alias_to_common);
597 if (GV->isDeclaration()) {
598 Diags.
Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
599 Diags.
Report(Location, diag::note_alias_requires_mangled_name)
600 << IsIFunc << IsIFunc;
603 for (
const auto &[
Decl, Name] : MangledDeclNames) {
604 if (
const auto *ND = dyn_cast<NamedDecl>(
Decl.getDecl())) {
606 if (II && II->
getName() == GV->getName()) {
607 Diags.
Report(Location, diag::note_alias_mangled_name_alternative)
611 (Twine(IsIFunc ?
"ifunc" :
"alias") +
"(\"" + Name +
"\")")
621 const auto *F = dyn_cast<llvm::Function>(GV);
623 Diags.
Report(Location, diag::err_alias_to_undefined)
624 << IsIFunc << IsIFunc;
628 llvm::FunctionType *FTy = F->getFunctionType();
629 if (!FTy->getReturnType()->isPointerTy()) {
630 Diags.
Report(Location, diag::err_ifunc_resolver_return);
644 if (GVar->hasAttribute(
"toc-data")) {
645 auto GVId = GVar->getName();
648 Diags.
Report(Location, diag::warn_toc_unsupported_type)
649 << GVId <<
"the variable has an alias";
651 llvm::AttributeSet CurrAttributes = GVar->getAttributes();
652 llvm::AttributeSet NewAttributes =
653 CurrAttributes.removeAttribute(GVar->getContext(),
"toc-data");
654 GVar->setAttributes(NewAttributes);
658void CodeGenModule::checkAliases() {
665 const auto *
D = cast<ValueDecl>(GD.getDecl());
668 bool IsIFunc =
D->
hasAttr<IFuncAttr>();
670 Location = A->getLocation();
671 Range = A->getRange();
673 llvm_unreachable(
"Not an alias or ifunc?");
677 const llvm::GlobalValue *GV =
nullptr;
679 MangledDeclNames,
Range)) {
685 if (
const llvm::GlobalVariable *GVar =
686 dyn_cast<const llvm::GlobalVariable>(GV))
690 llvm::Constant *Aliasee =
691 IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver()
692 : cast<llvm::GlobalAlias>(Alias)->getAliasee();
694 llvm::GlobalValue *AliaseeGV;
695 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
696 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
698 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
700 if (
const SectionAttr *SA =
D->
getAttr<SectionAttr>()) {
701 StringRef AliasSection = SA->getName();
702 if (AliasSection != AliaseeGV->getSection())
703 Diags.
Report(SA->getLocation(), diag::warn_alias_with_section)
704 << AliasSection << IsIFunc << IsIFunc;
712 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
713 if (GA->isInterposable()) {
714 Diags.
Report(Location, diag::warn_alias_to_weak_alias)
715 << GV->getName() << GA->getName() << IsIFunc;
716 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
717 GA->getAliasee(), Alias->getType());
720 cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee);
722 cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee);
728 cast<llvm::Function>(Aliasee)->addFnAttr(
729 llvm::Attribute::DisableSanitizerInstrumentation);
737 Alias->replaceAllUsesWith(llvm::PoisonValue::get(Alias->getType()));
738 Alias->eraseFromParent();
743 DeferredDeclsToEmit.clear();
744 EmittedDeferredDecls.clear();
745 DeferredAnnotations.clear();
747 OpenMPRuntime->clear();
751 StringRef MainFile) {
754 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
755 if (MainFile.empty())
756 MainFile =
"<stdin>";
757 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
760 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
763 Diags.
Report(diag::warn_profile_data_missing) << Visited << Missing;
767static std::optional<llvm::GlobalValue::VisibilityTypes>
774 return llvm::GlobalValue::DefaultVisibility;
776 return llvm::GlobalValue::HiddenVisibility;
778 return llvm::GlobalValue::ProtectedVisibility;
780 llvm_unreachable(
"unknown option value!");
785 std::optional<llvm::GlobalValue::VisibilityTypes>
V) {
794 GV.setDSOLocal(
false);
795 GV.setVisibility(*
V);
800 if (!LO.VisibilityFromDLLStorageClass)
803 std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
806 std::optional<llvm::GlobalValue::VisibilityTypes>
807 NoDLLStorageClassVisibility =
810 std::optional<llvm::GlobalValue::VisibilityTypes>
811 ExternDeclDLLImportVisibility =
814 std::optional<llvm::GlobalValue::VisibilityTypes>
815 ExternDeclNoDLLStorageClassVisibility =
818 for (llvm::GlobalValue &GV : M.global_values()) {
819 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
822 if (GV.isDeclarationForLinker())
824 llvm::GlobalValue::DLLImportStorageClass
825 ? ExternDeclDLLImportVisibility
826 : ExternDeclNoDLLStorageClassVisibility);
829 llvm::GlobalValue::DLLExportStorageClass
830 ? DLLExportVisibility
831 : NoDLLStorageClassVisibility);
833 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
838 const llvm::Triple &Triple,
840 if (Triple.isAMDGPU() || Triple.isNVPTX())
842 return LangOpts.getStackProtector() == Mode;
848 EmitModuleInitializers(Primary);
850 DeferredDecls.insert(EmittedDeferredDecls.begin(),
851 EmittedDeferredDecls.end());
852 EmittedDeferredDecls.clear();
853 EmitVTablesOpportunistically();
854 applyGlobalValReplacements();
856 emitMultiVersionFunctions();
859 GlobalTopLevelStmtBlockInFlight.first) {
861 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->
getEndLoc());
862 GlobalTopLevelStmtBlockInFlight = {
nullptr,
nullptr};
868 EmitCXXModuleInitFunc(Primary);
870 EmitCXXGlobalInitFunc();
871 EmitCXXGlobalCleanUpFunc();
872 registerGlobalDtorsWithAtExit();
873 EmitCXXThreadLocalInitFunc();
875 if (llvm::Function *ObjCInitFunction =
ObjCRuntime->ModuleInitFunction())
878 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
882 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
883 OpenMPRuntime->clear();
887 PGOReader->getSummary(
false).getMD(VMContext),
888 llvm::ProfileSummary::PSK_Instr);
895 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
896 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
898 EmitStaticExternCAliases();
904 CoverageMapping->emit();
905 if (CodeGenOpts.SanitizeCfiCrossDso) {
911 emitAtAvailableLinkGuard();
919 if (
getTarget().getTargetOpts().CodeObjectVersion !=
920 llvm::CodeObjectVersionKind::COV_None) {
921 getModule().addModuleFlag(llvm::Module::Error,
922 "amdhsa_code_object_version",
923 getTarget().getTargetOpts().CodeObjectVersion);
928 auto *MDStr = llvm::MDString::get(
933 getModule().addModuleFlag(llvm::Module::Error,
"amdgpu_printf_kind",
946 if (
auto *FD = dyn_cast<FunctionDecl>(
D))
950 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
954 llvm::ArrayType *ATy = llvm::ArrayType::get(
Int8PtrTy, UsedArray.size());
956 auto *GV =
new llvm::GlobalVariable(
957 getModule(), ATy,
false, llvm::GlobalValue::InternalLinkage,
958 llvm::ConstantArray::get(ATy, UsedArray),
"__clang_gpu_used_external");
961 if (LangOpts.HIP && !
getLangOpts().OffloadingNewDriver) {
964 auto *GV =
new llvm::GlobalVariable(
966 llvm::Constant::getNullValue(
Int8Ty),
974 if (CodeGenOpts.Autolink &&
975 (Context.
getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
976 EmitModuleLinkOptions();
991 if (!ELFDependentLibraries.empty() && !Context.
getLangOpts().CUDAIsDevice) {
992 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.dependent-libraries");
993 for (
auto *MD : ELFDependentLibraries)
997 if (CodeGenOpts.DwarfVersion) {
998 getModule().addModuleFlag(llvm::Module::Max,
"Dwarf Version",
999 CodeGenOpts.DwarfVersion);
1002 if (CodeGenOpts.Dwarf64)
1003 getModule().addModuleFlag(llvm::Module::Max,
"DWARF64", 1);
1007 getModule().setSemanticInterposition(
true);
1009 if (CodeGenOpts.EmitCodeView) {
1011 getModule().addModuleFlag(llvm::Module::Warning,
"CodeView", 1);
1013 if (CodeGenOpts.CodeViewGHash) {
1014 getModule().addModuleFlag(llvm::Module::Warning,
"CodeViewGHash", 1);
1016 if (CodeGenOpts.ControlFlowGuard) {
1018 getModule().addModuleFlag(llvm::Module::Warning,
"cfguard", 2);
1019 }
else if (CodeGenOpts.ControlFlowGuardNoChecks) {
1021 getModule().addModuleFlag(llvm::Module::Warning,
"cfguard", 1);
1023 if (CodeGenOpts.EHContGuard) {
1025 getModule().addModuleFlag(llvm::Module::Warning,
"ehcontguard", 1);
1029 getModule().addModuleFlag(llvm::Module::Warning,
"ms-kernel", 1);
1031 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
1036 getModule().addModuleFlag(llvm::Module::Error,
"StrictVTablePointers",1);
1038 llvm::Metadata *Ops[2] = {
1039 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
1040 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1041 llvm::Type::getInt32Ty(VMContext), 1))};
1043 getModule().addModuleFlag(llvm::Module::Require,
1044 "StrictVTablePointersRequirement",
1045 llvm::MDNode::get(VMContext, Ops));
1051 getModule().addModuleFlag(llvm::Module::Warning,
"Debug Info Version",
1052 llvm::DEBUG_METADATA_VERSION);
1057 uint64_t WCharWidth =
1059 getModule().addModuleFlag(llvm::Module::Error,
"wchar_size", WCharWidth);
1062 getModule().addModuleFlag(llvm::Module::Warning,
1063 "zos_product_major_version",
1064 uint32_t(CLANG_VERSION_MAJOR));
1065 getModule().addModuleFlag(llvm::Module::Warning,
1066 "zos_product_minor_version",
1067 uint32_t(CLANG_VERSION_MINOR));
1068 getModule().addModuleFlag(llvm::Module::Warning,
"zos_product_patchlevel",
1069 uint32_t(CLANG_VERSION_PATCHLEVEL));
1071 getModule().addModuleFlag(llvm::Module::Error,
"zos_product_id",
1072 llvm::MDString::get(VMContext, ProductId));
1077 getModule().addModuleFlag(llvm::Module::Error,
"zos_cu_language",
1078 llvm::MDString::get(VMContext, lang_str));
1082 : std::time(
nullptr);
1083 getModule().addModuleFlag(llvm::Module::Max,
"zos_translation_time",
1084 static_cast<uint64_t
>(TT));
1087 getModule().addModuleFlag(llvm::Module::Error,
"zos_le_char_mode",
1088 llvm::MDString::get(VMContext,
"ascii"));
1092 if (
T.isARM() ||
T.isThumb()) {
1094 uint64_t EnumWidth = Context.
getLangOpts().ShortEnums ? 1 : 4;
1095 getModule().addModuleFlag(llvm::Module::Error,
"min_enum_size", EnumWidth);
1099 StringRef ABIStr =
Target.getABI();
1100 llvm::LLVMContext &Ctx = TheModule.getContext();
1101 getModule().addModuleFlag(llvm::Module::Error,
"target-abi",
1102 llvm::MDString::get(Ctx, ABIStr));
1107 const std::vector<std::string> &Features =
1110 llvm::RISCVISAInfo::parseFeatures(
T.isRISCV64() ? 64 : 32, Features);
1111 if (!errorToBool(ParseResult.takeError()))
1113 llvm::Module::AppendUnique,
"riscv-isa",
1115 Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString())));
1118 if (CodeGenOpts.SanitizeCfiCrossDso) {
1120 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
1123 if (CodeGenOpts.WholeProgramVTables) {
1127 getModule().addModuleFlag(llvm::Module::Error,
"Virtual Function Elim",
1128 CodeGenOpts.VirtualFunctionElimination);
1131 if (LangOpts.
Sanitize.
has(SanitizerKind::CFIICall)) {
1132 getModule().addModuleFlag(llvm::Module::Override,
1133 "CFI Canonical Jump Tables",
1134 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1137 if (CodeGenOpts.SanitizeCfiICallNormalizeIntegers) {
1138 getModule().addModuleFlag(llvm::Module::Override,
"cfi-normalize-integers",
1143 getModule().addModuleFlag(llvm::Module::Override,
"kcfi", 1);
1146 if (CodeGenOpts.PatchableFunctionEntryOffset)
1147 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-offset",
1148 CodeGenOpts.PatchableFunctionEntryOffset);
1151 if (CodeGenOpts.CFProtectionReturn &&
1154 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-return",
1158 if (CodeGenOpts.CFProtectionBranch &&
1161 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-branch",
1164 auto Scheme = CodeGenOpts.getCFBranchLabelScheme();
1165 if (
Target.checkCFBranchLabelSchemeSupported(Scheme,
getDiags())) {
1167 Scheme =
Target.getDefaultCFBranchLabelScheme();
1169 llvm::Module::Error,
"cf-branch-label-scheme",
1175 if (CodeGenOpts.FunctionReturnThunks)
1176 getModule().addModuleFlag(llvm::Module::Override,
"function_return_thunk_extern", 1);
1178 if (CodeGenOpts.IndirectBranchCSPrefix)
1179 getModule().addModuleFlag(llvm::Module::Override,
"indirect_branch_cs_prefix", 1);
1191 LangOpts.getSignReturnAddressScope() !=
1193 getModule().addModuleFlag(llvm::Module::Override,
1194 "sign-return-address-buildattr", 1);
1195 if (LangOpts.
Sanitize.
has(SanitizerKind::MemtagStack))
1196 getModule().addModuleFlag(llvm::Module::Override,
1197 "tag-stack-memory-buildattr", 1);
1199 if (
T.isARM() ||
T.isThumb() ||
T.isAArch64()) {
1200 if (LangOpts.BranchTargetEnforcement)
1201 getModule().addModuleFlag(llvm::Module::Min,
"branch-target-enforcement",
1203 if (LangOpts.BranchProtectionPAuthLR)
1204 getModule().addModuleFlag(llvm::Module::Min,
"branch-protection-pauth-lr",
1206 if (LangOpts.GuardedControlStack)
1207 getModule().addModuleFlag(llvm::Module::Min,
"guarded-control-stack", 1);
1209 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address", 1);
1211 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address-all",
1214 getModule().addModuleFlag(llvm::Module::Min,
1215 "sign-return-address-with-bkey", 1);
1217 if (LangOpts.PointerAuthELFGOT)
1218 getModule().addModuleFlag(llvm::Module::Min,
"ptrauth-elf-got", 1);
1221 if (LangOpts.PointerAuthCalls)
1222 getModule().addModuleFlag(llvm::Module::Min,
"ptrauth-sign-personality",
1225 using namespace llvm::ELF;
1226 uint64_t PAuthABIVersion =
1227 (LangOpts.PointerAuthIntrinsics
1228 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS) |
1229 (LangOpts.PointerAuthCalls
1230 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS) |
1231 (LangOpts.PointerAuthReturns
1232 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS) |
1233 (LangOpts.PointerAuthAuthTraps
1234 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS) |
1235 (LangOpts.PointerAuthVTPtrAddressDiscrimination
1236 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR) |
1237 (LangOpts.PointerAuthVTPtrTypeDiscrimination
1238 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR) |
1239 (LangOpts.PointerAuthInitFini
1240 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI) |
1241 (LangOpts.PointerAuthInitFiniAddressDiscrimination
1242 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC) |
1243 (LangOpts.PointerAuthELFGOT
1244 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT) |
1245 (LangOpts.PointerAuthIndirectGotos
1246 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS) |
1247 (LangOpts.PointerAuthTypeInfoVTPtrDiscrimination
1248 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR) |
1249 (LangOpts.PointerAuthFunctionTypeDiscrimination
1250 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR);
1251 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR ==
1252 AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
1253 "Update when new enum items are defined");
1254 if (PAuthABIVersion != 0) {
1255 getModule().addModuleFlag(llvm::Module::Error,
1256 "aarch64-elf-pauthabi-platform",
1257 AARCH64_PAUTH_PLATFORM_LLVM_LINUX);
1258 getModule().addModuleFlag(llvm::Module::Error,
1259 "aarch64-elf-pauthabi-version",
1265 if (CodeGenOpts.StackClashProtector)
1267 llvm::Module::Override,
"probe-stack",
1268 llvm::MDString::get(TheModule.getContext(),
"inline-asm"));
1270 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
1271 getModule().addModuleFlag(llvm::Module::Min,
"stack-probe-size",
1272 CodeGenOpts.StackProbeSize);
1275 llvm::LLVMContext &Ctx = TheModule.getContext();
1277 llvm::Module::Error,
"MemProfProfileFilename",
1281 if (LangOpts.CUDAIsDevice &&
getTriple().isNVPTX()) {
1285 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
1287 llvm::DenormalMode::IEEE);
1290 if (LangOpts.EHAsynch)
1291 getModule().addModuleFlag(llvm::Module::Warning,
"eh-asynch", 1);
1295 getModule().addModuleFlag(llvm::Module::Max,
"openmp", LangOpts.OpenMP);
1297 getModule().addModuleFlag(llvm::Module::Max,
"openmp-device",
1301 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())) {
1302 EmitOpenCLMetadata();
1310 llvm::Metadata *SPIRVerElts[] = {
1311 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1313 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1314 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
1315 llvm::NamedMDNode *SPIRVerMD =
1316 TheModule.getOrInsertNamedMetadata(
"opencl.spir.version");
1317 llvm::LLVMContext &Ctx = TheModule.getContext();
1318 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
1326 if (uint32_t PLevel = Context.
getLangOpts().PICLevel) {
1327 assert(PLevel < 3 &&
"Invalid PIC Level");
1328 getModule().setPICLevel(
static_cast<llvm::PICLevel::Level
>(PLevel));
1330 getModule().setPIELevel(
static_cast<llvm::PIELevel::Level
>(PLevel));
1334 unsigned CM = llvm::StringSwitch<unsigned>(
getCodeGenOpts().CodeModel)
1335 .Case(
"tiny", llvm::CodeModel::Tiny)
1336 .Case(
"small", llvm::CodeModel::Small)
1337 .Case(
"kernel", llvm::CodeModel::Kernel)
1338 .Case(
"medium", llvm::CodeModel::Medium)
1339 .Case(
"large", llvm::CodeModel::Large)
1342 llvm::CodeModel::Model codeModel =
static_cast<llvm::CodeModel::Model
>(CM);
1345 if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
1347 llvm::Triple::x86_64) {
1353 if (CodeGenOpts.NoPLT)
1356 CodeGenOpts.DirectAccessExternalData !=
1357 getModule().getDirectAccessExternalData()) {
1358 getModule().setDirectAccessExternalData(
1359 CodeGenOpts.DirectAccessExternalData);
1361 if (CodeGenOpts.UnwindTables)
1362 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1364 switch (CodeGenOpts.getFramePointer()) {
1369 getModule().setFramePointer(llvm::FramePointerKind::Reserved);
1372 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1375 getModule().setFramePointer(llvm::FramePointerKind::All);
1379 SimplifyPersonality();
1392 EmitVersionIdentMetadata();
1395 EmitCommandLineMetadata();
1403 getModule().setStackProtectorGuardSymbol(
1406 getModule().setStackProtectorGuardOffset(
1411 getModule().addModuleFlag(llvm::Module::Override,
"SkipRaxSetup", 1);
1413 getModule().addModuleFlag(llvm::Module::Override,
"RegCallv4", 1);
1415 if (
getContext().getTargetInfo().getMaxTLSAlign())
1416 getModule().addModuleFlag(llvm::Module::Error,
"MaxTLSAlign",
1417 getContext().getTargetInfo().getMaxTLSAlign());
1435 if (
getTriple().isPPC() && !MustTailCallUndefinedGlobals.empty()) {
1436 for (
auto &I : MustTailCallUndefinedGlobals) {
1437 if (!I.first->isDefined())
1438 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1442 if (!Entry || Entry->isWeakForLinker() ||
1443 Entry->isDeclarationForLinker())
1444 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1450void CodeGenModule::EmitOpenCLMetadata() {
1456 auto EmitVersion = [
this](StringRef MDName,
int Version) {
1457 llvm::Metadata *OCLVerElts[] = {
1458 llvm::ConstantAsMetadata::get(
1459 llvm::ConstantInt::get(
Int32Ty, Version / 100)),
1460 llvm::ConstantAsMetadata::get(
1461 llvm::ConstantInt::get(
Int32Ty, (Version % 100) / 10))};
1462 llvm::NamedMDNode *OCLVerMD = TheModule.getOrInsertNamedMetadata(MDName);
1463 llvm::LLVMContext &Ctx = TheModule.getContext();
1464 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
1467 EmitVersion(
"opencl.ocl.version", CLVersion);
1468 if (LangOpts.OpenCLCPlusPlus) {
1470 EmitVersion(
"opencl.cxx.version", LangOpts.OpenCLCPlusPlusVersion);
1474void CodeGenModule::EmitBackendOptionsMetadata(
1477 getModule().addModuleFlag(llvm::Module::Min,
"SmallDataLimit",
1478 CodeGenOpts.SmallDataLimit);
1495 return TBAA->getTypeInfo(QTy);
1514 return TBAA->getAccessInfo(AccessType);
1521 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
1527 return TBAA->getTBAAStructInfo(QTy);
1533 return TBAA->getBaseTypeInfo(QTy);
1539 return TBAA->getAccessTagInfo(Info);
1546 return TBAA->mergeTBAAInfoForCast(SourceInfo,
TargetInfo);
1554 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
1562 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
1568 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
1573 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
1586 "cannot compile this %0 yet");
1587 std::string Msg =
Type;
1589 << Msg << S->getSourceRange();
1596 "cannot compile this %0 yet");
1597 std::string Msg =
Type;
1602 llvm::function_ref<
void()> Fn) {
1613 if (GV->hasLocalLinkage()) {
1614 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1628 Context.
getLangOpts().OpenMPIsTargetDevice && isa<VarDecl>(
D) &&
1629 D->
hasAttr<OMPDeclareTargetDeclAttr>() &&
1630 D->
getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
1631 OMPDeclareTargetDeclAttr::DT_NoHost &&
1633 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1637 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
1641 if (GV->hasDLLExportStorageClass()) {
1644 diag::err_hidden_visibility_dllexport);
1647 diag::err_non_default_visibility_dllimport);
1653 !GV->isDeclarationForLinker())
1658 llvm::GlobalValue *GV) {
1659 if (GV->hasLocalLinkage())
1662 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
1666 if (GV->hasDLLImportStorageClass())
1669 const llvm::Triple &TT = CGM.
getTriple();
1671 if (TT.isWindowsGNUEnvironment()) {
1680 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
1689 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
1697 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
1701 if (!TT.isOSBinFormatELF())
1707 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1713 if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias()))
1715 return !(CGM.
getLangOpts().SemanticInterposition ||
1720 if (!GV->isDeclarationForLinker())
1726 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
1733 if (CGOpts.DirectAccessExternalData) {
1739 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1740 if (!Var->isThreadLocal())
1749 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
1765 const auto *
D = dyn_cast<NamedDecl>(GD.
getDecl());
1767 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(
D)) {
1776 if (
D &&
D->isExternallyVisible()) {
1778 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1779 else if ((
D->
hasAttr<DLLExportAttr>() ||
1781 !GV->isDeclarationForLinker())
1782 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
1806 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
1807 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
1808 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
1809 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
1810 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
1813llvm::GlobalVariable::ThreadLocalMode
1815 switch (CodeGenOpts.getDefaultTLSModel()) {
1817 return llvm::GlobalVariable::GeneralDynamicTLSModel;
1819 return llvm::GlobalVariable::LocalDynamicTLSModel;
1821 return llvm::GlobalVariable::InitialExecTLSModel;
1823 return llvm::GlobalVariable::LocalExecTLSModel;
1825 llvm_unreachable(
"Invalid TLS model!");
1829 assert(
D.getTLSKind() &&
"setting TLS mode on non-TLS var!");
1831 llvm::GlobalValue::ThreadLocalMode TLM;
1835 if (
const TLSModelAttr *
Attr =
D.
getAttr<TLSModelAttr>()) {
1839 GV->setThreadLocalMode(TLM);
1845 return (Twine(
'.') + Twine(
Target.CPUSpecificManglingCharacter(Name))).str();
1849 const CPUSpecificAttr *
Attr,
1871 bool OmitMultiVersionMangling =
false) {
1873 llvm::raw_svector_ostream Out(Buffer);
1882 assert(II &&
"Attempt to mangle unnamed decl.");
1883 const auto *FD = dyn_cast<FunctionDecl>(ND);
1888 Out <<
"__regcall4__" << II->
getName();
1890 Out <<
"__regcall3__" << II->
getName();
1891 }
else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
1893 Out <<
"__device_stub__" << II->
getName();
1909 "Hash computed when not explicitly requested");
1913 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
1914 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
1915 switch (FD->getMultiVersionKind()) {
1919 FD->getAttr<CPUSpecificAttr>(),
1923 auto *
Attr = FD->getAttr<TargetAttr>();
1924 assert(
Attr &&
"Expected TargetAttr to be present "
1925 "for attribute mangling");
1931 auto *
Attr = FD->getAttr<TargetVersionAttr>();
1932 assert(
Attr &&
"Expected TargetVersionAttr to be present "
1933 "for attribute mangling");
1939 auto *
Attr = FD->getAttr<TargetClonesAttr>();
1940 assert(
Attr &&
"Expected TargetClonesAttr to be present "
1941 "for attribute mangling");
1948 llvm_unreachable(
"None multiversion type isn't valid here");
1958 return std::string(Out.str());
1961void CodeGenModule::UpdateMultiVersionNames(
GlobalDecl GD,
1963 StringRef &CurName) {
1970 std::string NonTargetName =
1978 "Other GD should now be a multiversioned function");
1988 if (OtherName != NonTargetName) {
1991 const auto ExistingRecord = Manglings.find(NonTargetName);
1992 if (ExistingRecord != std::end(Manglings))
1993 Manglings.remove(&(*ExistingRecord));
1994 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1999 CurName = OtherNameRef;
2001 Entry->setName(OtherName);
2011 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
2025 auto FoundName = MangledDeclNames.find(CanonicalGD);
2026 if (FoundName != MangledDeclNames.end())
2027 return FoundName->second;
2031 const auto *ND = cast<NamedDecl>(GD.
getDecl());
2043 assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
2063 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
2064 return MangledDeclNames[CanonicalGD] =
Result.first->first();
2073 llvm::raw_svector_ostream Out(Buffer);
2076 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.
getDecl()), Out);
2077 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(
D))
2079 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(
D))
2084 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
2085 return Result.first->first();
2089 auto it = MangledDeclNames.begin();
2090 while (it != MangledDeclNames.end()) {
2091 if (it->second == Name)
2106 llvm::Constant *AssociatedData) {
2114 bool IsDtorAttrFunc) {
2115 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2117 DtorsUsingAtExit[
Priority].push_back(Dtor);
2125void CodeGenModule::EmitCtorList(CtorList &Fns,
const char *GlobalName) {
2126 if (Fns.empty())
return;
2132 llvm::PointerType *PtrTy = llvm::PointerType::get(
2133 getLLVMContext(), TheModule.getDataLayout().getProgramAddressSpace());
2136 llvm::StructType *CtorStructTy = llvm::StructType::get(
Int32Ty, PtrTy, PtrTy);
2140 auto Ctors = Builder.beginArray(CtorStructTy);
2141 for (
const auto &I : Fns) {
2142 auto Ctor = Ctors.beginStruct(CtorStructTy);
2143 Ctor.addInt(
Int32Ty, I.Priority);
2144 if (InitFiniAuthSchema) {
2145 llvm::Constant *StorageAddress =
2147 ? llvm::ConstantExpr::getIntToPtr(
2148 llvm::ConstantInt::get(
2150 llvm::ConstantPtrAuth::AddrDiscriminator_CtorsDtors),
2154 I.Initializer, InitFiniAuthSchema.
getKey(), StorageAddress,
2155 llvm::ConstantInt::get(
2157 Ctor.add(SignedCtorPtr);
2159 Ctor.add(I.Initializer);
2161 if (I.AssociatedData)
2162 Ctor.add(I.AssociatedData);
2164 Ctor.addNullPointer(PtrTy);
2165 Ctor.finishAndAddTo(Ctors);
2168 auto List = Ctors.finishAndCreateGlobal(GlobalName,
getPointerAlign(),
2170 llvm::GlobalValue::AppendingLinkage);
2174 List->setAlignment(std::nullopt);
2179llvm::GlobalValue::LinkageTypes
2181 const auto *
D = cast<FunctionDecl>(GD.
getDecl());
2185 if (
const auto *Dtor = dyn_cast<CXXDestructorDecl>(
D))
2192 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2193 if (!MDS)
return nullptr;
2195 return llvm::ConstantInt::get(
Int64Ty, llvm::MD5Hash(MDS->getString()));
2201 FnType->getReturnType(), FnType->getParamTypes(),
2202 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
2204 std::string OutName;
2205 llvm::raw_string_ostream Out(OutName);
2210 Out <<
".normalized";
2212 return llvm::ConstantInt::get(
Int32Ty,
2213 static_cast<uint32_t
>(llvm::xxHash64(OutName)));
2218 llvm::Function *F,
bool IsThunk) {
2220 llvm::AttributeList PAL;
2223 if (
CallingConv == llvm::CallingConv::X86_VectorCall &&
2229 Error(
Loc,
"__vectorcall calling convention is not currently supported");
2231 F->setAttributes(PAL);
2232 F->setCallingConv(
static_cast<llvm::CallingConv::ID
>(
CallingConv));
2236 std::string ReadOnlyQual(
"__read_only");
2237 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2238 if (ReadOnlyPos != std::string::npos)
2240 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2242 std::string WriteOnlyQual(
"__write_only");
2243 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2244 if (WriteOnlyPos != std::string::npos)
2245 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2247 std::string ReadWriteQual(
"__read_write");
2248 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2249 if (ReadWritePos != std::string::npos)
2250 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2283 assert(((FD && CGF) || (!FD && !CGF)) &&
2284 "Incorrect use - FD and CGF should either be both null or not!");
2310 for (
unsigned i = 0, e = FD->
getNumParams(); i != e; ++i) {
2313 argNames.push_back(llvm::MDString::get(VMContext, parm->
getName()));
2318 std::string typeQuals;
2322 const Decl *PDecl = parm;
2324 PDecl = TD->getDecl();
2325 const OpenCLAccessAttr *A = PDecl->
getAttr<OpenCLAccessAttr>();
2326 if (A && A->isWriteOnly())
2327 accessQuals.push_back(llvm::MDString::get(VMContext,
"write_only"));
2328 else if (A && A->isReadWrite())
2329 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_write"));
2331 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_only"));
2333 accessQuals.push_back(llvm::MDString::get(VMContext,
"none"));
2335 auto getTypeSpelling = [&](
QualType Ty) {
2336 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2338 if (Ty.isCanonical()) {
2339 StringRef typeNameRef = typeName;
2341 if (typeNameRef.consume_front(
"unsigned "))
2342 return std::string(
"u") + typeNameRef.str();
2343 if (typeNameRef.consume_front(
"signed "))
2344 return typeNameRef.str();
2354 addressQuals.push_back(
2355 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(
2359 std::string typeName = getTypeSpelling(pointeeTy) +
"*";
2360 std::string baseTypeName =
2362 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2363 argBaseTypeNames.push_back(
2364 llvm::MDString::get(VMContext, baseTypeName));
2368 typeQuals =
"restrict";
2371 typeQuals += typeQuals.empty() ?
"const" :
" const";
2373 typeQuals += typeQuals.empty() ?
"volatile" :
" volatile";
2375 uint32_t AddrSpc = 0;
2380 addressQuals.push_back(
2381 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(AddrSpc)));
2385 std::string typeName = getTypeSpelling(ty);
2397 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2398 argBaseTypeNames.push_back(
2399 llvm::MDString::get(VMContext, baseTypeName));
2404 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
2408 Fn->setMetadata(
"kernel_arg_addr_space",
2409 llvm::MDNode::get(VMContext, addressQuals));
2410 Fn->setMetadata(
"kernel_arg_access_qual",
2411 llvm::MDNode::get(VMContext, accessQuals));
2412 Fn->setMetadata(
"kernel_arg_type",
2413 llvm::MDNode::get(VMContext, argTypeNames));
2414 Fn->setMetadata(
"kernel_arg_base_type",
2415 llvm::MDNode::get(VMContext, argBaseTypeNames));
2416 Fn->setMetadata(
"kernel_arg_type_qual",
2417 llvm::MDNode::get(VMContext, argTypeQuals));
2421 Fn->setMetadata(
"kernel_arg_name",
2422 llvm::MDNode::get(VMContext, argNames));
2432 if (!LangOpts.Exceptions)
return false;
2435 if (LangOpts.CXXExceptions)
return true;
2438 if (LangOpts.ObjCExceptions) {
2455 !isa<CXXConstructorDecl, CXXDestructorDecl>(MD);
2460 llvm::SetVector<const CXXRecordDecl *> MostBases;
2462 std::function<void (
const CXXRecordDecl *)> CollectMostBases;
2465 MostBases.insert(RD);
2467 CollectMostBases(B.getType()->getAsCXXRecordDecl());
2469 CollectMostBases(RD);
2470 return MostBases.takeVector();
2474 llvm::Function *F) {
2475 llvm::AttrBuilder B(F->getContext());
2477 if ((!
D || !
D->
hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2478 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2480 if (CodeGenOpts.StackClashProtector)
2481 B.addAttribute(
"probe-stack",
"inline-asm");
2483 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
2484 B.addAttribute(
"stack-probe-size",
2485 std::to_string(CodeGenOpts.StackProbeSize));
2488 B.addAttribute(llvm::Attribute::NoUnwind);
2490 if (
D &&
D->
hasAttr<NoStackProtectorAttr>())
2492 else if (
D &&
D->
hasAttr<StrictGuardStackCheckAttr>() &&
2494 B.addAttribute(llvm::Attribute::StackProtectStrong);
2496 B.addAttribute(llvm::Attribute::StackProtect);
2498 B.addAttribute(llvm::Attribute::StackProtectStrong);
2500 B.addAttribute(llvm::Attribute::StackProtectReq);
2504 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline))
2505 B.addAttribute(llvm::Attribute::AlwaysInline);
2509 else if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2511 B.addAttribute(llvm::Attribute::NoInline);
2519 if (
D->
hasAttr<ArmLocallyStreamingAttr>())
2520 B.addAttribute(
"aarch64_pstate_sm_body");
2523 if (
Attr->isNewZA())
2524 B.addAttribute(
"aarch64_new_za");
2525 if (
Attr->isNewZT0())
2526 B.addAttribute(
"aarch64_new_zt0");
2531 bool ShouldAddOptNone =
2532 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
2534 ShouldAddOptNone &= !
D->
hasAttr<MinSizeAttr>();
2535 ShouldAddOptNone &= !
D->
hasAttr<AlwaysInlineAttr>();
2538 if (
getLangOpts().HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline) &&
2540 B.addAttribute(llvm::Attribute::AlwaysInline);
2541 }
else if ((ShouldAddOptNone ||
D->
hasAttr<OptimizeNoneAttr>()) &&
2542 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2544 B.addAttribute(llvm::Attribute::OptimizeNone);
2547 B.addAttribute(llvm::Attribute::NoInline);
2552 B.addAttribute(llvm::Attribute::Naked);
2555 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
2556 F->removeFnAttr(llvm::Attribute::MinSize);
2557 }
else if (
D->
hasAttr<NakedAttr>()) {
2559 B.addAttribute(llvm::Attribute::Naked);
2560 B.addAttribute(llvm::Attribute::NoInline);
2561 }
else if (
D->
hasAttr<NoDuplicateAttr>()) {
2562 B.addAttribute(llvm::Attribute::NoDuplicate);
2563 }
else if (
D->
hasAttr<NoInlineAttr>() &&
2564 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2566 B.addAttribute(llvm::Attribute::NoInline);
2567 }
else if (
D->
hasAttr<AlwaysInlineAttr>() &&
2568 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
2570 B.addAttribute(llvm::Attribute::AlwaysInline);
2574 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
2575 B.addAttribute(llvm::Attribute::NoInline);
2579 if (
auto *FD = dyn_cast<FunctionDecl>(
D)) {
2582 auto CheckRedeclForInline = [](
const FunctionDecl *Redecl) {
2583 return Redecl->isInlineSpecified();
2585 if (any_of(FD->
redecls(), CheckRedeclForInline))
2590 return any_of(Pattern->
redecls(), CheckRedeclForInline);
2592 if (CheckForInline(FD)) {
2593 B.addAttribute(llvm::Attribute::InlineHint);
2594 }
else if (CodeGenOpts.getInlining() ==
2597 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2598 B.addAttribute(llvm::Attribute::NoInline);
2605 if (!
D->
hasAttr<OptimizeNoneAttr>()) {
2607 if (!ShouldAddOptNone)
2608 B.addAttribute(llvm::Attribute::OptimizeForSize);
2609 B.addAttribute(llvm::Attribute::Cold);
2612 B.addAttribute(llvm::Attribute::Hot);
2614 B.addAttribute(llvm::Attribute::MinSize);
2621 F->setAlignment(llvm::Align(alignment));
2624 if (LangOpts.FunctionAlignment)
2625 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
2632 if (isa<CXXMethodDecl>(
D) && F->getPointerAlignment(
getDataLayout()) < 2)
2633 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
2638 if (CodeGenOpts.SanitizeCfiCrossDso &&
2639 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2640 if (
auto *FD = dyn_cast<FunctionDecl>(
D)) {
2651 auto *MD = dyn_cast<CXXMethodDecl>(
D);
2654 llvm::Metadata *
Id =
2657 F->addTypeMetadata(0,
Id);
2664 if (isa_and_nonnull<NamedDecl>(
D))
2667 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2672 if (
const auto *VD = dyn_cast_if_present<VarDecl>(
D);
2674 ((CodeGenOpts.KeepPersistentStorageVariables &&
2675 (VD->getStorageDuration() ==
SD_Static ||
2676 VD->getStorageDuration() ==
SD_Thread)) ||
2677 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
2678 VD->getType().isConstQualified())))
2682bool CodeGenModule::GetCPUAndFeaturesAttributes(
GlobalDecl GD,
2683 llvm::AttrBuilder &Attrs,
2684 bool SetTargetFeatures) {
2690 std::vector<std::string> Features;
2691 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.
getDecl());
2693 const auto *TD = FD ? FD->
getAttr<TargetAttr>() :
nullptr;
2694 const auto *TV = FD ? FD->
getAttr<TargetVersionAttr>() :
nullptr;
2695 assert((!TD || !TV) &&
"both target_version and target specified");
2696 const auto *SD = FD ? FD->
getAttr<CPUSpecificAttr>() :
nullptr;
2697 const auto *TC = FD ? FD->
getAttr<TargetClonesAttr>() :
nullptr;
2698 bool AddedAttr =
false;
2699 if (TD || TV || SD || TC) {
2700 llvm::StringMap<bool> FeatureMap;
2704 for (
const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
2705 Features.push_back((Entry.getValue() ?
"+" :
"-") + Entry.getKey().str());
2713 Target.parseTargetAttr(TD->getFeaturesStr());
2735 if (!TargetCPU.empty()) {
2736 Attrs.addAttribute(
"target-cpu", TargetCPU);
2739 if (!TuneCPU.empty()) {
2740 Attrs.addAttribute(
"tune-cpu", TuneCPU);
2743 if (!Features.empty() && SetTargetFeatures) {
2744 llvm::erase_if(Features, [&](
const std::string& F) {
2747 llvm::sort(Features);
2748 Attrs.addAttribute(
"target-features", llvm::join(Features,
","));
2754 TV->getFeatures(Feats);
2757 if (!Feats.empty()) {
2759 std::string FMVFeatures;
2760 for (StringRef F : Feats)
2761 FMVFeatures.append(
",+" + F.str());
2762 Attrs.addAttribute(
"fmv-features", FMVFeatures.substr(1));
2769void CodeGenModule::setNonAliasAttributes(
GlobalDecl GD,
2770 llvm::GlobalObject *GO) {
2775 if (
auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
2778 if (
auto *SA =
D->
getAttr<PragmaClangBSSSectionAttr>())
2779 GV->addAttribute(
"bss-section", SA->getName());
2780 if (
auto *SA =
D->
getAttr<PragmaClangDataSectionAttr>())
2781 GV->addAttribute(
"data-section", SA->getName());
2782 if (
auto *SA =
D->
getAttr<PragmaClangRodataSectionAttr>())
2783 GV->addAttribute(
"rodata-section", SA->getName());
2784 if (
auto *SA =
D->
getAttr<PragmaClangRelroSectionAttr>())
2785 GV->addAttribute(
"relro-section", SA->getName());
2788 if (
auto *F = dyn_cast<llvm::Function>(GO)) {
2791 if (
auto *SA =
D->
getAttr<PragmaClangTextSectionAttr>())
2793 F->setSection(SA->getName());
2795 llvm::AttrBuilder Attrs(F->getContext());
2796 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
2800 llvm::AttributeMask RemoveAttrs;
2801 RemoveAttrs.addAttribute(
"target-cpu");
2802 RemoveAttrs.addAttribute(
"target-features");
2803 RemoveAttrs.addAttribute(
"tune-cpu");
2804 F->removeFnAttrs(RemoveAttrs);
2805 F->addFnAttrs(Attrs);
2809 if (
const auto *CSA =
D->
getAttr<CodeSegAttr>())
2810 GO->setSection(CSA->getName());
2811 else if (
const auto *SA =
D->
getAttr<SectionAttr>())
2812 GO->setSection(SA->getName());
2825 F->setLinkage(llvm::Function::InternalLinkage);
2827 setNonAliasAttributes(GD, F);
2838 GV->
setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2842 llvm::Function *F) {
2844 if (!LangOpts.
Sanitize.
has(SanitizerKind::CFIICall))
2849 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2853 F->addTypeMetadata(0, MD);
2857 if (CodeGenOpts.SanitizeCfiCrossDso)
2859 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
2863 llvm::LLVMContext &Ctx = F->getContext();
2864 llvm::MDBuilder MDB(Ctx);
2865 F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
2874 return llvm::all_of(Name, [](
const char &
C) {
2875 return llvm::isAlnum(
C) ||
C ==
'_' ||
C ==
'.';
2881 for (
auto &F : M.functions()) {
2883 bool AddressTaken = F.hasAddressTaken();
2884 if (!AddressTaken && F.hasLocalLinkage())
2885 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
2890 if (!AddressTaken || !F.isDeclaration())
2893 const llvm::ConstantInt *
Type;
2894 if (
const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
2895 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
2899 StringRef Name = F.getName();
2903 std::string
Asm = (
".weak __kcfi_typeid_" + Name +
"\n.set __kcfi_typeid_" +
2904 Name +
", " + Twine(
Type->getZExtValue()) +
"\n")
2906 M.appendModuleInlineAsm(
Asm);
2910void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
2911 bool IsIncompleteFunction,
2914 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
2917 F->setAttributes(llvm::Intrinsic::getAttributes(
getLLVMContext(), IID));
2921 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
2923 if (!IsIncompleteFunction)
2930 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
2932 assert(!F->arg_empty() &&
2933 F->arg_begin()->getType()
2934 ->canLosslesslyBitCastTo(F->getReturnType()) &&
2935 "unexpected this return");
2936 F->addParamAttr(0, llvm::Attribute::Returned);
2946 if (!IsIncompleteFunction && F->isDeclaration())
2949 if (
const auto *CSA = FD->
getAttr<CodeSegAttr>())
2950 F->setSection(CSA->getName());
2951 else if (
const auto *SA = FD->
getAttr<SectionAttr>())
2952 F->setSection(SA->getName());
2954 if (
const auto *EA = FD->
getAttr<ErrorAttr>()) {
2956 F->addFnAttr(
"dontcall-error", EA->getUserDiagnostic());
2957 else if (EA->isWarning())
2958 F->addFnAttr(
"dontcall-warn", EA->getUserDiagnostic());
2964 bool HasBody = FD->
hasBody(FDBody);
2966 assert(HasBody &&
"Inline builtin declarations should always have an "
2968 if (shouldEmitFunction(FDBody))
2969 F->addFnAttr(llvm::Attribute::NoBuiltin);
2975 F->addFnAttr(llvm::Attribute::NoBuiltin);
2978 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
2979 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2980 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
2981 if (MD->isVirtual())
2982 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2988 if (!CodeGenOpts.SanitizeCfiCrossDso ||
2989 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
2998 if (CodeGenOpts.InlineMaxStackSize !=
UINT_MAX)
2999 F->addFnAttr(
"inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
3001 if (
const auto *CB = FD->
getAttr<CallbackAttr>()) {
3005 llvm::LLVMContext &Ctx = F->getContext();
3006 llvm::MDBuilder MDB(Ctx);
3010 int CalleeIdx = *CB->encoding_begin();
3011 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
3012 F->addMetadata(llvm::LLVMContext::MD_callback,
3013 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
3014 CalleeIdx, PayloadIndices,
3020 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
3021 "Only globals with definition can force usage.");
3022 LLVMUsed.emplace_back(GV);
3026 assert(!GV->isDeclaration() &&
3027 "Only globals with definition can force usage.");
3028 LLVMCompilerUsed.emplace_back(GV);
3032 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
3033 "Only globals with definition can force usage.");
3035 LLVMCompilerUsed.emplace_back(GV);
3037 LLVMUsed.emplace_back(GV);
3041 std::vector<llvm::WeakTrackingVH> &List) {
3048 UsedArray.resize(List.size());
3049 for (
unsigned i = 0, e = List.size(); i != e; ++i) {
3051 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3052 cast<llvm::Constant>(&*List[i]), CGM.
Int8PtrTy);
3055 if (UsedArray.empty())
3057 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
3059 auto *GV =
new llvm::GlobalVariable(
3060 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
3061 llvm::ConstantArray::get(ATy, UsedArray), Name);
3063 GV->setSection(
"llvm.metadata");
3066void CodeGenModule::emitLLVMUsed() {
3067 emitUsed(*
this,
"llvm.used", LLVMUsed);
3068 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
3073 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3082 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3088 ELFDependentLibraries.push_back(
3089 llvm::MDNode::get(
C, llvm::MDString::get(
C, Lib)));
3096 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
C, MDOpts));
3111 if (
Visited.insert(Import).second)
3128 if (LL.IsFramework) {
3129 llvm::Metadata *Args[2] = {llvm::MDString::get(Context,
"-framework"),
3130 llvm::MDString::get(Context, LL.Library)};
3132 Metadata.push_back(llvm::MDNode::get(Context, Args));
3138 llvm::Metadata *Args[2] = {
3139 llvm::MDString::get(Context,
"lib"),
3140 llvm::MDString::get(Context, LL.Library),
3142 Metadata.push_back(llvm::MDNode::get(Context, Args));
3146 auto *OptString = llvm::MDString::get(Context, Opt);
3147 Metadata.push_back(llvm::MDNode::get(Context, OptString));
3152void CodeGenModule::EmitModuleInitializers(
clang::Module *Primary) {
3154 "We should only emit module initializers for named modules.");
3160 if (isa<ImportDecl>(
D))
3162 assert(isa<VarDecl>(
D) &&
"GMF initializer decl is not a var?");
3169 if (isa<ImportDecl>(
D))
3177 if (isa<ImportDecl>(
D))
3179 assert(isa<VarDecl>(
D) &&
"PMF initializer decl is not a var?");
3185void CodeGenModule::EmitModuleLinkOptions() {
3189 llvm::SetVector<clang::Module *> LinkModules;
3194 for (
Module *M : ImportedModules) {
3197 if (M->getTopLevelModuleName() ==
getLangOpts().CurrentModule &&
3206 while (!Stack.empty()) {
3209 bool AnyChildren =
false;
3219 Stack.push_back(
SM);
3227 LinkModules.insert(Mod);
3236 for (
Module *M : LinkModules)
3239 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
3240 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
3243 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.linker.options");
3244 for (
auto *MD : LinkerOptionsMetadata)
3245 NMD->addOperand(MD);
3248void CodeGenModule::EmitDeferred() {
3257 if (!DeferredVTables.empty()) {
3258 EmitDeferredVTables();
3263 assert(DeferredVTables.empty());
3270 llvm::append_range(DeferredDeclsToEmit,
3274 if (DeferredDeclsToEmit.empty())
3279 std::vector<GlobalDecl> CurDeclsToEmit;
3280 CurDeclsToEmit.swap(DeferredDeclsToEmit);
3287 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
3305 if (!GV->isDeclaration())
3309 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(
D))
3313 EmitGlobalDefinition(
D, GV);
3318 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
3320 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
3325void CodeGenModule::EmitVTablesOpportunistically() {
3331 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
3332 &&
"Only emit opportunistic vtables with optimizations");
3336 "This queue should only contain external vtables");
3337 if (
getCXXABI().canSpeculativelyEmitVTable(RD))
3340 OpportunisticVTables.clear();
3344 for (
const auto& [MangledName, VD] : DeferredAnnotations) {
3349 DeferredAnnotations.clear();
3351 if (Annotations.empty())
3355 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
3356 Annotations[0]->getType(), Annotations.size()), Annotations);
3357 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
3358 llvm::GlobalValue::AppendingLinkage,
3359 Array,
"llvm.global.annotations");
3364 llvm::Constant *&AStr = AnnotationStrings[Str];
3369 llvm::Constant *
s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
3370 auto *gv =
new llvm::GlobalVariable(
3371 getModule(),
s->getType(),
true, llvm::GlobalValue::PrivateLinkage,
s,
3372 ".str",
nullptr, llvm::GlobalValue::NotThreadLocal,
3375 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3392 SM.getExpansionLineNumber(L);
3393 return llvm::ConstantInt::get(
Int32Ty, LineNo);
3401 llvm::FoldingSetNodeID ID;
3402 for (
Expr *
E : Exprs) {
3403 ID.Add(cast<clang::ConstantExpr>(
E)->getAPValueResult());
3405 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
3410 LLVMArgs.reserve(Exprs.size());
3412 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](
const Expr *
E) {
3413 const auto *CE = cast<clang::ConstantExpr>(
E);
3414 return ConstEmiter.
emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
3417 auto *
Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
3418 auto *GV =
new llvm::GlobalVariable(
getModule(),
Struct->getType(),
true,
3419 llvm::GlobalValue::PrivateLinkage,
Struct,
3422 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3429 const AnnotateAttr *AA,
3437 llvm::Constant *GVInGlobalsAS = GV;
3438 if (GV->getAddressSpace() !=
3440 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
3442 llvm::PointerType::get(
3443 GV->getContext(),
getDataLayout().getDefaultGlobalsAddressSpace()));
3447 llvm::Constant *Fields[] = {
3448 GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
3450 return llvm::ConstantStruct::getAnon(Fields);
3454 llvm::GlobalValue *GV) {
3455 assert(
D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
3465 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
3470 if (NoSanitizeL.containsMainFile(Kind, MainFile.
getName()))
3475 return NoSanitizeL.containsLocation(Kind,
Loc);
3478 return NoSanitizeL.containsFile(Kind, MainFile.
getName());
3482 llvm::GlobalVariable *GV,
3486 if (NoSanitizeL.containsGlobal(Kind, GV->getName(),
Category))
3489 if (NoSanitizeL.containsMainFile(
3490 Kind,
SM.getFileEntryRefForID(
SM.getMainFileID())->getName(),
3493 if (NoSanitizeL.containsLocation(Kind,
Loc,
Category))
3500 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
3501 Ty = AT->getElementType();
3506 if (NoSanitizeL.containsType(Kind, TypeStr,
Category))
3517 auto Attr = ImbueAttr::NONE;
3520 if (
Attr == ImbueAttr::NONE)
3521 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
3523 case ImbueAttr::NONE:
3525 case ImbueAttr::ALWAYS:
3526 Fn->addFnAttr(
"function-instrument",
"xray-always");
3528 case ImbueAttr::ALWAYS_ARG1:
3529 Fn->addFnAttr(
"function-instrument",
"xray-always");
3530 Fn->addFnAttr(
"xray-log-args",
"1");
3532 case ImbueAttr::NEVER:
3533 Fn->addFnAttr(
"function-instrument",
"xray-never");
3557 if (
auto MainFile =
SM.getFileEntryRefForID(
SM.getMainFileID()))
3571 if (NumGroups > 1) {
3572 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
3581 if (LangOpts.EmitAllDecls)
3584 const auto *VD = dyn_cast<VarDecl>(
Global);
3586 ((CodeGenOpts.KeepPersistentStorageVariables &&
3587 (VD->getStorageDuration() ==
SD_Static ||
3588 VD->getStorageDuration() ==
SD_Thread)) ||
3589 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
3590 VD->getType().isConstQualified())))
3603 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
3604 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
3605 OMPDeclareTargetDeclAttr::getActiveAttr(
Global);
3606 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (
unsigned)-1)
3610 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
3619 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
3625 if (CXX20ModuleInits && VD->getOwningModule() &&
3626 !VD->getOwningModule()->isModuleMapModule()) {
3635 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
3638 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
Global))
3651 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
3655 llvm::Constant *
Init;
3658 if (!
V.isAbsent()) {
3669 llvm::Constant *Fields[4] = {
3673 llvm::ConstantDataArray::getRaw(
3674 StringRef(
reinterpret_cast<char *
>(Parts.
Part4And5), 8), 8,
3676 Init = llvm::ConstantStruct::getAnon(Fields);
3679 auto *GV =
new llvm::GlobalVariable(
3681 true, llvm::GlobalValue::LinkOnceODRLinkage,
Init, Name);
3683 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3686 if (!
V.isAbsent()) {
3699 llvm::GlobalVariable **Entry =
nullptr;
3700 Entry = &UnnamedGlobalConstantDeclMap[GCD];
3705 llvm::Constant *
Init;
3709 assert(!
V.isAbsent());
3713 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
3715 llvm::GlobalValue::PrivateLinkage,
Init,
3717 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3731 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
3735 llvm::Constant *
Init =
Emitter.emitForInitializer(
3743 llvm::GlobalValue::LinkageTypes
Linkage =
3745 ? llvm::GlobalValue::LinkOnceODRLinkage
3746 : llvm::GlobalValue::InternalLinkage;
3747 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
3751 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3758 const AliasAttr *AA = VD->
getAttr<AliasAttr>();
3759 assert(AA &&
"No alias?");
3769 llvm::Constant *Aliasee;
3770 if (isa<llvm::FunctionType>(DeclTy))
3771 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
3778 auto *F = cast<llvm::GlobalValue>(Aliasee);
3779 F->setLinkage(llvm::Function::ExternalWeakLinkage);
3780 WeakRefReferences.insert(F);
3789 return A->isImplicit();
3793bool CodeGenModule::shouldEmitCUDAGlobalVar(
const VarDecl *
Global)
const {
3794 assert(LangOpts.CUDA &&
"Should not be called by non-CUDA languages");
3799 return !LangOpts.CUDAIsDevice ||
Global->hasAttr<CUDADeviceAttr>() ||
3800 Global->hasAttr<CUDAConstantAttr>() ||
3801 Global->hasAttr<CUDASharedAttr>() ||
3802 Global->getType()->isCUDADeviceBuiltinSurfaceType() ||
3803 Global->getType()->isCUDADeviceBuiltinTextureType();
3810 if (
Global->hasAttr<WeakRefAttr>())
3815 if (
Global->hasAttr<AliasAttr>())
3816 return EmitAliasDefinition(GD);
3819 if (
Global->hasAttr<IFuncAttr>())
3820 return emitIFuncDefinition(GD);
3823 if (
Global->hasAttr<CPUDispatchAttr>())
3824 return emitCPUDispatchDefinition(GD);
3829 if (LangOpts.CUDA) {
3830 assert((isa<FunctionDecl>(
Global) || isa<VarDecl>(
Global)) &&
3831 "Expected Variable or Function");
3832 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
3833 if (!shouldEmitCUDAGlobalVar(VD))
3835 }
else if (LangOpts.CUDAIsDevice) {
3836 const auto *FD = dyn_cast<FunctionDecl>(
Global);
3837 if ((!
Global->hasAttr<CUDADeviceAttr>() ||
3838 (LangOpts.OffloadImplicitHostDeviceTemplates &&
3839 hasImplicitAttr<CUDAHostAttr>(FD) &&
3840 hasImplicitAttr<CUDADeviceAttr>(FD) && !FD->
isConstexpr() &&
3842 !
getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
3843 !
Global->hasAttr<CUDAGlobalAttr>() &&
3844 !(LangOpts.HIPStdPar && isa<FunctionDecl>(
Global) &&
3845 !
Global->hasAttr<CUDAHostAttr>()))
3848 }
else if (!
Global->hasAttr<CUDAHostAttr>() &&
3849 Global->hasAttr<CUDADeviceAttr>())
3853 if (LangOpts.OpenMP) {
3855 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
3857 if (
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(
Global)) {
3858 if (MustBeEmitted(
Global))
3862 if (
auto *DMD = dyn_cast<OMPDeclareMapperDecl>(
Global)) {
3863 if (MustBeEmitted(
Global))
3870 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
3873 if (FD->
hasAttr<AnnotateAttr>()) {
3876 DeferredAnnotations[MangledName] = FD;
3891 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
3896 const auto *VD = cast<VarDecl>(
Global);
3897 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
3900 if (LangOpts.OpenMP) {
3902 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3903 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
3907 if (VD->hasExternalStorage() &&
3908 Res != OMPDeclareTargetDeclAttr::MT_Link)
3911 bool UnifiedMemoryEnabled =
3913 if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3914 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3915 !UnifiedMemoryEnabled) {
3918 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3919 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3920 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3921 UnifiedMemoryEnabled)) &&
3922 "Link clause or to clause with unified memory expected.");
3941 if (MustBeEmitted(
Global) && MayBeEmittedEagerly(
Global)) {
3943 EmitGlobalDefinition(GD);
3944 addEmittedDeferredDecl(GD);
3951 cast<VarDecl>(
Global)->hasInit()) {
3952 DelayedCXXInitPosition[
Global] = CXXGlobalInits.size();
3953 CXXGlobalInits.push_back(
nullptr);
3959 addDeferredDeclToEmit(GD);
3960 }
else if (MustBeEmitted(
Global)) {
3962 assert(!MayBeEmittedEagerly(
Global));
3963 addDeferredDeclToEmit(GD);
3968 DeferredDecls[MangledName] = GD;
3975 if (
CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
3976 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
3983 struct FunctionIsDirectlyRecursive
3985 const StringRef Name;
3995 if (
Attr && Name ==
Attr->getLabel())
4000 StringRef BuiltinName = BI.
getName(BuiltinID);
4001 if (BuiltinName.starts_with(
"__builtin_") &&
4002 Name == BuiltinName.slice(strlen(
"__builtin_"), StringRef::npos)) {
4008 bool VisitStmt(
const Stmt *S) {
4009 for (
const Stmt *Child : S->children())
4010 if (Child && this->Visit(Child))
4017 struct DLLImportFunctionVisitor
4019 bool SafeToInline =
true;
4021 bool shouldVisitImplicitCode()
const {
return true; }
4023 bool VisitVarDecl(
VarDecl *VD) {
4026 SafeToInline =
false;
4027 return SafeToInline;
4034 return SafeToInline;
4038 if (
const auto *
D =
E->getTemporary()->getDestructor())
4039 SafeToInline =
D->
hasAttr<DLLImportAttr>();
4040 return SafeToInline;
4045 if (isa<FunctionDecl>(VD))
4046 SafeToInline = VD->
hasAttr<DLLImportAttr>();
4047 else if (
VarDecl *
V = dyn_cast<VarDecl>(VD))
4048 SafeToInline = !
V->hasGlobalStorage() ||
V->hasAttr<DLLImportAttr>();
4049 return SafeToInline;
4053 SafeToInline =
E->getConstructor()->hasAttr<DLLImportAttr>();
4054 return SafeToInline;
4061 SafeToInline =
true;
4063 SafeToInline = M->
hasAttr<DLLImportAttr>();
4065 return SafeToInline;
4069 SafeToInline =
E->getOperatorDelete()->hasAttr<DLLImportAttr>();
4070 return SafeToInline;
4074 SafeToInline =
E->getOperatorNew()->hasAttr<DLLImportAttr>();
4075 return SafeToInline;
4084CodeGenModule::isTriviallyRecursive(
const FunctionDecl *FD) {
4086 if (
getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
4091 Name =
Attr->getLabel();
4096 FunctionIsDirectlyRecursive Walker(Name, Context.
BuiltinInfo);
4098 return Body ? Walker.Visit(Body) :
false;
4101bool CodeGenModule::shouldEmitFunction(
GlobalDecl GD) {
4105 const auto *F = cast<FunctionDecl>(GD.
getDecl());
4108 if (F->isInlineBuiltinDeclaration())
4111 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
4116 if (
const Module *M = F->getOwningModule();
4117 M && M->getTopLevelModule()->isNamedModule() &&
4118 getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
4128 if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
4133 if (F->hasAttr<NoInlineAttr>())
4136 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
4138 DLLImportFunctionVisitor Visitor;
4139 Visitor.TraverseFunctionDecl(
const_cast<FunctionDecl*
>(F));
4140 if (!Visitor.SafeToInline)
4146 for (
const Decl *
Member : Dtor->getParent()->decls())
4147 if (isa<FieldDecl>(
Member))
4161 return !isTriviallyRecursive(F);
4164bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
4165 return CodeGenOpts.OptimizationLevel > 0;
4168void CodeGenModule::EmitMultiVersionFunctionDefinition(
GlobalDecl GD,
4169 llvm::GlobalValue *GV) {
4170 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4173 auto *Spec = FD->
getAttr<CPUSpecificAttr>();
4174 for (
unsigned I = 0; I < Spec->cpus_size(); ++I)
4176 }
else if (
auto *TC = FD->
getAttr<TargetClonesAttr>()) {
4177 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I)
4180 TC->isFirstOfVersion(I))
4183 GetOrCreateMultiVersionResolver(GD);
4185 EmitGlobalFunctionDefinition(GD, GV);
4190 AddDeferredMultiVersionResolverToEmit(GD);
4193void CodeGenModule::EmitGlobalDefinition(
GlobalDecl GD, llvm::GlobalValue *GV) {
4194 const auto *
D = cast<ValueDecl>(GD.
getDecl());
4198 "Generating code for declaration");
4200 if (
const auto *FD = dyn_cast<FunctionDecl>(
D)) {
4203 if (!shouldEmitFunction(GD))
4206 llvm::TimeTraceScope TimeScope(
"CodeGen Function", [&]() {
4208 llvm::raw_string_ostream OS(Name);
4214 if (
const auto *Method = dyn_cast<CXXMethodDecl>(
D)) {
4217 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
4218 ABI->emitCXXStructor(GD);
4220 EmitMultiVersionFunctionDefinition(GD, GV);
4222 EmitGlobalFunctionDefinition(GD, GV);
4224 if (Method->isVirtual())
4231 return EmitMultiVersionFunctionDefinition(GD, GV);
4232 return EmitGlobalFunctionDefinition(GD, GV);
4235 if (
const auto *VD = dyn_cast<VarDecl>(
D))
4236 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
4238 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
4242 llvm::Function *NewFn);
4245 const CodeGenFunction::FMVResolverOption &RO) {
4247 if (RO.Architecture)
4248 Features.push_back(*RO.Architecture);
4257static llvm::GlobalValue::LinkageTypes
4261 return llvm::GlobalValue::InternalLinkage;
4262 return llvm::GlobalValue::WeakODRLinkage;
4265void CodeGenModule::emitMultiVersionFunctions() {
4266 std::vector<GlobalDecl> MVFuncsToEmit;
4267 MultiVersionFuncs.swap(MVFuncsToEmit);
4269 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4270 assert(FD &&
"Expected a FunctionDecl");
4277 if (
Decl->isDefined()) {
4278 EmitGlobalFunctionDefinition(CurGD,
nullptr);
4286 assert(
Func &&
"This should have just been created");
4288 return cast<llvm::Function>(
Func);
4302 if (
const auto *TA = CurFD->
getAttr<TargetAttr>()) {
4303 assert(getTarget().getTriple().isX86() &&
"Unsupported target");
4304 TA->getX86AddedFeatures(Feats);
4305 llvm::Function *Func = createFunction(CurFD);
4306 Options.emplace_back(Func, Feats, TA->getX86Architecture());
4307 }
else if (
const auto *TVA = CurFD->
getAttr<TargetVersionAttr>()) {
4308 if (TVA->isDefaultVersion() && IsDefined)
4309 ShouldEmitResolver = true;
4310 llvm::Function *Func = createFunction(CurFD);
4311 char Delim = getTarget().getTriple().isAArch64() ?
'+' :
',';
4312 TVA->getFeatures(Feats, Delim);
4313 Options.emplace_back(Func, Feats);
4314 }
else if (
const auto *TC = CurFD->
getAttr<TargetClonesAttr>()) {
4316 ShouldEmitResolver = true;
4317 for (unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
4318 if (!TC->isFirstOfVersion(I))
4321 llvm::Function *Func = createFunction(CurFD, I);
4323 if (getTarget().getTriple().isX86()) {
4324 TC->getX86Feature(Feats, I);
4325 Options.emplace_back(Func, Feats, TC->getX86Architecture(I));
4327 char Delim = getTarget().getTriple().isAArch64() ?
'+' :
',';
4328 TC->getFeatures(Feats, I, Delim);
4329 Options.emplace_back(Func, Feats);
4333 llvm_unreachable(
"unexpected MultiVersionKind");
4336 if (!ShouldEmitResolver)
4339 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
4340 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
4341 ResolverConstant = IFunc->getResolver();
4345 *
this, GD, FD,
true);
4352 auto *Alias = llvm::GlobalAlias::create(
4354 MangledName +
".ifunc", IFunc, &
getModule());
4359 llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant);
4364 ResolverFunc->setComdat(
4365 getModule().getOrInsertComdat(ResolverFunc->getName()));
4369 Options, [&TI](
const CodeGenFunction::FMVResolverOption &LHS,
4370 const CodeGenFunction::FMVResolverOption &RHS) {
4374 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4380 if (!MVFuncsToEmit.empty())
4385 if (!MultiVersionFuncs.empty())
4386 emitMultiVersionFunctions();
4390 llvm::Constant *New) {
4391 assert(cast<llvm::Function>(Old)->isDeclaration() &&
"Not a declaration");
4393 Old->replaceAllUsesWith(New);
4394 Old->eraseFromParent();
4397void CodeGenModule::emitCPUDispatchDefinition(
GlobalDecl GD) {
4398 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4399 assert(FD &&
"Not a FunctionDecl?");
4401 const auto *DD = FD->
getAttr<CPUDispatchAttr>();
4402 assert(DD &&
"Not a cpu_dispatch Function?");
4408 UpdateMultiVersionNames(GD, FD, ResolverName);
4410 llvm::Type *ResolverType;
4413 ResolverType = llvm::FunctionType::get(
4414 llvm::PointerType::get(DeclTy,
4423 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
4424 ResolverName, ResolverType, ResolverGD,
false));
4427 ResolverFunc->setComdat(
4428 getModule().getOrInsertComdat(ResolverFunc->getName()));
4441 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
4444 EmitGlobalFunctionDefinition(ExistingDecl,
nullptr);
4450 Func = GetOrCreateLLVMFunction(
4451 MangledName, DeclTy, ExistingDecl,
4458 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
4459 llvm::transform(Features, Features.begin(),
4460 [](StringRef Str) { return Str.substr(1); });
4461 llvm::erase_if(Features, [&
Target](StringRef Feat) {
4462 return !
Target.validateCpuSupports(Feat);
4464 Options.emplace_back(cast<llvm::Function>(
Func), Features);
4468 llvm::stable_sort(Options, [](
const CodeGenFunction::FMVResolverOption &LHS,
4469 const CodeGenFunction::FMVResolverOption &RHS) {
4470 return llvm::X86::getCpuSupportsMask(LHS.Features) >
4471 llvm::X86::getCpuSupportsMask(RHS.Features);
4478 while (Options.size() > 1 && llvm::all_of(llvm::X86::getCpuSupportsMask(
4479 (Options.end() - 2)->Features),
4480 [](
auto X) { return X == 0; })) {
4481 StringRef LHSName = (Options.end() - 2)->
Function->getName();
4482 StringRef RHSName = (Options.end() - 1)->
Function->getName();
4483 if (LHSName.compare(RHSName) < 0)
4484 Options.erase(Options.end() - 2);
4486 Options.erase(Options.end() - 1);
4490 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4494 auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD));
4495 unsigned AS = IFunc->getType()->getPointerAddressSpace();
4499 if (!isa<llvm::GlobalIFunc>(IFunc)) {
4500 auto *GI = llvm::GlobalIFunc::create(DeclTy, AS,
Linkage,
"",
4507 *
this, GD, FD,
true);
4510 auto *GA = llvm::GlobalAlias::create(DeclTy, AS,
Linkage, AliasName,
4518void CodeGenModule::AddDeferredMultiVersionResolverToEmit(
GlobalDecl GD) {
4519 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4520 assert(FD &&
"Not a FunctionDecl?");
4523 std::string MangledName =
4525 if (!DeferredResolversToEmit.insert(MangledName).second)
4528 MultiVersionFuncs.push_back(GD);
4534llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
GlobalDecl GD) {
4535 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4536 assert(FD &&
"Not a FunctionDecl?");
4538 std::string MangledName =
4543 std::string ResolverName = MangledName;
4547 llvm_unreachable(
"unexpected MultiVersionKind::None for resolver");
4551 ResolverName +=
".ifunc";
4558 ResolverName +=
".resolver";
4561 bool ShouldReturnIFunc =
4571 if (ResolverGV && (isa<llvm::GlobalIFunc>(ResolverGV) || !ShouldReturnIFunc))
4580 AddDeferredMultiVersionResolverToEmit(GD);
4584 if (ShouldReturnIFunc) {
4586 llvm::Type *ResolverType =
4587 llvm::FunctionType::get(llvm::PointerType::get(DeclTy, AS),
false);
4588 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4589 MangledName +
".resolver", ResolverType,
GlobalDecl{},
4591 llvm::GlobalIFunc *GIF =
4594 GIF->setName(ResolverName);
4601 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4603 assert(isa<llvm::GlobalValue>(Resolver) && !ResolverGV &&
4604 "Resolver should be created for the first time");
4609bool CodeGenModule::shouldDropDLLAttribute(
const Decl *
D,
4610 const llvm::GlobalValue *GV)
const {
4611 auto SC = GV->getDLLStorageClass();
4612 if (SC == llvm::GlobalValue::DefaultStorageClass)
4615 return (((SC == llvm::GlobalValue::DLLImportStorageClass &&
4616 !MRD->
hasAttr<DLLImportAttr>()) ||
4617 (SC == llvm::GlobalValue::DLLExportStorageClass &&
4618 !MRD->
hasAttr<DLLExportAttr>())) &&
4629llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
4630 StringRef MangledName, llvm::Type *Ty,
GlobalDecl GD,
bool ForVTable,
4631 bool DontDefer,
bool IsThunk, llvm::AttributeList ExtraAttrs,
4635 std::string NameWithoutMultiVersionMangling;
4638 if (
const FunctionDecl *FD = cast_or_null<FunctionDecl>(
D)) {
4640 if (
getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
4641 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->
isDefined() &&
4642 !DontDefer && !IsForDefinition) {
4645 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
4647 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
4656 UpdateMultiVersionNames(GD, FD, MangledName);
4657 if (!IsForDefinition) {
4663 AddDeferredMultiVersionResolverToEmit(GD);
4665 *
this, GD, FD,
true);
4667 return GetOrCreateMultiVersionResolver(GD);
4672 if (!NameWithoutMultiVersionMangling.empty())
4673 MangledName = NameWithoutMultiVersionMangling;
4678 if (WeakRefReferences.erase(Entry)) {
4680 if (FD && !FD->
hasAttr<WeakAttr>())
4681 Entry->setLinkage(llvm::Function::ExternalLinkage);
4685 if (
D && shouldDropDLLAttribute(
D, Entry)) {
4686 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4692 if (IsForDefinition && !Entry->isDeclaration()) {
4699 DiagnosedConflictingDefinitions.insert(GD).second) {
4703 diag::note_previous_definition);
4707 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
4708 (Entry->getValueType() == Ty)) {
4715 if (!IsForDefinition)
4722 bool IsIncompleteFunction =
false;
4724 llvm::FunctionType *FTy;
4725 if (isa<llvm::FunctionType>(Ty)) {
4726 FTy = cast<llvm::FunctionType>(Ty);
4728 FTy = llvm::FunctionType::get(
VoidTy,
false);
4729 IsIncompleteFunction =
true;
4733 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
4734 Entry ? StringRef() : MangledName, &
getModule());
4739 DeferredAnnotations[MangledName] = cast<ValueDecl>(
D);
4756 if (!Entry->use_empty()) {
4758 Entry->removeDeadConstantUsers();
4764 assert(F->getName() == MangledName &&
"name was uniqued!");
4766 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
4767 if (ExtraAttrs.hasFnAttrs()) {
4768 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
4776 if (isa_and_nonnull<CXXDestructorDecl>(
D) &&
4777 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(
D),
4779 addDeferredDeclToEmit(GD);
4784 auto DDI = DeferredDecls.find(MangledName);
4785 if (DDI != DeferredDecls.end()) {
4789 addDeferredDeclToEmit(DDI->second);
4790 DeferredDecls.erase(DDI);
4805 for (
const auto *FD = cast<FunctionDecl>(
D)->getMostRecentDecl(); FD;
4818 if (!IsIncompleteFunction) {
4819 assert(F->getFunctionType() == Ty);
4835 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4842 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(GD.
getDecl())) {
4845 DD->getParent()->getNumVBases() == 0)
4850 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
4851 false, llvm::AttributeList(),
4854 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
4855 cast<FunctionDecl>(GD.
getDecl())->hasAttr<CUDAGlobalAttr>()) {
4857 cast<llvm::Function>(F->stripPointerCasts()), GD);
4858 if (IsForDefinition)
4866 llvm::GlobalValue *F =
4869 return llvm::NoCFIValue::get(F);
4879 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
4882 if (!
C.getLangOpts().CPlusPlus)
4887 (Name ==
"_ZSt9terminatev" || Name ==
"?terminate@@YAXXZ")
4888 ?
C.Idents.get(
"terminate")
4889 :
C.Idents.get(Name);
4891 for (
const auto &N : {
"__cxxabiv1",
"std"}) {
4895 if (
auto *LSD = dyn_cast<LinkageSpecDecl>(
Result))
4896 for (
const auto *
Result : LSD->lookup(&NS))
4897 if ((ND = dyn_cast<NamespaceDecl>(
Result)))
4902 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
4911 llvm::Function *F, StringRef Name) {
4917 if (!Local && CGM.
getTriple().isWindowsItaniumEnvironment() &&
4920 if (!FD || FD->
hasAttr<DLLImportAttr>()) {
4921 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4922 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
4929 llvm::AttributeList ExtraAttrs,
bool Local,
bool AssumeConvergent) {
4930 if (AssumeConvergent) {
4932 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
4940 llvm::Constant *
C = GetOrCreateLLVMFunction(
4942 false,
false, ExtraAttrs);
4944 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
4960 llvm::AttributeList ExtraAttrs,
bool Local,
4961 bool AssumeConvergent) {
4962 if (AssumeConvergent) {
4964 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
4968 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
4972 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
4981 markRegisterParameterAttributes(F);
5007 if (WeakRefReferences.erase(Entry)) {
5009 Entry->setLinkage(llvm::Function::ExternalLinkage);
5013 if (
D && shouldDropDLLAttribute(
D, Entry))
5014 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5016 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd &&
D)
5019 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
5024 if (IsForDefinition && !Entry->isDeclaration()) {
5032 (OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
5034 DiagnosedConflictingDefinitions.insert(
D).second) {
5038 diag::note_previous_definition);
5043 if (Entry->getType()->getAddressSpace() != TargetAS)
5044 return llvm::ConstantExpr::getAddrSpaceCast(
5045 Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
5049 if (!IsForDefinition)
5055 auto *GV =
new llvm::GlobalVariable(
5056 getModule(), Ty,
false, llvm::GlobalValue::ExternalLinkage,
nullptr,
5057 MangledName,
nullptr, llvm::GlobalVariable::NotThreadLocal,
5058 getContext().getTargetAddressSpace(DAddrSpace));
5063 GV->takeName(Entry);
5065 if (!Entry->use_empty()) {
5066 Entry->replaceAllUsesWith(GV);
5069 Entry->eraseFromParent();
5075 auto DDI = DeferredDecls.find(MangledName);
5076 if (DDI != DeferredDecls.end()) {
5079 addDeferredDeclToEmit(DDI->second);
5080 DeferredDecls.erase(DDI);
5085 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
5090 GV->setConstant(
D->getType().isConstantStorage(
getContext(),
false,
false));
5092 GV->setAlignment(
getContext().getDeclAlign(
D).getAsAlign());
5096 if (
D->getTLSKind()) {
5098 CXXThreadLocals.push_back(
D);
5106 if (
getContext().isMSStaticDataMemberInlineDefinition(
D)) {
5107 EmitGlobalVarDefinition(
D);
5111 if (
D->hasExternalStorage()) {
5112 if (
const SectionAttr *SA =
D->
getAttr<SectionAttr>())
5113 GV->setSection(SA->getName());
5117 if (
getTriple().getArch() == llvm::Triple::xcore &&
5119 D->getType().isConstant(Context) &&
5121 GV->setSection(
".cp.rodata");
5124 if (
const auto *CMA =
D->
getAttr<CodeModelAttr>())
5125 GV->setCodeModel(CMA->getModel());
5130 if (Context.
getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
5131 D->getType().isConstQualified() && !GV->hasInitializer() &&
5132 !
D->hasDefinition() &&
D->hasInit() && !
D->
hasAttr<DLLImportAttr>()) {
5136 if (!HasMutableFields) {
5138 const Expr *InitExpr =
D->getAnyInitializer(InitDecl);
5143 auto *InitType =
Init->getType();
5144 if (GV->getValueType() != InitType) {
5149 GV->setName(StringRef());
5152 auto *NewGV = cast<llvm::GlobalVariable>(
5154 ->stripPointerCasts());
5157 GV->eraseFromParent();
5160 GV->setInitializer(
Init);
5161 GV->setConstant(
true);
5162 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
5177 D->hasExternalStorage())
5182 SanitizerMD->reportGlobal(GV, *
D);
5185 D ?
D->getType().getAddressSpace()
5187 assert(
getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
5188 if (DAddrSpace != ExpectedAS) {
5190 *
this, GV, DAddrSpace, ExpectedAS,
5201 if (isa<CXXConstructorDecl>(
D) || isa<CXXDestructorDecl>(
D))
5203 false, IsForDefinition);
5205 if (isa<CXXMethodDecl>(
D)) {
5213 if (isa<FunctionDecl>(
D)) {
5224 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes
Linkage,
5225 llvm::Align Alignment) {
5226 llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
5227 llvm::GlobalVariable *OldGV =
nullptr;
5231 if (GV->getValueType() == Ty)
5236 assert(GV->isDeclaration() &&
"Declaration has wrong type!");
5241 GV =
new llvm::GlobalVariable(
getModule(), Ty,
true,
5246 GV->takeName(OldGV);
5248 if (!OldGV->use_empty()) {
5249 OldGV->replaceAllUsesWith(GV);
5252 OldGV->eraseFromParent();
5256 !GV->hasAvailableExternallyLinkage())
5257 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5259 GV->setAlignment(Alignment);
5273 assert(
D->hasGlobalStorage() &&
"Not a global variable");
5291 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
5296 assert(!
D->getInit() &&
"Cannot emit definite definitions here!");
5304 if (GV && !GV->isDeclaration())
5309 if (!MustBeEmitted(
D) && !GV) {
5310 DeferredDecls[MangledName] =
D;
5315 EmitGlobalVarDefinition(
D);
5319 if (
auto const *
V = dyn_cast<const VarDecl>(
D))
5320 EmitExternalVarDeclaration(
V);
5321 if (
auto const *FD = dyn_cast<const FunctionDecl>(
D))
5322 EmitExternalFunctionDeclaration(FD);
5331 if (LangOpts.OpenCL) {
5342 if (LangOpts.SYCLIsDevice &&
5346 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
5348 if (
D->
hasAttr<CUDAConstantAttr>())
5354 if (
D->getType().isConstQualified())
5360 if (LangOpts.OpenMP) {
5362 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(
D, AS))
5370 if (LangOpts.OpenCL)
5372 if (LangOpts.SYCLIsDevice)
5374 if (LangOpts.HIP && LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())
5382 if (
auto AS =
getTarget().getConstantAddressSpace())
5395static llvm::Constant *
5397 llvm::GlobalVariable *GV) {
5398 llvm::Constant *Cast = GV;
5404 llvm::PointerType::get(
5411template<
typename SomeDecl>
5413 llvm::GlobalValue *GV) {
5419 if (!
D->template hasAttr<UsedAttr>())
5428 const SomeDecl *
First =
D->getFirstDecl();
5429 if (
First->getDeclContext()->isRecord() || !
First->isInExternCContext())
5435 std::pair<StaticExternCMap::iterator, bool> R =
5436 StaticExternCValues.insert(std::make_pair(
D->getIdentifier(), GV));
5441 R.first->second =
nullptr;
5452 if (
auto *VD = dyn_cast<VarDecl>(&
D))
5466 llvm_unreachable(
"No such linkage");
5474 llvm::GlobalObject &GO) {
5477 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
5485void CodeGenModule::EmitGlobalVarDefinition(
const VarDecl *
D,
5495 if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
5496 OpenMPRuntime->emitTargetGlobalVariable(
D))
5499 llvm::TrackingVH<llvm::Constant>
Init;
5500 bool NeedsGlobalCtor =
false;
5504 bool IsDefinitionAvailableExternally =
5506 bool NeedsGlobalDtor =
5507 !IsDefinitionAvailableExternally &&
5514 if (IsDefinitionAvailableExternally &&
5515 (!
D->hasConstantInitialization() ||
5519 !
D->getType().isConstantStorage(
getContext(),
true,
true)))
5523 const Expr *InitExpr =
D->getAnyInitializer(InitDecl);
5525 std::optional<ConstantEmitter> emitter;
5530 bool IsCUDASharedVar =
5535 bool IsCUDAShadowVar =
5539 bool IsCUDADeviceShadowVar =
5541 (
D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5542 D->getType()->isCUDADeviceBuiltinTextureType());
5544 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
5545 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
5546 else if (
D->
hasAttr<LoaderUninitializedAttr>())
5547 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
5548 else if (!InitExpr) {
5562 emitter.emplace(*
this);
5563 llvm::Constant *
Initializer = emitter->tryEmitForInitializer(*InitDecl);
5566 if (
D->getType()->isReferenceType())
5571 if (!IsDefinitionAvailableExternally)
5572 NeedsGlobalCtor =
true;
5576 NeedsGlobalCtor =
false;
5588 DelayedCXXInitPosition.erase(
D);
5595 assert(VarSize == CstSize &&
"Emitted constant has unexpected size");
5600 llvm::Type* InitType =
Init->getType();
5601 llvm::Constant *Entry =
5605 Entry = Entry->stripPointerCasts();
5608 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
5619 if (!GV || GV->getValueType() != InitType ||
5620 GV->getType()->getAddressSpace() !=
5624 Entry->setName(StringRef());
5627 GV = cast<llvm::GlobalVariable>(
5629 ->stripPointerCasts());
5632 llvm::Constant *NewPtrForOldDecl =
5633 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5635 Entry->replaceAllUsesWith(NewPtrForOldDecl);
5638 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
5656 if (LangOpts.CUDA) {
5657 if (LangOpts.CUDAIsDevice) {
5658 if (
Linkage != llvm::GlobalValue::InternalLinkage &&
5660 D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5661 D->getType()->isCUDADeviceBuiltinTextureType()))
5662 GV->setExternallyInitialized(
true);
5672 GV->setInitializer(
Init);
5674 emitter->finalize(GV);
5677 GV->setConstant((
D->
hasAttr<CUDAConstantAttr>() && LangOpts.CUDAIsDevice) ||
5678 (!NeedsGlobalCtor && !NeedsGlobalDtor &&
5679 D->getType().isConstantStorage(
getContext(),
true,
true)));
5682 if (
const SectionAttr *SA =
D->
getAttr<SectionAttr>()) {
5685 GV->setConstant(
true);
5690 if (std::optional<CharUnits> AlignValFromAllocate =
5692 AlignVal = *AlignValFromAllocate;
5710 Linkage == llvm::GlobalValue::ExternalLinkage &&
5713 Linkage = llvm::GlobalValue::InternalLinkage;
5717 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
5718 else if (
D->
hasAttr<DLLExportAttr>())
5719 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
5721 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
5723 if (
Linkage == llvm::GlobalVariable::CommonLinkage) {
5725 GV->setConstant(
false);
5730 if (!GV->getInitializer()->isNullValue())
5731 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
5734 setNonAliasAttributes(
D, GV);
5736 if (
D->getTLSKind() && !GV->isThreadLocal()) {
5738 CXXThreadLocals.push_back(
D);
5745 if (NeedsGlobalCtor || NeedsGlobalDtor)
5746 EmitCXXGlobalVarDeclInitFunc(
D, GV, NeedsGlobalCtor);
5748 SanitizerMD->reportGlobal(GV, *
D, NeedsGlobalCtor);
5753 DI->EmitGlobalVariable(GV,
D);
5756void CodeGenModule::EmitExternalVarDeclaration(
const VarDecl *
D) {
5761 llvm::Constant *GV =
5763 DI->EmitExternalVariable(
5764 cast<llvm::GlobalVariable>(GV->stripPointerCasts()),
D);
5768void CodeGenModule::EmitExternalFunctionDeclaration(
const FunctionDecl *FD) {
5773 auto *
Fn = cast<llvm::Function>(
5774 GetOrCreateLLVMFunction(MangledName, Ty, FD,
false));
5775 if (!
Fn->getSubprogram())
5792 if (
D->getInit() ||
D->hasExternalStorage())
5802 if (
D->
hasAttr<PragmaClangBSSSectionAttr>() ||
5803 D->
hasAttr<PragmaClangDataSectionAttr>() ||
5804 D->
hasAttr<PragmaClangRelroSectionAttr>() ||
5805 D->
hasAttr<PragmaClangRodataSectionAttr>())
5809 if (
D->getTLSKind())
5832 if (FD->isBitField())
5834 if (FD->
hasAttr<AlignedAttr>())
5856llvm::GlobalValue::LinkageTypes
5860 return llvm::Function::InternalLinkage;
5863 return llvm::GlobalVariable::WeakAnyLinkage;
5867 return llvm::GlobalVariable::LinkOnceAnyLinkage;
5872 return llvm::GlobalValue::AvailableExternallyLinkage;
5886 return !Context.
getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
5887 : llvm::Function::InternalLinkage;
5901 return llvm::Function::ExternalLinkage;
5904 return D->
hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
5905 : llvm::Function::InternalLinkage;
5906 return llvm::Function::WeakODRLinkage;
5913 CodeGenOpts.NoCommon))
5914 return llvm::GlobalVariable::CommonLinkage;
5921 return llvm::GlobalVariable::WeakODRLinkage;
5925 return llvm::GlobalVariable::ExternalLinkage;
5928llvm::GlobalValue::LinkageTypes
5937 llvm::Function *newFn) {
5939 if (old->use_empty())
5942 llvm::Type *newRetTy = newFn->getReturnType();
5947 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
5949 llvm::User *user = ui->getUser();
5953 if (
auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
5954 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
5960 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
5963 if (!callSite->isCallee(&*ui))
5968 if (callSite->getType() != newRetTy && !callSite->use_empty())
5973 llvm::AttributeList oldAttrs = callSite->getAttributes();
5976 unsigned newNumArgs = newFn->arg_size();
5977 if (callSite->arg_size() < newNumArgs)
5983 bool dontTransform =
false;
5984 for (llvm::Argument &A : newFn->args()) {
5985 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
5986 dontTransform =
true;
5991 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
5999 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
6003 callSite->getOperandBundlesAsDefs(newBundles);
6005 llvm::CallBase *newCall;
6006 if (isa<llvm::CallInst>(callSite)) {
6007 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles,
"",
6008 callSite->getIterator());
6010 auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
6011 newCall = llvm::InvokeInst::Create(
6012 newFn, oldInvoke->getNormalDest(), oldInvoke->getUnwindDest(),
6013 newArgs, newBundles,
"", callSite->getIterator());
6017 if (!newCall->getType()->isVoidTy())
6018 newCall->takeName(callSite);
6019 newCall->setAttributes(
6020 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
6021 oldAttrs.getRetAttrs(), newArgAttrs));
6022 newCall->setCallingConv(callSite->getCallingConv());
6025 if (!callSite->use_empty())
6026 callSite->replaceAllUsesWith(newCall);
6029 if (callSite->getDebugLoc())
6030 newCall->setDebugLoc(callSite->getDebugLoc());
6032 callSitesToBeRemovedFromParent.push_back(callSite);
6035 for (
auto *callSite : callSitesToBeRemovedFromParent) {
6036 callSite->eraseFromParent();
6050 llvm::Function *NewFn) {
6052 if (!isa<llvm::Function>(Old))
return;
6060 (LangOpts.CUDA && !shouldEmitCUDAGlobalVar(VD)))
6072void CodeGenModule::EmitGlobalFunctionDefinition(
GlobalDecl GD,
6073 llvm::GlobalValue *GV) {
6074 const auto *
D = cast<FunctionDecl>(GD.
getDecl());
6081 if (!GV || (GV->getValueType() != Ty))
6087 if (!GV->isDeclaration())
6094 auto *Fn = cast<llvm::Function>(GV);
6106 setNonAliasAttributes(GD, Fn);
6109 if (
const ConstructorAttr *CA =
D->
getAttr<ConstructorAttr>())
6111 if (
const DestructorAttr *DA =
D->
getAttr<DestructorAttr>())
6117void CodeGenModule::EmitAliasDefinition(
GlobalDecl GD) {
6118 const auto *
D = cast<ValueDecl>(GD.
getDecl());
6119 const AliasAttr *AA =
D->
getAttr<AliasAttr>();
6120 assert(AA &&
"Not an alias?");
6124 if (AA->getAliasee() == MangledName) {
6125 Diags.
Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6132 if (Entry && !Entry->isDeclaration())
6135 Aliases.push_back(GD);
6141 llvm::Constant *Aliasee;
6142 llvm::GlobalValue::LinkageTypes
LT;
6143 if (isa<llvm::FunctionType>(DeclTy)) {
6144 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
6150 if (
const auto *VD = dyn_cast<VarDecl>(GD.
getDecl()))
6157 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
6159 llvm::GlobalAlias::create(DeclTy, AS,
LT,
"", Aliasee, &
getModule());
6162 if (GA->getAliasee() == Entry) {
6163 Diags.
Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6167 assert(Entry->isDeclaration());
6176 GA->takeName(Entry);
6178 Entry->replaceAllUsesWith(GA);
6179 Entry->eraseFromParent();
6181 GA->setName(MangledName);
6189 GA->setLinkage(llvm::Function::WeakAnyLinkage);
6192 if (
const auto *VD = dyn_cast<VarDecl>(
D))
6193 if (VD->getTLSKind())
6199 if (isa<VarDecl>(
D))
6201 DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD);
6204void CodeGenModule::emitIFuncDefinition(
GlobalDecl GD) {
6205 const auto *
D = cast<ValueDecl>(GD.
getDecl());
6206 const IFuncAttr *IFA =
D->
getAttr<IFuncAttr>();
6207 assert(IFA &&
"Not an ifunc?");
6211 if (IFA->getResolver() == MangledName) {
6212 Diags.
Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6218 if (Entry && !Entry->isDeclaration()) {
6221 DiagnosedConflictingDefinitions.insert(GD).second) {
6225 diag::note_previous_definition);
6230 Aliases.push_back(GD);
6236 llvm::Constant *Resolver =
6237 GetOrCreateLLVMFunction(IFA->getResolver(),
VoidTy, {},
6241 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
6242 DeclTy, AS, llvm::Function::ExternalLinkage,
"", Resolver, &
getModule());
6244 if (GIF->getResolver() == Entry) {
6245 Diags.
Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6248 assert(Entry->isDeclaration());
6257 GIF->takeName(Entry);
6259 Entry->replaceAllUsesWith(GIF);
6260 Entry->eraseFromParent();
6262 GIF->setName(MangledName);
6268 return llvm::Intrinsic::getOrInsertDeclaration(&
getModule(),
6269 (llvm::Intrinsic::ID)IID, Tys);
6272static llvm::StringMapEntry<llvm::GlobalVariable *> &
6275 bool &IsUTF16,
unsigned &StringLength) {
6276 StringRef String = Literal->getString();
6277 unsigned NumBytes = String.size();
6280 if (!Literal->containsNonAsciiOrNull()) {
6281 StringLength = NumBytes;
6282 return *Map.insert(std::make_pair(String,
nullptr)).first;
6289 const llvm::UTF8 *FromPtr = (
const llvm::UTF8 *)String.data();
6290 llvm::UTF16 *ToPtr = &ToBuf[0];
6292 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6293 ToPtr + NumBytes, llvm::strictConversion);
6296 StringLength = ToPtr - &ToBuf[0];
6300 return *Map.insert(std::make_pair(
6301 StringRef(
reinterpret_cast<const char *
>(ToBuf.data()),
6302 (StringLength + 1) * 2),
6308 unsigned StringLength = 0;
6309 bool isUTF16 =
false;
6310 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
6315 if (
auto *
C = Entry.second)
6320 const llvm::Triple &Triple =
getTriple();
6323 const bool IsSwiftABI =
6324 static_cast<unsigned>(CFRuntime) >=
6329 if (!CFConstantStringClassRef) {
6330 const char *CFConstantStringClassName =
"__CFConstantStringClassReference";
6332 Ty = llvm::ArrayType::get(Ty, 0);
6334 switch (CFRuntime) {
6338 CFConstantStringClassName =
6339 Triple.isOSDarwin() ?
"$s15SwiftFoundation19_NSCFConstantStringCN"
6340 :
"$s10Foundation19_NSCFConstantStringCN";
6344 CFConstantStringClassName =
6345 Triple.isOSDarwin() ?
"$S15SwiftFoundation19_NSCFConstantStringCN"
6346 :
"$S10Foundation19_NSCFConstantStringCN";
6350 CFConstantStringClassName =
6351 Triple.isOSDarwin() ?
"__T015SwiftFoundation19_NSCFConstantStringCN"
6352 :
"__T010Foundation19_NSCFConstantStringCN";
6359 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
6360 llvm::GlobalValue *GV =
nullptr;
6362 if ((GV = dyn_cast<llvm::GlobalValue>(
C))) {
6369 if ((VD = dyn_cast<VarDecl>(
Result)))
6372 if (Triple.isOSBinFormatELF()) {
6374 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6376 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6377 if (!VD || !VD->
hasAttr<DLLExportAttr>())
6378 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
6380 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
6388 CFConstantStringClassRef =
6389 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(
C, Ty) :
C;
6394 auto *STy = cast<llvm::StructType>(
getTypes().ConvertType(CFTy));
6397 auto Fields = Builder.beginStruct(STy);
6400 Fields.add(cast<llvm::Constant>(CFConstantStringClassRef));
6404 Fields.addInt(
IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
6405 Fields.addInt(
Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
6407 Fields.addInt(
IntTy, isUTF16 ? 0x07d0 : 0x07C8);
6411 llvm::Constant *
C =
nullptr;
6414 reinterpret_cast<uint16_t *
>(
const_cast<char *
>(Entry.first().data())),
6415 Entry.first().size() / 2);
6416 C = llvm::ConstantDataArray::get(VMContext, Arr);
6418 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
6424 new llvm::GlobalVariable(
getModule(),
C->getType(),
true,
6425 llvm::GlobalValue::PrivateLinkage,
C,
".str");
6426 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6436 if (Triple.isOSBinFormatMachO())
6437 GV->setSection(isUTF16 ?
"__TEXT,__ustring"
6438 :
"__TEXT,__cstring,cstring_literals");
6441 else if (Triple.isOSBinFormatELF())
6442 GV->setSection(
".rodata");
6448 llvm::IntegerType *LengthTy =
6458 Fields.addInt(LengthTy, StringLength);
6466 GV = Fields.finishAndCreateGlobal(
"_unnamed_cfstring_", Alignment,
6468 llvm::GlobalVariable::PrivateLinkage);
6469 GV->addAttribute(
"objc_arc_inert");
6470 switch (Triple.getObjectFormat()) {
6471 case llvm::Triple::UnknownObjectFormat:
6472 llvm_unreachable(
"unknown file format");
6473 case llvm::Triple::DXContainer:
6474 case llvm::Triple::GOFF:
6475 case llvm::Triple::SPIRV:
6476 case llvm::Triple::XCOFF:
6477 llvm_unreachable(
"unimplemented");
6478 case llvm::Triple::COFF:
6479 case llvm::Triple::ELF:
6480 case llvm::Triple::Wasm:
6481 GV->setSection(
"cfstring");
6483 case llvm::Triple::MachO:
6484 GV->setSection(
"__DATA,__cfstring");
6493 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
6497 if (ObjCFastEnumerationStateType.
isNull()) {
6499 D->startDefinition();
6507 for (
size_t i = 0; i < 4; ++i) {
6512 FieldTypes[i],
nullptr,
6520 D->completeDefinition();
6524 return ObjCFastEnumerationStateType;
6533 if (
E->getCharByteWidth() == 1) {
6538 assert(CAT &&
"String literal not of constant array type!");
6540 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
6544 llvm::Type *ElemTy = AType->getElementType();
6545 unsigned NumElements = AType->getNumElements();
6548 if (ElemTy->getPrimitiveSizeInBits() == 16) {
6550 Elements.reserve(NumElements);
6552 for(
unsigned i = 0, e =
E->getLength(); i != e; ++i)
6553 Elements.push_back(
E->getCodeUnit(i));
6554 Elements.resize(NumElements);
6555 return llvm::ConstantDataArray::get(VMContext, Elements);
6558 assert(ElemTy->getPrimitiveSizeInBits() == 32);
6560 Elements.reserve(NumElements);
6562 for(
unsigned i = 0, e =
E->getLength(); i != e; ++i)
6563 Elements.push_back(
E->getCodeUnit(i));
6564 Elements.resize(NumElements);
6565 return llvm::ConstantDataArray::get(VMContext, Elements);
6568static llvm::GlobalVariable *
6577 auto *GV =
new llvm::GlobalVariable(
6578 M,
C->getType(), !CGM.
getLangOpts().WritableStrings,
LT,
C, GlobalName,
6579 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
6581 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6582 if (GV->isWeakForLinker()) {
6583 assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
6584 GV->setComdat(M.getOrInsertComdat(GV->getName()));
6600 llvm::GlobalVariable **Entry =
nullptr;
6601 if (!LangOpts.WritableStrings) {
6602 Entry = &ConstantStringMap[
C];
6603 if (
auto GV = *Entry) {
6604 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
6607 GV->getValueType(), Alignment);
6612 StringRef GlobalVariableName;
6613 llvm::GlobalValue::LinkageTypes
LT;
6618 if (
getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
6619 !LangOpts.WritableStrings) {
6620 llvm::raw_svector_ostream Out(MangledNameBuffer);
6622 LT = llvm::GlobalValue::LinkOnceODRLinkage;
6623 GlobalVariableName = MangledNameBuffer;
6625 LT = llvm::GlobalValue::PrivateLinkage;
6626 GlobalVariableName = Name;
6638 SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0),
"<string literal>");
6641 GV->getValueType(), Alignment);
6658 const std::string &Str,
const char *GlobalName) {
6659 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
6664 llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
6667 llvm::GlobalVariable **Entry =
nullptr;
6668 if (!LangOpts.WritableStrings) {
6669 Entry = &ConstantStringMap[
C];
6670 if (
auto GV = *Entry) {
6671 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
6674 GV->getValueType(), Alignment);
6680 GlobalName =
".str";
6683 GlobalName, Alignment);
6688 GV->getValueType(), Alignment);
6693 assert((
E->getStorageDuration() ==
SD_Static ||
6694 E->getStorageDuration() ==
SD_Thread) &&
"not a global temporary");
6695 const auto *VD = cast<VarDecl>(
E->getExtendingDecl());
6700 if (
Init ==
E->getSubExpr())
6705 auto InsertResult = MaterializedGlobalTemporaryMap.insert({
E,
nullptr});
6706 if (!InsertResult.second) {
6709 if (!InsertResult.first->second) {
6714 InsertResult.first->second =
new llvm::GlobalVariable(
6715 getModule(),
Type,
false, llvm::GlobalVariable::InternalLinkage,
6719 llvm::cast<llvm::GlobalVariable>(
6720 InsertResult.first->second->stripPointerCasts())
6729 llvm::raw_svector_ostream Out(Name);
6731 VD,
E->getManglingNumber(), Out);
6734 if (
E->getStorageDuration() ==
SD_Static && VD->evaluateValue()) {
6740 Value =
E->getOrCreateValue(
false);
6751 std::optional<ConstantEmitter> emitter;
6752 llvm::Constant *InitialValue =
nullptr;
6753 bool Constant =
false;
6757 emitter.emplace(*
this);
6758 InitialValue = emitter->emitForInitializer(*
Value, AddrSpace,
6763 Type = InitialValue->getType();
6772 if (
Linkage == llvm::GlobalVariable::ExternalLinkage) {
6774 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
6778 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
6782 Linkage = llvm::GlobalVariable::InternalLinkage;
6786 auto *GV =
new llvm::GlobalVariable(
6788 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
6789 if (emitter) emitter->finalize(GV);
6791 if (!llvm::GlobalValue::isLocalLinkage(
Linkage)) {
6793 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
6795 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6799 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
6800 if (VD->getTLSKind())
6802 llvm::Constant *CV = GV;
6806 llvm::PointerType::get(
6812 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[
E];
6814 Entry->replaceAllUsesWith(CV);
6815 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
6824void CodeGenModule::EmitObjCPropertyImplementations(
const
6826 for (
const auto *PID :
D->property_impls()) {
6837 if (!Getter || Getter->isSynthesizedAccessorStub())
6840 auto *Setter = PID->getSetterMethodDecl();
6841 if (!PD->
isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
6852 if (ivar->getType().isDestructedType())
6862 E =
D->init_end(); B !=
E; ++B) {
6885 D->addInstanceMethod(DTORMethod);
6887 D->setHasDestructors(
true);
6892 if (
D->getNumIvarInitializers() == 0 ||
6906 D->addInstanceMethod(CTORMethod);
6908 D->setHasNonZeroConstructors(
true);
6919 EmitDeclContext(LSD);
6924 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
6927 std::unique_ptr<CodeGenFunction> &CurCGF =
6928 GlobalTopLevelStmtBlockInFlight.first;
6932 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
6940 std::string Name =
"__stmts__" + llvm::utostr(CXXGlobalInits.size());
6946 llvm::Function *
Fn = llvm::Function::Create(
6947 FnTy, llvm::GlobalValue::InternalLinkage, Name, &
getModule());
6950 GlobalTopLevelStmtBlockInFlight.second =
D;
6951 CurCGF->StartFunction(
GlobalDecl(), RetTy, Fn, FnInfo, Args,
6953 CXXGlobalInits.push_back(Fn);
6956 CurCGF->EmitStmt(
D->getStmt());
6959void CodeGenModule::EmitDeclContext(
const DeclContext *DC) {
6960 for (
auto *I : DC->
decls()) {
6966 if (
auto *OID = dyn_cast<ObjCImplDecl>(I)) {
6967 for (
auto *M : OID->methods())
6986 case Decl::CXXConversion:
6987 case Decl::CXXMethod:
6988 case Decl::Function:
6995 case Decl::CXXDeductionGuide:
7000 case Decl::Decomposition:
7001 case Decl::VarTemplateSpecialization:
7003 if (
auto *DD = dyn_cast<DecompositionDecl>(
D))
7004 for (
auto *B : DD->bindings())
7005 if (
auto *HD = B->getHoldingVar())
7011 case Decl::IndirectField:
7015 case Decl::Namespace:
7016 EmitDeclContext(cast<NamespaceDecl>(
D));
7018 case Decl::ClassTemplateSpecialization: {
7019 const auto *Spec = cast<ClassTemplateSpecializationDecl>(
D);
7021 if (Spec->getSpecializationKind() ==
7023 Spec->hasDefinition())
7024 DI->completeTemplateDefinition(*Spec);
7026 case Decl::CXXRecord: {
7033 DI->completeUnusedClass(*CRD);
7036 for (
auto *I : CRD->
decls())
7037 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
7042 case Decl::UsingShadow:
7043 case Decl::ClassTemplate:
7044 case Decl::VarTemplate:
7046 case Decl::VarTemplatePartialSpecialization:
7047 case Decl::FunctionTemplate:
7048 case Decl::TypeAliasTemplate:
7055 DI->EmitUsingDecl(cast<UsingDecl>(*
D));
7057 case Decl::UsingEnum:
7059 DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*
D));
7061 case Decl::NamespaceAlias:
7063 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*
D));
7065 case Decl::UsingDirective:
7067 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*
D));
7069 case Decl::CXXConstructor:
7072 case Decl::CXXDestructor:
7076 case Decl::StaticAssert:
7083 case Decl::ObjCInterface:
7084 case Decl::ObjCCategory:
7087 case Decl::ObjCProtocol: {
7088 auto *Proto = cast<ObjCProtocolDecl>(
D);
7089 if (Proto->isThisDeclarationADefinition())
7094 case Decl::ObjCCategoryImpl:
7097 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(
D));
7100 case Decl::ObjCImplementation: {
7101 auto *OMD = cast<ObjCImplementationDecl>(
D);
7102 EmitObjCPropertyImplementations(OMD);
7103 EmitObjCIvarInitializations(OMD);
7108 DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
7109 OMD->getClassInterface()), OMD->getLocation());
7112 case Decl::ObjCMethod: {
7113 auto *OMD = cast<ObjCMethodDecl>(
D);
7119 case Decl::ObjCCompatibleAlias:
7120 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(
D));
7123 case Decl::PragmaComment: {
7124 const auto *PCD = cast<PragmaCommentDecl>(
D);
7125 switch (PCD->getCommentKind()) {
7127 llvm_unreachable(
"unexpected pragma comment kind");
7142 case Decl::PragmaDetectMismatch: {
7143 const auto *PDMD = cast<PragmaDetectMismatchDecl>(
D);
7148 case Decl::LinkageSpec:
7149 EmitLinkageSpec(cast<LinkageSpecDecl>(
D));
7152 case Decl::FileScopeAsm: {
7154 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7157 if (LangOpts.OpenMPIsTargetDevice)
7160 if (LangOpts.SYCLIsDevice)
7162 auto *AD = cast<FileScopeAsmDecl>(
D);
7163 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
7167 case Decl::TopLevelStmt:
7168 EmitTopLevelStmt(cast<TopLevelStmtDecl>(
D));
7171 case Decl::Import: {
7172 auto *Import = cast<ImportDecl>(
D);
7175 if (!ImportedModules.insert(Import->getImportedModule()))
7179 if (!Import->getImportedOwningModule()) {
7181 DI->EmitImportDecl(*Import);
7187 if (CXX20ModuleInits && Import->getImportedModule() &&
7188 Import->getImportedModule()->isNamedModule())
7197 Visited.insert(Import->getImportedModule());
7198 Stack.push_back(Import->getImportedModule());
7200 while (!Stack.empty()) {
7202 if (!EmittedModuleInitializers.insert(Mod).second)
7212 if (Submodule->IsExplicit)
7215 if (
Visited.insert(Submodule).second)
7216 Stack.push_back(Submodule);
7223 EmitDeclContext(cast<ExportDecl>(
D));
7226 case Decl::OMPThreadPrivate:
7230 case Decl::OMPAllocate:
7234 case Decl::OMPDeclareReduction:
7238 case Decl::OMPDeclareMapper:
7242 case Decl::OMPRequires:
7247 case Decl::TypeAlias:
7249 DI->EmitAndRetainType(
7250 getContext().getTypedefType(cast<TypedefNameDecl>(
D)));
7262 DI->EmitAndRetainType(
getContext().getEnumType(cast<EnumDecl>(
D)));
7265 case Decl::HLSLBuffer:
7273 assert(isa<TypeDecl>(
D) &&
"Unsupported decl kind");
7280 if (!CodeGenOpts.CoverageMapping)
7283 case Decl::CXXConversion:
7284 case Decl::CXXMethod:
7285 case Decl::Function:
7286 case Decl::ObjCMethod:
7287 case Decl::CXXConstructor:
7288 case Decl::CXXDestructor: {
7289 if (!cast<FunctionDecl>(
D)->doesThisDeclarationHaveABody())
7297 DeferredEmptyCoverageMappingDecls.try_emplace(
D,
true);
7307 if (!CodeGenOpts.CoverageMapping)
7309 if (
const auto *Fn = dyn_cast<FunctionDecl>(
D)) {
7310 if (Fn->isTemplateInstantiation())
7313 DeferredEmptyCoverageMappingDecls.insert_or_assign(
D,
false);
7321 for (
const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
7324 const Decl *
D = Entry.first;
7326 case Decl::CXXConversion:
7327 case Decl::CXXMethod:
7328 case Decl::Function:
7329 case Decl::ObjCMethod: {
7336 case Decl::CXXConstructor: {
7343 case Decl::CXXDestructor: {
7360 if (llvm::Function *F =
getModule().getFunction(
"main")) {
7361 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
7363 auto *GA = llvm::GlobalAlias::create(
"__main_void", F);
7364 GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
7373 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
7374 return llvm::ConstantInt::get(i64, PtrInt);
7378 llvm::NamedMDNode *&GlobalMetadata,
7380 llvm::GlobalValue *Addr) {
7381 if (!GlobalMetadata)
7383 CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
7386 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
7389 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
7392bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
7393 llvm::GlobalValue *CppFunc) {
7401 if (Elem == CppFunc)
7407 for (llvm::User *User : Elem->users()) {
7411 if (
auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
7412 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
7415 for (llvm::User *CEUser : ConstExpr->users()) {
7416 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
7417 IFuncs.push_back(IFunc);
7422 CEs.push_back(ConstExpr);
7423 }
else if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
7424 IFuncs.push_back(IFunc);
7436 for (llvm::GlobalIFunc *IFunc : IFuncs)
7437 IFunc->setResolver(
nullptr);
7438 for (llvm::ConstantExpr *ConstExpr : CEs)
7439 ConstExpr->destroyConstant();
7443 Elem->eraseFromParent();
7445 for (llvm::GlobalIFunc *IFunc : IFuncs) {
7450 llvm::FunctionType::get(IFunc->getType(),
false);
7451 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
7452 CppFunc->getName(), ResolverTy, {},
false);
7453 IFunc->setResolver(Resolver);
7463void CodeGenModule::EmitStaticExternCAliases() {
7466 for (
auto &I : StaticExternCValues) {
7468 llvm::GlobalValue *Val = I.second;
7476 llvm::GlobalValue *ExistingElem =
7477 getModule().getNamedValue(Name->getName());
7481 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
7488 auto Res = Manglings.find(MangledName);
7489 if (Res == Manglings.end())
7491 Result = Res->getValue();
7502void CodeGenModule::EmitDeclMetadata() {
7503 llvm::NamedMDNode *GlobalMetadata =
nullptr;
7505 for (
auto &I : MangledDeclNames) {
7506 llvm::GlobalValue *Addr =
getModule().getNamedValue(I.second);
7516void CodeGenFunction::EmitDeclMetadata() {
7517 if (LocalDeclMap.empty())
return;
7522 unsigned DeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
7524 llvm::NamedMDNode *GlobalMetadata =
nullptr;
7526 for (
auto &I : LocalDeclMap) {
7527 const Decl *
D = I.first;
7528 llvm::Value *Addr = I.second.emitRawPointer(*
this);
7529 if (
auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
7531 Alloca->setMetadata(
7532 DeclPtrKind, llvm::MDNode::get(
7533 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
7534 }
else if (
auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
7541void CodeGenModule::EmitVersionIdentMetadata() {
7542 llvm::NamedMDNode *IdentMetadata =
7543 TheModule.getOrInsertNamedMetadata(
"llvm.ident");
7545 llvm::LLVMContext &Ctx = TheModule.getContext();
7547 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
7548 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
7551void CodeGenModule::EmitCommandLineMetadata() {
7552 llvm::NamedMDNode *CommandLineMetadata =
7553 TheModule.getOrInsertNamedMetadata(
"llvm.commandline");
7555 llvm::LLVMContext &Ctx = TheModule.getContext();
7557 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
7558 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
7561void CodeGenModule::EmitCoverageFile() {
7562 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu");
7566 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
7567 llvm::LLVMContext &Ctx = TheModule.getContext();
7568 auto *CoverageDataFile =
7570 auto *CoverageNotesFile =
7572 for (
int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
7573 llvm::MDNode *CU = CUNode->getOperand(i);
7574 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
7575 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
7596 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
7598 for (
auto RefExpr :
D->varlist()) {
7599 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
7601 VD->getAnyInitializer() &&
7602 !VD->getAnyInitializer()->isConstantInitializer(
getContext(),
7609 VD, Addr, RefExpr->getBeginLoc(), PerformInit))
7610 CXXGlobalInits.push_back(InitFunction);
7615CodeGenModule::CreateMetadataIdentifierImpl(
QualType T, MetadataTypeMap &Map,
7619 FnType->getReturnType(), FnType->getParamTypes(),
7620 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
7622 llvm::Metadata *&InternalId = Map[
T.getCanonicalType()];
7627 std::string OutName;
7628 llvm::raw_string_ostream Out(OutName);
7633 Out <<
".normalized";
7647 return CreateMetadataIdentifierImpl(
T, MetadataIdMap,
"");
7652 return CreateMetadataIdentifierImpl(
T, VirtualMetadataIdMap,
".virtual");
7672 for (
auto &Param : FnType->param_types())
7677 GeneralizedParams, FnType->getExtProtoInfo());
7684 llvm_unreachable(
"Encountered unknown FunctionType");
7689 GeneralizedMetadataIdMap,
".generalized");
7696 return ((LangOpts.
Sanitize.
has(SanitizerKind::CFIVCall) &&
7698 (LangOpts.
Sanitize.
has(SanitizerKind::CFINVCall) &&
7700 (LangOpts.
Sanitize.
has(SanitizerKind::CFIDerivedCast) &&
7702 (LangOpts.
Sanitize.
has(SanitizerKind::CFIUnrelatedCast) &&
7709 llvm::Metadata *MD =
7711 VTable->addTypeMetadata(Offset.getQuantity(), MD);
7713 if (CodeGenOpts.SanitizeCfiCrossDso)
7715 VTable->addTypeMetadata(Offset.getQuantity(),
7716 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
7719 llvm::Metadata *MD = llvm::MDString::get(
getLLVMContext(),
"all-vtables");
7720 VTable->addTypeMetadata(Offset.getQuantity(), MD);
7726 SanStats = std::make_unique<llvm::SanitizerStatReport>(&
getModule());
7736 auto *FTy = llvm::FunctionType::get(SamplerT, {
C->getType()},
false);
7751 bool forPointeeType) {
7762 if (
auto Align = TT->getDecl()->getMaxAlignment()) {
7792 if (
T.getQualifiers().hasUnaligned()) {
7794 }
else if (forPointeeType && !AlignForArray &&
7806 if (
unsigned MaxAlign =
getLangOpts().MaxTypeAlign) {
7819 if (NumAutoVarInit >= StopAfter) {
7822 if (!NumAutoVarInit) {
7825 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
7826 "number of times ftrivial-auto-var-init=%1 gets applied.");
7840 const Decl *
D)
const {
7844 OS << (isa<VarDecl>(
D) ?
".static." :
".intern.");
7846 OS << (isa<VarDecl>(
D) ?
"__static__" :
"__intern__");
7852 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
7856 llvm::MD5::MD5Result
Result;
7857 for (
const auto &Arg : PreprocessorOpts.
Macros)
7858 Hash.update(Arg.first);
7862 llvm::sys::fs::UniqueID ID;
7863 if (llvm::sys::fs::getUniqueID(PLoc.
getFilename(), ID)) {
7865 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
7866 if (
auto EC = llvm::sys::fs::getUniqueID(PLoc.
getFilename(), ID))
7867 SM.getDiagnostics().Report(diag::err_cannot_open_file)
7870 OS << llvm::format(
"%x", ID.getFile()) << llvm::format(
"%x", ID.getDevice())
7871 <<
"_" << llvm::utohexstr(
Result.low(),
true, 8);
7878 assert(DeferredDeclsToEmit.empty() &&
7879 "Should have emitted all decls deferred to emit.");
7880 assert(NewBuilder->DeferredDecls.empty() &&
7881 "Newly created module should not have deferred decls");
7882 NewBuilder->DeferredDecls = std::move(DeferredDecls);
7883 assert(EmittedDeferredDecls.empty() &&
7884 "Still have (unmerged) EmittedDeferredDecls deferred decls");
7886 assert(NewBuilder->DeferredVTables.empty() &&
7887 "Newly created module should not have deferred vtables");
7888 NewBuilder->DeferredVTables = std::move(DeferredVTables);
7890 assert(NewBuilder->MangledDeclNames.empty() &&
7891 "Newly created module should not have mangled decl names");
7892 assert(NewBuilder->Manglings.empty() &&
7893 "Newly created module should not have manglings");
7894 NewBuilder->Manglings = std::move(Manglings);
7896 NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
7898 NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
Defines the clang::ASTContext interface.
ASTImporterLookupTable & LT
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines the Diagnostic-related interfaces.
Defines enum values for all the target-independent builtin functions.
static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, const CPUSpecificAttr *Attr, unsigned CPUIndex, raw_ostream &Out)
static unsigned getFMVPriority(const TargetInfo &TI, const CodeGenFunction::FMVResolverOption &RO)
static bool AllTrivialInitializers(CodeGenModule &CGM, ObjCImplementationDecl *D)
static const FunctionDecl * GetRuntimeFunctionDecl(ASTContext &C, StringRef Name)
static void checkAliasForTocData(llvm::GlobalVariable *GVar, const CodeGenOptions &CodeGenOpts, DiagnosticsEngine &Diags, SourceLocation Location)
static bool hasImplicitAttr(const ValueDecl *D)
static void emitUsed(CodeGenModule &CGM, StringRef Name, std::vector< llvm::WeakTrackingVH > &List)
static bool HasNonDllImportDtor(QualType T)
static llvm::Constant * GetPointerConstant(llvm::LLVMContext &Context, const void *Ptr)
Turns the given pointer into a constant.
static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S)
static llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM, GlobalDecl GD)
static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO, llvm::Module &M)
static std::string getCPUSpecificMangling(const CodeGenModule &CGM, StringRef Name)
static void setWindowsItaniumDLLImport(CodeGenModule &CGM, bool Local, llvm::Function *F, StringRef Name)
static const char AnnotationSection[]
static bool isUniqueInternalLinkageDecl(GlobalDecl GD, CodeGenModule &CGM)
static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty)
static bool allowKCFIIdentifier(StringRef Name)
static bool shouldAssumeDSOLocal(const CodeGenModule &CGM, llvm::GlobalValue *GV)
static void replaceUsesOfNonProtoConstant(llvm::Constant *old, llvm::Function *newFn)
Replace the uses of a function that was declared with a non-proto type.
static llvm::Constant * castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, llvm::GlobalVariable *GV)
static bool needsDestructMethod(ObjCImplementationDecl *impl)
static bool isStackProtectorOn(const LangOptions &LangOpts, const llvm::Triple &Triple, clang::LangOptions::StackProtectorMode Mode)
static void removeImageAccessQualifier(std::string &TyName)
static llvm::StringMapEntry< llvm::GlobalVariable * > & GetConstantCFStringEntry(llvm::StringMap< llvm::GlobalVariable * > &Map, const StringLiteral *Literal, bool TargetIsLSB, bool &IsUTF16, unsigned &StringLength)
static void setLLVMVisibility(llvm::GlobalValue &GV, std::optional< llvm::GlobalValue::VisibilityTypes > V)
static llvm::GlobalVariable * GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, CodeGenModule &CGM, StringRef GlobalName, CharUnits Alignment)
static bool hasUnwindExceptions(const LangOptions &LangOpts)
Determines whether the language options require us to model unwind exceptions.
static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, SmallVectorImpl< llvm::MDNode * > &Metadata, llvm::SmallPtrSet< Module *, 16 > &Visited)
Add link options implied by the given module, including modules it depends on, using a postorder walk...
static llvm::cl::opt< bool > LimitedCoverage("limited-coverage-experimental", llvm::cl::Hidden, llvm::cl::desc("Emit limited coverage mapping information (experimental)"))
static CGCXXABI * createCXXABI(CodeGenModule &CGM)
static std::unique_ptr< TargetCodeGenInfo > createTargetCodeGenInfo(CodeGenModule &CGM)
static const llvm::GlobalValue * getAliasedGlobal(const llvm::GlobalValue *GV)
static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D)
static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD, const NamedDecl *ND, bool OmitMultiVersionMangling=false)
static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND)
static unsigned ArgInfoAddressSpace(LangAS AS)
static void replaceDeclarationWith(llvm::GlobalValue *Old, llvm::Constant *New)
static QualType GeneralizeType(ASTContext &Ctx, QualType Ty)
static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, llvm::Function *NewFn)
ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we implement a function with...
static bool isVarDeclStrongDefinition(const ASTContext &Context, CodeGenModule &CGM, const VarDecl *D, bool NoCommon)
static std::optional< llvm::GlobalValue::VisibilityTypes > getLLVMVisibility(clang::LangOptions::VisibilityFromDLLStorageClassKinds K)
static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, const CXXMethodDecl *MD)
static bool checkAliasedGlobal(const ASTContext &Context, DiagnosticsEngine &Diags, SourceLocation Location, bool IsIFunc, const llvm::GlobalValue *Alias, const llvm::GlobalValue *&GV, const llvm::MapVector< GlobalDecl, StringRef > &MangledDeclNames, SourceRange AliasRange)
static void EmitGlobalDeclMetadata(CodeGenModule &CGM, llvm::NamedMDNode *&GlobalMetadata, GlobalDecl D, llvm::GlobalValue *Addr)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
llvm::DenseSet< const void * > Visited
llvm::MachO::Target Target
llvm::MachO::Record Record
Defines the clang::Module class, which describes a module in the source code.
static const RecordType * getRecordType(QualType QT)
Checks that the passed in QualType either is of RecordType or points to RecordType.
static const NamedDecl * getDefinition(const Decl *D)
Defines the SourceManager interface.
static CharUnits getTypeAllocSize(CodeGenModule &CGM, llvm::Type *type)
Defines version macros and version-related utility functions for Clang.
__device__ __2f16 float __ockl_bool s
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
SourceManager & getSourceManager()
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
@ Strong
Strong definition.
@ WeakUnknown
Weak for now, might become strong later in this TU.
const ProfileList & getProfileList() const
llvm::StringMap< SectionInfo > SectionInfos
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
QualType getRecordType(const RecordDecl *Decl) const
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
FullSourceLoc getFullLoc(SourceLocation Loc) const
const XRayFunctionFilter & getXRayFilter() const
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=RecordDecl::TagKind::Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
StringRef getCUIDHash() const
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
Builtin::Context & BuiltinInfo
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
SelectorTable & Selectors
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
llvm::SetVector< const ValueDecl * > CUDAExternalDeviceDeclODRUsedByHost
Keep track of CUDA/HIP external kernels or device variables ODR-used by host code.
QualType getCFConstantStringType() const
Return the C structure type used to represent constant CFStrings.
const NoSanitizeList & getNoSanitizeList() const
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
CanQualType UnsignedLongTy
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
const clang::PrintingPolicy & getPrintingPolicy() const
CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const
Return the alignment in characters that should be given to a global variable with type T.
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
QualType getObjCIdType() const
Represents the Objective-CC id type.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
unsigned getTypeAlignIfKnown(QualType T, bool NeedsPreferredAlignment=false) const
Return the alignment of a type, in bits, or 0 if the type is incomplete and we cannot determine the a...
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
const TargetInfo & getTargetInfo() const
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
unsigned getTargetAddressSpace(LangAS AS) const
QualType getWideCharType() const
Return the type of wide characters.
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
Module * getCurrentNamedModule() const
Get module under construction, nullptr if this is not a C++20 module.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Attr - This represents one attribute.
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
bool isLibFunction(unsigned ID) const
Return true if this is a builtin for a libc/libm function, with a "__builtin_" prefix (e....
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Represents a base class of a C++ class.
Represents binding an expression to a temporary.
Represents a call to a C++ constructor.
Represents a C++ base or member initializer.
Expr * getInit() const
Get the initializer.
Represents a delete expression for memory deallocation and destructor calls, e.g.
Represents a C++ destructor within a class.
Represents a call to a member function that may be written either with member call syntax (e....
Represents a static or instance method of a struct/union/class.
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Represents a C++ struct/union/class.
bool hasMutableFields() const
Determine whether this class, or any of its class subobjects, contains a mutable field.
unsigned getNumBases() const
Retrieves the number of base classes of this class.
bool hasDefinition() const
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
CanProxy< U > castAs() const
CharUnits - This is an opaque type for sizes expressed in character units.
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
static CharUnits One()
One - Construct a CharUnits quantity of one.
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::string RecordCommandLine
The string containing the commandline for the llvm.commandline metadata, if non-empty.
std::string FloatABI
The ABI to use for passing floating point arguments.
llvm::Reloc::Model RelocationModel
The name of the relocation model to use.
std::string CoverageNotesFile
The filename with path we use for coverage notes files.
std::string ProfileInstrumentUsePath
Name of the profile file to use as input for -fprofile-instr-use.
std::string MemoryProfileOutput
Name of the profile file to use as output for with -fmemory-profile.
std::vector< std::string > TocDataVarsUserSpecified
List of global variables explicitly specified by the user as toc-data.
std::string CoverageDataFile
The filename with path we use for coverage data files.
PointerAuthOptions PointerAuth
Configuration for pointer-signing.
llvm::DenormalMode FP32DenormalMode
The floating-point denormal mode to use, for float.
SanitizerSet SanitizeTrap
Set of sanitizer checks that trap rather than diagnose.
std::string ProfileRemappingFile
Name of the profile remapping file to apply to the profile data supplied by -fprofile-sample-use or -...
bool hasProfileClangUse() const
Check if Clang profile use is on.
std::string SymbolPartition
The name of the partition that symbols are assigned to, specified with -fsymbol-partition (see https:...
ABIInfo - Target specific hooks for defining how a type should be passed or returned from functions.
virtual void appendAttributeMangling(TargetAttr *Attr, raw_ostream &Out) const
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
virtual void handleVarRegistration(const VarDecl *VD, llvm::GlobalVariable &Var)=0
Check whether a variable is a device variable and register it if true.
virtual llvm::GlobalValue * getKernelHandle(llvm::Function *Stub, GlobalDecl GD)=0
Get kernel handle by stub function.
virtual void internalizeDeviceSideVar(const VarDecl *D, llvm::GlobalValue::LinkageTypes &Linkage)=0
Adjust linkage of shadow variables in host compilation.
Implements C++ ABI-specific code generation functions.
virtual void EmitCXXConstructors(const CXXConstructorDecl *D)=0
Emit constructor variants required by this ABI.
virtual llvm::Constant * getAddrOfRTTIDescriptor(QualType Ty)=0
virtual void EmitCXXDestructors(const CXXDestructorDecl *D)=0
Emit destructor variants required by this ABI.
virtual void setCXXDestructorDLLStorage(llvm::GlobalValue *GV, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
virtual llvm::GlobalValue::LinkageTypes getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
MangleContext & getMangleContext()
Gets the mangle context.
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
void AddStringLiteralDebugInfo(llvm::GlobalVariable *GV, const StringLiteral *S)
DebugInfo isn't attached to string literals by default.
CGFunctionInfo - Class to encapsulate the information about a function definition.
void handleGlobalVarDefinition(const VarDecl *VD, llvm::GlobalVariable *Var)
void addBuffer(const HLSLBufferDecl *D)
llvm::Type * getSamplerType(const Type *T)
void emitDeferredTargetDecls() const
Emit deferred declare target variables marked for deferred emission.
virtual void emitDeclareTargetFunction(const FunctionDecl *FD, llvm::GlobalValue *GV)
Emit code for handling declare target functions in the runtime.
virtual ConstantAddress getAddrOfDeclareTargetVar(const VarDecl *VD)
Returns the address of the variable marked as declare target with link clause OR as declare target wi...
bool hasRequiresUnifiedSharedMemory() const
Return whether the unified_shared_memory has been specified.
virtual void emitDeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn)
Marks function Fn with properly mangled versions of vector functions.
virtual void registerTargetGlobalVariable(const VarDecl *VD, llvm::Constant *Addr)
Checks if the provided global decl GD is a declare target variable and registers it when emitting cod...
Class supports emissionof SIMD-only code.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, ObjCMethodDecl *MD, bool ctor)
void GenerateObjCMethod(const ObjCMethodDecl *OMD)
void EmitCfiCheckStub()
Emit a stub for the cross-DSO CFI check function.
void EmitCfiCheckFail()
Emit a cross-DSO CFI failure handling function.
bool isTrivialInitializer(const Expr *Init)
Determine whether the given initializer is trivial in the sense that it requires no code to be genera...
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
void GenerateObjCSetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCSetter - Synthesize an Objective-C property setter function for the given property.
void GenerateObjCGetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCGetter - Synthesize an Objective-C property getter function.
llvm::LLVMContext & getLLVMContext()
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
This class organizes the cross-function state that is used while generating LLVM code.
StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD)
ConstantAddress GetAddrOfMSGuidDecl(const MSGuidDecl *GD)
Get the address of a GUID.
void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const
Set visibility, dllimport/dllexport and dso_local.
void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD)
Create and attach type metadata for the given vtable.
void UpdateCompletedType(const TagDecl *TD)
llvm::MDNode * getTBAAAccessTagInfo(TBAAAccessInfo Info)
getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
llvm::GlobalVariable::ThreadLocalMode GetDefaultLLVMTLSModel() const
Get LLVM TLS mode from CodeGenOptions.
void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F, const CGFunctionInfo &FI)
Set the attributes on the LLVM function for the given decl and function info.
void setDSOLocal(llvm::GlobalValue *GV) const
llvm::MDNode * getTBAAStructInfo(QualType QTy)
CGHLSLRuntime & getHLSLRuntime()
Return a reference to the configured HLSL runtime.
llvm::Constant * EmitAnnotationArgs(const AnnotateAttr *Attr)
Emit additional args of the annotation.
llvm::Module & getModule() const
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
CGDebugInfo * getModuleDebugInfo()
bool NeedAllVtablesTypeId() const
Returns whether this module needs the "all-vtables" type identifier.
void addCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
CodeGenVTables & getVTables()
llvm::ConstantInt * CreateCrossDsoCfiTypeId(llvm::Metadata *MD)
Generate a cross-DSO type identifier for MD.
CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const
Return the store size, in character units, of the given LLVM type.
bool getExpressionLocationsEnabled() const
Return true if we should emit location information for expressions.
void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C)
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
void setGVPropertiesAux(llvm::GlobalValue *GV, const NamedDecl *D) const
const ABIInfo & getABIInfo()
void EmitMainVoidAlias()
Emit an alias for "main" if it has no arguments (needed for wasm).
void DecorateInstructionWithInvariantGroup(llvm::Instruction *I, const CXXRecordDecl *RD)
Adds !invariant.barrier !tag to instruction.
DiagnosticsEngine & getDiags() const
bool isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, SourceLocation Loc) const
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
llvm::Constant * getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the constructor/destructor of the given type.
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
llvm::Constant * EmitAnnotateAttr(llvm::GlobalValue *GV, const AnnotateAttr *AA, SourceLocation L)
Generate the llvm::ConstantStruct which contains the annotation information for a given GlobalValue.
llvm::GlobalValue::LinkageTypes getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage)
Returns LLVM linkage for a declarator.
TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, TBAAAccessInfo SrcInfo)
mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the purposes of memory transfer call...
const LangOptions & getLangOpts() const
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
llvm::Constant * EmitAnnotationLineNo(SourceLocation L)
Emit the annotation line number.
QualType getObjCFastEnumerationStateType()
Retrieve the record type that describes the state of an Objective-C fast enumeration loop (for....
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
CodeGenTypes & getTypes()
bool shouldMapVisibilityToDLLExport(const NamedDecl *D) const
CGOpenCLRuntime & getOpenCLRuntime()
Return a reference to the configured OpenCL runtime.
const std::string & getModuleNameHash() const
const TargetInfo & getTarget() const
bool shouldEmitRTTI(bool ForEH=false)
void EmitGlobal(GlobalDecl D)
Emit code for a single global function or var decl.
llvm::Metadata * CreateMetadataIdentifierForType(QualType T)
Create a metadata identifier for the given type.
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
void AppendLinkerOptions(StringRef Opts)
Appends Opts to the "llvm.linker.options" metadata value.
void EmitExternalDeclaration(const DeclaratorDecl *D)
void AddDependentLib(StringRef Lib)
Appends a dependent lib to the appropriate metadata value.
void Release()
Finalize LLVM code generation.
ProfileList::ExclusionType isFunctionBlockedByProfileList(llvm::Function *Fn, SourceLocation Loc) const
llvm::MDNode * getTBAABaseTypeInfo(QualType QTy)
getTBAABaseTypeInfo - Get metadata that describes the given base access type.
bool lookupRepresentativeDecl(StringRef MangledName, GlobalDecl &Result) const
void EmitOMPAllocateDecl(const OMPAllocateDecl *D)
Emit a code for the allocate directive.
void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const
Set the visibility for the given LLVM GlobalValue.
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD)
Returns LLVM linkage for a declarator.
bool HasHiddenLTOVisibility(const CXXRecordDecl *RD)
Returns whether the given record has hidden LTO visibility and therefore may participate in (single-m...
const llvm::DataLayout & getDataLayout() const
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can't be done.
TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType)
getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an access to a virtual table poi...
CGCXXABI & getCXXABI() const
ConstantAddress GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
llvm::Constant * GetFunctionStart(const ValueDecl *Decl)
static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V)
void EmitTentativeDefinition(const VarDecl *D)
void EmitDeferredUnusedCoverageMappings()
Emit all the deferred coverage mappings for the uninstrumented functions.
void addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, StringRef Category=StringRef()) const
Imbue XRay attributes to a function, applying the always/never attribute lists in the process.
llvm::Metadata * CreateMetadataIdentifierGeneralized(QualType T)
Create a metadata identifier for the generalization of the given type.
void EmitGlobalAnnotations()
Emit all the global annotations.
CharUnits getClassPointerAlignment(const CXXRecordDecl *CD)
Returns the assumed alignment of an opaque pointer to the given class.
const llvm::Triple & getTriple() const
SmallVector< const CXXRecordDecl *, 0 > getMostBaseClasses(const CXXRecordDecl *RD)
Return a vector of most-base classes for RD.
void AddDeferredUnusedCoverageMapping(Decl *D)
Stored a deferred empty coverage mapping for an unused and thus uninstrumented top level declaration.
void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV)
If the declaration has internal linkage but is inside an extern "C" linkage specification,...
void DecorateInstructionWithTBAA(llvm::Instruction *Inst, TBAAAccessInfo TBAAInfo)
DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD)
void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535, bool IsDtorAttrFunc=false)
AddGlobalDtor - Add a function to the list that will be called when the module is unloaded.
llvm::Constant * CreateRuntimeVariable(llvm::Type *Ty, StringRef Name)
Create a new runtime global variable with the specified type and name.
void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info, CGCalleeInfo CalleeInfo, llvm::AttributeList &Attrs, unsigned &CallingConv, bool AttrOnCallSite, bool IsThunk)
Get the LLVM attributes and calling convention to use for a particular function type.
llvm::Constant * GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, LangAS AddrSpace, const VarDecl *D, ForDefinition_t IsForDefinition=NotForDefinition)
GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, create and return an llvm...
TBAAAccessInfo getTBAAAccessInfo(QualType AccessType)
getTBAAAccessInfo - Get TBAA information that describes an access to an object of the given type.
void setFunctionLinkage(GlobalDecl GD, llvm::Function *F)
llvm::Constant * GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition=NotForDefinition)
ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal)
Return a pointer to a constant CFString object for the given string.
ProfileList::ExclusionType isFunctionBlockedFromProfileInstr(llvm::Function *Fn, SourceLocation Loc) const
void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV)
Add global annotations that are set on D, for the global GV.
void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const
Set the TLS mode for the given LLVM GlobalValue for the thread-local variable declaration D.
ConstantAddress GetAddrOfConstantStringFromLiteral(const StringLiteral *S, StringRef Name=".str")
Return a pointer to a constant array for the given string literal.
ASTContext & getContext() const
ConstantAddress GetAddrOfTemplateParamObject(const TemplateParamObjectDecl *TPO)
Get the address of a template parameter object.
void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D)
Emit a code for threadprivate directive.
ConstantAddress GetAddrOfUnnamedGlobalConstantDecl(const UnnamedGlobalConstantDecl *GCD)
Get the address of a UnnamedGlobalConstant.
TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, TBAAAccessInfo TargetInfo)
mergeTBAAInfoForCast - Get merged TBAA information for the purposes of type casts.
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
llvm::SanitizerStatReport & getSanStats()
llvm::Constant * EmitAnnotationString(StringRef Str)
Emit an annotation string.
void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare mapper construct.
bool supportsCOMDAT() const
void RefreshTypeCacheForClass(const CXXRecordDecl *Class)
llvm::MDNode * getTBAATypeInfo(QualType QTy)
getTBAATypeInfo - Get metadata used to describe accesses to objects of the given type.
void EmitOMPRequiresDecl(const OMPRequiresDecl *D)
Emit a code for requires directive.
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD)
Tell the consumer that this variable has been instantiated.
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
llvm::Constant * GetConstantArrayFromStringLiteral(const StringLiteral *E)
Return a constant array for the given string.
void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV)
Set attributes which are common to any form of a global definition (alias, Objective-C method,...
std::optional< CharUnits > getOMPAllocateAlignment(const VarDecl *VD)
Return the alignment specified in an allocate directive, if present.
llvm::GlobalVariable * CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, llvm::Align Alignment)
Will return a global variable of the given type.
CharUnits getNaturalPointeeTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, TBAAAccessInfo InfoB)
mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the purposes of conditional ope...
llvm::LLVMContext & getLLVMContext()
llvm::GlobalValue * GetGlobalValue(StringRef Ref)
void GenKernelArgMetadata(llvm::Function *FN, const FunctionDecl *FD=nullptr, CodeGenFunction *CGF=nullptr)
OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument information in the program executab...
void CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, llvm::Function *F)
Create and attach type metadata to the given function.
void setKCFIType(const FunctionDecl *FD, llvm::Function *F)
Set type metadata to the given function.
void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO)
void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare reduction construct.
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
void AddDetectMismatch(StringRef Name, StringRef Value)
Appends a detect mismatch command to the linker options.
void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const
llvm::Value * createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF)
ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
LangAS GetGlobalConstantAddressSpace() const
Return the AST address space of constant literal, which is used to emit the constant literal as globa...
LangAS GetGlobalVarAddressSpace(const VarDecl *D)
Return the AST address space of the underlying global variable for D, as determined by its declaratio...
void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info, llvm::Function *F, bool IsThunk)
Set the LLVM function attributes (sext, zext, etc).
void addReplacement(StringRef Name, llvm::Constant *C)
llvm::ConstantInt * CreateKCFITypeId(QualType T)
Generate a KCFI type identifier for T.
llvm::Constant * getConstantSignedPointer(llvm::Constant *Pointer, const PointerAuthSchema &Schema, llvm::Constant *StorageAddress, GlobalDecl SchemaDecl, QualType SchemaType)
Sign a constant pointer using the given scheme, producing a constant with the same IR type.
void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535, unsigned LexOrder=~0U, llvm::Constant *AssociatedData=nullptr)
AddGlobalCtor - Add a function to the list that will be called before main() runs.
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
llvm::Metadata * CreateMetadataIdentifierForVirtualMemPtrType(QualType T)
Create a metadata identifier that is intended to be used to check virtual calls via a member function...
ConstantAddress GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *)
Return a pointer to a constant array for the given ObjCEncodeExpr node.
const GlobalDecl getMangledNameDecl(StringRef)
void ClearUnusedCoverageMapping(const Decl *D)
Remove the deferred empty coverage mapping as this declaration is actually instrumented.
void EmitTopLevelDecl(Decl *D)
Emit code for a single top level declaration.
llvm::Constant * EmitAnnotationUnit(SourceLocation Loc)
Emit the annotation's translation unit.
ConstantAddress GetAddrOfConstantCString(const std::string &Str, const char *GlobalName=nullptr)
Returns a pointer to a character array containing the literal and a terminating '\0' character.
void printPostfixForExternalizedDecl(llvm::raw_ostream &OS, const Decl *D) const
Print the postfix for externalized static variable or kernels for single source offloading languages ...
void moveLazyEmissionStates(CodeGenModule *NewBuilder)
Move some lazily-emitted states to the NewBuilder.
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
void finalizeKCFITypes()
Emit KCFI type identifier constants and remove unused identifiers.
void setValueProfilingFlag(llvm::Module &M)
void setProfileVersion(llvm::Module &M)
void emitEmptyCounterMapping(const Decl *D, StringRef FuncName, llvm::GlobalValue::LinkageTypes Linkage)
Emit a coverage mapping range with a counter zero for an unused declaration.
CodeGenTBAA - This class organizes the cross-module state that is used while lowering AST types to LL...
This class organizes the cross-module state that is used while lowering AST types to LLVM types.
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
const CGFunctionInfo & arrangeCXXMethodDeclaration(const CXXMethodDecl *MD)
C++ methods have some special rules and also have implicit parameters.
const CGFunctionInfo & arrangeFreeFunctionType(CanQual< FunctionProtoType > Ty)
Arrange the argument and result information for a value of the given freestanding function type.
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
unsigned getTargetAddressSpace(QualType T) const
void RefreshTypeCacheForClass(const CXXRecordDecl *RD)
Remove stale types from the type cache when an inheritance model gets assigned to a class.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
void UpdateCompletedType(const TagDecl *TD)
UpdateCompletedType - When we find the full definition for a TagDecl, replace the 'opaque' type we pr...
const CGFunctionInfo & arrangeGlobalDeclaration(GlobalDecl GD)
void GenerateClassData(const CXXRecordDecl *RD)
GenerateClassData - Generate all the class data required to be generated upon definition of a KeyFunc...
void EmitThunks(GlobalDecl GD)
EmitThunks - Emit the associated thunks for the given global decl.
A specialization of Address that requires the address to be an LLVM Constant.
static ConstantAddress invalid()
llvm::Constant * tryEmitForInitializer(const VarDecl &D)
Try to emit the initiaizer of the given declaration as an abstract constant.
void finalize(llvm::GlobalVariable *global)
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded.
The standard implementation of ConstantInitBuilder used in Clang.
Organizes the cross-function state that is used while generating code coverage mapping data.
FunctionArgList - Type for representing both the decl and type of parameters to a function.
bool hasDiagnostics()
Whether or not the stats we've gathered indicate any potential problems.
void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile)
Report potential problems we've found to Diags.
TargetCodeGenInfo - This class organizes various target-specific codegeneration issues,...
virtual void getDependentLibraryOption(llvm::StringRef Lib, llvm::SmallString< 24 > &Opt) const
Gets the linker options necessary to link a dependent library on this platform.
Address performAddrSpaceCast(CodeGen::CodeGenFunction &CGF, Address Addr, LangAS SrcAddr, LangAS DestAddr, llvm::Type *DestTy, bool IsNonNull=false) const
const T & getABIInfo() const
virtual LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, const VarDecl *D) const
Get target favored AST address space of a global variable for languages other than OpenCL and CUDA.
virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const
setTargetAttributes - Provides a convenient hook to handle extra target-specific attributes for the g...
virtual LangAS getASTAllocaAddressSpace() const
Get the AST address space for alloca.
virtual void emitTargetMetadata(CodeGen::CodeGenModule &CGM, const llvm::MapVector< GlobalDecl, StringRef > &MangledDeclNames) const
emitTargetMetadata - Provides a convenient hook to handle extra target-specific metadata for the give...
virtual void emitTargetGlobals(CodeGen::CodeGenModule &CGM) const
Provides a convenient hook to handle extra target-specific globals.
virtual void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, llvm::SmallString< 32 > &Opt) const
Gets the linker options necessary to detect object file mismatches on this platform.
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Represents the canonical version of C arrays with a specified constant size.
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Stores additional source code information like skipped ranges which is required by the coverage mappi...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
A reference to a declared variable, function, enum, etc.
Decl - This represents one declaration (or definition), e.g.
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
SourceLocation getEndLoc() const LLVM_READONLY
ASTContext & getASTContext() const LLVM_READONLY
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
const Attr * getDefiningAttr() const
Return this declaration's defining attribute if it has one.
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
SourceLocation getLocation() const
SourceLocation getBeginLoc() const LLVM_READONLY
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Represents a ValueDecl that came out of a declarator.
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
This represents one expression.
Represents a member of a struct/union/class.
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
StringRef getName() const
The name of this FileEntry.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Represents a function declaration or definition.
bool isTargetClonesMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target-clones functional...
bool isMultiVersion() const
True if this function is considered a multiversioned function.
const ParmVarDecl * getParamDecl(unsigned i) const
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
bool isImmediateFunction() const
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
bool isInlineBuiltinDeclaration() const
Determine if this function provides an inline implementation of a builtin.
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
FunctionDecl * getDefinition()
Get the definition for this declaration.
bool isTargetVersionMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target-version functiona...
bool isReplaceableGlobalAllocationFunction(std::optional< unsigned > *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
bool doesDeclarationForceExternallyVisibleDefinition() const
For a function declaration in C or C++, determine whether this declaration causes the definition to b...
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const override
Appends a human-readable name for this declaration into the given stream.
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Represents a prototype with parameter type info, e.g.
FunctionType - C99 6.7.5.3 - Function Declarators.
CallingConv getCallConv() const
GlobalDecl - represents a global declaration.
GlobalDecl getWithMultiVersionIndex(unsigned Index)
CXXCtorType getCtorType() const
GlobalDecl getWithKernelReferenceKind(KernelReferenceKind Kind)
GlobalDecl getCanonicalDecl() const
KernelReferenceKind getKernelReferenceKind() const
GlobalDecl getWithDecl(const Decl *D)
unsigned getMultiVersionIndex() const
CXXDtorType getDtorType() const
const Decl * getDecl() const
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
@ None
No signing for any function.
@ Swift5_0
Interoperability with the Swift 5.0 runtime.
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
VisibilityFromDLLStorageClassKinds
@ Keep
Keep the IR-gen assigned visibility.
@ Protected
Override the IR-gen assigned visibility with protected visibility.
@ Default
Override the IR-gen assigned visibility with default visibility.
@ Hidden
Override the IR-gen assigned visibility with hidden visibility.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
bool isSignReturnAddressWithAKey() const
Check if return address signing uses AKey.
clang::ObjCRuntime ObjCRuntime
CoreFoundationABI CFRuntime
SanitizerSet Sanitize
Set of enabled sanitizers.
bool hasSignReturnAddress() const
Check if return address signing is enabled.
std::map< std::string, std::string, std::greater< std::string > > MacroPrefixMap
A prefix map for FILE, BASE_FILE and __builtin_FILE().
LangStandard::Kind LangStd
The used language standard.
bool isSignReturnAddressScopeAll() const
Check if leaf functions are also signed.
std::string CUID
The user provided compilation unit ID, if non-empty.
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Visibility getVisibility() const
void setLinkage(Linkage L)
Linkage getLinkage() const
bool isVisibilityExplicit() const
Represents a linkage specification.
LinkageSpecLanguageIDs getLanguage() const
Return the language specified by this linkage specification.
Parts getParts() const
Get the decomposed parts of this declaration.
APValue & getAsAPValue() const
Get the value of this MSGuidDecl as an APValue.
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
void mangleBlock(const DeclContext *DC, const BlockDecl *BD, raw_ostream &Out)
void mangleCtorBlock(const CXXConstructorDecl *CD, CXXCtorType CT, const BlockDecl *BD, raw_ostream &Out)
void mangleGlobalBlock(const BlockDecl *BD, const NamedDecl *ID, raw_ostream &Out)
bool shouldMangleDeclName(const NamedDecl *D)
void mangleName(GlobalDecl GD, raw_ostream &)
virtual void mangleCanonicalTypeName(QualType T, raw_ostream &, bool NormalizeIntegers=false)=0
Generates a unique string for an externally visible type for use with TBAA or type uniquing.
virtual void mangleStringLiteral(const StringLiteral *SL, raw_ostream &)=0
ManglerKind getKind() const
virtual void needsUniqueInternalLinkageNames()
virtual void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber, raw_ostream &)=0
void mangleDtorBlock(const CXXDestructorDecl *CD, CXXDtorType DT, const BlockDecl *BD, raw_ostream &Out)
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Describes a module or submodule.
bool isInterfaceOrPartition() const
bool isNamedModuleUnit() const
Is this a C++20 named module unit.
Module * Parent
The parent of this module.
Module * getPrivateModuleFragment() const
Get the Private Module Fragment (sub-module) for this module, it there is one.
llvm::SmallSetVector< Module *, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Module * getGlobalModuleFragment() const
Get the Global Module Fragment (sub-module) for this module, it there is one.
llvm::iterator_range< submodule_iterator > submodules()
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used.
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
bool UseExportAsModuleLinkName
Autolinking uses the framework name for linking purposes when this is false and the export_as name ot...
This represents a decl that may have a name.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
LinkageInfo getLinkageAndVisibility() const
Determines the linkage and visibility of this entity.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Represent a C++ namespace.
This represents '#pragma omp threadprivate ...' directive.
ObjCEncodeExpr, used for @encode in Objective-C.
const ObjCInterfaceDecl * getClassInterface() const
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Represents an ObjC class declaration.
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
ObjCIvarDecl - Represents an ObjC instance variable.
ObjCIvarDecl * getNextIvar()
ObjCMethodDecl - Represents an instance or class method declaration.
static ObjCMethodDecl * Create(ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc, Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo, DeclContext *contextDecl, bool isInstance=true, bool isVariadic=false, bool isPropertyAccessor=false, bool isSynthesizedAccessorStub=false, bool isImplicitlyDeclared=false, bool isDefined=false, ObjCImplementationControl impControl=ObjCImplementationControl::None, bool HasRelatedResultType=false)
Represents one property declaration in an Objective-C interface.
ObjCMethodDecl * getGetterMethodDecl() const
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
The basic abstraction for the target Objective-C runtime.
bool hasUnwindExceptions() const
Does this runtime use zero-cost exceptions?
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
@ MacOSX
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
@ FragileMacOSX
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
@ GNUstep
'gnustep' is the modern non-fragile GNUstep runtime.
@ ObjFW
'objfw' is the Objective-C runtime included in ObjFW
@ iOS
'ios' is the Apple-provided NeXT-derived runtime on iOS or the iOS simulator; it is always non-fragil...
@ GCC
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI
@ WatchOS
'watchos' is a variant of iOS for Apple's watchOS.
Represents a parameter to a function.
ParsedAttr - Represents a syntactic attribute.
bool isAddressDiscriminated() const
uint16_t getConstantDiscrimination() const
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::optional< uint64_t > SourceDateEpoch
If set, the UNIX timestamp specified by SOURCE_DATE_EPOCH.
std::vector< std::pair< std::string, bool > > Macros
Represents an unpacked "presumed" location which can be presented to the user.
const char * getFilename() const
Return the presumed filename of this location.
unsigned getLine() const
Return the presumed line number of this location.
PrettyStackTraceDecl - If a crash occurs, indicate that it happened when doing something to a specifi...
std::optional< ExclusionType > isFunctionExcluded(StringRef FunctionName, CodeGenOptions::ProfileInstrKind Kind) const
std::optional< ExclusionType > isLocationExcluded(SourceLocation Loc, CodeGenOptions::ProfileInstrKind Kind) const
ExclusionType
Represents if an how something should be excluded from profiling.
@ Skip
Profiling is skipped using the skipprofile attribute.
@ Allow
Profiling is allowed.
ExclusionType getDefault(CodeGenOptions::ProfileInstrKind Kind) const
std::optional< ExclusionType > isFileExcluded(StringRef FileName, CodeGenOptions::ProfileInstrKind Kind) const
A (possibly-)qualified type.
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
LangAS getAddressSpace() const
Return the address space of this type.
QualType getCanonicalType() const
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
QualType withCVRQualifiers(unsigned CVR) const
bool isConstQualified() const
Determine whether this type is const-qualified.
bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Represents a struct/union/class.
field_range fields() const
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Selector getSelector(unsigned NumArgs, const IdentifierInfo **IIV)
Can create any sort of selector.
Smart pointer class that efficiently represents Objective-C method names.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Stmt - This represents one statement.
StringLiteral - This represents a string literal expression, e.g.
Represents the declaration of a struct/union/class/enum.
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Exposes information about the current target.
TargetOptions & getTargetOpts() const
Retrieve the target options.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
bool isReadOnlyFeature(StringRef Feature) const
Determine whether the given target feature is read only.
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
virtual unsigned getFMVPriority(ArrayRef< StringRef > Features) const
bool supportsIFunc() const
Identify whether this target supports IFuncs.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
std::string TuneCPU
If given, the name of the target CPU to tune code for.
std::string CPU
If given, the name of the target CPU to generate code for.
@ Hostcall
printf lowering scheme involving hostcalls, currently used by HIP programs by default
A template parameter object.
const APValue & getValue() const
A declaration that models statements at global scope.
The top declaration context.
static DeclContext * castToDeclContext(const TranslationUnitDecl *D)
const Type * getTypeForDecl() const
The base class of the type hierarchy.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
bool isPointerType() const
const T * castAs() const
Member-template castAs<specific type>.
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
bool isObjCObjectPointerType() const
Linkage getLinkage() const
Determine the linkage of this type.
const T * getAs() const
Member-template getAs<specific type>'.
bool isRecordType() const
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
const APValue & getValue() const
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Represents a variable declaration or definition.
TLSKind getTLSKind() const
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
bool hasFlexibleArrayInit(const ASTContext &Ctx) const
Whether this variable has a flexible array member initialized with one or more elements.
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
@ TLS_Dynamic
TLS with a dynamic initializer.
@ DeclarationOnly
This declaration is only a declaration.
@ Definition
This declaration is definitely a definition.
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Defines the clang::TargetInfo interface.
std::unique_ptr< TargetCodeGenInfo > createARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind Kind)
std::unique_ptr< TargetCodeGenInfo > createM68kTargetCodeGenInfo(CodeGenModule &CGM)
@ AttributedType
The l-value was considered opaque, so the alignment was determined from a type, but that type was an ...
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
std::unique_ptr< TargetCodeGenInfo > createBPFTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createMSP430TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel)
std::unique_ptr< TargetCodeGenInfo > createWebAssemblyTargetCodeGenInfo(CodeGenModule &CGM, WebAssemblyABIKind K)
std::unique_ptr< TargetCodeGenInfo > createPPC64_SVR4_TargetCodeGenInfo(CodeGenModule &CGM, PPC64_SVR4_ABIKind Kind, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createMIPSTargetCodeGenInfo(CodeGenModule &CGM, bool IsOS32)
std::unique_ptr< TargetCodeGenInfo > createHexagonTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createNVPTXTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createSystemZTargetCodeGenInfo(CodeGenModule &CGM, bool HasVector, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createWinX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters)
std::unique_ptr< TargetCodeGenInfo > createAIXTargetCodeGenInfo(CodeGenModule &CGM, bool Is64Bit)
std::unique_ptr< TargetCodeGenInfo > createAMDGPUTargetCodeGenInfo(CodeGenModule &CGM)
CGObjCRuntime * CreateMacObjCRuntime(CodeGenModule &CGM)
X86AVXABILevel
The AVX ABI level for X86 targets.
std::unique_ptr< TargetCodeGenInfo > createTCETargetCodeGenInfo(CodeGenModule &CGM)
CGObjCRuntime * CreateGNUObjCRuntime(CodeGenModule &CGM)
Creates an instance of an Objective-C runtime class.
std::unique_ptr< TargetCodeGenInfo > createWindowsARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind K)
std::unique_ptr< TargetCodeGenInfo > createAVRTargetCodeGenInfo(CodeGenModule &CGM, unsigned NPR, unsigned NRR)
std::unique_ptr< TargetCodeGenInfo > createDirectXTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createARCTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createDefaultTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind Kind)
std::unique_ptr< TargetCodeGenInfo > createSPIRVTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createSparcV8TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createVETargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createCommonSPIRTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createRISCVTargetCodeGenInfo(CodeGenModule &CGM, unsigned XLen, unsigned FLen, bool EABI)
std::unique_ptr< TargetCodeGenInfo > createWindowsAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind K)
std::unique_ptr< TargetCodeGenInfo > createSparcV9TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createPNaClTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createLanaiTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createPPC32TargetCodeGenInfo(CodeGenModule &CGM, bool SoftFloatABI)
CGCUDARuntime * CreateNVCUDARuntime(CodeGenModule &CGM)
Creates an instance of a CUDA runtime class.
std::unique_ptr< TargetCodeGenInfo > createLoongArchTargetCodeGenInfo(CodeGenModule &CGM, unsigned GRLen, unsigned FLen)
std::unique_ptr< TargetCodeGenInfo > createPPC64TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createWinX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel)
std::unique_ptr< TargetCodeGenInfo > createXCoreTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createCSKYTargetCodeGenInfo(CodeGenModule &CGM, unsigned FLen)
llvm::PointerUnion< const Decl *, const Expr * > DeclTy
The JSON file list parser is used to communicate input to InstallAPI.
CXXCtorType
C++ constructor types.
@ Ctor_Base
Base object ctor.
@ Ctor_Complete
Complete object ctor.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, DiagnosticsEngine &Diags)
GVALinkage
A more specific kind of linkage than enum Linkage.
@ GVA_AvailableExternally
std::string getClangVendor()
Retrieves the Clang vendor tag.
@ ICIS_NoInit
No in-class initializer.
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ Asm
Assembly: we accept this only so that we can preprocess it.
@ SD_Thread
Thread storage duration.
@ SD_Static
Static storage duration.
bool isLambdaCallOperator(const CXXMethodDecl *MD)
@ Result
The result type of a method or function.
StringRef languageToString(Language L)
@ Dtor_Base
Base object dtor.
@ Dtor_Complete
Complete object dtor.
LangAS
Defines the address space values used by the address space qualifier of QualType.
@ FirstTargetAddressSpace
static const char * getCFBranchLabelSchemeFlagVal(const CFBranchLabelSchemeKind Scheme)
const FunctionProtoType * T
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
bool isExternallyVisible(Linkage L)
@ EST_None
no exception specification
std::string getClangFullVersion()
Retrieves a string representing the complete clang version, which includes the clang version number,...
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
@ DefaultVisibility
Objects with "default" visibility are seen by the dynamic linker and act like normal objects.
cl::opt< bool > SystemHeadersCoverage
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
llvm::CallingConv::ID RuntimeCC
llvm::IntegerType * Int64Ty
llvm::PointerType * ConstGlobalsPtrTy
void* in the address space for constant globals
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::IntegerType * CharTy
char
LangAS ASTAllocaAddressSpace
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
unsigned char IntAlignInBytes
llvm::Type * HalfTy
half, bfloat, float, double
unsigned char SizeSizeInBytes
llvm::CallingConv::ID getRuntimeCC() const
llvm::IntegerType * SizeTy
llvm::PointerType * GlobalsInt8PtrTy
llvm::IntegerType * Int32Ty
llvm::IntegerType * IntPtrTy
llvm::IntegerType * IntTy
int
llvm::IntegerType * Int16Ty
unsigned char PointerAlignInBytes
llvm::PointerType * Int8PtrTy
CharUnits getPointerAlign() const
llvm::PointerType * AllocaInt8PtrTy
EvalResult is a struct with detailed info about an evaluated expression.
APValue Val
Val - This is the value the expression can be folded to.
bool hasSideEffects() const
Extra information about a function prototype.
static const LangStandard & getLangStandardForKind(Kind K)
Parts of a decomposed MSGuidDecl.
uint16_t Part2
...-89ab-...
uint32_t Part1
{01234567-...
uint16_t Part3
...-cdef-...
uint8_t Part4And5[8]
...-0123-456789abcdef}
A library or framework to link against when an entity from this module is used.
Contains information gathered from parsing the contents of TargetAttr.
PointerAuthSchema InitFiniPointers
The ABI for function addresses in .init_array and .fini_array.
Describes how types, statements, expressions, and declarations should be printed.
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
bool hasOneOf(SanitizerMask K) const
Check if one or more sanitizers are enabled.