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"
79using namespace CodeGen;
82 "limited-coverage-experimental", llvm::cl::Hidden,
83 llvm::cl::desc(
"Emit limited coverage mapping information (experimental)"));
89 case TargetCXXABI::AppleARM64:
90 case TargetCXXABI::Fuchsia:
91 case TargetCXXABI::GenericAArch64:
92 case TargetCXXABI::GenericARM:
93 case TargetCXXABI::iOS:
94 case TargetCXXABI::WatchOS:
95 case TargetCXXABI::GenericMIPS:
96 case TargetCXXABI::GenericItanium:
97 case TargetCXXABI::WebAssembly:
98 case TargetCXXABI::XL:
100 case TargetCXXABI::Microsoft:
104 llvm_unreachable(
"invalid C++ ABI kind");
107static std::unique_ptr<TargetCodeGenInfo>
113 switch (Triple.getArch()) {
117 case llvm::Triple::m68k:
119 case llvm::Triple::mips:
120 case llvm::Triple::mipsel:
121 if (Triple.getOS() == llvm::Triple::NaCl)
123 else if (Triple.getOS() == llvm::Triple::Win32)
127 case llvm::Triple::mips64:
128 case llvm::Triple::mips64el:
131 case llvm::Triple::avr: {
135 unsigned NPR =
Target.getABI() ==
"avrtiny" ? 6 : 18;
136 unsigned NRR =
Target.getABI() ==
"avrtiny" ? 4 : 8;
140 case llvm::Triple::aarch64:
141 case llvm::Triple::aarch64_32:
142 case llvm::Triple::aarch64_be: {
144 if (
Target.getABI() ==
"darwinpcs")
145 Kind = AArch64ABIKind::DarwinPCS;
146 else if (Triple.isOSWindows())
148 else if (
Target.getABI() ==
"aapcs-soft")
149 Kind = AArch64ABIKind::AAPCSSoft;
150 else if (
Target.getABI() ==
"pauthtest")
151 Kind = AArch64ABIKind::PAuthTest;
156 case llvm::Triple::wasm32:
157 case llvm::Triple::wasm64: {
159 if (
Target.getABI() ==
"experimental-mv")
160 Kind = WebAssemblyABIKind::ExperimentalMV;
164 case llvm::Triple::arm:
165 case llvm::Triple::armeb:
166 case llvm::Triple::thumb:
167 case llvm::Triple::thumbeb: {
168 if (Triple.getOS() == llvm::Triple::Win32)
172 StringRef ABIStr =
Target.getABI();
173 if (ABIStr ==
"apcs-gnu")
174 Kind = ARMABIKind::APCS;
175 else if (ABIStr ==
"aapcs16")
176 Kind = ARMABIKind::AAPCS16_VFP;
177 else if (CodeGenOpts.
FloatABI ==
"hard" ||
178 (CodeGenOpts.
FloatABI !=
"soft" && Triple.isHardFloatABI()))
179 Kind = ARMABIKind::AAPCS_VFP;
184 case llvm::Triple::ppc: {
185 if (Triple.isOSAIX())
192 case llvm::Triple::ppcle: {
193 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
196 case llvm::Triple::ppc64:
197 if (Triple.isOSAIX())
200 if (Triple.isOSBinFormatELF()) {
202 if (
Target.getABI() ==
"elfv2")
203 Kind = PPC64_SVR4_ABIKind::ELFv2;
204 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
209 case llvm::Triple::ppc64le: {
210 assert(Triple.isOSBinFormatELF() &&
"PPC64 LE non-ELF not supported!");
212 if (
Target.getABI() ==
"elfv1")
213 Kind = PPC64_SVR4_ABIKind::ELFv1;
214 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
219 case llvm::Triple::nvptx:
220 case llvm::Triple::nvptx64:
223 case llvm::Triple::msp430:
226 case llvm::Triple::riscv32:
227 case llvm::Triple::riscv64: {
228 StringRef ABIStr =
Target.getABI();
229 unsigned XLen =
Target.getPointerWidth(LangAS::Default);
230 unsigned ABIFLen = 0;
231 if (ABIStr.ends_with(
"f"))
233 else if (ABIStr.ends_with(
"d"))
235 bool EABI = ABIStr.ends_with(
"e");
239 case llvm::Triple::systemz: {
240 bool SoftFloat = CodeGenOpts.
FloatABI ==
"soft";
241 bool HasVector = !SoftFloat &&
Target.getABI() ==
"vector";
245 case llvm::Triple::tce:
246 case llvm::Triple::tcele:
249 case llvm::Triple::x86: {
250 bool IsDarwinVectorABI = Triple.isOSDarwin();
251 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
253 if (Triple.getOS() == llvm::Triple::Win32) {
255 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
256 CodeGenOpts.NumRegisterParameters);
259 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
260 CodeGenOpts.NumRegisterParameters, CodeGenOpts.
FloatABI ==
"soft");
263 case llvm::Triple::x86_64: {
264 StringRef ABI =
Target.getABI();
265 X86AVXABILevel AVXLevel = (ABI ==
"avx512" ? X86AVXABILevel::AVX512
266 : ABI ==
"avx" ? X86AVXABILevel::AVX
267 : X86AVXABILevel::None);
269 switch (Triple.getOS()) {
270 case llvm::Triple::Win32:
276 case llvm::Triple::hexagon:
278 case llvm::Triple::lanai:
280 case llvm::Triple::r600:
282 case llvm::Triple::amdgcn:
284 case llvm::Triple::sparc:
286 case llvm::Triple::sparcv9:
288 case llvm::Triple::xcore:
290 case llvm::Triple::arc:
292 case llvm::Triple::spir:
293 case llvm::Triple::spir64:
295 case llvm::Triple::spirv32:
296 case llvm::Triple::spirv64:
297 case llvm::Triple::spirv:
299 case llvm::Triple::dxil:
301 case llvm::Triple::ve:
303 case llvm::Triple::csky: {
304 bool IsSoftFloat = !
Target.hasFeature(
"hard-float-abi");
306 Target.hasFeature(
"fpuv2_df") ||
Target.hasFeature(
"fpuv3_df");
311 case llvm::Triple::bpfeb:
312 case llvm::Triple::bpfel:
314 case llvm::Triple::loongarch32:
315 case llvm::Triple::loongarch64: {
316 StringRef ABIStr =
Target.getABI();
317 unsigned ABIFRLen = 0;
318 if (ABIStr.ends_with(
"f"))
320 else if (ABIStr.ends_with(
"d"))
323 CGM,
Target.getPointerWidth(LangAS::Default), ABIFRLen);
329 if (!TheTargetCodeGenInfo)
331 return *TheTargetCodeGenInfo;
341 : Context(
C), LangOpts(
C.getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
342 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
344 VMContext(M.getContext()), VTables(*this), StackHandler(diags),
349 llvm::LLVMContext &LLVMContext = M.getContext();
350 VoidTy = llvm::Type::getVoidTy(LLVMContext);
351 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
352 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
353 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
354 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
355 HalfTy = llvm::Type::getHalfTy(LLVMContext);
356 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
357 FloatTy = llvm::Type::getFloatTy(LLVMContext);
358 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
364 C.toCharUnitsFromBits(
C.getTargetInfo().getMaxPointerWidth()).getQuantity();
366 C.toCharUnitsFromBits(
C.getTargetInfo().getIntAlign()).getQuantity();
368 llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getCharWidth());
369 IntTy = llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getIntWidth());
370 IntPtrTy = llvm::IntegerType::get(LLVMContext,
371 C.getTargetInfo().getMaxPointerWidth());
372 Int8PtrTy = llvm::PointerType::get(LLVMContext,
374 const llvm::DataLayout &DL = M.getDataLayout();
376 llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
378 llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
395 createOpenCLRuntime();
397 createOpenMPRuntime();
404 if (LangOpts.
Sanitize.
hasOneOf(SanitizerKind::Thread | SanitizerKind::Type) ||
405 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
411 if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
416 Block.GlobalUniqueCount = 0;
418 if (
C.getLangOpts().ObjC)
422 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
429 PGOReader = std::move(ReaderOrErr.get());
434 if (CodeGenOpts.CoverageMapping)
438 if (CodeGenOpts.UniqueInternalLinkageNames &&
439 !
getModule().getSourceFileName().empty()) {
443 if (
Path.rfind(Entry.first, 0) != std::string::npos) {
444 Path = Entry.second +
Path.substr(Entry.first.size());
447 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(
Path);
452 getModule().addModuleFlag(llvm::Module::Error,
"NumRegisterParameters",
453 CodeGenOpts.NumRegisterParameters);
458void CodeGenModule::createObjCRuntime() {
475 llvm_unreachable(
"bad runtime kind");
478void CodeGenModule::createOpenCLRuntime() {
482void CodeGenModule::createOpenMPRuntime() {
486 case llvm::Triple::nvptx:
487 case llvm::Triple::nvptx64:
488 case llvm::Triple::amdgcn:
490 "OpenMP AMDGPU/NVPTX is only prepared to deal with device code.");
494 if (LangOpts.OpenMPSimd)
502void CodeGenModule::createCUDARuntime() {
506void CodeGenModule::createHLSLRuntime() {
511 Replacements[Name] =
C;
514void CodeGenModule::applyReplacements() {
515 for (
auto &I : Replacements) {
516 StringRef MangledName = I.first;
517 llvm::Constant *Replacement = I.second;
521 auto *OldF = cast<llvm::Function>(Entry);
522 auto *NewF = dyn_cast<llvm::Function>(Replacement);
524 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
525 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
527 auto *CE = cast<llvm::ConstantExpr>(Replacement);
528 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
529 CE->getOpcode() == llvm::Instruction::GetElementPtr);
530 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
535 OldF->replaceAllUsesWith(Replacement);
537 NewF->removeFromParent();
538 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
541 OldF->eraseFromParent();
546 GlobalValReplacements.push_back(std::make_pair(GV,
C));
549void CodeGenModule::applyGlobalValReplacements() {
550 for (
auto &I : GlobalValReplacements) {
551 llvm::GlobalValue *GV = I.first;
552 llvm::Constant *
C = I.second;
554 GV->replaceAllUsesWith(
C);
555 GV->eraseFromParent();
562 const llvm::Constant *
C;
563 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
564 C = GA->getAliasee();
565 else if (
auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
566 C = GI->getResolver();
570 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(
C->stripPointerCasts());
574 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
583 bool IsIFunc,
const llvm::GlobalValue *Alias,
const llvm::GlobalValue *&GV,
584 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
588 Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
592 if (GV->hasCommonLinkage()) {
594 if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
595 Diags.
Report(Location, diag::err_alias_to_common);
600 if (GV->isDeclaration()) {
601 Diags.
Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
602 Diags.
Report(Location, diag::note_alias_requires_mangled_name)
603 << IsIFunc << IsIFunc;
606 for (
const auto &[
Decl, Name] : MangledDeclNames) {
607 if (
const auto *ND = dyn_cast<NamedDecl>(
Decl.getDecl())) {
609 if (II && II->
getName() == GV->getName()) {
610 Diags.
Report(Location, diag::note_alias_mangled_name_alternative)
614 (Twine(IsIFunc ?
"ifunc" :
"alias") +
"(\"" + Name +
"\")")
624 const auto *F = dyn_cast<llvm::Function>(GV);
626 Diags.
Report(Location, diag::err_alias_to_undefined)
627 << IsIFunc << IsIFunc;
631 llvm::FunctionType *FTy = F->getFunctionType();
632 if (!FTy->getReturnType()->isPointerTy()) {
633 Diags.
Report(Location, diag::err_ifunc_resolver_return);
647 if (GVar->hasAttribute(
"toc-data")) {
648 auto GVId = GVar->getName();
651 Diags.
Report(Location, diag::warn_toc_unsupported_type)
652 << GVId <<
"the variable has an alias";
654 llvm::AttributeSet CurrAttributes = GVar->getAttributes();
655 llvm::AttributeSet NewAttributes =
656 CurrAttributes.removeAttribute(GVar->getContext(),
"toc-data");
657 GVar->setAttributes(NewAttributes);
661void CodeGenModule::checkAliases() {
668 const auto *
D = cast<ValueDecl>(GD.getDecl());
671 bool IsIFunc =
D->
hasAttr<IFuncAttr>();
673 Location = A->getLocation();
674 Range = A->getRange();
676 llvm_unreachable(
"Not an alias or ifunc?");
680 const llvm::GlobalValue *GV =
nullptr;
682 MangledDeclNames,
Range)) {
688 if (
const llvm::GlobalVariable *GVar =
689 dyn_cast<const llvm::GlobalVariable>(GV))
693 llvm::Constant *Aliasee =
694 IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver()
695 : cast<llvm::GlobalAlias>(Alias)->getAliasee();
697 llvm::GlobalValue *AliaseeGV;
698 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
699 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
701 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
703 if (
const SectionAttr *SA =
D->
getAttr<SectionAttr>()) {
704 StringRef AliasSection = SA->getName();
705 if (AliasSection != AliaseeGV->getSection())
706 Diags.
Report(SA->getLocation(), diag::warn_alias_with_section)
707 << AliasSection << IsIFunc << IsIFunc;
715 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
716 if (GA->isInterposable()) {
717 Diags.
Report(Location, diag::warn_alias_to_weak_alias)
718 << GV->getName() << GA->getName() << IsIFunc;
719 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
720 GA->getAliasee(), Alias->getType());
723 cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee);
725 cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee);
731 cast<llvm::Function>(Aliasee)->addFnAttr(
732 llvm::Attribute::DisableSanitizerInstrumentation);
740 Alias->replaceAllUsesWith(llvm::PoisonValue::get(Alias->getType()));
741 Alias->eraseFromParent();
746 DeferredDeclsToEmit.clear();
747 EmittedDeferredDecls.clear();
748 DeferredAnnotations.clear();
750 OpenMPRuntime->clear();
754 StringRef MainFile) {
757 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
758 if (MainFile.empty())
759 MainFile =
"<stdin>";
760 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
763 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
766 Diags.
Report(diag::warn_profile_data_missing) << Visited << Missing;
770static std::optional<llvm::GlobalValue::VisibilityTypes>
777 return llvm::GlobalValue::DefaultVisibility;
779 return llvm::GlobalValue::HiddenVisibility;
781 return llvm::GlobalValue::ProtectedVisibility;
783 llvm_unreachable(
"unknown option value!");
788 std::optional<llvm::GlobalValue::VisibilityTypes>
V) {
797 GV.setDSOLocal(
false);
798 GV.setVisibility(*
V);
803 if (!LO.VisibilityFromDLLStorageClass)
806 std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
809 std::optional<llvm::GlobalValue::VisibilityTypes>
810 NoDLLStorageClassVisibility =
813 std::optional<llvm::GlobalValue::VisibilityTypes>
814 ExternDeclDLLImportVisibility =
817 std::optional<llvm::GlobalValue::VisibilityTypes>
818 ExternDeclNoDLLStorageClassVisibility =
821 for (llvm::GlobalValue &GV : M.global_values()) {
822 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
825 if (GV.isDeclarationForLinker())
827 llvm::GlobalValue::DLLImportStorageClass
828 ? ExternDeclDLLImportVisibility
829 : ExternDeclNoDLLStorageClassVisibility);
832 llvm::GlobalValue::DLLExportStorageClass
833 ? DLLExportVisibility
834 : NoDLLStorageClassVisibility);
836 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
841 const llvm::Triple &Triple,
843 if (Triple.isAMDGPU() || Triple.isNVPTX())
845 return LangOpts.getStackProtector() == Mode;
851 EmitModuleInitializers(Primary);
853 DeferredDecls.insert(EmittedDeferredDecls.begin(),
854 EmittedDeferredDecls.end());
855 EmittedDeferredDecls.clear();
856 EmitVTablesOpportunistically();
857 applyGlobalValReplacements();
859 emitMultiVersionFunctions();
862 GlobalTopLevelStmtBlockInFlight.first) {
864 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->
getEndLoc());
865 GlobalTopLevelStmtBlockInFlight = {
nullptr,
nullptr};
871 EmitCXXModuleInitFunc(Primary);
873 EmitCXXGlobalInitFunc();
874 EmitCXXGlobalCleanUpFunc();
875 registerGlobalDtorsWithAtExit();
876 EmitCXXThreadLocalInitFunc();
878 if (llvm::Function *ObjCInitFunction =
ObjCRuntime->ModuleInitFunction())
881 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
885 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
886 OpenMPRuntime->clear();
890 PGOReader->getSummary(
false).getMD(VMContext),
891 llvm::ProfileSummary::PSK_Instr);
898 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
899 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
901 EmitStaticExternCAliases();
907 CoverageMapping->emit();
908 if (CodeGenOpts.SanitizeCfiCrossDso) {
914 emitAtAvailableLinkGuard();
922 if (
getTarget().getTargetOpts().CodeObjectVersion !=
923 llvm::CodeObjectVersionKind::COV_None) {
924 getModule().addModuleFlag(llvm::Module::Error,
925 "amdhsa_code_object_version",
926 getTarget().getTargetOpts().CodeObjectVersion);
931 auto *MDStr = llvm::MDString::get(
936 getModule().addModuleFlag(llvm::Module::Error,
"amdgpu_printf_kind",
949 if (
auto *FD = dyn_cast<FunctionDecl>(
D))
953 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
957 llvm::ArrayType *ATy = llvm::ArrayType::get(
Int8PtrTy, UsedArray.size());
959 auto *GV =
new llvm::GlobalVariable(
960 getModule(), ATy,
false, llvm::GlobalValue::InternalLinkage,
961 llvm::ConstantArray::get(ATy, UsedArray),
"__clang_gpu_used_external");
964 if (LangOpts.HIP && !
getLangOpts().OffloadingNewDriver) {
967 auto *GV =
new llvm::GlobalVariable(
969 llvm::Constant::getNullValue(
Int8Ty),
977 if (CodeGenOpts.Autolink &&
978 (Context.
getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
979 EmitModuleLinkOptions();
994 if (!ELFDependentLibraries.empty() && !Context.
getLangOpts().CUDAIsDevice) {
995 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.dependent-libraries");
996 for (
auto *MD : ELFDependentLibraries)
1000 if (CodeGenOpts.DwarfVersion) {
1001 getModule().addModuleFlag(llvm::Module::Max,
"Dwarf Version",
1002 CodeGenOpts.DwarfVersion);
1005 if (CodeGenOpts.Dwarf64)
1006 getModule().addModuleFlag(llvm::Module::Max,
"DWARF64", 1);
1010 getModule().setSemanticInterposition(
true);
1012 if (CodeGenOpts.EmitCodeView) {
1014 getModule().addModuleFlag(llvm::Module::Warning,
"CodeView", 1);
1016 if (CodeGenOpts.CodeViewGHash) {
1017 getModule().addModuleFlag(llvm::Module::Warning,
"CodeViewGHash", 1);
1019 if (CodeGenOpts.ControlFlowGuard) {
1021 getModule().addModuleFlag(llvm::Module::Warning,
"cfguard", 2);
1022 }
else if (CodeGenOpts.ControlFlowGuardNoChecks) {
1024 getModule().addModuleFlag(llvm::Module::Warning,
"cfguard", 1);
1026 if (CodeGenOpts.EHContGuard) {
1028 getModule().addModuleFlag(llvm::Module::Warning,
"ehcontguard", 1);
1032 getModule().addModuleFlag(llvm::Module::Warning,
"ms-kernel", 1);
1034 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
1039 getModule().addModuleFlag(llvm::Module::Error,
"StrictVTablePointers",1);
1041 llvm::Metadata *Ops[2] = {
1042 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
1043 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1044 llvm::Type::getInt32Ty(VMContext), 1))};
1046 getModule().addModuleFlag(llvm::Module::Require,
1047 "StrictVTablePointersRequirement",
1048 llvm::MDNode::get(VMContext, Ops));
1054 getModule().addModuleFlag(llvm::Module::Warning,
"Debug Info Version",
1055 llvm::DEBUG_METADATA_VERSION);
1060 uint64_t WCharWidth =
1062 getModule().addModuleFlag(llvm::Module::Error,
"wchar_size", WCharWidth);
1065 getModule().addModuleFlag(llvm::Module::Warning,
1066 "zos_product_major_version",
1067 uint32_t(CLANG_VERSION_MAJOR));
1068 getModule().addModuleFlag(llvm::Module::Warning,
1069 "zos_product_minor_version",
1070 uint32_t(CLANG_VERSION_MINOR));
1071 getModule().addModuleFlag(llvm::Module::Warning,
"zos_product_patchlevel",
1072 uint32_t(CLANG_VERSION_PATCHLEVEL));
1074 getModule().addModuleFlag(llvm::Module::Error,
"zos_product_id",
1075 llvm::MDString::get(VMContext, ProductId));
1080 getModule().addModuleFlag(llvm::Module::Error,
"zos_cu_language",
1081 llvm::MDString::get(VMContext, lang_str));
1085 : std::time(
nullptr);
1086 getModule().addModuleFlag(llvm::Module::Max,
"zos_translation_time",
1087 static_cast<uint64_t
>(TT));
1090 getModule().addModuleFlag(llvm::Module::Error,
"zos_le_char_mode",
1091 llvm::MDString::get(VMContext,
"ascii"));
1095 if (
T.isARM() ||
T.isThumb()) {
1097 uint64_t EnumWidth = Context.
getLangOpts().ShortEnums ? 1 : 4;
1098 getModule().addModuleFlag(llvm::Module::Error,
"min_enum_size", EnumWidth);
1102 StringRef ABIStr =
Target.getABI();
1103 llvm::LLVMContext &Ctx = TheModule.getContext();
1104 getModule().addModuleFlag(llvm::Module::Error,
"target-abi",
1105 llvm::MDString::get(Ctx, ABIStr));
1110 const std::vector<std::string> &Features =
1113 llvm::RISCVISAInfo::parseFeatures(
T.isRISCV64() ? 64 : 32, Features);
1114 if (!errorToBool(ParseResult.takeError()))
1116 llvm::Module::AppendUnique,
"riscv-isa",
1118 Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString())));
1121 if (CodeGenOpts.SanitizeCfiCrossDso) {
1123 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
1126 if (CodeGenOpts.WholeProgramVTables) {
1130 getModule().addModuleFlag(llvm::Module::Error,
"Virtual Function Elim",
1131 CodeGenOpts.VirtualFunctionElimination);
1134 if (LangOpts.
Sanitize.
has(SanitizerKind::CFIICall)) {
1135 getModule().addModuleFlag(llvm::Module::Override,
1136 "CFI Canonical Jump Tables",
1137 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1140 if (CodeGenOpts.SanitizeCfiICallNormalizeIntegers) {
1141 getModule().addModuleFlag(llvm::Module::Override,
"cfi-normalize-integers",
1146 getModule().addModuleFlag(llvm::Module::Override,
"kcfi", 1);
1149 if (CodeGenOpts.PatchableFunctionEntryOffset)
1150 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-offset",
1151 CodeGenOpts.PatchableFunctionEntryOffset);
1154 if (CodeGenOpts.CFProtectionReturn &&
1157 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-return",
1161 if (CodeGenOpts.CFProtectionBranch &&
1164 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-branch",
1167 auto Scheme = CodeGenOpts.getCFBranchLabelScheme();
1168 if (
Target.checkCFBranchLabelSchemeSupported(Scheme,
getDiags())) {
1170 Scheme =
Target.getDefaultCFBranchLabelScheme();
1172 llvm::Module::Error,
"cf-branch-label-scheme",
1178 if (CodeGenOpts.FunctionReturnThunks)
1179 getModule().addModuleFlag(llvm::Module::Override,
"function_return_thunk_extern", 1);
1181 if (CodeGenOpts.IndirectBranchCSPrefix)
1182 getModule().addModuleFlag(llvm::Module::Override,
"indirect_branch_cs_prefix", 1);
1194 LangOpts.getSignReturnAddressScope() !=
1196 getModule().addModuleFlag(llvm::Module::Override,
1197 "sign-return-address-buildattr", 1);
1198 if (LangOpts.
Sanitize.
has(SanitizerKind::MemtagStack))
1199 getModule().addModuleFlag(llvm::Module::Override,
1200 "tag-stack-memory-buildattr", 1);
1202 if (
T.isARM() ||
T.isThumb() ||
T.isAArch64()) {
1203 if (LangOpts.BranchTargetEnforcement)
1204 getModule().addModuleFlag(llvm::Module::Min,
"branch-target-enforcement",
1206 if (LangOpts.BranchProtectionPAuthLR)
1207 getModule().addModuleFlag(llvm::Module::Min,
"branch-protection-pauth-lr",
1209 if (LangOpts.GuardedControlStack)
1210 getModule().addModuleFlag(llvm::Module::Min,
"guarded-control-stack", 1);
1212 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address", 1);
1214 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address-all",
1217 getModule().addModuleFlag(llvm::Module::Min,
1218 "sign-return-address-with-bkey", 1);
1220 if (LangOpts.PointerAuthELFGOT)
1221 getModule().addModuleFlag(llvm::Module::Min,
"ptrauth-elf-got", 1);
1224 if (LangOpts.PointerAuthCalls)
1225 getModule().addModuleFlag(llvm::Module::Min,
"ptrauth-sign-personality",
1228 using namespace llvm::ELF;
1229 uint64_t PAuthABIVersion =
1230 (LangOpts.PointerAuthIntrinsics
1231 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS) |
1232 (LangOpts.PointerAuthCalls
1233 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS) |
1234 (LangOpts.PointerAuthReturns
1235 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS) |
1236 (LangOpts.PointerAuthAuthTraps
1237 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS) |
1238 (LangOpts.PointerAuthVTPtrAddressDiscrimination
1239 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR) |
1240 (LangOpts.PointerAuthVTPtrTypeDiscrimination
1241 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR) |
1242 (LangOpts.PointerAuthInitFini
1243 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI) |
1244 (LangOpts.PointerAuthInitFiniAddressDiscrimination
1245 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC) |
1246 (LangOpts.PointerAuthELFGOT
1247 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT) |
1248 (LangOpts.PointerAuthIndirectGotos
1249 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS) |
1250 (LangOpts.PointerAuthTypeInfoVTPtrDiscrimination
1251 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR) |
1252 (LangOpts.PointerAuthFunctionTypeDiscrimination
1253 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR);
1254 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR ==
1255 AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
1256 "Update when new enum items are defined");
1257 if (PAuthABIVersion != 0) {
1258 getModule().addModuleFlag(llvm::Module::Error,
1259 "aarch64-elf-pauthabi-platform",
1260 AARCH64_PAUTH_PLATFORM_LLVM_LINUX);
1261 getModule().addModuleFlag(llvm::Module::Error,
1262 "aarch64-elf-pauthabi-version",
1268 if (CodeGenOpts.StackClashProtector)
1270 llvm::Module::Override,
"probe-stack",
1271 llvm::MDString::get(TheModule.getContext(),
"inline-asm"));
1273 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
1274 getModule().addModuleFlag(llvm::Module::Min,
"stack-probe-size",
1275 CodeGenOpts.StackProbeSize);
1278 llvm::LLVMContext &Ctx = TheModule.getContext();
1280 llvm::Module::Error,
"MemProfProfileFilename",
1284 if (LangOpts.CUDAIsDevice &&
getTriple().isNVPTX()) {
1288 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
1290 llvm::DenormalMode::IEEE);
1293 if (LangOpts.EHAsynch)
1294 getModule().addModuleFlag(llvm::Module::Warning,
"eh-asynch", 1);
1298 getModule().addModuleFlag(llvm::Module::Max,
"openmp", LangOpts.OpenMP);
1300 getModule().addModuleFlag(llvm::Module::Max,
"openmp-device",
1304 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())) {
1305 EmitOpenCLMetadata();
1313 llvm::Metadata *SPIRVerElts[] = {
1314 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1316 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1317 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
1318 llvm::NamedMDNode *SPIRVerMD =
1319 TheModule.getOrInsertNamedMetadata(
"opencl.spir.version");
1320 llvm::LLVMContext &Ctx = TheModule.getContext();
1321 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
1329 if (uint32_t PLevel = Context.
getLangOpts().PICLevel) {
1330 assert(PLevel < 3 &&
"Invalid PIC Level");
1331 getModule().setPICLevel(
static_cast<llvm::PICLevel::Level
>(PLevel));
1333 getModule().setPIELevel(
static_cast<llvm::PIELevel::Level
>(PLevel));
1337 unsigned CM = llvm::StringSwitch<unsigned>(
getCodeGenOpts().CodeModel)
1338 .Case(
"tiny", llvm::CodeModel::Tiny)
1339 .Case(
"small", llvm::CodeModel::Small)
1340 .Case(
"kernel", llvm::CodeModel::Kernel)
1341 .Case(
"medium", llvm::CodeModel::Medium)
1342 .Case(
"large", llvm::CodeModel::Large)
1345 llvm::CodeModel::Model codeModel =
static_cast<llvm::CodeModel::Model
>(CM);
1348 if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
1350 llvm::Triple::x86_64) {
1356 if (CodeGenOpts.NoPLT)
1359 CodeGenOpts.DirectAccessExternalData !=
1360 getModule().getDirectAccessExternalData()) {
1361 getModule().setDirectAccessExternalData(
1362 CodeGenOpts.DirectAccessExternalData);
1364 if (CodeGenOpts.UnwindTables)
1365 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1367 switch (CodeGenOpts.getFramePointer()) {
1372 getModule().setFramePointer(llvm::FramePointerKind::Reserved);
1375 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1378 getModule().setFramePointer(llvm::FramePointerKind::All);
1382 SimplifyPersonality();
1395 EmitVersionIdentMetadata();
1398 EmitCommandLineMetadata();
1406 getModule().setStackProtectorGuardSymbol(
1409 getModule().setStackProtectorGuardOffset(
1414 getModule().addModuleFlag(llvm::Module::Override,
"SkipRaxSetup", 1);
1416 getModule().addModuleFlag(llvm::Module::Override,
"RegCallv4", 1);
1418 if (
getContext().getTargetInfo().getMaxTLSAlign())
1419 getModule().addModuleFlag(llvm::Module::Error,
"MaxTLSAlign",
1420 getContext().getTargetInfo().getMaxTLSAlign());
1438 if (
getTriple().isPPC() && !MustTailCallUndefinedGlobals.empty()) {
1439 for (
auto &I : MustTailCallUndefinedGlobals) {
1440 if (!I.first->isDefined())
1441 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1445 if (!Entry || Entry->isWeakForLinker() ||
1446 Entry->isDeclarationForLinker())
1447 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1453void CodeGenModule::EmitOpenCLMetadata() {
1459 auto EmitVersion = [
this](StringRef MDName,
int Version) {
1460 llvm::Metadata *OCLVerElts[] = {
1461 llvm::ConstantAsMetadata::get(
1462 llvm::ConstantInt::get(
Int32Ty, Version / 100)),
1463 llvm::ConstantAsMetadata::get(
1464 llvm::ConstantInt::get(
Int32Ty, (Version % 100) / 10))};
1465 llvm::NamedMDNode *OCLVerMD = TheModule.getOrInsertNamedMetadata(MDName);
1466 llvm::LLVMContext &Ctx = TheModule.getContext();
1467 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
1470 EmitVersion(
"opencl.ocl.version", CLVersion);
1471 if (LangOpts.OpenCLCPlusPlus) {
1473 EmitVersion(
"opencl.cxx.version", LangOpts.OpenCLCPlusPlusVersion);
1477void CodeGenModule::EmitBackendOptionsMetadata(
1480 getModule().addModuleFlag(llvm::Module::Min,
"SmallDataLimit",
1481 CodeGenOpts.SmallDataLimit);
1498 return TBAA->getTypeInfo(QTy);
1517 return TBAA->getAccessInfo(AccessType);
1524 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
1530 return TBAA->getTBAAStructInfo(QTy);
1536 return TBAA->getBaseTypeInfo(QTy);
1542 return TBAA->getAccessTagInfo(Info);
1549 return TBAA->mergeTBAAInfoForCast(SourceInfo,
TargetInfo);
1557 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
1565 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
1571 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
1576 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
1589 "cannot compile this %0 yet");
1590 std::string Msg =
Type;
1592 << Msg << S->getSourceRange();
1599 "cannot compile this %0 yet");
1600 std::string Msg =
Type;
1605 llvm::function_ref<
void()> Fn) {
1616 if (GV->hasLocalLinkage()) {
1617 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1631 Context.
getLangOpts().OpenMPIsTargetDevice && isa<VarDecl>(
D) &&
1632 D->
hasAttr<OMPDeclareTargetDeclAttr>() &&
1633 D->
getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
1634 OMPDeclareTargetDeclAttr::DT_NoHost &&
1636 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1640 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
1644 if (GV->hasDLLExportStorageClass()) {
1647 diag::err_hidden_visibility_dllexport);
1650 diag::err_non_default_visibility_dllimport);
1656 !GV->isDeclarationForLinker())
1661 llvm::GlobalValue *GV) {
1662 if (GV->hasLocalLinkage())
1665 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
1669 if (GV->hasDLLImportStorageClass())
1672 const llvm::Triple &TT = CGM.
getTriple();
1674 if (TT.isWindowsGNUEnvironment()) {
1683 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
1692 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
1700 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
1704 if (!TT.isOSBinFormatELF())
1710 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1716 if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias()))
1718 return !(CGM.
getLangOpts().SemanticInterposition ||
1723 if (!GV->isDeclarationForLinker())
1729 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
1736 if (CGOpts.DirectAccessExternalData) {
1742 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1743 if (!Var->isThreadLocal())
1752 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
1768 const auto *
D = dyn_cast<NamedDecl>(GD.
getDecl());
1770 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(
D)) {
1779 if (
D &&
D->isExternallyVisible()) {
1781 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1782 else if ((
D->
hasAttr<DLLExportAttr>() ||
1784 !GV->isDeclarationForLinker())
1785 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
1809 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
1810 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
1811 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
1812 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
1813 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
1816llvm::GlobalVariable::ThreadLocalMode
1818 switch (CodeGenOpts.getDefaultTLSModel()) {
1820 return llvm::GlobalVariable::GeneralDynamicTLSModel;
1822 return llvm::GlobalVariable::LocalDynamicTLSModel;
1824 return llvm::GlobalVariable::InitialExecTLSModel;
1826 return llvm::GlobalVariable::LocalExecTLSModel;
1828 llvm_unreachable(
"Invalid TLS model!");
1832 assert(
D.getTLSKind() &&
"setting TLS mode on non-TLS var!");
1834 llvm::GlobalValue::ThreadLocalMode TLM;
1838 if (
const TLSModelAttr *
Attr =
D.
getAttr<TLSModelAttr>()) {
1842 GV->setThreadLocalMode(TLM);
1848 return (Twine(
'.') + Twine(
Target.CPUSpecificManglingCharacter(Name))).str();
1852 const CPUSpecificAttr *
Attr,
1874 bool OmitMultiVersionMangling =
false) {
1876 llvm::raw_svector_ostream Out(Buffer);
1885 assert(II &&
"Attempt to mangle unnamed decl.");
1886 const auto *FD = dyn_cast<FunctionDecl>(ND);
1891 Out <<
"__regcall4__" << II->
getName();
1893 Out <<
"__regcall3__" << II->
getName();
1894 }
else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
1896 Out <<
"__device_stub__" << II->
getName();
1912 "Hash computed when not explicitly requested");
1916 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
1917 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
1918 switch (FD->getMultiVersionKind()) {
1922 FD->getAttr<CPUSpecificAttr>(),
1926 auto *
Attr = FD->getAttr<TargetAttr>();
1927 assert(
Attr &&
"Expected TargetAttr to be present "
1928 "for attribute mangling");
1934 auto *
Attr = FD->getAttr<TargetVersionAttr>();
1935 assert(
Attr &&
"Expected TargetVersionAttr to be present "
1936 "for attribute mangling");
1942 auto *
Attr = FD->getAttr<TargetClonesAttr>();
1943 assert(
Attr &&
"Expected TargetClonesAttr to be present "
1944 "for attribute mangling");
1951 llvm_unreachable(
"None multiversion type isn't valid here");
1961 return std::string(Out.str());
1964void CodeGenModule::UpdateMultiVersionNames(
GlobalDecl GD,
1966 StringRef &CurName) {
1973 std::string NonTargetName =
1981 "Other GD should now be a multiversioned function");
1991 if (OtherName != NonTargetName) {
1994 const auto ExistingRecord = Manglings.find(NonTargetName);
1995 if (ExistingRecord != std::end(Manglings))
1996 Manglings.remove(&(*ExistingRecord));
1997 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
2002 CurName = OtherNameRef;
2004 Entry->setName(OtherName);
2014 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
2028 auto FoundName = MangledDeclNames.find(CanonicalGD);
2029 if (FoundName != MangledDeclNames.end())
2030 return FoundName->second;
2034 const auto *ND = cast<NamedDecl>(GD.
getDecl());
2046 assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
2066 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
2067 return MangledDeclNames[CanonicalGD] =
Result.first->first();
2076 llvm::raw_svector_ostream Out(Buffer);
2079 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.
getDecl()), Out);
2080 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(
D))
2082 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(
D))
2087 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
2088 return Result.first->first();
2092 auto it = MangledDeclNames.begin();
2093 while (it != MangledDeclNames.end()) {
2094 if (it->second == Name)
2109 llvm::Constant *AssociatedData) {
2117 bool IsDtorAttrFunc) {
2118 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2120 DtorsUsingAtExit[
Priority].push_back(Dtor);
2128void CodeGenModule::EmitCtorList(CtorList &Fns,
const char *GlobalName) {
2129 if (Fns.empty())
return;
2135 llvm::PointerType *PtrTy = llvm::PointerType::get(
2136 getLLVMContext(), TheModule.getDataLayout().getProgramAddressSpace());
2139 llvm::StructType *CtorStructTy = llvm::StructType::get(
Int32Ty, PtrTy, PtrTy);
2143 auto Ctors = Builder.beginArray(CtorStructTy);
2144 for (
const auto &I : Fns) {
2145 auto Ctor = Ctors.beginStruct(CtorStructTy);
2146 Ctor.addInt(
Int32Ty, I.Priority);
2147 if (InitFiniAuthSchema) {
2148 llvm::Constant *StorageAddress =
2150 ? llvm::ConstantExpr::getIntToPtr(
2151 llvm::ConstantInt::get(
2153 llvm::ConstantPtrAuth::AddrDiscriminator_CtorsDtors),
2157 I.Initializer, InitFiniAuthSchema.
getKey(), StorageAddress,
2158 llvm::ConstantInt::get(
2160 Ctor.add(SignedCtorPtr);
2162 Ctor.add(I.Initializer);
2164 if (I.AssociatedData)
2165 Ctor.add(I.AssociatedData);
2167 Ctor.addNullPointer(PtrTy);
2168 Ctor.finishAndAddTo(Ctors);
2171 auto List = Ctors.finishAndCreateGlobal(GlobalName,
getPointerAlign(),
2173 llvm::GlobalValue::AppendingLinkage);
2177 List->setAlignment(std::nullopt);
2182llvm::GlobalValue::LinkageTypes
2184 const auto *
D = cast<FunctionDecl>(GD.
getDecl());
2188 if (
const auto *Dtor = dyn_cast<CXXDestructorDecl>(
D))
2195 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2196 if (!MDS)
return nullptr;
2198 return llvm::ConstantInt::get(
Int64Ty, llvm::MD5Hash(MDS->getString()));
2204 FnType->getReturnType(), FnType->getParamTypes(),
2205 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
2207 std::string OutName;
2208 llvm::raw_string_ostream Out(OutName);
2213 Out <<
".normalized";
2215 return llvm::ConstantInt::get(
Int32Ty,
2216 static_cast<uint32_t
>(llvm::xxHash64(OutName)));
2221 llvm::Function *F,
bool IsThunk) {
2223 llvm::AttributeList PAL;
2226 if (
CallingConv == llvm::CallingConv::X86_VectorCall &&
2232 Error(
Loc,
"__vectorcall calling convention is not currently supported");
2234 F->setAttributes(PAL);
2235 F->setCallingConv(
static_cast<llvm::CallingConv::ID
>(
CallingConv));
2239 std::string ReadOnlyQual(
"__read_only");
2240 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2241 if (ReadOnlyPos != std::string::npos)
2243 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2245 std::string WriteOnlyQual(
"__write_only");
2246 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2247 if (WriteOnlyPos != std::string::npos)
2248 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2250 std::string ReadWriteQual(
"__read_write");
2251 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2252 if (ReadWritePos != std::string::npos)
2253 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2286 assert(((FD && CGF) || (!FD && !CGF)) &&
2287 "Incorrect use - FD and CGF should either be both null or not!");
2313 for (
unsigned i = 0, e = FD->
getNumParams(); i != e; ++i) {
2316 argNames.push_back(llvm::MDString::get(VMContext, parm->
getName()));
2321 std::string typeQuals;
2325 const Decl *PDecl = parm;
2327 PDecl = TD->getDecl();
2328 const OpenCLAccessAttr *A = PDecl->
getAttr<OpenCLAccessAttr>();
2329 if (A && A->isWriteOnly())
2330 accessQuals.push_back(llvm::MDString::get(VMContext,
"write_only"));
2331 else if (A && A->isReadWrite())
2332 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_write"));
2334 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_only"));
2336 accessQuals.push_back(llvm::MDString::get(VMContext,
"none"));
2338 auto getTypeSpelling = [&](
QualType Ty) {
2339 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2341 if (Ty.isCanonical()) {
2342 StringRef typeNameRef = typeName;
2344 if (typeNameRef.consume_front(
"unsigned "))
2345 return std::string(
"u") + typeNameRef.str();
2346 if (typeNameRef.consume_front(
"signed "))
2347 return typeNameRef.str();
2357 addressQuals.push_back(
2358 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(
2362 std::string typeName = getTypeSpelling(pointeeTy) +
"*";
2363 std::string baseTypeName =
2365 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2366 argBaseTypeNames.push_back(
2367 llvm::MDString::get(VMContext, baseTypeName));
2371 typeQuals =
"restrict";
2374 typeQuals += typeQuals.empty() ?
"const" :
" const";
2376 typeQuals += typeQuals.empty() ?
"volatile" :
" volatile";
2378 uint32_t AddrSpc = 0;
2383 addressQuals.push_back(
2384 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(AddrSpc)));
2388 std::string typeName = getTypeSpelling(ty);
2400 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2401 argBaseTypeNames.push_back(
2402 llvm::MDString::get(VMContext, baseTypeName));
2407 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
2411 Fn->setMetadata(
"kernel_arg_addr_space",
2412 llvm::MDNode::get(VMContext, addressQuals));
2413 Fn->setMetadata(
"kernel_arg_access_qual",
2414 llvm::MDNode::get(VMContext, accessQuals));
2415 Fn->setMetadata(
"kernel_arg_type",
2416 llvm::MDNode::get(VMContext, argTypeNames));
2417 Fn->setMetadata(
"kernel_arg_base_type",
2418 llvm::MDNode::get(VMContext, argBaseTypeNames));
2419 Fn->setMetadata(
"kernel_arg_type_qual",
2420 llvm::MDNode::get(VMContext, argTypeQuals));
2424 Fn->setMetadata(
"kernel_arg_name",
2425 llvm::MDNode::get(VMContext, argNames));
2435 if (!LangOpts.Exceptions)
return false;
2438 if (LangOpts.CXXExceptions)
return true;
2441 if (LangOpts.ObjCExceptions) {
2458 !isa<CXXConstructorDecl, CXXDestructorDecl>(MD);
2463 llvm::SetVector<const CXXRecordDecl *> MostBases;
2465 std::function<void (
const CXXRecordDecl *)> CollectMostBases;
2468 MostBases.insert(RD);
2470 CollectMostBases(B.getType()->getAsCXXRecordDecl());
2472 CollectMostBases(RD);
2473 return MostBases.takeVector();
2477 llvm::Function *F) {
2478 llvm::AttrBuilder B(F->getContext());
2480 if ((!
D || !
D->
hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2481 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2483 if (CodeGenOpts.StackClashProtector)
2484 B.addAttribute(
"probe-stack",
"inline-asm");
2486 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
2487 B.addAttribute(
"stack-probe-size",
2488 std::to_string(CodeGenOpts.StackProbeSize));
2491 B.addAttribute(llvm::Attribute::NoUnwind);
2493 if (
D &&
D->
hasAttr<NoStackProtectorAttr>())
2495 else if (
D &&
D->
hasAttr<StrictGuardStackCheckAttr>() &&
2497 B.addAttribute(llvm::Attribute::StackProtectStrong);
2499 B.addAttribute(llvm::Attribute::StackProtect);
2501 B.addAttribute(llvm::Attribute::StackProtectStrong);
2503 B.addAttribute(llvm::Attribute::StackProtectReq);
2507 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline))
2508 B.addAttribute(llvm::Attribute::AlwaysInline);
2512 else if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2514 B.addAttribute(llvm::Attribute::NoInline);
2522 if (
D->
hasAttr<ArmLocallyStreamingAttr>())
2523 B.addAttribute(
"aarch64_pstate_sm_body");
2526 if (
Attr->isNewZA())
2527 B.addAttribute(
"aarch64_new_za");
2528 if (
Attr->isNewZT0())
2529 B.addAttribute(
"aarch64_new_zt0");
2534 bool ShouldAddOptNone =
2535 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
2537 ShouldAddOptNone &= !
D->
hasAttr<MinSizeAttr>();
2538 ShouldAddOptNone &= !
D->
hasAttr<AlwaysInlineAttr>();
2541 if (
getLangOpts().HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline) &&
2543 B.addAttribute(llvm::Attribute::AlwaysInline);
2544 }
else if ((ShouldAddOptNone ||
D->
hasAttr<OptimizeNoneAttr>()) &&
2545 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2547 B.addAttribute(llvm::Attribute::OptimizeNone);
2550 B.addAttribute(llvm::Attribute::NoInline);
2555 B.addAttribute(llvm::Attribute::Naked);
2558 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
2559 F->removeFnAttr(llvm::Attribute::MinSize);
2560 }
else if (
D->
hasAttr<NakedAttr>()) {
2562 B.addAttribute(llvm::Attribute::Naked);
2563 B.addAttribute(llvm::Attribute::NoInline);
2564 }
else if (
D->
hasAttr<NoDuplicateAttr>()) {
2565 B.addAttribute(llvm::Attribute::NoDuplicate);
2566 }
else if (
D->
hasAttr<NoInlineAttr>() &&
2567 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2569 B.addAttribute(llvm::Attribute::NoInline);
2570 }
else if (
D->
hasAttr<AlwaysInlineAttr>() &&
2571 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
2573 B.addAttribute(llvm::Attribute::AlwaysInline);
2577 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
2578 B.addAttribute(llvm::Attribute::NoInline);
2582 if (
auto *FD = dyn_cast<FunctionDecl>(
D)) {
2585 auto CheckRedeclForInline = [](
const FunctionDecl *Redecl) {
2586 return Redecl->isInlineSpecified();
2588 if (any_of(FD->
redecls(), CheckRedeclForInline))
2593 return any_of(Pattern->
redecls(), CheckRedeclForInline);
2595 if (CheckForInline(FD)) {
2596 B.addAttribute(llvm::Attribute::InlineHint);
2597 }
else if (CodeGenOpts.getInlining() ==
2600 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2601 B.addAttribute(llvm::Attribute::NoInline);
2608 if (!
D->
hasAttr<OptimizeNoneAttr>()) {
2610 if (!ShouldAddOptNone)
2611 B.addAttribute(llvm::Attribute::OptimizeForSize);
2612 B.addAttribute(llvm::Attribute::Cold);
2615 B.addAttribute(llvm::Attribute::Hot);
2617 B.addAttribute(llvm::Attribute::MinSize);
2624 F->setAlignment(llvm::Align(alignment));
2627 if (LangOpts.FunctionAlignment)
2628 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
2635 if (isa<CXXMethodDecl>(
D) && F->getPointerAlignment(
getDataLayout()) < 2)
2636 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
2641 if (CodeGenOpts.SanitizeCfiCrossDso &&
2642 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2643 if (
auto *FD = dyn_cast<FunctionDecl>(
D)) {
2654 auto *MD = dyn_cast<CXXMethodDecl>(
D);
2657 llvm::Metadata *
Id =
2660 F->addTypeMetadata(0,
Id);
2667 if (isa_and_nonnull<NamedDecl>(
D))
2670 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2675 if (
const auto *VD = dyn_cast_if_present<VarDecl>(
D);
2677 ((CodeGenOpts.KeepPersistentStorageVariables &&
2678 (VD->getStorageDuration() ==
SD_Static ||
2679 VD->getStorageDuration() ==
SD_Thread)) ||
2680 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
2681 VD->getType().isConstQualified())))
2685bool CodeGenModule::GetCPUAndFeaturesAttributes(
GlobalDecl GD,
2686 llvm::AttrBuilder &Attrs,
2687 bool SetTargetFeatures) {
2693 std::vector<std::string> Features;
2694 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.
getDecl());
2696 const auto *TD = FD ? FD->
getAttr<TargetAttr>() :
nullptr;
2697 const auto *TV = FD ? FD->
getAttr<TargetVersionAttr>() :
nullptr;
2698 assert((!TD || !TV) &&
"both target_version and target specified");
2699 const auto *SD = FD ? FD->
getAttr<CPUSpecificAttr>() :
nullptr;
2700 const auto *TC = FD ? FD->
getAttr<TargetClonesAttr>() :
nullptr;
2701 bool AddedAttr =
false;
2702 if (TD || TV || SD || TC) {
2703 llvm::StringMap<bool> FeatureMap;
2707 for (
const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
2708 Features.push_back((Entry.getValue() ?
"+" :
"-") + Entry.getKey().str());
2716 Target.parseTargetAttr(TD->getFeaturesStr());
2738 if (!TargetCPU.empty()) {
2739 Attrs.addAttribute(
"target-cpu", TargetCPU);
2742 if (!TuneCPU.empty()) {
2743 Attrs.addAttribute(
"tune-cpu", TuneCPU);
2746 if (!Features.empty() && SetTargetFeatures) {
2747 llvm::erase_if(Features, [&](
const std::string& F) {
2750 llvm::sort(Features);
2751 Attrs.addAttribute(
"target-features", llvm::join(Features,
","));
2757 bool IsDefault =
false;
2759 IsDefault = TV->isDefaultVersion();
2760 TV->getFeatures(Feats);
2766 Attrs.addAttribute(
"fmv-features");
2768 }
else if (!Feats.empty()) {
2770 std::set<StringRef> OrderedFeats(Feats.begin(), Feats.end());
2771 std::string FMVFeatures;
2772 for (StringRef F : OrderedFeats)
2773 FMVFeatures.append(
"," + F.str());
2774 Attrs.addAttribute(
"fmv-features", FMVFeatures.substr(1));
2781void CodeGenModule::setNonAliasAttributes(
GlobalDecl GD,
2782 llvm::GlobalObject *GO) {
2787 if (
auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
2790 if (
auto *SA =
D->
getAttr<PragmaClangBSSSectionAttr>())
2791 GV->addAttribute(
"bss-section", SA->getName());
2792 if (
auto *SA =
D->
getAttr<PragmaClangDataSectionAttr>())
2793 GV->addAttribute(
"data-section", SA->getName());
2794 if (
auto *SA =
D->
getAttr<PragmaClangRodataSectionAttr>())
2795 GV->addAttribute(
"rodata-section", SA->getName());
2796 if (
auto *SA =
D->
getAttr<PragmaClangRelroSectionAttr>())
2797 GV->addAttribute(
"relro-section", SA->getName());
2800 if (
auto *F = dyn_cast<llvm::Function>(GO)) {
2803 if (
auto *SA =
D->
getAttr<PragmaClangTextSectionAttr>())
2805 F->setSection(SA->getName());
2807 llvm::AttrBuilder Attrs(F->getContext());
2808 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
2812 llvm::AttributeMask RemoveAttrs;
2813 RemoveAttrs.addAttribute(
"target-cpu");
2814 RemoveAttrs.addAttribute(
"target-features");
2815 RemoveAttrs.addAttribute(
"fmv-features");
2816 RemoveAttrs.addAttribute(
"tune-cpu");
2817 F->removeFnAttrs(RemoveAttrs);
2818 F->addFnAttrs(Attrs);
2822 if (
const auto *CSA =
D->
getAttr<CodeSegAttr>())
2823 GO->setSection(CSA->getName());
2824 else if (
const auto *SA =
D->
getAttr<SectionAttr>())
2825 GO->setSection(SA->getName());
2838 F->setLinkage(llvm::Function::InternalLinkage);
2840 setNonAliasAttributes(GD, F);
2851 GV->
setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2855 llvm::Function *F) {
2857 if (!LangOpts.
Sanitize.
has(SanitizerKind::CFIICall))
2862 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2866 F->addTypeMetadata(0, MD);
2870 if (CodeGenOpts.SanitizeCfiCrossDso)
2872 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
2876 llvm::LLVMContext &Ctx = F->getContext();
2877 llvm::MDBuilder MDB(Ctx);
2878 F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
2887 return llvm::all_of(Name, [](
const char &
C) {
2888 return llvm::isAlnum(
C) ||
C ==
'_' ||
C ==
'.';
2894 for (
auto &F : M.functions()) {
2896 bool AddressTaken = F.hasAddressTaken();
2897 if (!AddressTaken && F.hasLocalLinkage())
2898 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
2903 if (!AddressTaken || !F.isDeclaration())
2906 const llvm::ConstantInt *
Type;
2907 if (
const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
2908 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
2912 StringRef Name = F.getName();
2916 std::string
Asm = (
".weak __kcfi_typeid_" + Name +
"\n.set __kcfi_typeid_" +
2917 Name +
", " + Twine(
Type->getZExtValue()) +
"\n")
2919 M.appendModuleInlineAsm(
Asm);
2923void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
2924 bool IsIncompleteFunction,
2927 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
2930 F->setAttributes(llvm::Intrinsic::getAttributes(
getLLVMContext(), IID));
2934 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
2936 if (!IsIncompleteFunction)
2943 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
2945 assert(!F->arg_empty() &&
2946 F->arg_begin()->getType()
2947 ->canLosslesslyBitCastTo(F->getReturnType()) &&
2948 "unexpected this return");
2949 F->addParamAttr(0, llvm::Attribute::Returned);
2959 if (!IsIncompleteFunction && F->isDeclaration())
2962 if (
const auto *CSA = FD->
getAttr<CodeSegAttr>())
2963 F->setSection(CSA->getName());
2964 else if (
const auto *SA = FD->
getAttr<SectionAttr>())
2965 F->setSection(SA->getName());
2967 if (
const auto *EA = FD->
getAttr<ErrorAttr>()) {
2969 F->addFnAttr(
"dontcall-error", EA->getUserDiagnostic());
2970 else if (EA->isWarning())
2971 F->addFnAttr(
"dontcall-warn", EA->getUserDiagnostic());
2977 bool HasBody = FD->
hasBody(FDBody);
2979 assert(HasBody &&
"Inline builtin declarations should always have an "
2981 if (shouldEmitFunction(FDBody))
2982 F->addFnAttr(llvm::Attribute::NoBuiltin);
2988 F->addFnAttr(llvm::Attribute::NoBuiltin);
2991 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
2992 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2993 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
2994 if (MD->isVirtual())
2995 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3001 if (!CodeGenOpts.SanitizeCfiCrossDso ||
3002 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
3011 if (CodeGenOpts.InlineMaxStackSize !=
UINT_MAX)
3012 F->addFnAttr(
"inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
3014 if (
const auto *CB = FD->
getAttr<CallbackAttr>()) {
3018 llvm::LLVMContext &Ctx = F->getContext();
3019 llvm::MDBuilder MDB(Ctx);
3023 int CalleeIdx = *CB->encoding_begin();
3024 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
3025 F->addMetadata(llvm::LLVMContext::MD_callback,
3026 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
3027 CalleeIdx, PayloadIndices,
3033 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
3034 "Only globals with definition can force usage.");
3035 LLVMUsed.emplace_back(GV);
3039 assert(!GV->isDeclaration() &&
3040 "Only globals with definition can force usage.");
3041 LLVMCompilerUsed.emplace_back(GV);
3045 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
3046 "Only globals with definition can force usage.");
3048 LLVMCompilerUsed.emplace_back(GV);
3050 LLVMUsed.emplace_back(GV);
3054 std::vector<llvm::WeakTrackingVH> &List) {
3061 UsedArray.resize(List.size());
3062 for (
unsigned i = 0, e = List.size(); i != e; ++i) {
3064 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3065 cast<llvm::Constant>(&*List[i]), CGM.
Int8PtrTy);
3068 if (UsedArray.empty())
3070 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
3072 auto *GV =
new llvm::GlobalVariable(
3073 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
3074 llvm::ConstantArray::get(ATy, UsedArray), Name);
3076 GV->setSection(
"llvm.metadata");
3079void CodeGenModule::emitLLVMUsed() {
3080 emitUsed(*
this,
"llvm.used", LLVMUsed);
3081 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
3086 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3095 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3101 ELFDependentLibraries.push_back(
3102 llvm::MDNode::get(
C, llvm::MDString::get(
C, Lib)));
3109 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
C, MDOpts));
3124 if (
Visited.insert(Import).second)
3141 if (LL.IsFramework) {
3142 llvm::Metadata *Args[2] = {llvm::MDString::get(Context,
"-framework"),
3143 llvm::MDString::get(Context, LL.Library)};
3145 Metadata.push_back(llvm::MDNode::get(Context, Args));
3151 llvm::Metadata *Args[2] = {
3152 llvm::MDString::get(Context,
"lib"),
3153 llvm::MDString::get(Context, LL.Library),
3155 Metadata.push_back(llvm::MDNode::get(Context, Args));
3159 auto *OptString = llvm::MDString::get(Context, Opt);
3160 Metadata.push_back(llvm::MDNode::get(Context, OptString));
3165void CodeGenModule::EmitModuleInitializers(
clang::Module *Primary) {
3167 "We should only emit module initializers for named modules.");
3173 if (isa<ImportDecl>(
D))
3175 assert(isa<VarDecl>(
D) &&
"GMF initializer decl is not a var?");
3182 if (isa<ImportDecl>(
D))
3190 if (isa<ImportDecl>(
D))
3192 assert(isa<VarDecl>(
D) &&
"PMF initializer decl is not a var?");
3198void CodeGenModule::EmitModuleLinkOptions() {
3202 llvm::SetVector<clang::Module *> LinkModules;
3207 for (
Module *M : ImportedModules) {
3210 if (M->getTopLevelModuleName() ==
getLangOpts().CurrentModule &&
3219 while (!Stack.empty()) {
3222 bool AnyChildren =
false;
3232 Stack.push_back(
SM);
3240 LinkModules.insert(Mod);
3249 for (
Module *M : LinkModules)
3252 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
3253 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
3256 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.linker.options");
3257 for (
auto *MD : LinkerOptionsMetadata)
3258 NMD->addOperand(MD);
3261void CodeGenModule::EmitDeferred() {
3270 if (!DeferredVTables.empty()) {
3271 EmitDeferredVTables();
3276 assert(DeferredVTables.empty());
3283 llvm::append_range(DeferredDeclsToEmit,
3287 if (DeferredDeclsToEmit.empty())
3292 std::vector<GlobalDecl> CurDeclsToEmit;
3293 CurDeclsToEmit.swap(DeferredDeclsToEmit);
3300 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
3318 if (!GV->isDeclaration())
3322 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(
D))
3326 EmitGlobalDefinition(
D, GV);
3331 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
3333 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
3338void CodeGenModule::EmitVTablesOpportunistically() {
3344 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
3345 &&
"Only emit opportunistic vtables with optimizations");
3349 "This queue should only contain external vtables");
3350 if (
getCXXABI().canSpeculativelyEmitVTable(RD))
3353 OpportunisticVTables.clear();
3357 for (
const auto& [MangledName, VD] : DeferredAnnotations) {
3362 DeferredAnnotations.clear();
3364 if (Annotations.empty())
3368 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
3369 Annotations[0]->getType(), Annotations.size()), Annotations);
3370 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
3371 llvm::GlobalValue::AppendingLinkage,
3372 Array,
"llvm.global.annotations");
3377 llvm::Constant *&AStr = AnnotationStrings[Str];
3382 llvm::Constant *
s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
3383 auto *gv =
new llvm::GlobalVariable(
3384 getModule(),
s->getType(),
true, llvm::GlobalValue::PrivateLinkage,
s,
3385 ".str",
nullptr, llvm::GlobalValue::NotThreadLocal,
3388 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3405 SM.getExpansionLineNumber(L);
3406 return llvm::ConstantInt::get(
Int32Ty, LineNo);
3414 llvm::FoldingSetNodeID ID;
3415 for (
Expr *
E : Exprs) {
3416 ID.Add(cast<clang::ConstantExpr>(
E)->getAPValueResult());
3418 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
3423 LLVMArgs.reserve(Exprs.size());
3425 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](
const Expr *
E) {
3426 const auto *CE = cast<clang::ConstantExpr>(
E);
3427 return ConstEmiter.
emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
3430 auto *
Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
3431 auto *GV =
new llvm::GlobalVariable(
getModule(),
Struct->getType(),
true,
3432 llvm::GlobalValue::PrivateLinkage,
Struct,
3435 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3442 const AnnotateAttr *AA,
3450 llvm::Constant *GVInGlobalsAS = GV;
3451 if (GV->getAddressSpace() !=
3453 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
3455 llvm::PointerType::get(
3456 GV->getContext(),
getDataLayout().getDefaultGlobalsAddressSpace()));
3460 llvm::Constant *Fields[] = {
3461 GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
3463 return llvm::ConstantStruct::getAnon(Fields);
3467 llvm::GlobalValue *GV) {
3468 assert(
D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
3478 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
3483 if (NoSanitizeL.containsMainFile(Kind, MainFile.
getName()))
3488 return NoSanitizeL.containsLocation(Kind,
Loc);
3491 return NoSanitizeL.containsFile(Kind, MainFile.
getName());
3495 llvm::GlobalVariable *GV,
3499 if (NoSanitizeL.containsGlobal(Kind, GV->getName(),
Category))
3502 if (NoSanitizeL.containsMainFile(
3503 Kind,
SM.getFileEntryRefForID(
SM.getMainFileID())->getName(),
3506 if (NoSanitizeL.containsLocation(Kind,
Loc,
Category))
3513 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
3514 Ty = AT->getElementType();
3519 if (NoSanitizeL.containsType(Kind, TypeStr,
Category))
3530 auto Attr = ImbueAttr::NONE;
3533 if (
Attr == ImbueAttr::NONE)
3534 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
3536 case ImbueAttr::NONE:
3538 case ImbueAttr::ALWAYS:
3539 Fn->addFnAttr(
"function-instrument",
"xray-always");
3541 case ImbueAttr::ALWAYS_ARG1:
3542 Fn->addFnAttr(
"function-instrument",
"xray-always");
3543 Fn->addFnAttr(
"xray-log-args",
"1");
3545 case ImbueAttr::NEVER:
3546 Fn->addFnAttr(
"function-instrument",
"xray-never");
3570 if (
auto MainFile =
SM.getFileEntryRefForID(
SM.getMainFileID()))
3584 if (NumGroups > 1) {
3585 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
3594 if (LangOpts.EmitAllDecls)
3597 const auto *VD = dyn_cast<VarDecl>(
Global);
3599 ((CodeGenOpts.KeepPersistentStorageVariables &&
3600 (VD->getStorageDuration() ==
SD_Static ||
3601 VD->getStorageDuration() ==
SD_Thread)) ||
3602 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
3603 VD->getType().isConstQualified())))
3616 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
3617 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
3618 OMPDeclareTargetDeclAttr::getActiveAttr(
Global);
3619 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (
unsigned)-1)
3623 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
3632 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
3638 if (CXX20ModuleInits && VD->getOwningModule() &&
3639 !VD->getOwningModule()->isModuleMapModule()) {
3648 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
3651 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
Global))
3664 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
3668 llvm::Constant *
Init;
3671 if (!
V.isAbsent()) {
3682 llvm::Constant *Fields[4] = {
3686 llvm::ConstantDataArray::getRaw(
3687 StringRef(
reinterpret_cast<char *
>(Parts.
Part4And5), 8), 8,
3689 Init = llvm::ConstantStruct::getAnon(Fields);
3692 auto *GV =
new llvm::GlobalVariable(
3694 true, llvm::GlobalValue::LinkOnceODRLinkage,
Init, Name);
3696 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3699 if (!
V.isAbsent()) {
3712 llvm::GlobalVariable **Entry =
nullptr;
3713 Entry = &UnnamedGlobalConstantDeclMap[GCD];
3718 llvm::Constant *
Init;
3722 assert(!
V.isAbsent());
3726 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
3728 llvm::GlobalValue::PrivateLinkage,
Init,
3730 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3744 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
3748 llvm::Constant *
Init =
Emitter.emitForInitializer(
3756 llvm::GlobalValue::LinkageTypes
Linkage =
3758 ? llvm::GlobalValue::LinkOnceODRLinkage
3759 : llvm::GlobalValue::InternalLinkage;
3760 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
3764 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3771 const AliasAttr *AA = VD->
getAttr<AliasAttr>();
3772 assert(AA &&
"No alias?");
3782 llvm::Constant *Aliasee;
3783 if (isa<llvm::FunctionType>(DeclTy))
3784 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
3791 auto *F = cast<llvm::GlobalValue>(Aliasee);
3792 F->setLinkage(llvm::Function::ExternalWeakLinkage);
3793 WeakRefReferences.insert(F);
3802 return A->isImplicit();
3806bool CodeGenModule::shouldEmitCUDAGlobalVar(
const VarDecl *
Global)
const {
3807 assert(LangOpts.CUDA &&
"Should not be called by non-CUDA languages");
3812 return !LangOpts.CUDAIsDevice ||
Global->hasAttr<CUDADeviceAttr>() ||
3813 Global->hasAttr<CUDAConstantAttr>() ||
3814 Global->hasAttr<CUDASharedAttr>() ||
3815 Global->getType()->isCUDADeviceBuiltinSurfaceType() ||
3816 Global->getType()->isCUDADeviceBuiltinTextureType();
3823 if (
Global->hasAttr<WeakRefAttr>())
3828 if (
Global->hasAttr<AliasAttr>())
3829 return EmitAliasDefinition(GD);
3832 if (
Global->hasAttr<IFuncAttr>())
3833 return emitIFuncDefinition(GD);
3836 if (
Global->hasAttr<CPUDispatchAttr>())
3837 return emitCPUDispatchDefinition(GD);
3842 if (LangOpts.CUDA) {
3843 assert((isa<FunctionDecl>(
Global) || isa<VarDecl>(
Global)) &&
3844 "Expected Variable or Function");
3845 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
3846 if (!shouldEmitCUDAGlobalVar(VD))
3848 }
else if (LangOpts.CUDAIsDevice) {
3849 const auto *FD = dyn_cast<FunctionDecl>(
Global);
3850 if ((!
Global->hasAttr<CUDADeviceAttr>() ||
3851 (LangOpts.OffloadImplicitHostDeviceTemplates &&
3852 hasImplicitAttr<CUDAHostAttr>(FD) &&
3853 hasImplicitAttr<CUDADeviceAttr>(FD) && !FD->
isConstexpr() &&
3855 !
getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
3856 !
Global->hasAttr<CUDAGlobalAttr>() &&
3857 !(LangOpts.HIPStdPar && isa<FunctionDecl>(
Global) &&
3858 !
Global->hasAttr<CUDAHostAttr>()))
3861 }
else if (!
Global->hasAttr<CUDAHostAttr>() &&
3862 Global->hasAttr<CUDADeviceAttr>())
3866 if (LangOpts.OpenMP) {
3868 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
3870 if (
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(
Global)) {
3871 if (MustBeEmitted(
Global))
3875 if (
auto *DMD = dyn_cast<OMPDeclareMapperDecl>(
Global)) {
3876 if (MustBeEmitted(
Global))
3883 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
3886 if (FD->
hasAttr<AnnotateAttr>()) {
3889 DeferredAnnotations[MangledName] = FD;
3904 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
3909 const auto *VD = cast<VarDecl>(
Global);
3910 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
3913 if (LangOpts.OpenMP) {
3915 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3916 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
3920 if (VD->hasExternalStorage() &&
3921 Res != OMPDeclareTargetDeclAttr::MT_Link)
3924 bool UnifiedMemoryEnabled =
3926 if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3927 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3928 !UnifiedMemoryEnabled) {
3931 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3932 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3933 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3934 UnifiedMemoryEnabled)) &&
3935 "Link clause or to clause with unified memory expected.");
3954 if (MustBeEmitted(
Global) && MayBeEmittedEagerly(
Global)) {
3956 EmitGlobalDefinition(GD);
3957 addEmittedDeferredDecl(GD);
3964 cast<VarDecl>(
Global)->hasInit()) {
3965 DelayedCXXInitPosition[
Global] = CXXGlobalInits.size();
3966 CXXGlobalInits.push_back(
nullptr);
3972 addDeferredDeclToEmit(GD);
3973 }
else if (MustBeEmitted(
Global)) {
3975 assert(!MayBeEmittedEagerly(
Global));
3976 addDeferredDeclToEmit(GD);
3981 DeferredDecls[MangledName] = GD;
3988 if (
CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
3989 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
3996 struct FunctionIsDirectlyRecursive
3998 const StringRef Name;
4008 if (
Attr && Name ==
Attr->getLabel())
4013 StringRef BuiltinName = BI.
getName(BuiltinID);
4014 if (BuiltinName.starts_with(
"__builtin_") &&
4015 Name == BuiltinName.slice(strlen(
"__builtin_"), StringRef::npos)) {
4021 bool VisitStmt(
const Stmt *S) {
4022 for (
const Stmt *Child : S->children())
4023 if (Child && this->Visit(Child))
4030 struct DLLImportFunctionVisitor
4032 bool SafeToInline =
true;
4034 bool shouldVisitImplicitCode()
const {
return true; }
4036 bool VisitVarDecl(
VarDecl *VD) {
4039 SafeToInline =
false;
4040 return SafeToInline;
4047 return SafeToInline;
4051 if (
const auto *
D =
E->getTemporary()->getDestructor())
4052 SafeToInline =
D->
hasAttr<DLLImportAttr>();
4053 return SafeToInline;
4058 if (isa<FunctionDecl>(VD))
4059 SafeToInline = VD->
hasAttr<DLLImportAttr>();
4060 else if (
VarDecl *
V = dyn_cast<VarDecl>(VD))
4061 SafeToInline = !
V->hasGlobalStorage() ||
V->hasAttr<DLLImportAttr>();
4062 return SafeToInline;
4066 SafeToInline =
E->getConstructor()->hasAttr<DLLImportAttr>();
4067 return SafeToInline;
4074 SafeToInline =
true;
4076 SafeToInline = M->
hasAttr<DLLImportAttr>();
4078 return SafeToInline;
4082 SafeToInline =
E->getOperatorDelete()->hasAttr<DLLImportAttr>();
4083 return SafeToInline;
4087 SafeToInline =
E->getOperatorNew()->hasAttr<DLLImportAttr>();
4088 return SafeToInline;
4097CodeGenModule::isTriviallyRecursive(
const FunctionDecl *FD) {
4099 if (
getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
4104 Name =
Attr->getLabel();
4109 FunctionIsDirectlyRecursive Walker(Name, Context.
BuiltinInfo);
4111 return Body ? Walker.Visit(Body) :
false;
4114bool CodeGenModule::shouldEmitFunction(
GlobalDecl GD) {
4118 const auto *F = cast<FunctionDecl>(GD.
getDecl());
4121 if (F->isInlineBuiltinDeclaration())
4124 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
4129 if (
const Module *M = F->getOwningModule();
4130 M && M->getTopLevelModule()->isNamedModule() &&
4131 getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
4141 if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
4146 if (F->hasAttr<NoInlineAttr>())
4149 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
4151 DLLImportFunctionVisitor Visitor;
4152 Visitor.TraverseFunctionDecl(
const_cast<FunctionDecl*
>(F));
4153 if (!Visitor.SafeToInline)
4159 for (
const Decl *
Member : Dtor->getParent()->decls())
4160 if (isa<FieldDecl>(
Member))
4174 return !isTriviallyRecursive(F);
4177bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
4178 return CodeGenOpts.OptimizationLevel > 0;
4181void CodeGenModule::EmitMultiVersionFunctionDefinition(
GlobalDecl GD,
4182 llvm::GlobalValue *GV) {
4183 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4186 auto *Spec = FD->
getAttr<CPUSpecificAttr>();
4187 for (
unsigned I = 0; I < Spec->cpus_size(); ++I)
4189 }
else if (
auto *TC = FD->
getAttr<TargetClonesAttr>()) {
4190 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I)
4193 TC->isFirstOfVersion(I))
4196 GetOrCreateMultiVersionResolver(GD);
4198 EmitGlobalFunctionDefinition(GD, GV);
4203 AddDeferredMultiVersionResolverToEmit(GD);
4206void CodeGenModule::EmitGlobalDefinition(
GlobalDecl GD, llvm::GlobalValue *GV) {
4207 const auto *
D = cast<ValueDecl>(GD.
getDecl());
4211 "Generating code for declaration");
4213 if (
const auto *FD = dyn_cast<FunctionDecl>(
D)) {
4216 if (!shouldEmitFunction(GD))
4219 llvm::TimeTraceScope TimeScope(
"CodeGen Function", [&]() {
4221 llvm::raw_string_ostream OS(Name);
4227 if (
const auto *Method = dyn_cast<CXXMethodDecl>(
D)) {
4230 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
4231 ABI->emitCXXStructor(GD);
4233 EmitMultiVersionFunctionDefinition(GD, GV);
4235 EmitGlobalFunctionDefinition(GD, GV);
4237 if (Method->isVirtual())
4244 return EmitMultiVersionFunctionDefinition(GD, GV);
4245 return EmitGlobalFunctionDefinition(GD, GV);
4248 if (
const auto *VD = dyn_cast<VarDecl>(
D))
4249 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
4251 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
4255 llvm::Function *NewFn);
4258 const CodeGenFunction::FMVResolverOption &RO) {
4260 if (RO.Architecture)
4261 Features.push_back(*RO.Architecture);
4270static llvm::GlobalValue::LinkageTypes
4274 return llvm::GlobalValue::InternalLinkage;
4275 return llvm::GlobalValue::WeakODRLinkage;
4278void CodeGenModule::emitMultiVersionFunctions() {
4279 std::vector<GlobalDecl> MVFuncsToEmit;
4280 MultiVersionFuncs.swap(MVFuncsToEmit);
4282 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4283 assert(FD &&
"Expected a FunctionDecl");
4290 if (
Decl->isDefined()) {
4291 EmitGlobalFunctionDefinition(CurGD,
nullptr);
4299 assert(
Func &&
"This should have just been created");
4301 return cast<llvm::Function>(
Func);
4315 if (
const auto *TA = CurFD->
getAttr<TargetAttr>()) {
4316 assert(getTarget().getTriple().isX86() &&
"Unsupported target");
4317 TA->getX86AddedFeatures(Feats);
4318 llvm::Function *Func = createFunction(CurFD);
4319 Options.emplace_back(Func, Feats, TA->getX86Architecture());
4320 }
else if (
const auto *TVA = CurFD->
getAttr<TargetVersionAttr>()) {
4321 if (TVA->isDefaultVersion() && IsDefined)
4322 ShouldEmitResolver = true;
4323 llvm::Function *Func = createFunction(CurFD);
4324 char Delim = getTarget().getTriple().isAArch64() ?
'+' :
',';
4325 TVA->getFeatures(Feats, Delim);
4326 Options.emplace_back(Func, Feats);
4327 }
else if (
const auto *TC = CurFD->
getAttr<TargetClonesAttr>()) {
4329 ShouldEmitResolver = true;
4330 for (unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
4331 if (!TC->isFirstOfVersion(I))
4334 llvm::Function *Func = createFunction(CurFD, I);
4336 if (getTarget().getTriple().isX86()) {
4337 TC->getX86Feature(Feats, I);
4338 Options.emplace_back(Func, Feats, TC->getX86Architecture(I));
4340 char Delim = getTarget().getTriple().isAArch64() ?
'+' :
',';
4341 TC->getFeatures(Feats, I, Delim);
4342 Options.emplace_back(Func, Feats);
4346 llvm_unreachable(
"unexpected MultiVersionKind");
4349 if (!ShouldEmitResolver)
4352 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
4353 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
4354 ResolverConstant = IFunc->getResolver();
4358 *
this, GD, FD,
true);
4365 auto *Alias = llvm::GlobalAlias::create(
4367 MangledName +
".ifunc", IFunc, &
getModule());
4372 llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant);
4377 ResolverFunc->setComdat(
4378 getModule().getOrInsertComdat(ResolverFunc->getName()));
4382 Options, [&TI](
const CodeGenFunction::FMVResolverOption &LHS,
4383 const CodeGenFunction::FMVResolverOption &RHS) {
4387 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4393 if (!MVFuncsToEmit.empty())
4398 if (!MultiVersionFuncs.empty())
4399 emitMultiVersionFunctions();
4403 llvm::Constant *New) {
4404 assert(cast<llvm::Function>(Old)->isDeclaration() &&
"Not a declaration");
4406 Old->replaceAllUsesWith(New);
4407 Old->eraseFromParent();
4410void CodeGenModule::emitCPUDispatchDefinition(
GlobalDecl GD) {
4411 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4412 assert(FD &&
"Not a FunctionDecl?");
4414 const auto *DD = FD->
getAttr<CPUDispatchAttr>();
4415 assert(DD &&
"Not a cpu_dispatch Function?");
4421 UpdateMultiVersionNames(GD, FD, ResolverName);
4423 llvm::Type *ResolverType;
4426 ResolverType = llvm::FunctionType::get(
4427 llvm::PointerType::get(DeclTy,
4436 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
4437 ResolverName, ResolverType, ResolverGD,
false));
4440 ResolverFunc->setComdat(
4441 getModule().getOrInsertComdat(ResolverFunc->getName()));
4454 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
4457 EmitGlobalFunctionDefinition(ExistingDecl,
nullptr);
4463 Func = GetOrCreateLLVMFunction(
4464 MangledName, DeclTy, ExistingDecl,
4471 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
4472 llvm::transform(Features, Features.begin(),
4473 [](StringRef Str) { return Str.substr(1); });
4474 llvm::erase_if(Features, [&
Target](StringRef Feat) {
4475 return !
Target.validateCpuSupports(Feat);
4477 Options.emplace_back(cast<llvm::Function>(
Func), Features);
4481 llvm::stable_sort(Options, [](
const CodeGenFunction::FMVResolverOption &LHS,
4482 const CodeGenFunction::FMVResolverOption &RHS) {
4483 return llvm::X86::getCpuSupportsMask(LHS.Features) >
4484 llvm::X86::getCpuSupportsMask(RHS.Features);
4491 while (Options.size() > 1 && llvm::all_of(llvm::X86::getCpuSupportsMask(
4492 (Options.end() - 2)->Features),
4493 [](
auto X) { return X == 0; })) {
4494 StringRef LHSName = (Options.end() - 2)->
Function->getName();
4495 StringRef RHSName = (Options.end() - 1)->
Function->getName();
4496 if (LHSName.compare(RHSName) < 0)
4497 Options.erase(Options.end() - 2);
4499 Options.erase(Options.end() - 1);
4503 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4507 auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD));
4508 unsigned AS = IFunc->getType()->getPointerAddressSpace();
4512 if (!isa<llvm::GlobalIFunc>(IFunc)) {
4513 auto *GI = llvm::GlobalIFunc::create(DeclTy, AS,
Linkage,
"",
4520 *
this, GD, FD,
true);
4523 auto *GA = llvm::GlobalAlias::create(DeclTy, AS,
Linkage, AliasName,
4531void CodeGenModule::AddDeferredMultiVersionResolverToEmit(
GlobalDecl GD) {
4532 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4533 assert(FD &&
"Not a FunctionDecl?");
4536 std::string MangledName =
4538 if (!DeferredResolversToEmit.insert(MangledName).second)
4541 MultiVersionFuncs.push_back(GD);
4547llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
GlobalDecl GD) {
4548 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4549 assert(FD &&
"Not a FunctionDecl?");
4551 std::string MangledName =
4556 std::string ResolverName = MangledName;
4560 llvm_unreachable(
"unexpected MultiVersionKind::None for resolver");
4564 ResolverName +=
".ifunc";
4571 ResolverName +=
".resolver";
4574 bool ShouldReturnIFunc =
4584 if (ResolverGV && (isa<llvm::GlobalIFunc>(ResolverGV) || !ShouldReturnIFunc))
4593 AddDeferredMultiVersionResolverToEmit(GD);
4597 if (ShouldReturnIFunc) {
4599 llvm::Type *ResolverType =
4600 llvm::FunctionType::get(llvm::PointerType::get(DeclTy, AS),
false);
4601 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4602 MangledName +
".resolver", ResolverType,
GlobalDecl{},
4604 llvm::GlobalIFunc *GIF =
4607 GIF->setName(ResolverName);
4614 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4616 assert(isa<llvm::GlobalValue>(Resolver) && !ResolverGV &&
4617 "Resolver should be created for the first time");
4622bool CodeGenModule::shouldDropDLLAttribute(
const Decl *
D,
4623 const llvm::GlobalValue *GV)
const {
4624 auto SC = GV->getDLLStorageClass();
4625 if (SC == llvm::GlobalValue::DefaultStorageClass)
4628 return (((SC == llvm::GlobalValue::DLLImportStorageClass &&
4629 !MRD->
hasAttr<DLLImportAttr>()) ||
4630 (SC == llvm::GlobalValue::DLLExportStorageClass &&
4631 !MRD->
hasAttr<DLLExportAttr>())) &&
4642llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
4643 StringRef MangledName, llvm::Type *Ty,
GlobalDecl GD,
bool ForVTable,
4644 bool DontDefer,
bool IsThunk, llvm::AttributeList ExtraAttrs,
4648 std::string NameWithoutMultiVersionMangling;
4651 if (
const FunctionDecl *FD = cast_or_null<FunctionDecl>(
D)) {
4653 if (
getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
4654 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->
isDefined() &&
4655 !DontDefer && !IsForDefinition) {
4658 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
4660 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
4669 UpdateMultiVersionNames(GD, FD, MangledName);
4670 if (!IsForDefinition) {
4676 AddDeferredMultiVersionResolverToEmit(GD);
4678 *
this, GD, FD,
true);
4680 return GetOrCreateMultiVersionResolver(GD);
4685 if (!NameWithoutMultiVersionMangling.empty())
4686 MangledName = NameWithoutMultiVersionMangling;
4691 if (WeakRefReferences.erase(Entry)) {
4693 if (FD && !FD->
hasAttr<WeakAttr>())
4694 Entry->setLinkage(llvm::Function::ExternalLinkage);
4698 if (
D && shouldDropDLLAttribute(
D, Entry)) {
4699 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4705 if (IsForDefinition && !Entry->isDeclaration()) {
4712 DiagnosedConflictingDefinitions.insert(GD).second) {
4716 diag::note_previous_definition);
4720 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
4721 (Entry->getValueType() == Ty)) {
4728 if (!IsForDefinition)
4735 bool IsIncompleteFunction =
false;
4737 llvm::FunctionType *FTy;
4738 if (isa<llvm::FunctionType>(Ty)) {
4739 FTy = cast<llvm::FunctionType>(Ty);
4741 FTy = llvm::FunctionType::get(
VoidTy,
false);
4742 IsIncompleteFunction =
true;
4746 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
4747 Entry ? StringRef() : MangledName, &
getModule());
4752 DeferredAnnotations[MangledName] = cast<ValueDecl>(
D);
4769 if (!Entry->use_empty()) {
4771 Entry->removeDeadConstantUsers();
4777 assert(F->getName() == MangledName &&
"name was uniqued!");
4779 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
4780 if (ExtraAttrs.hasFnAttrs()) {
4781 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
4789 if (isa_and_nonnull<CXXDestructorDecl>(
D) &&
4790 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(
D),
4792 addDeferredDeclToEmit(GD);
4797 auto DDI = DeferredDecls.find(MangledName);
4798 if (DDI != DeferredDecls.end()) {
4802 addDeferredDeclToEmit(DDI->second);
4803 DeferredDecls.erase(DDI);
4818 for (
const auto *FD = cast<FunctionDecl>(
D)->getMostRecentDecl(); FD;
4831 if (!IsIncompleteFunction) {
4832 assert(F->getFunctionType() == Ty);
4848 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4855 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(GD.
getDecl())) {
4858 DD->getParent()->getNumVBases() == 0)
4863 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
4864 false, llvm::AttributeList(),
4867 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
4868 cast<FunctionDecl>(GD.
getDecl())->hasAttr<CUDAGlobalAttr>()) {
4870 cast<llvm::Function>(F->stripPointerCasts()), GD);
4871 if (IsForDefinition)
4879 llvm::GlobalValue *F =
4882 return llvm::NoCFIValue::get(F);
4892 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
4895 if (!
C.getLangOpts().CPlusPlus)
4900 (Name ==
"_ZSt9terminatev" || Name ==
"?terminate@@YAXXZ")
4901 ?
C.Idents.get(
"terminate")
4902 :
C.Idents.get(Name);
4904 for (
const auto &N : {
"__cxxabiv1",
"std"}) {
4908 if (
auto *LSD = dyn_cast<LinkageSpecDecl>(
Result))
4909 for (
const auto *
Result : LSD->lookup(&NS))
4910 if ((ND = dyn_cast<NamespaceDecl>(
Result)))
4915 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
4924 llvm::Function *F, StringRef Name) {
4930 if (!Local && CGM.
getTriple().isWindowsItaniumEnvironment() &&
4933 if (!FD || FD->
hasAttr<DLLImportAttr>()) {
4934 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4935 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
4942 llvm::AttributeList ExtraAttrs,
bool Local,
bool AssumeConvergent) {
4943 if (AssumeConvergent) {
4945 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
4953 llvm::Constant *
C = GetOrCreateLLVMFunction(
4955 false,
false, ExtraAttrs);
4957 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
4973 llvm::AttributeList ExtraAttrs,
bool Local,
4974 bool AssumeConvergent) {
4975 if (AssumeConvergent) {
4977 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
4981 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
4985 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
4994 markRegisterParameterAttributes(F);
5020 if (WeakRefReferences.erase(Entry)) {
5022 Entry->setLinkage(llvm::Function::ExternalLinkage);
5026 if (
D && shouldDropDLLAttribute(
D, Entry))
5027 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5029 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd &&
D)
5032 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
5037 if (IsForDefinition && !Entry->isDeclaration()) {
5045 (OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
5047 DiagnosedConflictingDefinitions.insert(
D).second) {
5051 diag::note_previous_definition);
5056 if (Entry->getType()->getAddressSpace() != TargetAS)
5057 return llvm::ConstantExpr::getAddrSpaceCast(
5058 Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
5062 if (!IsForDefinition)
5068 auto *GV =
new llvm::GlobalVariable(
5069 getModule(), Ty,
false, llvm::GlobalValue::ExternalLinkage,
nullptr,
5070 MangledName,
nullptr, llvm::GlobalVariable::NotThreadLocal,
5071 getContext().getTargetAddressSpace(DAddrSpace));
5076 GV->takeName(Entry);
5078 if (!Entry->use_empty()) {
5079 Entry->replaceAllUsesWith(GV);
5082 Entry->eraseFromParent();
5088 auto DDI = DeferredDecls.find(MangledName);
5089 if (DDI != DeferredDecls.end()) {
5092 addDeferredDeclToEmit(DDI->second);
5093 DeferredDecls.erase(DDI);
5098 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
5103 GV->setConstant(
D->getType().isConstantStorage(
getContext(),
false,
false));
5105 GV->setAlignment(
getContext().getDeclAlign(
D).getAsAlign());
5109 if (
D->getTLSKind()) {
5111 CXXThreadLocals.push_back(
D);
5119 if (
getContext().isMSStaticDataMemberInlineDefinition(
D)) {
5120 EmitGlobalVarDefinition(
D);
5124 if (
D->hasExternalStorage()) {
5125 if (
const SectionAttr *SA =
D->
getAttr<SectionAttr>())
5126 GV->setSection(SA->getName());
5130 if (
getTriple().getArch() == llvm::Triple::xcore &&
5132 D->getType().isConstant(Context) &&
5134 GV->setSection(
".cp.rodata");
5137 if (
const auto *CMA =
D->
getAttr<CodeModelAttr>())
5138 GV->setCodeModel(CMA->getModel());
5143 if (Context.
getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
5144 D->getType().isConstQualified() && !GV->hasInitializer() &&
5145 !
D->hasDefinition() &&
D->hasInit() && !
D->
hasAttr<DLLImportAttr>()) {
5149 if (!HasMutableFields) {
5151 const Expr *InitExpr =
D->getAnyInitializer(InitDecl);
5156 auto *InitType =
Init->getType();
5157 if (GV->getValueType() != InitType) {
5162 GV->setName(StringRef());
5165 auto *NewGV = cast<llvm::GlobalVariable>(
5167 ->stripPointerCasts());
5170 GV->eraseFromParent();
5173 GV->setInitializer(
Init);
5174 GV->setConstant(
true);
5175 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
5190 D->hasExternalStorage())
5195 SanitizerMD->reportGlobal(GV, *
D);
5198 D ?
D->getType().getAddressSpace()
5200 assert(
getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
5201 if (DAddrSpace != ExpectedAS) {
5203 *
this, GV, DAddrSpace, ExpectedAS,
5214 if (isa<CXXConstructorDecl>(
D) || isa<CXXDestructorDecl>(
D))
5216 false, IsForDefinition);
5218 if (isa<CXXMethodDecl>(
D)) {
5226 if (isa<FunctionDecl>(
D)) {
5237 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes
Linkage,
5238 llvm::Align Alignment) {
5239 llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
5240 llvm::GlobalVariable *OldGV =
nullptr;
5244 if (GV->getValueType() == Ty)
5249 assert(GV->isDeclaration() &&
"Declaration has wrong type!");
5254 GV =
new llvm::GlobalVariable(
getModule(), Ty,
true,
5259 GV->takeName(OldGV);
5261 if (!OldGV->use_empty()) {
5262 OldGV->replaceAllUsesWith(GV);
5265 OldGV->eraseFromParent();
5269 !GV->hasAvailableExternallyLinkage())
5270 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5272 GV->setAlignment(Alignment);
5286 assert(
D->hasGlobalStorage() &&
"Not a global variable");
5304 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
5309 assert(!
D->getInit() &&
"Cannot emit definite definitions here!");
5317 if (GV && !GV->isDeclaration())
5322 if (!MustBeEmitted(
D) && !GV) {
5323 DeferredDecls[MangledName] =
D;
5328 EmitGlobalVarDefinition(
D);
5332 if (
auto const *
V = dyn_cast<const VarDecl>(
D))
5333 EmitExternalVarDeclaration(
V);
5334 if (
auto const *FD = dyn_cast<const FunctionDecl>(
D))
5335 EmitExternalFunctionDeclaration(FD);
5344 if (LangOpts.OpenCL) {
5355 if (LangOpts.SYCLIsDevice &&
5359 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
5361 if (
D->
hasAttr<CUDAConstantAttr>())
5367 if (
D->getType().isConstQualified())
5373 if (LangOpts.OpenMP) {
5375 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(
D, AS))
5383 if (LangOpts.OpenCL)
5385 if (LangOpts.SYCLIsDevice)
5387 if (LangOpts.HIP && LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())
5395 if (
auto AS =
getTarget().getConstantAddressSpace())
5408static llvm::Constant *
5410 llvm::GlobalVariable *GV) {
5411 llvm::Constant *Cast = GV;
5417 llvm::PointerType::get(
5424template<
typename SomeDecl>
5426 llvm::GlobalValue *GV) {
5432 if (!
D->template hasAttr<UsedAttr>())
5441 const SomeDecl *
First =
D->getFirstDecl();
5442 if (
First->getDeclContext()->isRecord() || !
First->isInExternCContext())
5448 std::pair<StaticExternCMap::iterator, bool> R =
5449 StaticExternCValues.insert(std::make_pair(
D->getIdentifier(), GV));
5454 R.first->second =
nullptr;
5465 if (
auto *VD = dyn_cast<VarDecl>(&
D))
5479 llvm_unreachable(
"No such linkage");
5487 llvm::GlobalObject &GO) {
5490 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
5498void CodeGenModule::EmitGlobalVarDefinition(
const VarDecl *
D,
5508 if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
5509 OpenMPRuntime->emitTargetGlobalVariable(
D))
5512 llvm::TrackingVH<llvm::Constant>
Init;
5513 bool NeedsGlobalCtor =
false;
5517 bool IsDefinitionAvailableExternally =
5519 bool NeedsGlobalDtor =
5520 !IsDefinitionAvailableExternally &&
5527 if (IsDefinitionAvailableExternally &&
5528 (!
D->hasConstantInitialization() ||
5532 !
D->getType().isConstantStorage(
getContext(),
true,
true)))
5536 const Expr *InitExpr =
D->getAnyInitializer(InitDecl);
5538 std::optional<ConstantEmitter> emitter;
5543 bool IsCUDASharedVar =
5548 bool IsCUDAShadowVar =
5552 bool IsCUDADeviceShadowVar =
5554 (
D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5555 D->getType()->isCUDADeviceBuiltinTextureType());
5557 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
5558 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
5559 else if (
D->
hasAttr<LoaderUninitializedAttr>())
5560 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
5561 else if (!InitExpr) {
5575 emitter.emplace(*
this);
5576 llvm::Constant *
Initializer = emitter->tryEmitForInitializer(*InitDecl);
5579 if (
D->getType()->isReferenceType())
5584 if (!IsDefinitionAvailableExternally)
5585 NeedsGlobalCtor =
true;
5589 NeedsGlobalCtor =
false;
5601 DelayedCXXInitPosition.erase(
D);
5608 assert(VarSize == CstSize &&
"Emitted constant has unexpected size");
5613 llvm::Type* InitType =
Init->getType();
5614 llvm::Constant *Entry =
5618 Entry = Entry->stripPointerCasts();
5621 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
5632 if (!GV || GV->getValueType() != InitType ||
5633 GV->getType()->getAddressSpace() !=
5637 Entry->setName(StringRef());
5640 GV = cast<llvm::GlobalVariable>(
5642 ->stripPointerCasts());
5645 llvm::Constant *NewPtrForOldDecl =
5646 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5648 Entry->replaceAllUsesWith(NewPtrForOldDecl);
5651 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
5669 if (LangOpts.CUDA) {
5670 if (LangOpts.CUDAIsDevice) {
5671 if (
Linkage != llvm::GlobalValue::InternalLinkage &&
5673 D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5674 D->getType()->isCUDADeviceBuiltinTextureType()))
5675 GV->setExternallyInitialized(
true);
5685 GV->setInitializer(
Init);
5687 emitter->finalize(GV);
5690 GV->setConstant((
D->
hasAttr<CUDAConstantAttr>() && LangOpts.CUDAIsDevice) ||
5691 (!NeedsGlobalCtor && !NeedsGlobalDtor &&
5692 D->getType().isConstantStorage(
getContext(),
true,
true)));
5695 if (
const SectionAttr *SA =
D->
getAttr<SectionAttr>()) {
5698 GV->setConstant(
true);
5703 if (std::optional<CharUnits> AlignValFromAllocate =
5705 AlignVal = *AlignValFromAllocate;
5723 Linkage == llvm::GlobalValue::ExternalLinkage &&
5726 Linkage = llvm::GlobalValue::InternalLinkage;
5730 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
5731 else if (
D->
hasAttr<DLLExportAttr>())
5732 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
5734 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
5736 if (
Linkage == llvm::GlobalVariable::CommonLinkage) {
5738 GV->setConstant(
false);
5743 if (!GV->getInitializer()->isNullValue())
5744 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
5747 setNonAliasAttributes(
D, GV);
5749 if (
D->getTLSKind() && !GV->isThreadLocal()) {
5751 CXXThreadLocals.push_back(
D);
5758 if (NeedsGlobalCtor || NeedsGlobalDtor)
5759 EmitCXXGlobalVarDeclInitFunc(
D, GV, NeedsGlobalCtor);
5761 SanitizerMD->reportGlobal(GV, *
D, NeedsGlobalCtor);
5766 DI->EmitGlobalVariable(GV,
D);
5769void CodeGenModule::EmitExternalVarDeclaration(
const VarDecl *
D) {
5774 llvm::Constant *GV =
5776 DI->EmitExternalVariable(
5777 cast<llvm::GlobalVariable>(GV->stripPointerCasts()),
D);
5781void CodeGenModule::EmitExternalFunctionDeclaration(
const FunctionDecl *FD) {
5786 auto *
Fn = cast<llvm::Function>(
5787 GetOrCreateLLVMFunction(MangledName, Ty, FD,
false));
5788 if (!
Fn->getSubprogram())
5805 if (
D->getInit() ||
D->hasExternalStorage())
5815 if (
D->
hasAttr<PragmaClangBSSSectionAttr>() ||
5816 D->
hasAttr<PragmaClangDataSectionAttr>() ||
5817 D->
hasAttr<PragmaClangRelroSectionAttr>() ||
5818 D->
hasAttr<PragmaClangRodataSectionAttr>())
5822 if (
D->getTLSKind())
5845 if (FD->isBitField())
5847 if (FD->
hasAttr<AlignedAttr>())
5869llvm::GlobalValue::LinkageTypes
5873 return llvm::Function::InternalLinkage;
5876 return llvm::GlobalVariable::WeakAnyLinkage;
5880 return llvm::GlobalVariable::LinkOnceAnyLinkage;
5885 return llvm::GlobalValue::AvailableExternallyLinkage;
5899 return !Context.
getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
5900 : llvm::Function::InternalLinkage;
5914 return llvm::Function::ExternalLinkage;
5917 return D->
hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
5918 : llvm::Function::InternalLinkage;
5919 return llvm::Function::WeakODRLinkage;
5926 CodeGenOpts.NoCommon))
5927 return llvm::GlobalVariable::CommonLinkage;
5934 return llvm::GlobalVariable::WeakODRLinkage;
5938 return llvm::GlobalVariable::ExternalLinkage;
5941llvm::GlobalValue::LinkageTypes
5950 llvm::Function *newFn) {
5952 if (old->use_empty())
5955 llvm::Type *newRetTy = newFn->getReturnType();
5960 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
5962 llvm::User *user = ui->getUser();
5966 if (
auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
5967 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
5973 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
5976 if (!callSite->isCallee(&*ui))
5981 if (callSite->getType() != newRetTy && !callSite->use_empty())
5986 llvm::AttributeList oldAttrs = callSite->getAttributes();
5989 unsigned newNumArgs = newFn->arg_size();
5990 if (callSite->arg_size() < newNumArgs)
5996 bool dontTransform =
false;
5997 for (llvm::Argument &A : newFn->args()) {
5998 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
5999 dontTransform =
true;
6004 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
6012 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
6016 callSite->getOperandBundlesAsDefs(newBundles);
6018 llvm::CallBase *newCall;
6019 if (isa<llvm::CallInst>(callSite)) {
6020 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles,
"",
6021 callSite->getIterator());
6023 auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
6024 newCall = llvm::InvokeInst::Create(
6025 newFn, oldInvoke->getNormalDest(), oldInvoke->getUnwindDest(),
6026 newArgs, newBundles,
"", callSite->getIterator());
6030 if (!newCall->getType()->isVoidTy())
6031 newCall->takeName(callSite);
6032 newCall->setAttributes(
6033 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
6034 oldAttrs.getRetAttrs(), newArgAttrs));
6035 newCall->setCallingConv(callSite->getCallingConv());
6038 if (!callSite->use_empty())
6039 callSite->replaceAllUsesWith(newCall);
6042 if (callSite->getDebugLoc())
6043 newCall->setDebugLoc(callSite->getDebugLoc());
6045 callSitesToBeRemovedFromParent.push_back(callSite);
6048 for (
auto *callSite : callSitesToBeRemovedFromParent) {
6049 callSite->eraseFromParent();
6063 llvm::Function *NewFn) {
6065 if (!isa<llvm::Function>(Old))
return;
6073 (LangOpts.CUDA && !shouldEmitCUDAGlobalVar(VD)))
6085void CodeGenModule::EmitGlobalFunctionDefinition(
GlobalDecl GD,
6086 llvm::GlobalValue *GV) {
6087 const auto *
D = cast<FunctionDecl>(GD.
getDecl());
6094 if (!GV || (GV->getValueType() != Ty))
6100 if (!GV->isDeclaration())
6107 auto *Fn = cast<llvm::Function>(GV);
6119 setNonAliasAttributes(GD, Fn);
6122 if (
const ConstructorAttr *CA =
D->
getAttr<ConstructorAttr>())
6124 if (
const DestructorAttr *DA =
D->
getAttr<DestructorAttr>())
6130void CodeGenModule::EmitAliasDefinition(
GlobalDecl GD) {
6131 const auto *
D = cast<ValueDecl>(GD.
getDecl());
6132 const AliasAttr *AA =
D->
getAttr<AliasAttr>();
6133 assert(AA &&
"Not an alias?");
6137 if (AA->getAliasee() == MangledName) {
6138 Diags.
Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6145 if (Entry && !Entry->isDeclaration())
6148 Aliases.push_back(GD);
6154 llvm::Constant *Aliasee;
6155 llvm::GlobalValue::LinkageTypes
LT;
6156 if (isa<llvm::FunctionType>(DeclTy)) {
6157 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
6163 if (
const auto *VD = dyn_cast<VarDecl>(GD.
getDecl()))
6170 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
6172 llvm::GlobalAlias::create(DeclTy, AS,
LT,
"", Aliasee, &
getModule());
6175 if (GA->getAliasee() == Entry) {
6176 Diags.
Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6180 assert(Entry->isDeclaration());
6189 GA->takeName(Entry);
6191 Entry->replaceAllUsesWith(GA);
6192 Entry->eraseFromParent();
6194 GA->setName(MangledName);
6202 GA->setLinkage(llvm::Function::WeakAnyLinkage);
6205 if (
const auto *VD = dyn_cast<VarDecl>(
D))
6206 if (VD->getTLSKind())
6212 if (isa<VarDecl>(
D))
6214 DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD);
6217void CodeGenModule::emitIFuncDefinition(
GlobalDecl GD) {
6218 const auto *
D = cast<ValueDecl>(GD.
getDecl());
6219 const IFuncAttr *IFA =
D->
getAttr<IFuncAttr>();
6220 assert(IFA &&
"Not an ifunc?");
6224 if (IFA->getResolver() == MangledName) {
6225 Diags.
Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6231 if (Entry && !Entry->isDeclaration()) {
6234 DiagnosedConflictingDefinitions.insert(GD).second) {
6238 diag::note_previous_definition);
6243 Aliases.push_back(GD);
6249 llvm::Constant *Resolver =
6250 GetOrCreateLLVMFunction(IFA->getResolver(),
VoidTy, {},
6254 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
6255 DeclTy, AS, llvm::Function::ExternalLinkage,
"", Resolver, &
getModule());
6257 if (GIF->getResolver() == Entry) {
6258 Diags.
Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6261 assert(Entry->isDeclaration());
6270 GIF->takeName(Entry);
6272 Entry->replaceAllUsesWith(GIF);
6273 Entry->eraseFromParent();
6275 GIF->setName(MangledName);
6281 return llvm::Intrinsic::getOrInsertDeclaration(&
getModule(),
6282 (llvm::Intrinsic::ID)IID, Tys);
6285static llvm::StringMapEntry<llvm::GlobalVariable *> &
6288 bool &IsUTF16,
unsigned &StringLength) {
6289 StringRef String = Literal->getString();
6290 unsigned NumBytes = String.size();
6293 if (!Literal->containsNonAsciiOrNull()) {
6294 StringLength = NumBytes;
6295 return *Map.insert(std::make_pair(String,
nullptr)).first;
6302 const llvm::UTF8 *FromPtr = (
const llvm::UTF8 *)String.data();
6303 llvm::UTF16 *ToPtr = &ToBuf[0];
6305 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6306 ToPtr + NumBytes, llvm::strictConversion);
6309 StringLength = ToPtr - &ToBuf[0];
6313 return *Map.insert(std::make_pair(
6314 StringRef(
reinterpret_cast<const char *
>(ToBuf.data()),
6315 (StringLength + 1) * 2),
6321 unsigned StringLength = 0;
6322 bool isUTF16 =
false;
6323 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
6328 if (
auto *
C = Entry.second)
6333 const llvm::Triple &Triple =
getTriple();
6336 const bool IsSwiftABI =
6337 static_cast<unsigned>(CFRuntime) >=
6342 if (!CFConstantStringClassRef) {
6343 const char *CFConstantStringClassName =
"__CFConstantStringClassReference";
6345 Ty = llvm::ArrayType::get(Ty, 0);
6347 switch (CFRuntime) {
6351 CFConstantStringClassName =
6352 Triple.isOSDarwin() ?
"$s15SwiftFoundation19_NSCFConstantStringCN"
6353 :
"$s10Foundation19_NSCFConstantStringCN";
6357 CFConstantStringClassName =
6358 Triple.isOSDarwin() ?
"$S15SwiftFoundation19_NSCFConstantStringCN"
6359 :
"$S10Foundation19_NSCFConstantStringCN";
6363 CFConstantStringClassName =
6364 Triple.isOSDarwin() ?
"__T015SwiftFoundation19_NSCFConstantStringCN"
6365 :
"__T010Foundation19_NSCFConstantStringCN";
6372 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
6373 llvm::GlobalValue *GV =
nullptr;
6375 if ((GV = dyn_cast<llvm::GlobalValue>(
C))) {
6382 if ((VD = dyn_cast<VarDecl>(
Result)))
6385 if (Triple.isOSBinFormatELF()) {
6387 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6389 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6390 if (!VD || !VD->
hasAttr<DLLExportAttr>())
6391 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
6393 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
6401 CFConstantStringClassRef =
6402 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(
C, Ty) :
C;
6407 auto *STy = cast<llvm::StructType>(
getTypes().ConvertType(CFTy));
6410 auto Fields = Builder.beginStruct(STy);
6413 Fields.add(cast<llvm::Constant>(CFConstantStringClassRef));
6417 Fields.addInt(
IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
6418 Fields.addInt(
Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
6420 Fields.addInt(
IntTy, isUTF16 ? 0x07d0 : 0x07C8);
6424 llvm::Constant *
C =
nullptr;
6427 reinterpret_cast<uint16_t *
>(
const_cast<char *
>(Entry.first().data())),
6428 Entry.first().size() / 2);
6429 C = llvm::ConstantDataArray::get(VMContext, Arr);
6431 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
6437 new llvm::GlobalVariable(
getModule(),
C->getType(),
true,
6438 llvm::GlobalValue::PrivateLinkage,
C,
".str");
6439 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6449 if (Triple.isOSBinFormatMachO())
6450 GV->setSection(isUTF16 ?
"__TEXT,__ustring"
6451 :
"__TEXT,__cstring,cstring_literals");
6454 else if (Triple.isOSBinFormatELF())
6455 GV->setSection(
".rodata");
6461 llvm::IntegerType *LengthTy =
6471 Fields.addInt(LengthTy, StringLength);
6479 GV = Fields.finishAndCreateGlobal(
"_unnamed_cfstring_", Alignment,
6481 llvm::GlobalVariable::PrivateLinkage);
6482 GV->addAttribute(
"objc_arc_inert");
6483 switch (Triple.getObjectFormat()) {
6484 case llvm::Triple::UnknownObjectFormat:
6485 llvm_unreachable(
"unknown file format");
6486 case llvm::Triple::DXContainer:
6487 case llvm::Triple::GOFF:
6488 case llvm::Triple::SPIRV:
6489 case llvm::Triple::XCOFF:
6490 llvm_unreachable(
"unimplemented");
6491 case llvm::Triple::COFF:
6492 case llvm::Triple::ELF:
6493 case llvm::Triple::Wasm:
6494 GV->setSection(
"cfstring");
6496 case llvm::Triple::MachO:
6497 GV->setSection(
"__DATA,__cfstring");
6506 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
6510 if (ObjCFastEnumerationStateType.
isNull()) {
6512 D->startDefinition();
6520 for (
size_t i = 0; i < 4; ++i) {
6525 FieldTypes[i],
nullptr,
6533 D->completeDefinition();
6537 return ObjCFastEnumerationStateType;
6546 if (
E->getCharByteWidth() == 1) {
6551 assert(CAT &&
"String literal not of constant array type!");
6553 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
6557 llvm::Type *ElemTy = AType->getElementType();
6558 unsigned NumElements = AType->getNumElements();
6561 if (ElemTy->getPrimitiveSizeInBits() == 16) {
6563 Elements.reserve(NumElements);
6565 for(
unsigned i = 0, e =
E->getLength(); i != e; ++i)
6566 Elements.push_back(
E->getCodeUnit(i));
6567 Elements.resize(NumElements);
6568 return llvm::ConstantDataArray::get(VMContext, Elements);
6571 assert(ElemTy->getPrimitiveSizeInBits() == 32);
6573 Elements.reserve(NumElements);
6575 for(
unsigned i = 0, e =
E->getLength(); i != e; ++i)
6576 Elements.push_back(
E->getCodeUnit(i));
6577 Elements.resize(NumElements);
6578 return llvm::ConstantDataArray::get(VMContext, Elements);
6581static llvm::GlobalVariable *
6590 auto *GV =
new llvm::GlobalVariable(
6591 M,
C->getType(), !CGM.
getLangOpts().WritableStrings,
LT,
C, GlobalName,
6592 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
6594 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6595 if (GV->isWeakForLinker()) {
6596 assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
6597 GV->setComdat(M.getOrInsertComdat(GV->getName()));
6613 llvm::GlobalVariable **Entry =
nullptr;
6614 if (!LangOpts.WritableStrings) {
6615 Entry = &ConstantStringMap[
C];
6616 if (
auto GV = *Entry) {
6617 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
6620 GV->getValueType(), Alignment);
6625 StringRef GlobalVariableName;
6626 llvm::GlobalValue::LinkageTypes
LT;
6631 if (
getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
6632 !LangOpts.WritableStrings) {
6633 llvm::raw_svector_ostream Out(MangledNameBuffer);
6635 LT = llvm::GlobalValue::LinkOnceODRLinkage;
6636 GlobalVariableName = MangledNameBuffer;
6638 LT = llvm::GlobalValue::PrivateLinkage;
6639 GlobalVariableName = Name;
6651 SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0),
"<string literal>");
6654 GV->getValueType(), Alignment);
6671 const std::string &Str,
const char *GlobalName) {
6672 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
6677 llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
6680 llvm::GlobalVariable **Entry =
nullptr;
6681 if (!LangOpts.WritableStrings) {
6682 Entry = &ConstantStringMap[
C];
6683 if (
auto GV = *Entry) {
6684 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
6687 GV->getValueType(), Alignment);
6693 GlobalName =
".str";
6696 GlobalName, Alignment);
6701 GV->getValueType(), Alignment);
6706 assert((
E->getStorageDuration() ==
SD_Static ||
6707 E->getStorageDuration() ==
SD_Thread) &&
"not a global temporary");
6708 const auto *VD = cast<VarDecl>(
E->getExtendingDecl());
6713 if (
Init ==
E->getSubExpr())
6718 auto InsertResult = MaterializedGlobalTemporaryMap.insert({
E,
nullptr});
6719 if (!InsertResult.second) {
6722 if (!InsertResult.first->second) {
6727 InsertResult.first->second =
new llvm::GlobalVariable(
6728 getModule(),
Type,
false, llvm::GlobalVariable::InternalLinkage,
6732 llvm::cast<llvm::GlobalVariable>(
6733 InsertResult.first->second->stripPointerCasts())
6742 llvm::raw_svector_ostream Out(Name);
6744 VD,
E->getManglingNumber(), Out);
6747 if (
E->getStorageDuration() ==
SD_Static && VD->evaluateValue()) {
6753 Value =
E->getOrCreateValue(
false);
6764 std::optional<ConstantEmitter> emitter;
6765 llvm::Constant *InitialValue =
nullptr;
6766 bool Constant =
false;
6770 emitter.emplace(*
this);
6771 InitialValue = emitter->emitForInitializer(*
Value, AddrSpace,
6776 Type = InitialValue->getType();
6785 if (
Linkage == llvm::GlobalVariable::ExternalLinkage) {
6787 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
6791 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
6795 Linkage = llvm::GlobalVariable::InternalLinkage;
6799 auto *GV =
new llvm::GlobalVariable(
6801 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
6802 if (emitter) emitter->finalize(GV);
6804 if (!llvm::GlobalValue::isLocalLinkage(
Linkage)) {
6806 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
6808 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6812 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
6813 if (VD->getTLSKind())
6815 llvm::Constant *CV = GV;
6819 llvm::PointerType::get(
6825 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[
E];
6827 Entry->replaceAllUsesWith(CV);
6828 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
6837void CodeGenModule::EmitObjCPropertyImplementations(
const
6839 for (
const auto *PID :
D->property_impls()) {
6850 if (!Getter || Getter->isSynthesizedAccessorStub())
6853 auto *Setter = PID->getSetterMethodDecl();
6854 if (!PD->
isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
6865 if (ivar->getType().isDestructedType())
6875 E =
D->init_end(); B !=
E; ++B) {
6898 D->addInstanceMethod(DTORMethod);
6900 D->setHasDestructors(
true);
6905 if (
D->getNumIvarInitializers() == 0 ||
6919 D->addInstanceMethod(CTORMethod);
6921 D->setHasNonZeroConstructors(
true);
6932 EmitDeclContext(LSD);
6937 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
6940 std::unique_ptr<CodeGenFunction> &CurCGF =
6941 GlobalTopLevelStmtBlockInFlight.first;
6945 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
6953 std::string Name =
"__stmts__" + llvm::utostr(CXXGlobalInits.size());
6959 llvm::Function *
Fn = llvm::Function::Create(
6960 FnTy, llvm::GlobalValue::InternalLinkage, Name, &
getModule());
6963 GlobalTopLevelStmtBlockInFlight.second =
D;
6964 CurCGF->StartFunction(
GlobalDecl(), RetTy, Fn, FnInfo, Args,
6966 CXXGlobalInits.push_back(Fn);
6969 CurCGF->EmitStmt(
D->getStmt());
6972void CodeGenModule::EmitDeclContext(
const DeclContext *DC) {
6973 for (
auto *I : DC->
decls()) {
6979 if (
auto *OID = dyn_cast<ObjCImplDecl>(I)) {
6980 for (
auto *M : OID->methods())
6999 case Decl::CXXConversion:
7000 case Decl::CXXMethod:
7001 case Decl::Function:
7008 case Decl::CXXDeductionGuide:
7013 case Decl::Decomposition:
7014 case Decl::VarTemplateSpecialization:
7016 if (
auto *DD = dyn_cast<DecompositionDecl>(
D))
7017 for (
auto *B : DD->bindings())
7018 if (
auto *HD = B->getHoldingVar())
7024 case Decl::IndirectField:
7028 case Decl::Namespace:
7029 EmitDeclContext(cast<NamespaceDecl>(
D));
7031 case Decl::ClassTemplateSpecialization: {
7032 const auto *Spec = cast<ClassTemplateSpecializationDecl>(
D);
7034 if (Spec->getSpecializationKind() ==
7036 Spec->hasDefinition())
7037 DI->completeTemplateDefinition(*Spec);
7039 case Decl::CXXRecord: {
7046 DI->completeUnusedClass(*CRD);
7049 for (
auto *I : CRD->
decls())
7050 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
7055 case Decl::UsingShadow:
7056 case Decl::ClassTemplate:
7057 case Decl::VarTemplate:
7059 case Decl::VarTemplatePartialSpecialization:
7060 case Decl::FunctionTemplate:
7061 case Decl::TypeAliasTemplate:
7068 DI->EmitUsingDecl(cast<UsingDecl>(*
D));
7070 case Decl::UsingEnum:
7072 DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*
D));
7074 case Decl::NamespaceAlias:
7076 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*
D));
7078 case Decl::UsingDirective:
7080 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*
D));
7082 case Decl::CXXConstructor:
7085 case Decl::CXXDestructor:
7089 case Decl::StaticAssert:
7096 case Decl::ObjCInterface:
7097 case Decl::ObjCCategory:
7100 case Decl::ObjCProtocol: {
7101 auto *Proto = cast<ObjCProtocolDecl>(
D);
7102 if (Proto->isThisDeclarationADefinition())
7107 case Decl::ObjCCategoryImpl:
7110 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(
D));
7113 case Decl::ObjCImplementation: {
7114 auto *OMD = cast<ObjCImplementationDecl>(
D);
7115 EmitObjCPropertyImplementations(OMD);
7116 EmitObjCIvarInitializations(OMD);
7121 DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
7122 OMD->getClassInterface()), OMD->getLocation());
7125 case Decl::ObjCMethod: {
7126 auto *OMD = cast<ObjCMethodDecl>(
D);
7132 case Decl::ObjCCompatibleAlias:
7133 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(
D));
7136 case Decl::PragmaComment: {
7137 const auto *PCD = cast<PragmaCommentDecl>(
D);
7138 switch (PCD->getCommentKind()) {
7140 llvm_unreachable(
"unexpected pragma comment kind");
7155 case Decl::PragmaDetectMismatch: {
7156 const auto *PDMD = cast<PragmaDetectMismatchDecl>(
D);
7161 case Decl::LinkageSpec:
7162 EmitLinkageSpec(cast<LinkageSpecDecl>(
D));
7165 case Decl::FileScopeAsm: {
7167 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7170 if (LangOpts.OpenMPIsTargetDevice)
7173 if (LangOpts.SYCLIsDevice)
7175 auto *AD = cast<FileScopeAsmDecl>(
D);
7176 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
7180 case Decl::TopLevelStmt:
7181 EmitTopLevelStmt(cast<TopLevelStmtDecl>(
D));
7184 case Decl::Import: {
7185 auto *Import = cast<ImportDecl>(
D);
7188 if (!ImportedModules.insert(Import->getImportedModule()))
7192 if (!Import->getImportedOwningModule()) {
7194 DI->EmitImportDecl(*Import);
7200 if (CXX20ModuleInits && Import->getImportedModule() &&
7201 Import->getImportedModule()->isNamedModule())
7210 Visited.insert(Import->getImportedModule());
7211 Stack.push_back(Import->getImportedModule());
7213 while (!Stack.empty()) {
7215 if (!EmittedModuleInitializers.insert(Mod).second)
7225 if (Submodule->IsExplicit)
7228 if (
Visited.insert(Submodule).second)
7229 Stack.push_back(Submodule);
7236 EmitDeclContext(cast<ExportDecl>(
D));
7239 case Decl::OMPThreadPrivate:
7243 case Decl::OMPAllocate:
7247 case Decl::OMPDeclareReduction:
7251 case Decl::OMPDeclareMapper:
7255 case Decl::OMPRequires:
7260 case Decl::TypeAlias:
7262 DI->EmitAndRetainType(
7263 getContext().getTypedefType(cast<TypedefNameDecl>(
D)));
7275 DI->EmitAndRetainType(
getContext().getEnumType(cast<EnumDecl>(
D)));
7278 case Decl::HLSLBuffer:
7286 assert(isa<TypeDecl>(
D) &&
"Unsupported decl kind");
7293 if (!CodeGenOpts.CoverageMapping)
7296 case Decl::CXXConversion:
7297 case Decl::CXXMethod:
7298 case Decl::Function:
7299 case Decl::ObjCMethod:
7300 case Decl::CXXConstructor:
7301 case Decl::CXXDestructor: {
7302 if (!cast<FunctionDecl>(
D)->doesThisDeclarationHaveABody())
7310 DeferredEmptyCoverageMappingDecls.try_emplace(
D,
true);
7320 if (!CodeGenOpts.CoverageMapping)
7322 if (
const auto *Fn = dyn_cast<FunctionDecl>(
D)) {
7323 if (Fn->isTemplateInstantiation())
7326 DeferredEmptyCoverageMappingDecls.insert_or_assign(
D,
false);
7334 for (
const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
7337 const Decl *
D = Entry.first;
7339 case Decl::CXXConversion:
7340 case Decl::CXXMethod:
7341 case Decl::Function:
7342 case Decl::ObjCMethod: {
7349 case Decl::CXXConstructor: {
7356 case Decl::CXXDestructor: {
7373 if (llvm::Function *F =
getModule().getFunction(
"main")) {
7374 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
7376 auto *GA = llvm::GlobalAlias::create(
"__main_void", F);
7377 GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
7386 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
7387 return llvm::ConstantInt::get(i64, PtrInt);
7391 llvm::NamedMDNode *&GlobalMetadata,
7393 llvm::GlobalValue *Addr) {
7394 if (!GlobalMetadata)
7396 CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
7399 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
7402 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
7405bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
7406 llvm::GlobalValue *CppFunc) {
7414 if (Elem == CppFunc)
7420 for (llvm::User *User : Elem->users()) {
7424 if (
auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
7425 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
7428 for (llvm::User *CEUser : ConstExpr->users()) {
7429 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
7430 IFuncs.push_back(IFunc);
7435 CEs.push_back(ConstExpr);
7436 }
else if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
7437 IFuncs.push_back(IFunc);
7449 for (llvm::GlobalIFunc *IFunc : IFuncs)
7450 IFunc->setResolver(
nullptr);
7451 for (llvm::ConstantExpr *ConstExpr : CEs)
7452 ConstExpr->destroyConstant();
7456 Elem->eraseFromParent();
7458 for (llvm::GlobalIFunc *IFunc : IFuncs) {
7463 llvm::FunctionType::get(IFunc->getType(),
false);
7464 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
7465 CppFunc->getName(), ResolverTy, {},
false);
7466 IFunc->setResolver(Resolver);
7476void CodeGenModule::EmitStaticExternCAliases() {
7479 for (
auto &I : StaticExternCValues) {
7481 llvm::GlobalValue *Val = I.second;
7489 llvm::GlobalValue *ExistingElem =
7490 getModule().getNamedValue(Name->getName());
7494 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
7501 auto Res = Manglings.find(MangledName);
7502 if (Res == Manglings.end())
7504 Result = Res->getValue();
7515void CodeGenModule::EmitDeclMetadata() {
7516 llvm::NamedMDNode *GlobalMetadata =
nullptr;
7518 for (
auto &I : MangledDeclNames) {
7519 llvm::GlobalValue *Addr =
getModule().getNamedValue(I.second);
7529void CodeGenFunction::EmitDeclMetadata() {
7530 if (LocalDeclMap.empty())
return;
7535 unsigned DeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
7537 llvm::NamedMDNode *GlobalMetadata =
nullptr;
7539 for (
auto &I : LocalDeclMap) {
7540 const Decl *
D = I.first;
7541 llvm::Value *Addr = I.second.emitRawPointer(*
this);
7542 if (
auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
7544 Alloca->setMetadata(
7545 DeclPtrKind, llvm::MDNode::get(
7546 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
7547 }
else if (
auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
7554void CodeGenModule::EmitVersionIdentMetadata() {
7555 llvm::NamedMDNode *IdentMetadata =
7556 TheModule.getOrInsertNamedMetadata(
"llvm.ident");
7558 llvm::LLVMContext &Ctx = TheModule.getContext();
7560 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
7561 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
7564void CodeGenModule::EmitCommandLineMetadata() {
7565 llvm::NamedMDNode *CommandLineMetadata =
7566 TheModule.getOrInsertNamedMetadata(
"llvm.commandline");
7568 llvm::LLVMContext &Ctx = TheModule.getContext();
7570 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
7571 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
7574void CodeGenModule::EmitCoverageFile() {
7575 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu");
7579 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
7580 llvm::LLVMContext &Ctx = TheModule.getContext();
7581 auto *CoverageDataFile =
7583 auto *CoverageNotesFile =
7585 for (
int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
7586 llvm::MDNode *CU = CUNode->getOperand(i);
7587 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
7588 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
7609 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
7611 for (
auto RefExpr :
D->varlist()) {
7612 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
7614 VD->getAnyInitializer() &&
7615 !VD->getAnyInitializer()->isConstantInitializer(
getContext(),
7622 VD, Addr, RefExpr->getBeginLoc(), PerformInit))
7623 CXXGlobalInits.push_back(InitFunction);
7628CodeGenModule::CreateMetadataIdentifierImpl(
QualType T, MetadataTypeMap &Map,
7632 FnType->getReturnType(), FnType->getParamTypes(),
7633 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
7635 llvm::Metadata *&InternalId = Map[
T.getCanonicalType()];
7640 std::string OutName;
7641 llvm::raw_string_ostream Out(OutName);
7646 Out <<
".normalized";
7660 return CreateMetadataIdentifierImpl(
T, MetadataIdMap,
"");
7665 return CreateMetadataIdentifierImpl(
T, VirtualMetadataIdMap,
".virtual");
7685 for (
auto &Param : FnType->param_types())
7690 GeneralizedParams, FnType->getExtProtoInfo());
7697 llvm_unreachable(
"Encountered unknown FunctionType");
7702 GeneralizedMetadataIdMap,
".generalized");
7709 return ((LangOpts.
Sanitize.
has(SanitizerKind::CFIVCall) &&
7711 (LangOpts.
Sanitize.
has(SanitizerKind::CFINVCall) &&
7713 (LangOpts.
Sanitize.
has(SanitizerKind::CFIDerivedCast) &&
7715 (LangOpts.
Sanitize.
has(SanitizerKind::CFIUnrelatedCast) &&
7722 llvm::Metadata *MD =
7724 VTable->addTypeMetadata(Offset.getQuantity(), MD);
7726 if (CodeGenOpts.SanitizeCfiCrossDso)
7728 VTable->addTypeMetadata(Offset.getQuantity(),
7729 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
7732 llvm::Metadata *MD = llvm::MDString::get(
getLLVMContext(),
"all-vtables");
7733 VTable->addTypeMetadata(Offset.getQuantity(), MD);
7739 SanStats = std::make_unique<llvm::SanitizerStatReport>(&
getModule());
7749 auto *FTy = llvm::FunctionType::get(SamplerT, {
C->getType()},
false);
7764 bool forPointeeType) {
7775 if (
auto Align = TT->getDecl()->getMaxAlignment()) {
7805 if (
T.getQualifiers().hasUnaligned()) {
7807 }
else if (forPointeeType && !AlignForArray &&
7819 if (
unsigned MaxAlign =
getLangOpts().MaxTypeAlign) {
7832 if (NumAutoVarInit >= StopAfter) {
7835 if (!NumAutoVarInit) {
7838 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
7839 "number of times ftrivial-auto-var-init=%1 gets applied.");
7853 const Decl *
D)
const {
7857 OS << (isa<VarDecl>(
D) ?
".static." :
".intern.");
7859 OS << (isa<VarDecl>(
D) ?
"__static__" :
"__intern__");
7865 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
7869 llvm::MD5::MD5Result
Result;
7870 for (
const auto &Arg : PreprocessorOpts.
Macros)
7871 Hash.update(Arg.first);
7875 llvm::sys::fs::UniqueID ID;
7876 if (llvm::sys::fs::getUniqueID(PLoc.
getFilename(), ID)) {
7878 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
7879 if (
auto EC = llvm::sys::fs::getUniqueID(PLoc.
getFilename(), ID))
7880 SM.getDiagnostics().Report(diag::err_cannot_open_file)
7883 OS << llvm::format(
"%x", ID.getFile()) << llvm::format(
"%x", ID.getDevice())
7884 <<
"_" << llvm::utohexstr(
Result.low(),
true, 8);
7891 assert(DeferredDeclsToEmit.empty() &&
7892 "Should have emitted all decls deferred to emit.");
7893 assert(NewBuilder->DeferredDecls.empty() &&
7894 "Newly created module should not have deferred decls");
7895 NewBuilder->DeferredDecls = std::move(DeferredDecls);
7896 assert(EmittedDeferredDecls.empty() &&
7897 "Still have (unmerged) EmittedDeferredDecls deferred decls");
7899 assert(NewBuilder->DeferredVTables.empty() &&
7900 "Newly created module should not have deferred vtables");
7901 NewBuilder->DeferredVTables = std::move(DeferredVTables);
7903 assert(NewBuilder->MangledDeclNames.empty() &&
7904 "Newly created module should not have mangled decl names");
7905 assert(NewBuilder->Manglings.empty() &&
7906 "Newly created module should not have manglings");
7907 NewBuilder->Manglings = std::move(Manglings);
7909 NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
7911 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 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 uint64_t getFMVPriority(const TargetInfo &TI, const CodeGenFunction::FMVResolverOption &RO)
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,...
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 uint64_t getFMVPriority(ArrayRef< StringRef > Features) const
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 > createWindowsMIPSTargetCodeGenInfo(CodeGenModule &CGM, bool IsOS32)
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.