51#include "llvm/ABI/IRTypeMapper.h"
52#include "llvm/ABI/TargetInfo.h"
53#include "llvm/ADT/STLExtras.h"
54#include "llvm/ADT/StringExtras.h"
55#include "llvm/ADT/StringSwitch.h"
56#include "llvm/Analysis/TargetLibraryInfo.h"
57#include "llvm/BinaryFormat/ELF.h"
58#include "llvm/IR/AttributeMask.h"
59#include "llvm/IR/CallingConv.h"
60#include "llvm/IR/DataLayout.h"
61#include "llvm/IR/Intrinsics.h"
62#include "llvm/IR/LLVMContext.h"
63#include "llvm/IR/Module.h"
64#include "llvm/IR/ProfileSummary.h"
65#include "llvm/ProfileData/InstrProfReader.h"
66#include "llvm/ProfileData/SampleProf.h"
67#include "llvm/Support/ARMBuildAttributes.h"
68#include "llvm/Support/CRC.h"
69#include "llvm/Support/CodeGen.h"
70#include "llvm/Support/CommandLine.h"
71#include "llvm/Support/ConvertUTF.h"
72#include "llvm/Support/ErrorHandling.h"
73#include "llvm/Support/Hash.h"
74#include "llvm/Support/TimeProfiler.h"
75#include "llvm/TargetParser/AArch64TargetParser.h"
76#include "llvm/TargetParser/RISCVISAInfo.h"
77#include "llvm/TargetParser/Triple.h"
78#include "llvm/TargetParser/X86TargetParser.h"
79#include "llvm/Transforms/Instrumentation/KCFI.h"
80#include "llvm/Transforms/Utils/BuildLibCalls.h"
88 "limited-coverage-experimental", llvm::cl::Hidden,
89 llvm::cl::desc(
"Emit limited coverage mapping information (experimental)"));
96 case TargetCXXABI::AppleARM64:
97 case TargetCXXABI::Fuchsia:
98 case TargetCXXABI::GenericAArch64:
99 case TargetCXXABI::GenericARM:
100 case TargetCXXABI::iOS:
101 case TargetCXXABI::WatchOS:
102 case TargetCXXABI::GenericMIPS:
103 case TargetCXXABI::GenericItanium:
104 case TargetCXXABI::WebAssembly:
105 case TargetCXXABI::XL:
107 case TargetCXXABI::Microsoft:
111 llvm_unreachable(
"invalid C++ ABI kind");
114static std::unique_ptr<TargetCodeGenInfo>
117 const llvm::Triple &Triple =
Target.getTriple();
120 switch (Triple.getArch()) {
124 case llvm::Triple::m68k:
126 case llvm::Triple::mips:
127 case llvm::Triple::mipsel:
128 if (Triple.getOS() == llvm::Triple::Win32)
132 case llvm::Triple::mips64:
133 case llvm::Triple::mips64el:
136 case llvm::Triple::avr: {
140 unsigned NPR =
Target.getABI() ==
"avrtiny" ? 6 : 18;
141 unsigned NRR =
Target.getABI() ==
"avrtiny" ? 4 : 8;
145 case llvm::Triple::aarch64:
146 case llvm::Triple::aarch64_32:
147 case llvm::Triple::aarch64_be: {
149 if (
Target.getABI() ==
"darwinpcs")
150 Kind = AArch64ABIKind::DarwinPCS;
151 else if (Triple.isOSWindows())
153 else if (
Target.getABI() ==
"aapcs-soft")
154 Kind = AArch64ABIKind::AAPCSSoft;
159 case llvm::Triple::wasm32:
160 case llvm::Triple::wasm64: {
162 if (
Target.getABI() ==
"experimental-mv")
163 Kind = WebAssemblyABIKind::ExperimentalMV;
167 case llvm::Triple::arm:
168 case llvm::Triple::armeb:
169 case llvm::Triple::thumb:
170 case llvm::Triple::thumbeb: {
171 if (Triple.getOS() == llvm::Triple::Win32)
175 StringRef ABIStr =
Target.getABI();
176 if (ABIStr ==
"apcs-gnu")
177 Kind = ARMABIKind::APCS;
178 else if (ABIStr ==
"aapcs16")
179 Kind = ARMABIKind::AAPCS16_VFP;
180 else if (CodeGenOpts.
FloatABI ==
"hard" ||
181 (CodeGenOpts.
FloatABI !=
"soft" && Triple.isHardFloatABI()))
182 Kind = ARMABIKind::AAPCS_VFP;
187 case llvm::Triple::ppc: {
188 if (Triple.isOSAIX())
195 case llvm::Triple::ppcle: {
200 case llvm::Triple::ppc64:
201 if (Triple.isOSAIX())
204 if (Triple.isOSBinFormatELF()) {
206 if (
Target.getABI() ==
"elfv2")
207 Kind = PPC64_SVR4_ABIKind::ELFv2;
208 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
213 case llvm::Triple::ppc64le: {
214 assert(Triple.isOSBinFormatELF() &&
"PPC64 LE non-ELF not supported!");
216 if (
Target.getABI() ==
"elfv1")
217 Kind = PPC64_SVR4_ABIKind::ELFv1;
218 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
223 case llvm::Triple::nvptx:
224 case llvm::Triple::nvptx64:
227 case llvm::Triple::msp430:
230 case llvm::Triple::riscv32:
231 case llvm::Triple::riscv64:
232 case llvm::Triple::riscv32be:
233 case llvm::Triple::riscv64be: {
234 StringRef ABIStr =
Target.getABI();
236 unsigned ABIFLen = 0;
237 if (ABIStr.ends_with(
"f"))
239 else if (ABIStr.ends_with(
"d"))
241 bool EABI = ABIStr.ends_with(
"e");
245 case llvm::Triple::systemz: {
246 bool SoftFloat = CodeGenOpts.
FloatABI ==
"soft";
247 bool HasVector = !SoftFloat &&
Target.getABI() ==
"vector";
251 case llvm::Triple::tce:
252 case llvm::Triple::tcele:
253 case llvm::Triple::tcele64:
256 case llvm::Triple::x86: {
257 bool IsDarwinVectorABI = Triple.isOSDarwin();
258 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
260 if (Triple.getOS() == llvm::Triple::Win32) {
262 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
263 CodeGenOpts.NumRegisterParameters);
266 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
267 CodeGenOpts.NumRegisterParameters, CodeGenOpts.
FloatABI ==
"soft");
270 case llvm::Triple::x86_64: {
271 StringRef ABI =
Target.getABI();
272 X86AVXABILevel AVXLevel = (ABI ==
"avx512" ? X86AVXABILevel::AVX512
273 : ABI ==
"avx" ? X86AVXABILevel::AVX
274 : X86AVXABILevel::None);
276 switch (Triple.getOS()) {
277 case llvm::Triple::UEFI:
278 case llvm::Triple::Win32:
284 case llvm::Triple::hexagon:
286 case llvm::Triple::lanai:
288 case llvm::Triple::r600:
290 case llvm::Triple::amdgcn:
292 case llvm::Triple::sparc:
294 case llvm::Triple::sparcv9:
296 case llvm::Triple::xcore:
298 case llvm::Triple::arc:
300 case llvm::Triple::spir:
301 case llvm::Triple::spir64:
303 case llvm::Triple::spirv32:
304 case llvm::Triple::spirv64:
305 case llvm::Triple::spirv:
307 case llvm::Triple::dxil:
309 case llvm::Triple::ve:
311 case llvm::Triple::csky: {
312 bool IsSoftFloat = !
Target.hasFeature(
"hard-float-abi");
314 Target.hasFeature(
"fpuv2_df") ||
Target.hasFeature(
"fpuv3_df");
319 case llvm::Triple::bpfeb:
320 case llvm::Triple::bpfel:
322 case llvm::Triple::loongarch32:
323 case llvm::Triple::loongarch64: {
324 StringRef ABIStr =
Target.getABI();
325 unsigned ABIFRLen = 0;
326 if (ABIStr.ends_with(
"f"))
328 else if (ABIStr.ends_with(
"d"))
337 if (!TheTargetCodeGenInfo)
339 return *TheTargetCodeGenInfo;
343 if (!CodeGenOpts.ExperimentalABILowering)
350const llvm::abi::TargetInfo &
352 if (TheLLVMABITargetInfo)
353 return *TheLLVMABITargetInfo;
356 "LLVMABI lowering requested for an unsupported target");
357 TheLLVMABITargetInfo = llvm::abi::createBPFTargetInfo(TB);
358 return *TheLLVMABITargetInfo;
362 llvm::LLVMContext &Context,
366 if (Opts.AlignDouble || Opts.OpenCL)
369 llvm::Triple Triple =
Target.getTriple();
370 llvm::DataLayout DL(
Target.getDataLayoutString());
371 auto Check = [&](
const char *Name, llvm::Type *Ty,
unsigned Alignment) {
372 llvm::Align DLAlign = DL.getABITypeAlign(Ty);
373 llvm::Align ClangAlign(Alignment / 8);
374 if (DLAlign != ClangAlign) {
375 llvm::errs() <<
"For target " << Triple.str() <<
" type " << Name
376 <<
" mapping to " << *Ty <<
" has data layout alignment "
377 << DLAlign.value() <<
" while clang specifies "
378 << ClangAlign.value() <<
"\n";
383 Check(
"bool", llvm::Type::getIntNTy(Context,
Target.BoolWidth),
385 Check(
"short", llvm::Type::getIntNTy(Context,
Target.ShortWidth),
387 Check(
"int", llvm::Type::getIntNTy(Context,
Target.IntWidth),
389 Check(
"long", llvm::Type::getIntNTy(Context,
Target.LongWidth),
392 if (Triple.getArch() != llvm::Triple::m68k)
393 Check(
"long long", llvm::Type::getIntNTy(Context,
Target.LongLongWidth),
396 if (
Target.hasInt128Type() && !
Target.getTargetOpts().ForceEnableInt128 &&
397 !Triple.isAMDGPU() && !Triple.isSPIRV() &&
398 Triple.getArch() != llvm::Triple::ve)
399 Check(
"__int128", llvm::Type::getIntNTy(Context, 128),
Target.Int128Align);
401 if (
Target.hasFloat16Type())
402 Check(
"half", llvm::Type::getFloatingPointTy(Context, *
Target.HalfFormat),
404 if (
Target.hasBFloat16Type())
405 Check(
"bfloat", llvm::Type::getBFloatTy(Context),
Target.BFloat16Align);
406 Check(
"float", llvm::Type::getFloatingPointTy(Context, *
Target.FloatFormat),
408 Check(
"double", llvm::Type::getFloatingPointTy(Context, *
Target.DoubleFormat),
411 llvm::Type::getFloatingPointTy(Context, *
Target.LongDoubleFormat),
413 if (
Target.hasFloat128Type())
414 Check(
"__float128", llvm::Type::getFP128Ty(Context),
Target.Float128Align);
415 if (
Target.hasIbm128Type())
416 Check(
"__ibm128", llvm::Type::getPPC_FP128Ty(Context),
Target.Ibm128Align);
418 Check(
"void*", llvm::PointerType::getUnqual(Context),
Target.PointerAlign);
420 if (
Target.vectorsAreElementAligned() != DL.vectorsAreElementAligned()) {
421 llvm::errs() <<
"Datalayout for target " << Triple.str()
422 <<
" sets element-aligned vectors to '"
423 <<
Target.vectorsAreElementAligned()
424 <<
"' but clang specifies '" << DL.vectorsAreElementAligned()
438 : Context(
C), LangOpts(
C.
getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
439 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
441 VMContext(M.
getContext()), VTables(*this), StackHandler(diags),
445 AbiMapper = std::make_unique<QualTypeMapper>(
C, M.getDataLayout(), AbiAlloc);
446 AbiReverseMapper = std::make_unique<llvm::abi::IRTypeMapper>(
447 M.getContext(), M.getDataLayout());
451 llvm::LLVMContext &LLVMContext = M.getContext();
452 VoidTy = llvm::Type::getVoidTy(LLVMContext);
453 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
454 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
455 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
456 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
457 HalfTy = llvm::Type::getHalfTy(LLVMContext);
458 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
459 FloatTy = llvm::Type::getFloatTy(LLVMContext);
460 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
466 C.toCharUnitsFromBits(
C.getTargetInfo().getMaxPointerWidth()).getQuantity();
468 C.toCharUnitsFromBits(
C.getTargetInfo().getIntAlign()).getQuantity();
470 llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getCharWidth());
471 IntTy = llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getIntWidth());
472 IntPtrTy = llvm::IntegerType::get(LLVMContext,
473 C.getTargetInfo().getMaxPointerWidth());
474 Int8PtrTy = llvm::PointerType::get(LLVMContext,
476 const llvm::DataLayout &DL = M.getDataLayout();
478 llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
480 llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
482 llvm::PointerType::get(LLVMContext, DL.getProgramAddressSpace());
499 createOpenCLRuntime();
501 createOpenMPRuntime();
508 if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Thread | SanitizerKind::Type) ||
509 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
515 if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
516 CodeGenOpts.CoverageNotesFile.size() ||
517 CodeGenOpts.CoverageDataFile.size())
525 Block.GlobalUniqueCount = 0;
527 if (
C.getLangOpts().ObjC)
530 if (CodeGenOpts.hasProfileClangUse()) {
531 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
532 CodeGenOpts.ProfileInstrumentUsePath, *FS,
533 CodeGenOpts.ProfileRemappingFile);
534 if (
auto E = ReaderOrErr.takeError()) {
535 llvm::handleAllErrors(std::move(E), [&](
const llvm::ErrorInfoBase &EI) {
536 Diags.Report(diag::err_reading_profile)
537 << CodeGenOpts.ProfileInstrumentUsePath << EI.message();
541 PGOReader = std::move(ReaderOrErr.get());
546 if (CodeGenOpts.CoverageMapping)
550 if (CodeGenOpts.UniqueInternalLinkageNames &&
551 !
getModule().getSourceFileName().empty()) {
552 std::string Path =
getModule().getSourceFileName();
554 for (
const auto &Entry : LangOpts.MacroPrefixMap)
555 if (Path.rfind(Entry.first, 0) != std::string::npos) {
556 Path = Entry.second + Path.substr(Entry.first.size());
559 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path);
563 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
564 getModule().addModuleFlag(llvm::Module::Error,
"NumRegisterParameters",
565 CodeGenOpts.NumRegisterParameters);
574 const llvm::MemoryBuffer &FileBuffer = **BufOrErr;
575 for (llvm::line_iterator I(FileBuffer.getMemBufferRef(),
true), E;
577 this->MSHotPatchFunctions.push_back(std::string{*I});
579 auto &DE = Context.getDiagnostics();
580 DE.Report(diag::err_open_hotpatch_file_failed)
582 << BufOrErr.getError().message();
587 this->MSHotPatchFunctions.push_back(FuncName);
589 llvm::sort(this->MSHotPatchFunctions);
592 if (!Context.getAuxTargetInfo())
598void CodeGenModule::createObjCRuntime() {
615 llvm_unreachable(
"bad runtime kind");
618void CodeGenModule::createOpenCLRuntime() {
622void CodeGenModule::createOpenMPRuntime() {
623 if (!LangOpts.OMPHostIRFile.empty() && !FS->exists(LangOpts.OMPHostIRFile))
624 Diags.Report(diag::err_omp_host_ir_file_not_found)
625 << LangOpts.OMPHostIRFile;
630 case llvm::Triple::nvptx:
631 case llvm::Triple::nvptx64:
632 case llvm::Triple::amdgcn:
633 case llvm::Triple::spirv64:
636 "OpenMP AMDGPU/NVPTX/SPIRV is only prepared to deal with device code.");
637 OpenMPRuntime.reset(
new CGOpenMPRuntimeGPU(*
this));
640 if (LangOpts.OpenMPSimd)
641 OpenMPRuntime.reset(
new CGOpenMPSIMDRuntime(*
this));
643 OpenMPRuntime.reset(
new CGOpenMPRuntime(*
this));
648void CodeGenModule::createCUDARuntime() {
652void CodeGenModule::createHLSLRuntime() {
653 HLSLRuntime.reset(
new CGHLSLRuntime(*
this));
657 Replacements[Name] =
C;
660void CodeGenModule::applyReplacements() {
661 for (
auto &I : Replacements) {
662 StringRef MangledName = I.first;
663 llvm::Constant *Replacement = I.second;
668 auto *NewF = dyn_cast<llvm::Function>(Replacement);
670 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
671 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
674 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
675 CE->getOpcode() == llvm::Instruction::GetElementPtr);
676 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
681 OldF->replaceAllUsesWith(Replacement);
683 NewF->removeFromParent();
684 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
687 OldF->eraseFromParent();
692 GlobalValReplacements.push_back(std::make_pair(GV,
C));
695void CodeGenModule::applyGlobalValReplacements() {
696 for (
auto &I : GlobalValReplacements) {
697 llvm::GlobalValue *GV = I.first;
698 llvm::Constant *
C = I.second;
700 GV->replaceAllUsesWith(
C);
701 GV->eraseFromParent();
708 const llvm::Constant *
C;
709 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
710 C = GA->getAliasee();
711 else if (
auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
712 C = GI->getResolver();
716 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(
C->stripPointerCasts());
720 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
729 bool IsIFunc,
const llvm::GlobalValue *Alias,
const llvm::GlobalValue *&GV,
730 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
734 Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
738 if (GV->hasCommonLinkage()) {
739 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
740 if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
741 Diags.
Report(Location, diag::err_alias_to_common);
746 if (GV->isDeclaration()) {
747 Diags.
Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
748 Diags.
Report(Location, diag::note_alias_requires_mangled_name)
749 << IsIFunc << IsIFunc;
752 for (
const auto &[
Decl, Name] : MangledDeclNames) {
753 if (
const auto *ND = dyn_cast<NamedDecl>(
Decl.getDecl())) {
755 if (II && II->
getName() == GV->getName()) {
756 Diags.
Report(Location, diag::note_alias_mangled_name_alternative)
760 (Twine(IsIFunc ?
"ifunc" :
"alias") +
"(\"" + Name +
"\")")
770 const auto *F = dyn_cast<llvm::Function>(GV);
772 Diags.
Report(Location, diag::err_alias_to_undefined)
773 << IsIFunc << IsIFunc;
777 llvm::FunctionType *FTy = F->getFunctionType();
778 if (!FTy->getReturnType()->isPointerTy()) {
779 Diags.
Report(Location, diag::err_ifunc_resolver_return);
793 if (GVar->hasAttribute(
"toc-data")) {
794 auto GVId = GVar->getName();
797 Diags.
Report(Location, diag::warn_toc_unsupported_type)
798 << GVId <<
"the variable has an alias";
800 llvm::AttributeSet CurrAttributes = GVar->getAttributes();
801 llvm::AttributeSet NewAttributes =
802 CurrAttributes.removeAttribute(GVar->getContext(),
"toc-data");
803 GVar->setAttributes(NewAttributes);
807void CodeGenModule::checkAliases() {
812 DiagnosticsEngine &Diags =
getDiags();
813 for (
const GlobalDecl &GD : Aliases) {
815 SourceLocation Location;
817 bool IsIFunc = D->hasAttr<IFuncAttr>();
818 if (
const Attr *A = D->getDefiningAttr()) {
819 Location = A->getLocation();
820 Range = A->getRange();
822 llvm_unreachable(
"Not an alias or ifunc?");
826 const llvm::GlobalValue *GV =
nullptr;
828 MangledDeclNames, Range)) {
834 if (
const llvm::GlobalVariable *GVar =
835 dyn_cast<const llvm::GlobalVariable>(GV))
839 llvm::Constant *Aliasee =
843 llvm::GlobalValue *AliaseeGV;
844 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
849 if (
const SectionAttr *SA = D->getAttr<SectionAttr>()) {
850 StringRef AliasSection = SA->getName();
851 if (AliasSection != AliaseeGV->getSection())
852 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
853 << AliasSection << IsIFunc << IsIFunc;
861 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
862 if (GA->isInterposable()) {
863 Diags.Report(Location, diag::warn_alias_to_weak_alias)
864 << GV->getName() << GA->getName() << IsIFunc;
865 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
866 GA->getAliasee(), Alias->getType());
878 llvm::Attribute::DisableSanitizerInstrumentation);
883 for (
const GlobalDecl &GD : Aliases) {
886 Alias->replaceAllUsesWith(llvm::PoisonValue::get(Alias->getType()));
887 Alias->eraseFromParent();
892 DeferredDeclsToEmit.clear();
893 EmittedDeferredDecls.clear();
894 DeferredAnnotations.clear();
896 OpenMPRuntime->clear();
900 StringRef MainFile) {
903 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
904 if (MainFile.empty())
905 MainFile =
"<stdin>";
906 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
909 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
912 Diags.
Report(diag::warn_profile_data_missing) << Visited << Missing;
916static std::optional<llvm::GlobalValue::VisibilityTypes>
923 return llvm::GlobalValue::DefaultVisibility;
925 return llvm::GlobalValue::HiddenVisibility;
927 return llvm::GlobalValue::ProtectedVisibility;
929 llvm_unreachable(
"unknown option value!");
934 std::optional<llvm::GlobalValue::VisibilityTypes>
V) {
943 GV.setDSOLocal(
false);
944 GV.setVisibility(*
V);
949 if (!LO.VisibilityFromDLLStorageClass)
952 std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
955 std::optional<llvm::GlobalValue::VisibilityTypes>
956 NoDLLStorageClassVisibility =
959 std::optional<llvm::GlobalValue::VisibilityTypes>
960 ExternDeclDLLImportVisibility =
963 std::optional<llvm::GlobalValue::VisibilityTypes>
964 ExternDeclNoDLLStorageClassVisibility =
967 for (llvm::GlobalValue &GV : M.global_values()) {
968 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
971 if (GV.isDeclarationForLinker())
973 llvm::GlobalValue::DLLImportStorageClass
974 ? ExternDeclDLLImportVisibility
975 : ExternDeclNoDLLStorageClassVisibility);
978 llvm::GlobalValue::DLLExportStorageClass
979 ? DLLExportVisibility
980 : NoDLLStorageClassVisibility);
982 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
987 const llvm::Triple &Triple,
991 return LangOpts.getStackProtector() == Mode;
994std::optional<llvm::Attribute::AttrKind>
996 if (D && D->
hasAttr<NoStackProtectorAttr>())
998 else if (D && D->
hasAttr<StrictGuardStackCheckAttr>() &&
1000 return llvm::Attribute::StackProtectStrong;
1002 return llvm::Attribute::StackProtect;
1004 return llvm::Attribute::StackProtectStrong;
1006 return llvm::Attribute::StackProtectReq;
1007 return std::nullopt;
1013 EmitModuleInitializers(Primary);
1015 DeferredDecls.insert_range(EmittedDeferredDecls);
1016 EmittedDeferredDecls.clear();
1017 EmitVTablesOpportunistically();
1018 applyGlobalValReplacements();
1019 applyReplacements();
1020 emitMultiVersionFunctions();
1021 emitPFPFieldsWithEvaluatedOffset();
1023 if (Context.getLangOpts().IncrementalExtensions &&
1024 GlobalTopLevelStmtBlockInFlight.first) {
1026 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->
getEndLoc());
1027 GlobalTopLevelStmtBlockInFlight = {
nullptr,
nullptr};
1033 EmitCXXModuleInitFunc(Primary);
1035 EmitCXXGlobalInitFunc();
1036 EmitCXXGlobalCleanUpFunc();
1037 registerGlobalDtorsWithAtExit();
1038 EmitCXXThreadLocalInitFunc();
1040 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
1042 if (Context.getLangOpts().CUDA && CUDARuntime) {
1043 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
1046 if (OpenMPRuntime) {
1047 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
1048 OpenMPRuntime->clear();
1052 PGOReader->getSummary(
false).getMD(VMContext),
1053 llvm::ProfileSummary::PSK_Instr);
1054 if (PGOStats.hasDiagnostics())
1060 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
1061 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
1063 EmitStaticExternCAliases();
1068 if (CoverageMapping)
1069 CoverageMapping->emit();
1070 if (CodeGenOpts.SanitizeCfiCrossDso) {
1074 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
1076 emitAtAvailableLinkGuard();
1077 if (Context.getTargetInfo().getTriple().isWasm())
1084 if (
getTarget().getTargetOpts().CodeObjectVersion !=
1085 llvm::CodeObjectVersionKind::COV_None) {
1086 getModule().addModuleFlag(llvm::Module::Error,
1087 "amdhsa_code_object_version",
1088 getTarget().getTargetOpts().CodeObjectVersion);
1093 auto *MDStr = llvm::MDString::get(
1098 getModule().addModuleFlag(llvm::Module::Error,
"amdgpu_printf_kind",
1107 if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) {
1109 for (
auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) {
1111 if (
auto *FD = dyn_cast<FunctionDecl>(D))
1115 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1119 llvm::ArrayType *ATy = llvm::ArrayType::get(
Int8PtrTy, UsedArray.size());
1121 auto *GV =
new llvm::GlobalVariable(
1122 getModule(), ATy,
false, llvm::GlobalValue::InternalLinkage,
1123 llvm::ConstantArray::get(ATy, UsedArray),
"__clang_gpu_used_external");
1129 auto *GV =
new llvm::GlobalVariable(
1131 llvm::Constant::getNullValue(
Int8Ty),
1140 if (CodeGenOpts.Autolink &&
1141 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
1142 EmitModuleLinkOptions();
1157 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
1158 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.dependent-libraries");
1159 for (
auto *MD : ELFDependentLibraries)
1160 NMD->addOperand(MD);
1163 if (CodeGenOpts.DwarfVersion) {
1164 getModule().addModuleFlag(llvm::Module::Max,
"Dwarf Version",
1165 CodeGenOpts.DwarfVersion);
1168 if (CodeGenOpts.Dwarf64)
1169 getModule().addModuleFlag(llvm::Module::Max,
"DWARF64", 1);
1171 if (Context.getLangOpts().SemanticInterposition)
1173 getModule().setSemanticInterposition(
true);
1175 if (CodeGenOpts.EmitCodeView) {
1177 getModule().addModuleFlag(llvm::Module::Warning,
"CodeView", 1);
1179 if (CodeGenOpts.CodeViewGHash) {
1180 getModule().addModuleFlag(llvm::Module::Warning,
"CodeViewGHash", 1);
1182 if (CodeGenOpts.ControlFlowGuard) {
1185 llvm::Module::Warning,
"cfguard",
1186 static_cast<unsigned>(llvm::ControlFlowGuardMode::Enabled));
1187 }
else if (CodeGenOpts.ControlFlowGuardNoChecks) {
1190 llvm::Module::Warning,
"cfguard",
1191 static_cast<unsigned>(llvm::ControlFlowGuardMode::TableOnly));
1193 if (CodeGenOpts.getWinControlFlowGuardMechanism() !=
1194 llvm::ControlFlowGuardMechanism::Automatic) {
1197 llvm::Module::Warning,
"cfguard-mechanism",
1198 static_cast<unsigned>(CodeGenOpts.getWinControlFlowGuardMechanism()));
1200 if (CodeGenOpts.EHContGuard) {
1202 getModule().addModuleFlag(llvm::Module::Warning,
"ehcontguard", 1);
1204 if (Context.getLangOpts().Kernel) {
1206 getModule().addModuleFlag(llvm::Module::Warning,
"ms-kernel", 1);
1208 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
1213 getModule().addModuleFlag(llvm::Module::Error,
"StrictVTablePointers",1);
1215 llvm::Metadata *Ops[2] = {
1216 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
1217 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1218 llvm::Type::getInt32Ty(VMContext), 1))};
1220 getModule().addModuleFlag(llvm::Module::Require,
1221 "StrictVTablePointersRequirement",
1222 llvm::MDNode::get(VMContext, Ops));
1228 getModule().addModuleFlag(llvm::Module::Warning,
"Debug Info Version",
1229 llvm::DEBUG_METADATA_VERSION);
1234 uint64_t WCharWidth =
1235 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
1236 if (WCharWidth !=
getTriple().getDefaultWCharSize())
1237 getModule().addModuleFlag(llvm::Module::Error,
"wchar_size", WCharWidth);
1240 getModule().addModuleFlag(llvm::Module::Warning,
1241 "zos_product_major_version",
1242 uint32_t(CLANG_VERSION_MAJOR));
1243 getModule().addModuleFlag(llvm::Module::Warning,
1244 "zos_product_minor_version",
1245 uint32_t(CLANG_VERSION_MINOR));
1246 getModule().addModuleFlag(llvm::Module::Warning,
"zos_product_patchlevel",
1247 uint32_t(CLANG_VERSION_PATCHLEVEL));
1249 getModule().addModuleFlag(llvm::Module::Error,
"zos_product_id",
1250 llvm::MDString::get(VMContext, ProductId));
1255 getModule().addModuleFlag(llvm::Module::Error,
"zos_cu_language",
1256 llvm::MDString::get(VMContext, lang_str));
1258 time_t TT = PreprocessorOpts.SourceDateEpoch
1259 ? *PreprocessorOpts.SourceDateEpoch
1260 : std::time(
nullptr);
1261 getModule().addModuleFlag(llvm::Module::Max,
"zos_translation_time",
1262 static_cast<uint64_t
>(TT));
1265 getModule().addModuleFlag(llvm::Module::Error,
"zos_le_char_mode",
1266 llvm::MDString::get(VMContext,
"ascii"));
1269 llvm::Triple T = Context.getTargetInfo().getTriple();
1270 if (T.isARM() || T.isThumb()) {
1272 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
1273 getModule().addModuleFlag(llvm::Module::Error,
"min_enum_size", EnumWidth);
1277 StringRef ABIStr = Target.getABI();
1278 llvm::LLVMContext &Ctx = TheModule.getContext();
1279 getModule().addModuleFlag(llvm::Module::Error,
"target-abi",
1280 llvm::MDString::get(Ctx, ABIStr));
1285 const std::vector<std::string> &Features =
1288 llvm::RISCVISAInfo::parseFeatures(T.isRISCV64() ? 64 : 32, Features);
1289 if (!errorToBool(ParseResult.takeError()))
1291 llvm::Module::AppendUnique,
"riscv-isa",
1293 Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString())));
1296 if (CodeGenOpts.SanitizeCfiCrossDso) {
1298 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
1301 if (CodeGenOpts.WholeProgramVTables) {
1305 getModule().addModuleFlag(llvm::Module::Error,
"Virtual Function Elim",
1306 CodeGenOpts.VirtualFunctionElimination);
1309 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
1310 getModule().addModuleFlag(llvm::Module::Override,
1311 "CFI Canonical Jump Tables",
1312 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1315 if (CodeGenOpts.SanitizeCfiICallNormalizeIntegers) {
1316 getModule().addModuleFlag(llvm::Module::Override,
"cfi-normalize-integers",
1320 if (!CodeGenOpts.UniqueSourceFileIdentifier.empty()) {
1322 llvm::Module::Append,
"Unique Source File Identifier",
1324 TheModule.getContext(),
1325 llvm::MDString::get(TheModule.getContext(),
1326 CodeGenOpts.UniqueSourceFileIdentifier)));
1329 if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) {
1330 getModule().addModuleFlag(llvm::Module::Override,
"kcfi", 1);
1333 if (CodeGenOpts.PatchableFunctionEntryOffset)
1334 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-offset",
1335 CodeGenOpts.PatchableFunctionEntryOffset);
1336 if (CodeGenOpts.SanitizeKcfiArity)
1337 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-arity", 1);
1340 llvm::Module::Override,
"kcfi-hash",
1341 llvm::MDString::get(
1343 llvm::stringifyKCFIHashAlgorithm(CodeGenOpts.SanitizeKcfiHash)));
1346 if (CodeGenOpts.CFProtectionReturn &&
1347 Target.checkCFProtectionReturnSupported(
getDiags())) {
1349 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-return",
1353 if (CodeGenOpts.CFProtectionBranch &&
1354 Target.checkCFProtectionBranchSupported(
getDiags())) {
1356 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-branch",
1359 auto Scheme = CodeGenOpts.getCFBranchLabelScheme();
1360 if (Target.checkCFBranchLabelSchemeSupported(Scheme,
getDiags())) {
1362 Scheme = Target.getDefaultCFBranchLabelScheme();
1364 llvm::Module::Error,
"cf-branch-label-scheme",
1370 if (CodeGenOpts.FunctionReturnThunks)
1371 getModule().addModuleFlag(llvm::Module::Override,
"function_return_thunk_extern", 1);
1373 if (CodeGenOpts.IndirectBranchCSPrefix)
1374 getModule().addModuleFlag(llvm::Module::Override,
"indirect_branch_cs_prefix", 1);
1385 if (Context.getTargetInfo().hasFeature(
"ptrauth") &&
1386 LangOpts.getSignReturnAddressScope() !=
1388 getModule().addModuleFlag(llvm::Module::Override,
1389 "sign-return-address-buildattr", 1);
1390 if (LangOpts.Sanitize.has(SanitizerKind::MemtagStack))
1391 getModule().addModuleFlag(llvm::Module::Override,
1392 "tag-stack-memory-buildattr", 1);
1394 if (T.isARM() || T.isThumb() || T.isAArch64()) {
1402 if (LangOpts.BranchTargetEnforcement)
1403 getModule().addModuleFlag(llvm::Module::Min,
"branch-target-enforcement",
1405 if (LangOpts.BranchProtectionPAuthLR)
1406 getModule().addModuleFlag(llvm::Module::Min,
"branch-protection-pauth-lr",
1408 if (LangOpts.GuardedControlStack)
1409 getModule().addModuleFlag(llvm::Module::Min,
"guarded-control-stack", 2);
1410 if (LangOpts.hasSignReturnAddress())
1411 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address", 2);
1412 if (LangOpts.isSignReturnAddressScopeAll())
1413 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address-all",
1415 if (!LangOpts.isSignReturnAddressWithAKey())
1416 getModule().addModuleFlag(llvm::Module::Min,
1417 "sign-return-address-with-bkey", 2);
1419 if (LangOpts.PointerAuthELFGOT)
1420 getModule().addModuleFlag(llvm::Module::Error,
"ptrauth-elf-got", 1);
1423 if (LangOpts.PointerAuthCalls)
1424 getModule().addModuleFlag(llvm::Module::Error,
1425 "ptrauth-sign-personality", 1);
1427 using namespace llvm::ELF;
1428 uint64_t PAuthABIVersion =
1429 (LangOpts.PointerAuthIntrinsics
1430 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS) |
1431 (LangOpts.PointerAuthCalls
1432 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS) |
1433 (LangOpts.PointerAuthReturns
1434 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS) |
1435 (LangOpts.PointerAuthAuthTraps
1436 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS) |
1437 (LangOpts.PointerAuthVTPtrAddressDiscrimination
1438 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR) |
1439 (LangOpts.PointerAuthVTPtrTypeDiscrimination
1440 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR) |
1441 (LangOpts.PointerAuthInitFini
1442 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI) |
1443 (LangOpts.PointerAuthInitFiniAddressDiscrimination
1444 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC) |
1445 (LangOpts.PointerAuthELFGOT
1446 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT) |
1447 (LangOpts.PointerAuthIndirectGotos
1448 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS) |
1449 (LangOpts.PointerAuthTypeInfoVTPtrDiscrimination
1450 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR) |
1451 (LangOpts.PointerAuthFunctionTypeDiscrimination
1452 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR);
1453 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR ==
1454 AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
1455 "Update when new enum items are defined");
1456 if (PAuthABIVersion != 0) {
1457 getModule().addModuleFlag(llvm::Module::Error,
1458 "aarch64-elf-pauthabi-platform",
1459 AARCH64_PAUTH_PLATFORM_LLVM_LINUX);
1460 getModule().addModuleFlag(llvm::Module::Error,
1461 "aarch64-elf-pauthabi-version",
1466 if ((T.isARM() || T.isThumb()) &&
getTriple().isTargetAEABI() &&
1468 uint32_t TagVal = 0;
1469 llvm::Module::ModFlagBehavior DenormalTagBehavior = llvm::Module::Max;
1471 llvm::DenormalMode::getPositiveZero()) {
1472 TagVal = llvm::ARMBuildAttrs::PositiveZero;
1474 llvm::DenormalMode::getIEEE()) {
1475 TagVal = llvm::ARMBuildAttrs::IEEEDenormals;
1476 DenormalTagBehavior = llvm::Module::Override;
1478 llvm::DenormalMode::getPreserveSign()) {
1479 TagVal = llvm::ARMBuildAttrs::PreserveFPSign;
1481 getModule().addModuleFlag(DenormalTagBehavior,
"arm-eabi-fp-denormal",
1486 getModule().addModuleFlag(llvm::Module::Min,
"arm-eabi-fp-exceptions",
1487 llvm::ARMBuildAttrs::Allowed);
1490 TagVal = llvm::ARMBuildAttrs::AllowIEEENormal;
1492 TagVal = llvm::ARMBuildAttrs::AllowIEEE754;
1493 getModule().addModuleFlag(llvm::Module::Min,
"arm-eabi-fp-number-model",
1497 if (CodeGenOpts.StackClashProtector)
1499 llvm::Module::Override,
"probe-stack",
1500 llvm::MDString::get(TheModule.getContext(),
"inline-asm"));
1502 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
1503 getModule().addModuleFlag(llvm::Module::Min,
"stack-probe-size",
1504 CodeGenOpts.StackProbeSize);
1506 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1507 llvm::LLVMContext &Ctx = TheModule.getContext();
1509 llvm::Module::Error,
"MemProfProfileFilename",
1510 llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
1513 if (LangOpts.CUDAIsDevice &&
getTriple().isNVPTX()) {
1517 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
1518 CodeGenOpts.FP32DenormalMode.Output !=
1519 llvm::DenormalMode::IEEE);
1522 if (LangOpts.EHAsynch)
1523 getModule().addModuleFlag(llvm::Module::Warning,
"eh-asynch", 1);
1526 if (CodeGenOpts.ImportCallOptimization)
1527 getModule().addModuleFlag(llvm::Module::Warning,
"import-call-optimization",
1531 if (CodeGenOpts.getWinX64EHUnwindV2() != llvm::WinX64EHUnwindV2Mode::Disabled)
1533 llvm::Module::Warning,
"winx64-eh-unwindv2",
1534 static_cast<unsigned>(CodeGenOpts.getWinX64EHUnwindV2()));
1538 getModule().addModuleFlag(llvm::Module::Max,
"openmp", LangOpts.OpenMP);
1540 getModule().addModuleFlag(llvm::Module::Max,
"openmp-device",
1544 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())) {
1545 EmitOpenCLMetadata();
1552 auto Version = LangOpts.getOpenCLCompatibleVersion();
1553 llvm::Metadata *SPIRVerElts[] = {
1554 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1556 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1557 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
1558 llvm::NamedMDNode *SPIRVerMD =
1559 TheModule.getOrInsertNamedMetadata(
"opencl.spir.version");
1560 llvm::LLVMContext &Ctx = TheModule.getContext();
1561 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
1569 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
1570 assert(PLevel < 3 &&
"Invalid PIC Level");
1571 getModule().setPICLevel(
static_cast<llvm::PICLevel::Level
>(PLevel));
1572 if (Context.getLangOpts().PIE)
1573 getModule().setPIELevel(
static_cast<llvm::PIELevel::Level
>(PLevel));
1577 unsigned CM = llvm::StringSwitch<unsigned>(
getCodeGenOpts().CodeModel)
1578 .Case(
"tiny", llvm::CodeModel::Tiny)
1579 .Case(
"small", llvm::CodeModel::Small)
1580 .Case(
"kernel", llvm::CodeModel::Kernel)
1581 .Case(
"medium", llvm::CodeModel::Medium)
1582 .Case(
"large", llvm::CodeModel::Large)
1585 llvm::CodeModel::Model codeModel =
static_cast<llvm::CodeModel::Model
>(CM);
1588 if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
1589 Context.getTargetInfo().getTriple().getArch() ==
1590 llvm::Triple::x86_64) {
1596 if (CodeGenOpts.NoPLT)
1599 CodeGenOpts.DirectAccessExternalData !=
1600 getModule().getDirectAccessExternalData()) {
1601 getModule().setDirectAccessExternalData(
1602 CodeGenOpts.DirectAccessExternalData);
1604 if (CodeGenOpts.UnwindTables)
1605 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1607 switch (CodeGenOpts.getFramePointer()) {
1612 getModule().setFramePointer(llvm::FramePointerKind::Reserved);
1615 getModule().setFramePointer(llvm::FramePointerKind::NonLeafNoReserve);
1618 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1621 getModule().setFramePointer(llvm::FramePointerKind::All);
1625 SimplifyPersonality();
1638 EmitVersionIdentMetadata();
1641 EmitCommandLineMetadata();
1649 getModule().setStackProtectorGuardSymbol(
1652 getModule().setStackProtectorGuardOffset(
1657 getModule().addModuleFlag(llvm::Module::Override,
"SkipRaxSetup", 1);
1659 getModule().addModuleFlag(llvm::Module::Override,
"RegCallv4", 1);
1661 if (
getContext().getTargetInfo().getMaxTLSAlign())
1662 getModule().addModuleFlag(llvm::Module::Error,
"MaxTLSAlign",
1663 getContext().getTargetInfo().getMaxTLSAlign());
1681 if (!MustTailCallUndefinedGlobals.empty()) {
1683 for (
auto &I : MustTailCallUndefinedGlobals) {
1684 if (!I.first->isDefined())
1685 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1689 if (!Entry || Entry->isWeakForLinker() ||
1690 Entry->isDeclarationForLinker())
1691 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1695 for (
auto &I : MustTailCallUndefinedGlobals) {
1704 if (Entry->isDeclarationForLinker()) {
1707 Entry->hasHiddenVisibility() || Entry->hasProtectedVisibility();
1709 CalleeIsLocal = Entry->isDSOLocal();
1713 getDiags().
Report(I.second, diag::err_mips_impossible_musttail) << 1;
1724 auto *ErrnoTBAAMD = TheModule.getOrInsertNamedMetadata(
ErrnoTBAAMDName);
1725 ErrnoTBAAMD->addOperand(IntegerNode);
1730void CodeGenModule::EmitOpenCLMetadata() {
1736 auto EmitVersion = [
this](StringRef MDName,
int Version) {
1737 llvm::Metadata *OCLVerElts[] = {
1738 llvm::ConstantAsMetadata::get(
1739 llvm::ConstantInt::get(
Int32Ty, Version / 100)),
1740 llvm::ConstantAsMetadata::get(
1741 llvm::ConstantInt::get(
Int32Ty, (Version % 100) / 10))};
1742 llvm::NamedMDNode *OCLVerMD = TheModule.getOrInsertNamedMetadata(MDName);
1743 llvm::LLVMContext &Ctx = TheModule.getContext();
1744 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
1747 EmitVersion(
"opencl.ocl.version", CLVersion);
1748 if (LangOpts.OpenCLCPlusPlus) {
1750 EmitVersion(
"opencl.cxx.version", LangOpts.OpenCLCPlusPlusVersion);
1754void CodeGenModule::EmitBackendOptionsMetadata(
1755 const CodeGenOptions &CodeGenOpts) {
1757 getModule().addModuleFlag(llvm::Module::Min,
"SmallDataLimit",
1758 CodeGenOpts.SmallDataLimit);
1762 if (LangOpts.AllocTokenMode) {
1763 StringRef S = llvm::getAllocTokenModeAsString(*LangOpts.AllocTokenMode);
1764 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-mode",
1765 llvm::MDString::get(VMContext, S));
1767 if (LangOpts.AllocTokenMax)
1769 llvm::Module::Error,
"alloc-token-max",
1770 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1771 *LangOpts.AllocTokenMax));
1772 if (CodeGenOpts.SanitizeAllocTokenFastABI)
1773 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-fast-abi", 1);
1774 if (CodeGenOpts.SanitizeAllocTokenExtended)
1775 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-extended", 1);
1791 return TBAA->getTypeInfo(QTy);
1810 return TBAA->getAccessInfo(AccessType);
1817 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
1823 return TBAA->getTBAAStructInfo(QTy);
1829 return TBAA->getBaseTypeInfo(QTy);
1835 return TBAA->getAccessTagInfo(Info);
1842 return TBAA->mergeTBAAInfoForCast(SourceInfo,
TargetInfo);
1850 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
1858 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
1864 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
1869 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
1881 std::string Msg =
Type;
1883 diag::err_codegen_unsupported)
1889 diag::err_codegen_unsupported)
1896 std::string Msg =
Type;
1898 diag::err_codegen_unsupported)
1903 llvm::function_ref<
void()> Fn) {
1904 StackHandler.runWithSufficientStackSpace(Loc, Fn);
1914 if (GV->hasLocalLinkage()) {
1915 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1928 if (Context.getLangOpts().OpenMP &&
1929 Context.getLangOpts().OpenMPIsTargetDevice &&
isa<VarDecl>(D) &&
1930 D->
hasAttr<OMPDeclareTargetDeclAttr>() &&
1931 D->
getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
1932 OMPDeclareTargetDeclAttr::DT_NoHost &&
1934 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1941 if (Context.getLangOpts().CUDAIsDevice &&
1943 !D->
hasAttr<OMPDeclareTargetDeclAttr>()) {
1944 bool NeedsProtected =
false;
1948 else if (
const auto *VD = dyn_cast<VarDecl>(D))
1949 NeedsProtected = VD->hasAttr<CUDADeviceAttr>() ||
1950 VD->hasAttr<CUDAConstantAttr>() ||
1951 VD->getType()->isCUDADeviceBuiltinSurfaceType() ||
1952 VD->getType()->isCUDADeviceBuiltinTextureType();
1953 if (NeedsProtected) {
1954 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1960 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1964 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
1968 if (GV->hasDLLExportStorageClass()) {
1971 diag::err_hidden_visibility_dllexport);
1974 diag::err_non_default_visibility_dllimport);
1980 !GV->isDeclarationForLinker())
1985 llvm::GlobalValue *GV) {
1986 if (GV->hasLocalLinkage())
1989 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
1993 if (GV->hasDLLImportStorageClass())
1996 const llvm::Triple &TT = CGM.
getTriple();
1998 if (TT.isOSCygMing()) {
2016 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
2024 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
2028 if (!TT.isOSBinFormatELF())
2034 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
2042 return !(CGM.
getLangOpts().SemanticInterposition ||
2047 if (!GV->isDeclarationForLinker())
2053 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
2060 if (CGOpts.DirectAccessExternalData) {
2066 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
2067 if (!Var->isThreadLocal())
2092 const auto *D = dyn_cast<NamedDecl>(GD.
getDecl());
2094 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
2104 if (D->
hasAttr<DLLImportAttr>())
2105 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2106 else if ((D->
hasAttr<DLLExportAttr>() ||
2108 !GV->isDeclarationForLinker())
2109 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2129 GV->setPartition(CodeGenOpts.SymbolPartition);
2133 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
2134 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
2135 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
2136 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
2137 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
2140llvm::GlobalVariable::ThreadLocalMode
2142 switch (CodeGenOpts.getDefaultTLSModel()) {
2144 return llvm::GlobalVariable::GeneralDynamicTLSModel;
2146 return llvm::GlobalVariable::LocalDynamicTLSModel;
2148 return llvm::GlobalVariable::InitialExecTLSModel;
2150 return llvm::GlobalVariable::LocalExecTLSModel;
2152 llvm_unreachable(
"Invalid TLS model!");
2156 assert(D.
getTLSKind() &&
"setting TLS mode on non-TLS var!");
2158 llvm::GlobalValue::ThreadLocalMode TLM;
2162 if (
const TLSModelAttr *
Attr = D.
getAttr<TLSModelAttr>()) {
2166 GV->setThreadLocalMode(TLM);
2172 return (Twine(
'.') + Twine(
Target.CPUSpecificManglingCharacter(Name))).str();
2176 const CPUSpecificAttr *
Attr,
2198 bool OmitMultiVersionMangling =
false) {
2200 llvm::raw_svector_ostream Out(Buffer);
2209 assert(II &&
"Attempt to mangle unnamed decl.");
2210 const auto *FD = dyn_cast<FunctionDecl>(ND);
2215 Out <<
"__regcall4__" << II->
getName();
2217 Out <<
"__regcall3__" << II->
getName();
2218 }
else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
2220 Out <<
"__device_stub__" << II->
getName();
2222 DeviceKernelAttr::isOpenCLSpelling(
2223 FD->getAttr<DeviceKernelAttr>()) &&
2225 Out <<
"__clang_ocl_kern_imp_" << II->
getName();
2241 "Hash computed when not explicitly requested");
2245 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
2246 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
2247 switch (FD->getMultiVersionKind()) {
2251 FD->getAttr<CPUSpecificAttr>(),
2255 auto *
Attr = FD->getAttr<TargetAttr>();
2256 assert(
Attr &&
"Expected TargetAttr to be present "
2257 "for attribute mangling");
2263 auto *
Attr = FD->getAttr<TargetVersionAttr>();
2264 assert(
Attr &&
"Expected TargetVersionAttr to be present "
2265 "for attribute mangling");
2271 auto *
Attr = FD->getAttr<TargetClonesAttr>();
2272 assert(
Attr &&
"Expected TargetClonesAttr to be present "
2273 "for attribute mangling");
2280 llvm_unreachable(
"None multiversion type isn't valid here");
2290 return std::string(Out.str());
2293void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
2294 const FunctionDecl *FD,
2295 StringRef &CurName) {
2302 std::string NonTargetName =
2310 "Other GD should now be a multiversioned function");
2320 if (OtherName != NonTargetName) {
2323 const auto ExistingRecord = Manglings.find(NonTargetName);
2324 if (ExistingRecord != std::end(Manglings))
2325 Manglings.remove(&(*ExistingRecord));
2326 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
2331 CurName = OtherNameRef;
2333 Entry->setName(OtherName);
2343 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
2357 auto FoundName = MangledDeclNames.find(CanonicalGD);
2358 if (FoundName != MangledDeclNames.end())
2359 return FoundName->second;
2396 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
2397 return MangledDeclNames[CanonicalGD] =
Result.first->first();
2406 llvm::raw_svector_ostream Out(Buffer);
2409 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
2410 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(D))
2412 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(D))
2417 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
2418 return Result.first->first();
2422 auto it = MangledDeclNames.begin();
2423 while (it != MangledDeclNames.end()) {
2424 if (it->second == Name)
2439 llvm::Constant *AssociatedData) {
2441 GlobalCtors.push_back(
Structor(Priority, LexOrder, Ctor, AssociatedData));
2447 bool IsDtorAttrFunc) {
2448 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2450 DtorsUsingAtExit[Priority].push_back(Dtor);
2455 GlobalDtors.push_back(
Structor(Priority, ~0
U, Dtor,
nullptr));
2458void CodeGenModule::EmitCtorList(CtorList &Fns,
const char *GlobalName) {
2459 if (Fns.empty())
return;
2465 llvm::PointerType *PtrTy = llvm::PointerType::get(
2466 getLLVMContext(), TheModule.getDataLayout().getProgramAddressSpace());
2469 llvm::StructType *CtorStructTy = llvm::StructType::get(
Int32Ty, PtrTy, PtrTy);
2473 auto Ctors = Builder.beginArray(CtorStructTy);
2474 for (
const auto &I : Fns) {
2475 auto Ctor = Ctors.beginStruct(CtorStructTy);
2476 Ctor.addInt(
Int32Ty, I.Priority);
2477 if (InitFiniAuthSchema) {
2478 llvm::Constant *StorageAddress =
2480 ? llvm::ConstantExpr::getIntToPtr(
2481 llvm::ConstantInt::get(
2483 llvm::ConstantPtrAuth::AddrDiscriminator_CtorsDtors),
2487 I.Initializer, InitFiniAuthSchema.
getKey(), StorageAddress,
2488 llvm::ConstantInt::get(
2490 Ctor.add(SignedCtorPtr);
2492 Ctor.add(I.Initializer);
2494 if (I.AssociatedData)
2495 Ctor.add(I.AssociatedData);
2497 Ctor.addNullPointer(PtrTy);
2498 Ctor.finishAndAddTo(Ctors);
2501 auto List = Ctors.finishAndCreateGlobal(GlobalName,
getPointerAlign(),
2503 llvm::GlobalValue::AppendingLinkage);
2507 List->setAlignment(std::nullopt);
2512llvm::GlobalValue::LinkageTypes
2518 if (
const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
2525 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2526 if (!MDS)
return nullptr;
2528 return llvm::ConstantInt::get(
Int64Ty, llvm::MD5Hash(MDS->getString()));
2535 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2536 if (!UD->
hasAttr<TransparentUnionAttr>())
2538 if (!UD->
fields().empty())
2539 return UD->
fields().begin()->getType();
2548 bool GeneralizePointers) {
2561 bool GeneralizePointers) {
2564 for (
auto &Param : FnType->param_types())
2565 GeneralizedParams.push_back(
2569 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers),
2570 GeneralizedParams, FnType->getExtProtoInfo());
2575 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers));
2577 llvm_unreachable(
"Encountered unknown FunctionType");
2585 FnType->getReturnType(), FnType->getParamTypes(),
2586 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
2588 std::string OutName;
2589 llvm::raw_string_ostream Out(OutName);
2597 Out <<
".normalized";
2599 Out <<
".generalized";
2601 return llvm::ConstantInt::get(
2607 llvm::Function *F,
bool IsThunk) {
2609 llvm::AttributeList PAL;
2612 if (
CallingConv == llvm::CallingConv::X86_VectorCall &&
2616 Loc = D->getLocation();
2618 Error(Loc,
"__vectorcall calling convention is not currently supported");
2620 F->setAttributes(PAL);
2621 F->setCallingConv(
static_cast<llvm::CallingConv::ID
>(
CallingConv));
2625 std::string ReadOnlyQual(
"__read_only");
2626 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2627 if (ReadOnlyPos != std::string::npos)
2629 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2631 std::string WriteOnlyQual(
"__write_only");
2632 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2633 if (WriteOnlyPos != std::string::npos)
2634 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2636 std::string ReadWriteQual(
"__read_write");
2637 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2638 if (ReadWritePos != std::string::npos)
2639 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2672 assert(((FD && CGF) || (!FD && !CGF)) &&
2673 "Incorrect use - FD and CGF should either be both null or not!");
2699 for (
unsigned i = 0, e = FD->
getNumParams(); i != e; ++i) {
2702 argNames.push_back(llvm::MDString::get(VMContext, parm->
getName()));
2707 std::string typeQuals;
2711 const Decl *PDecl = parm;
2713 PDecl = TD->getDecl();
2714 const OpenCLAccessAttr *A = PDecl->
getAttr<OpenCLAccessAttr>();
2715 if (A && A->isWriteOnly())
2716 accessQuals.push_back(llvm::MDString::get(VMContext,
"write_only"));
2717 else if (A && A->isReadWrite())
2718 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_write"));
2720 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_only"));
2722 accessQuals.push_back(llvm::MDString::get(VMContext,
"none"));
2724 auto getTypeSpelling = [&](
QualType Ty) {
2725 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2727 if (Ty.isCanonical()) {
2728 StringRef typeNameRef = typeName;
2730 if (typeNameRef.consume_front(
"unsigned "))
2731 return std::string(
"u") + typeNameRef.str();
2732 if (typeNameRef.consume_front(
"signed "))
2733 return typeNameRef.str();
2743 addressQuals.push_back(
2744 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(
2748 std::string typeName = getTypeSpelling(pointeeTy) +
"*";
2749 std::string baseTypeName =
2751 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2752 argBaseTypeNames.push_back(
2753 llvm::MDString::get(VMContext, baseTypeName));
2757 typeQuals =
"restrict";
2760 typeQuals += typeQuals.empty() ?
"const" :
" const";
2762 typeQuals += typeQuals.empty() ?
"volatile" :
" volatile";
2764 uint32_t AddrSpc = 0;
2769 addressQuals.push_back(
2770 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(AddrSpc)));
2774 std::string typeName = getTypeSpelling(ty);
2786 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2787 argBaseTypeNames.push_back(
2788 llvm::MDString::get(VMContext, baseTypeName));
2793 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
2797 Fn->setMetadata(
"kernel_arg_addr_space",
2798 llvm::MDNode::get(VMContext, addressQuals));
2799 Fn->setMetadata(
"kernel_arg_access_qual",
2800 llvm::MDNode::get(VMContext, accessQuals));
2801 Fn->setMetadata(
"kernel_arg_type",
2802 llvm::MDNode::get(VMContext, argTypeNames));
2803 Fn->setMetadata(
"kernel_arg_base_type",
2804 llvm::MDNode::get(VMContext, argBaseTypeNames));
2805 Fn->setMetadata(
"kernel_arg_type_qual",
2806 llvm::MDNode::get(VMContext, argTypeQuals));
2810 Fn->setMetadata(
"kernel_arg_name",
2811 llvm::MDNode::get(VMContext, argNames));
2821 if (!LangOpts.Exceptions)
return false;
2824 if (LangOpts.CXXExceptions)
return true;
2827 if (LangOpts.ObjCExceptions) {
2847SmallVector<const CXXRecordDecl *, 0>
2849 llvm::SetVector<const CXXRecordDecl *> MostBases;
2854 MostBases.insert(RD);
2856 CollectMostBases(B.getType()->getAsCXXRecordDecl());
2858 CollectMostBases(RD);
2859 return MostBases.takeVector();
2863 llvm::Function *F) {
2864 llvm::AttrBuilder B(F->getContext());
2866 if ((!D || !D->
hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2867 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2869 if (CodeGenOpts.StackClashProtector)
2870 B.addAttribute(
"probe-stack",
"inline-asm");
2872 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
2873 B.addAttribute(
"stack-probe-size",
2874 std::to_string(CodeGenOpts.StackProbeSize));
2877 B.addAttribute(llvm::Attribute::NoUnwind);
2879 if (std::optional<llvm::Attribute::AttrKind>
Attr =
2881 B.addAttribute(*
Attr);
2886 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline))
2887 B.addAttribute(llvm::Attribute::AlwaysInline);
2891 else if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2893 B.addAttribute(llvm::Attribute::NoInline);
2901 if (D->
hasAttr<ArmLocallyStreamingAttr>())
2902 B.addAttribute(
"aarch64_pstate_sm_body");
2905 if (
Attr->isNewZA())
2906 B.addAttribute(
"aarch64_new_za");
2907 if (
Attr->isNewZT0())
2908 B.addAttribute(
"aarch64_new_zt0");
2913 bool ShouldAddOptNone =
2914 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
2916 ShouldAddOptNone &= !D->
hasAttr<MinSizeAttr>();
2917 ShouldAddOptNone &= !D->
hasAttr<AlwaysInlineAttr>();
2920 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline) &&
2921 !D->
hasAttr<NoInlineAttr>()) {
2922 B.addAttribute(llvm::Attribute::AlwaysInline);
2923 }
else if ((ShouldAddOptNone || D->
hasAttr<OptimizeNoneAttr>()) &&
2924 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2926 B.addAttribute(llvm::Attribute::OptimizeNone);
2929 B.addAttribute(llvm::Attribute::NoInline);
2934 B.addAttribute(llvm::Attribute::Naked);
2937 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
2938 F->removeFnAttr(llvm::Attribute::MinSize);
2939 }
else if (D->
hasAttr<NakedAttr>()) {
2941 B.addAttribute(llvm::Attribute::Naked);
2942 B.addAttribute(llvm::Attribute::NoInline);
2943 }
else if (D->
hasAttr<NoDuplicateAttr>()) {
2944 B.addAttribute(llvm::Attribute::NoDuplicate);
2945 }
else if (D->
hasAttr<NoInlineAttr>() &&
2946 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2948 B.addAttribute(llvm::Attribute::NoInline);
2949 }
else if (D->
hasAttr<AlwaysInlineAttr>() &&
2950 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
2952 B.addAttribute(llvm::Attribute::AlwaysInline);
2956 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
2957 B.addAttribute(llvm::Attribute::NoInline);
2961 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
2964 auto CheckRedeclForInline = [](
const FunctionDecl *Redecl) {
2965 return Redecl->isInlineSpecified();
2967 if (any_of(FD->
redecls(), CheckRedeclForInline))
2972 return any_of(Pattern->
redecls(), CheckRedeclForInline);
2974 if (CheckForInline(FD)) {
2975 B.addAttribute(llvm::Attribute::InlineHint);
2976 }
else if (CodeGenOpts.getInlining() ==
2979 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2980 B.addAttribute(llvm::Attribute::NoInline);
2987 if (!D->
hasAttr<OptimizeNoneAttr>()) {
2989 if (!ShouldAddOptNone)
2990 B.addAttribute(llvm::Attribute::OptimizeForSize);
2991 B.addAttribute(llvm::Attribute::Cold);
2994 B.addAttribute(llvm::Attribute::Hot);
2995 if (D->
hasAttr<MinSizeAttr>())
2996 B.addAttribute(llvm::Attribute::MinSize);
3001 if (CodeGenOpts.DisableOutlining || D->
hasAttr<NoOutlineAttr>())
3002 B.addAttribute(llvm::Attribute::NoOutline);
3006 llvm::MaybeAlign ExplicitAlignment;
3007 if (
unsigned alignment = D->
getMaxAlignment() / Context.getCharWidth())
3008 ExplicitAlignment = llvm::Align(alignment);
3009 else if (LangOpts.FunctionAlignment)
3010 ExplicitAlignment = llvm::Align(1ull << LangOpts.FunctionAlignment);
3012 if (ExplicitAlignment) {
3013 F->setAlignment(ExplicitAlignment);
3014 F->setPreferredAlignment(ExplicitAlignment);
3015 }
else if (LangOpts.PreferredFunctionAlignment) {
3016 F->setPreferredAlignment(llvm::Align(LangOpts.PreferredFunctionAlignment));
3025 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
3030 if (CodeGenOpts.SanitizeCfiCrossDso &&
3031 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
3032 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
3040 if (CodeGenOpts.CallGraphSection) {
3041 if (
auto *FD = dyn_cast<FunctionDecl>(D))
3048 auto *MD = dyn_cast<CXXMethodDecl>(D);
3051 llvm::Metadata *Id =
3053 MD->getType(), std::nullopt,
Base));
3054 F->addTypeMetadata(0, Id);
3061 if (
const auto *FD = dyn_cast<FunctionDecl>(D))
3062 if (FD->
hasAttr<SYCLExternalAttr>())
3063 addSYCLModuleIdAttr(F);
3067void CodeGenModule::addSYCLModuleIdAttr(llvm::Function *Fn) {
3069 Fn->addFnAttr(
"sycl-module-id",
getModule().getModuleIdentifier());
3074 if (isa_and_nonnull<NamedDecl>(D))
3077 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
3079 if (D && D->
hasAttr<UsedAttr>())
3082 if (
const auto *VD = dyn_cast_if_present<VarDecl>(D);
3084 ((CodeGenOpts.KeepPersistentStorageVariables &&
3085 (VD->getStorageDuration() ==
SD_Static ||
3086 VD->getStorageDuration() ==
SD_Thread)) ||
3087 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
3088 VD->getType().isConstQualified())))
3093static std::vector<std::string>
3095 llvm::StringMap<bool> &FeatureMap) {
3096 llvm::StringMap<bool> DefaultFeatureMap;
3100 std::vector<std::string> Delta;
3101 for (
const auto &[K,
V] : FeatureMap) {
3102 auto DefaultIt = DefaultFeatureMap.find(K);
3103 if (DefaultIt == DefaultFeatureMap.end() || DefaultIt->getValue() !=
V)
3104 Delta.push_back((
V ?
"+" :
"-") + K.str());
3110bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
3111 llvm::AttrBuilder &Attrs,
3112 bool SetTargetFeatures) {
3118 std::vector<std::string> Features;
3119 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.
getDecl());
3122 const auto *TV = FD ? FD->
getAttr<TargetVersionAttr>() :
nullptr;
3123 assert((!TD || !TV) &&
"both target_version and target specified");
3126 bool AddedAttr =
false;
3127 if (TD || TV || SD || TC) {
3128 llvm::StringMap<bool> FeatureMap;
3135 StringRef FeatureStr = TD ? TD->getFeaturesStr() : StringRef();
3138 if (!FeatureStr.empty()) {
3139 ParsedTargetAttr ParsedAttr = Target.parseTargetAttr(FeatureStr);
3140 if (!ParsedAttr.
CPU.empty() &&
3142 TargetCPU = ParsedAttr.
CPU;
3145 if (!ParsedAttr.
Tune.empty() &&
3147 TuneCPU = ParsedAttr.
Tune;
3163 for (
const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
3164 Features.push_back((Entry.getValue() ?
"+" :
"-") +
3165 Entry.getKey().str());
3171 llvm::StringMap<bool> FeatureMap;
3185 if (!TargetCPU.empty()) {
3186 Attrs.addAttribute(
"target-cpu", TargetCPU);
3189 if (!TuneCPU.empty()) {
3190 Attrs.addAttribute(
"tune-cpu", TuneCPU);
3193 if (!Features.empty() && SetTargetFeatures) {
3194 llvm::erase_if(Features, [&](
const std::string& F) {
3197 llvm::sort(Features);
3198 Attrs.addAttribute(
"target-features", llvm::join(Features,
","));
3203 llvm::SmallVector<StringRef, 8> Feats;
3204 bool IsDefault =
false;
3206 IsDefault = TV->isDefaultVersion();
3207 TV->getFeatures(Feats);
3213 Attrs.addAttribute(
"fmv-features");
3215 }
else if (!Feats.empty()) {
3217 std::set<StringRef> OrderedFeats(Feats.begin(), Feats.end());
3218 std::string FMVFeatures;
3219 for (StringRef F : OrderedFeats)
3220 FMVFeatures.append(
"," + F.str());
3221 Attrs.addAttribute(
"fmv-features", FMVFeatures.substr(1));
3228void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
3229 llvm::GlobalObject *GO) {
3234 if (
auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
3237 if (
auto *SA = D->
getAttr<PragmaClangBSSSectionAttr>())
3238 GV->addAttribute(
"bss-section", SA->getName());
3239 if (
auto *SA = D->
getAttr<PragmaClangDataSectionAttr>())
3240 GV->addAttribute(
"data-section", SA->getName());
3241 if (
auto *SA = D->
getAttr<PragmaClangRodataSectionAttr>())
3242 GV->addAttribute(
"rodata-section", SA->getName());
3243 if (
auto *SA = D->
getAttr<PragmaClangRelroSectionAttr>())
3244 GV->addAttribute(
"relro-section", SA->getName());
3247 if (
auto *F = dyn_cast<llvm::Function>(GO)) {
3250 if (
auto *SA = D->
getAttr<PragmaClangTextSectionAttr>())
3251 if (!D->
getAttr<SectionAttr>())
3252 F->setSection(SA->getName());
3254 llvm::AttrBuilder Attrs(F->getContext());
3255 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
3259 llvm::AttributeMask RemoveAttrs;
3260 RemoveAttrs.addAttribute(
"target-cpu");
3261 RemoveAttrs.addAttribute(
"target-features");
3262 RemoveAttrs.addAttribute(
"fmv-features");
3263 RemoveAttrs.addAttribute(
"tune-cpu");
3264 F->removeFnAttrs(RemoveAttrs);
3265 F->addFnAttrs(Attrs);
3269 if (
const auto *CSA = D->
getAttr<CodeSegAttr>())
3270 GO->setSection(CSA->getName());
3271 else if (
const auto *SA = D->
getAttr<SectionAttr>())
3272 GO->setSection(SA->getName());
3285 F->setLinkage(llvm::Function::InternalLinkage);
3287 setNonAliasAttributes(GD, F);
3298 GV->
setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
3302 llvm::MDNode *MD = F->getMetadata(llvm::LLVMContext::MD_type);
3303 return MD && MD->hasGeneralizedMDString();
3307 llvm::Function *F) {
3314 if (!F->hasLocalLinkage() ||
3315 F->getFunction().hasAddressTaken(
nullptr,
true,
3322 llvm::Function *F) {
3324 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
3335 F->addTypeMetadata(0, MD);
3344 if (CodeGenOpts.SanitizeCfiCrossDso)
3346 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
3350 llvm::CallBase *CB) {
3355 if (!CodeGenOpts.CallGraphSection || !CB->isIndirectCall() ||
3360 llvm::MDTuple *TypeTuple = llvm::MDTuple::get(
3361 getLLVMContext(), {llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
3364 llvm::MDTuple *MDN = llvm::MDNode::get(
getLLVMContext(), {TypeTuple});
3365 CB->setMetadata(llvm::LLVMContext::MD_callee_type, MDN);
3369 llvm::LLVMContext &Ctx = F->getContext();
3370 llvm::MDBuilder MDB(Ctx);
3371 llvm::StringRef Salt;
3374 if (
const auto &Info = FP->getExtraAttributeInfo())
3375 Salt = Info.CFISalt;
3377 F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
3386 return llvm::all_of(Name, [](
const char &
C) {
3387 return llvm::isAlnum(
C) ||
C ==
'_' ||
C ==
'.';
3393 for (
auto &F : M.functions()) {
3395 bool AddressTaken = F.hasAddressTaken();
3396 if (!AddressTaken && F.hasLocalLinkage())
3397 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
3402 if (!AddressTaken || !F.isDeclaration())
3405 const llvm::ConstantInt *
Type;
3406 if (
const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
3407 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
3411 StringRef Name = F.getName();
3415 std::string
Asm = (
".weak __kcfi_typeid_" + Name +
"\n.set __kcfi_typeid_" +
3416 Name +
", " + Twine(
Type->getZExtValue()) +
" /* " +
3417 Twine(
Type->getSExtValue()) +
" */\n")
3419 M.appendModuleInlineAsm(
Asm);
3423void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
3424 bool IsIncompleteFunction,
3427 if (F->getIntrinsicID() != llvm::Intrinsic::not_intrinsic) {
3435 if (!IsIncompleteFunction)
3442 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
3444 assert(!F->arg_empty() &&
3445 F->arg_begin()->getType()
3446 ->canLosslesslyBitCastTo(F->getReturnType()) &&
3447 "unexpected this return");
3448 F->addParamAttr(0, llvm::Attribute::Returned);
3458 if (!IsIncompleteFunction && F->isDeclaration())
3461 if (
const auto *CSA = FD->
getAttr<CodeSegAttr>())
3462 F->setSection(CSA->getName());
3463 else if (
const auto *SA = FD->
getAttr<SectionAttr>())
3464 F->setSection(SA->getName());
3466 if (
const auto *EA = FD->
getAttr<ErrorAttr>()) {
3468 F->addFnAttr(
"dontcall-error", EA->getUserDiagnostic());
3469 else if (EA->isWarning())
3470 F->addFnAttr(
"dontcall-warn", EA->getUserDiagnostic());
3475 const FunctionDecl *FDBody;
3476 bool HasBody = FD->
hasBody(FDBody);
3478 assert(HasBody &&
"Inline builtin declarations should always have an "
3480 if (shouldEmitFunction(FDBody))
3481 F->addFnAttr(llvm::Attribute::NoBuiltin);
3487 F->addFnAttr(llvm::Attribute::NoBuiltin);
3491 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3492 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
3493 if (MD->isVirtual())
3494 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3500 if (!CodeGenOpts.SanitizeCfiCrossDso ||
3501 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
3504 if (CodeGenOpts.CallGraphSection)
3507 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
3513 if (CodeGenOpts.InlineMaxStackSize !=
UINT_MAX)
3514 F->addFnAttr(
"inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
3516 if (
const auto *CB = FD->
getAttr<CallbackAttr>()) {
3520 llvm::LLVMContext &Ctx = F->getContext();
3521 llvm::MDBuilder MDB(Ctx);
3525 int CalleeIdx = *CB->encoding_begin();
3526 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
3527 F->addMetadata(llvm::LLVMContext::MD_callback,
3528 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
3529 CalleeIdx, PayloadIndices,
3536 "Only globals with definition can force usage.");
3537 LLVMUsed.emplace_back(GV);
3541 assert(!GV->isDeclaration() &&
3542 "Only globals with definition can force usage.");
3543 LLVMCompilerUsed.emplace_back(GV);
3548 "Only globals with definition can force usage.");
3550 LLVMCompilerUsed.emplace_back(GV);
3552 LLVMUsed.emplace_back(GV);
3556 std::vector<llvm::WeakTrackingVH> &List) {
3563 UsedArray.resize(List.size());
3564 for (
unsigned i = 0, e = List.size(); i != e; ++i) {
3566 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3570 if (UsedArray.empty())
3572 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
3574 auto *GV =
new llvm::GlobalVariable(
3575 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
3576 llvm::ConstantArray::get(ATy, UsedArray), Name);
3578 GV->setSection(
"llvm.metadata");
3581void CodeGenModule::emitLLVMUsed() {
3582 emitUsed(*
this,
"llvm.used", LLVMUsed);
3583 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
3588 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3597 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3603 ELFDependentLibraries.push_back(
3604 llvm::MDNode::get(
C, llvm::MDString::get(
C, Lib)));
3611 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
C, MDOpts));
3620 if (Mod->
Parent && Visited.insert(Mod->
Parent).second) {
3626 if (Visited.insert(Import).second)
3643 if (LL.IsFramework) {
3644 llvm::Metadata *Args[2] = {llvm::MDString::get(Context,
"-framework"),
3645 llvm::MDString::get(Context, LL.Library)};
3647 Metadata.push_back(llvm::MDNode::get(Context, Args));
3653 llvm::Metadata *Args[2] = {
3654 llvm::MDString::get(Context,
"lib"),
3655 llvm::MDString::get(Context, LL.Library),
3657 Metadata.push_back(llvm::MDNode::get(Context, Args));
3661 auto *OptString = llvm::MDString::get(Context, Opt);
3662 Metadata.push_back(llvm::MDNode::get(Context, OptString));
3667void CodeGenModule::EmitModuleInitializers(
clang::Module *Primary) {
3669 "We should only emit module initializers for named modules.");
3677 assert(
isa<VarDecl>(D) &&
"GMF initializer decl is not a var?");
3694 assert(
isa<VarDecl>(D) &&
"PMF initializer decl is not a var?");
3700void CodeGenModule::EmitModuleLinkOptions() {
3704 llvm::SetVector<clang::Module *> LinkModules;
3705 llvm::SmallPtrSet<clang::Module *, 16> Visited;
3706 SmallVector<clang::Module *, 16> Stack;
3709 for (
Module *M : ImportedModules) {
3712 if (M->getTopLevelModuleName() ==
getLangOpts().CurrentModule &&
3715 if (Visited.insert(M).second)
3721 while (!Stack.empty()) {
3724 bool AnyChildren =
false;
3733 if (Visited.insert(
SM).second) {
3734 Stack.push_back(
SM);
3742 LinkModules.insert(Mod);
3749 SmallVector<llvm::MDNode *, 16> MetadataArgs;
3751 for (
Module *M : LinkModules)
3752 if (Visited.insert(M).second)
3754 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
3755 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
3758 if (!LinkerOptionsMetadata.empty()) {
3759 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.linker.options");
3760 for (
auto *MD : LinkerOptionsMetadata)
3761 NMD->addOperand(MD);
3765void CodeGenModule::EmitDeferred() {
3774 if (!DeferredVTables.empty()) {
3775 EmitDeferredVTables();
3780 assert(DeferredVTables.empty());
3787 llvm::append_range(DeferredDeclsToEmit,
3791 if (DeferredDeclsToEmit.empty())
3796 std::vector<GlobalDecl> CurDeclsToEmit;
3797 CurDeclsToEmit.swap(DeferredDeclsToEmit);
3799 for (GlobalDecl &D : CurDeclsToEmit) {
3805 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>() &&
3809 if (!FD->
getAttr<SYCLKernelEntryPointAttr>()->isInvalidAttr()) {
3825 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
3843 if (!GV->isDeclaration())
3847 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
3851 EmitGlobalDefinition(D, GV);
3856 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
3858 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
3863void CodeGenModule::EmitVTablesOpportunistically() {
3869 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
3870 &&
"Only emit opportunistic vtables with optimizations");
3872 for (
const CXXRecordDecl *RD : OpportunisticVTables) {
3874 "This queue should only contain external vtables");
3875 if (
getCXXABI().canSpeculativelyEmitVTable(RD))
3876 VTables.GenerateClassData(RD);
3878 OpportunisticVTables.clear();
3882 for (
const auto& [MangledName, VD] : DeferredAnnotations) {
3887 DeferredAnnotations.clear();
3889 if (Annotations.empty())
3893 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
3894 Annotations[0]->
getType(), Annotations.size()), Annotations);
3895 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
3896 llvm::GlobalValue::AppendingLinkage,
3897 Array,
"llvm.global.annotations");
3902 llvm::Constant *&AStr = AnnotationStrings[Str];
3907 llvm::Constant *
s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
3908 auto *gv =
new llvm::GlobalVariable(
3909 getModule(),
s->getType(),
true, llvm::GlobalValue::PrivateLinkage,
s,
3910 ".str",
nullptr, llvm::GlobalValue::NotThreadLocal,
3913 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3930 SM.getExpansionLineNumber(L);
3931 return llvm::ConstantInt::get(
Int32Ty, LineNo);
3939 llvm::FoldingSetNodeID ID;
3940 for (
Expr *E : Exprs) {
3943 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
3948 LLVMArgs.reserve(Exprs.size());
3950 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](
const Expr *E) {
3952 return ConstEmiter.
emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
3955 auto *
Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
3956 auto *GV =
new llvm::GlobalVariable(
getModule(),
Struct->getType(),
true,
3957 llvm::GlobalValue::PrivateLinkage,
Struct,
3960 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3967 const AnnotateAttr *AA,
3975 llvm::Constant *GVInGlobalsAS = GV;
3976 if (GV->getAddressSpace() !=
3978 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
3980 llvm::PointerType::get(
3981 GV->getContext(),
getDataLayout().getDefaultGlobalsAddressSpace()));
3985 llvm::Constant *Fields[] = {
3986 GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
3988 return llvm::ConstantStruct::getAnon(Fields);
3992 llvm::GlobalValue *GV) {
3993 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
4003 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
4006 auto &
SM = Context.getSourceManager();
4008 if (NoSanitizeL.containsMainFile(Kind, MainFile.
getName()))
4013 return NoSanitizeL.containsLocation(Kind, Loc);
4016 return NoSanitizeL.containsFile(Kind, MainFile.
getName());
4020 llvm::GlobalVariable *GV,
4022 StringRef Category)
const {
4024 if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
4026 auto &
SM = Context.getSourceManager();
4027 if (NoSanitizeL.containsMainFile(
4028 Kind,
SM.getFileEntryRefForID(
SM.getMainFileID())->getName(),
4031 if (NoSanitizeL.containsLocation(Kind, Loc, Category))
4038 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
4039 Ty = AT->getElementType();
4044 if (NoSanitizeL.containsType(Kind, TypeStr, Category))
4052 StringRef Category)
const {
4055 auto Attr = ImbueAttr::NONE;
4057 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
4058 if (
Attr == ImbueAttr::NONE)
4059 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
4061 case ImbueAttr::NONE:
4063 case ImbueAttr::ALWAYS:
4064 Fn->addFnAttr(
"function-instrument",
"xray-always");
4066 case ImbueAttr::ALWAYS_ARG1:
4067 Fn->addFnAttr(
"function-instrument",
"xray-always");
4068 Fn->addFnAttr(
"xray-log-args",
"1");
4070 case ImbueAttr::NEVER:
4071 Fn->addFnAttr(
"function-instrument",
"xray-never");
4084 llvm::driver::ProfileInstrKind Kind =
getCodeGenOpts().getProfileInstr();
4094 auto &
SM = Context.getSourceManager();
4095 if (
auto MainFile =
SM.getFileEntryRefForID(
SM.getMainFileID()))
4109 if (NumGroups > 1) {
4110 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
4119 if (LangOpts.EmitAllDecls)
4122 const auto *VD = dyn_cast<VarDecl>(
Global);
4124 ((CodeGenOpts.KeepPersistentStorageVariables &&
4125 (VD->getStorageDuration() ==
SD_Static ||
4126 VD->getStorageDuration() ==
SD_Thread)) ||
4127 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
4128 VD->getType().isConstQualified())))
4141 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
4142 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
4143 OMPDeclareTargetDeclAttr::getActiveAttr(
Global);
4144 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (
unsigned)-1)
4148 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
4158 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>())
4161 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
4162 if (Context.getInlineVariableDefinitionKind(VD) ==
4167 if (CXX20ModuleInits && VD->getOwningModule() &&
4168 !VD->getOwningModule()->isModuleMapModule()) {
4177 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
4180 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
Global))
4193 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
4197 llvm::Constant *
Init;
4200 if (!
V.isAbsent()) {
4211 llvm::Constant *Fields[4] = {
4215 llvm::ConstantDataArray::getRaw(
4216 StringRef(
reinterpret_cast<char *
>(Parts.
Part4And5), 8), 8,
4218 Init = llvm::ConstantStruct::getAnon(Fields);
4221 auto *GV =
new llvm::GlobalVariable(
4223 true, llvm::GlobalValue::LinkOnceODRLinkage,
Init, Name);
4225 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4228 if (!
V.isAbsent()) {
4241 llvm::GlobalVariable **Entry =
nullptr;
4242 Entry = &UnnamedGlobalConstantDeclMap[GCD];
4247 llvm::Constant *
Init;
4251 assert(!
V.isAbsent());
4255 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
4257 llvm::GlobalValue::PrivateLinkage,
Init,
4259 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4273 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
4277 llvm::Constant *
Init =
Emitter.emitForInitializer(
4285 llvm::GlobalValue::LinkageTypes
Linkage =
4287 ? llvm::GlobalValue::LinkOnceODRLinkage
4288 : llvm::GlobalValue::InternalLinkage;
4289 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
4293 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4300 const AliasAttr *AA = VD->
getAttr<AliasAttr>();
4301 assert(AA &&
"No alias?");
4311 llvm::Constant *Aliasee;
4313 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
4321 F->setLinkage(llvm::Function::ExternalWeakLinkage);
4322 WeakRefReferences.insert(F);
4330 if (
auto *A = D->
getAttr<AttrT>())
4331 return A->isImplicit();
4338 if (!LangOpts.OpenMPIsTargetDevice && !LangOpts.CUDA)
4341 const auto *AA =
Global->getAttr<AliasAttr>();
4349 const auto *AliaseeDecl = dyn_cast<ValueDecl>(AliaseeGD.getDecl());
4350 if (LangOpts.OpenMPIsTargetDevice)
4351 return !AliaseeDecl ||
4352 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(AliaseeDecl);
4355 const bool HasDeviceAttr =
Global->hasAttr<CUDADeviceAttr>();
4356 const bool AliaseeHasDeviceAttr =
4357 AliaseeDecl && AliaseeDecl->hasAttr<CUDADeviceAttr>();
4359 if (LangOpts.CUDAIsDevice)
4360 return !HasDeviceAttr || !AliaseeHasDeviceAttr;
4367bool CodeGenModule::shouldEmitCUDAGlobalVar(
const VarDecl *
Global)
const {
4368 assert(LangOpts.CUDA &&
"Should not be called by non-CUDA languages");
4373 return !LangOpts.CUDAIsDevice ||
Global->hasAttr<CUDADeviceAttr>() ||
4374 Global->hasAttr<CUDAConstantAttr>() ||
4375 Global->hasAttr<CUDASharedAttr>() ||
4376 Global->getType()->isCUDADeviceBuiltinSurfaceType() ||
4377 Global->getType()->isCUDADeviceBuiltinTextureType();
4384 if (
Global->hasAttr<WeakRefAttr>())
4389 if (
Global->hasAttr<AliasAttr>()) {
4392 return EmitAliasDefinition(GD);
4396 if (
Global->hasAttr<IFuncAttr>())
4397 return emitIFuncDefinition(GD);
4400 if (
Global->hasAttr<CPUDispatchAttr>())
4401 return emitCPUDispatchDefinition(GD);
4406 if (LangOpts.CUDA) {
4408 "Expected Variable or Function");
4409 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
4410 if (!shouldEmitCUDAGlobalVar(VD))
4412 }
else if (LangOpts.CUDAIsDevice) {
4413 const auto *FD = dyn_cast<FunctionDecl>(
Global);
4414 if ((!
Global->hasAttr<CUDADeviceAttr>() ||
4415 (LangOpts.OffloadImplicitHostDeviceTemplates &&
4419 !
getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
4420 !
Global->hasAttr<CUDAGlobalAttr>() &&
4422 !
Global->hasAttr<CUDAHostAttr>()))
4425 }
else if (!
Global->hasAttr<CUDAHostAttr>() &&
4426 Global->hasAttr<CUDADeviceAttr>())
4430 if (LangOpts.OpenMP) {
4432 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
4434 if (
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(
Global)) {
4435 if (MustBeEmitted(
Global))
4439 if (
auto *DMD = dyn_cast<OMPDeclareMapperDecl>(
Global)) {
4440 if (MustBeEmitted(
Global))
4447 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
4448 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
4454 if (FD->
hasAttr<AnnotateAttr>()) {
4457 DeferredAnnotations[MangledName] = FD;
4472 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
4478 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
4480 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
4481 if (LangOpts.OpenMP) {
4483 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
4484 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
4488 if (VD->hasExternalStorage() &&
4489 Res != OMPDeclareTargetDeclAttr::MT_Link)
4492 bool UnifiedMemoryEnabled =
4494 if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4495 *Res == OMPDeclareTargetDeclAttr::MT_Enter ||
4496 *Res == OMPDeclareTargetDeclAttr::MT_Local) &&
4497 !UnifiedMemoryEnabled) {
4500 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
4501 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4502 *Res == OMPDeclareTargetDeclAttr::MT_Enter ||
4503 *Res == OMPDeclareTargetDeclAttr::MT_Local) &&
4504 UnifiedMemoryEnabled)) &&
4505 "Link clause or to clause with unified memory expected.");
4515 if (LangOpts.HLSL) {
4516 if (VD->getStorageClass() ==
SC_Extern) {
4525 if (Context.getInlineVariableDefinitionKind(VD) ==
4535 if (MustBeEmitted(
Global) && MayBeEmittedEagerly(
Global)) {
4537 EmitGlobalDefinition(GD);
4538 addEmittedDeferredDecl(GD);
4546 DelayedCXXInitPosition[
Global] = CXXGlobalInits.size();
4547 CXXGlobalInits.push_back(
nullptr);
4553 addDeferredDeclToEmit(GD);
4554 }
else if (MustBeEmitted(
Global)) {
4556 assert(!MayBeEmittedEagerly(
Global));
4557 addDeferredDeclToEmit(GD);
4562 DeferredDecls[MangledName] = GD;
4568 if (
const auto *RT =
4569 T->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
4570 if (
auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
4571 RD = RD->getDefinitionOrSelf();
4572 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
4580 struct FunctionIsDirectlyRecursive
4581 :
public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
4582 const StringRef Name;
4583 const Builtin::Context &BI;
4584 FunctionIsDirectlyRecursive(StringRef N,
const Builtin::Context &
C)
4587 bool VisitCallExpr(
const CallExpr *E) {
4591 AsmLabelAttr *Attr = FD->
getAttr<AsmLabelAttr>();
4592 if (Attr && Name == Attr->getLabel())
4597 std::string BuiltinNameStr = BI.
getName(BuiltinID);
4598 StringRef BuiltinName = BuiltinNameStr;
4599 return BuiltinName.consume_front(
"__builtin_") && Name == BuiltinName;
4602 bool VisitStmt(
const Stmt *S) {
4603 for (
const Stmt *Child : S->
children())
4604 if (Child && this->Visit(Child))
4611 struct DLLImportFunctionVisitor
4612 :
public RecursiveASTVisitor<DLLImportFunctionVisitor> {
4613 bool SafeToInline =
true;
4615 bool shouldVisitImplicitCode()
const {
return true; }
4617 bool VisitVarDecl(VarDecl *VD) {
4620 SafeToInline =
false;
4621 return SafeToInline;
4628 return SafeToInline;
4631 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
4633 SafeToInline = D->
hasAttr<DLLImportAttr>();
4634 return SafeToInline;
4637 bool VisitDeclRefExpr(DeclRefExpr *E) {
4640 SafeToInline = VD->
hasAttr<DLLImportAttr>();
4641 else if (VarDecl *
V = dyn_cast<VarDecl>(VD))
4642 SafeToInline = !
V->hasGlobalStorage() ||
V->hasAttr<DLLImportAttr>();
4643 return SafeToInline;
4646 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
4648 return SafeToInline;
4651 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4655 SafeToInline =
true;
4657 SafeToInline = M->
hasAttr<DLLImportAttr>();
4659 return SafeToInline;
4662 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
4664 return SafeToInline;
4667 bool VisitCXXNewExpr(CXXNewExpr *E) {
4669 return SafeToInline;
4678CodeGenModule::isTriviallyRecursive(
const FunctionDecl *FD) {
4680 if (
getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
4682 AsmLabelAttr *Attr = FD->
getAttr<AsmLabelAttr>();
4685 Name = Attr->getLabel();
4690 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
4691 const Stmt *Body = FD->
getBody();
4692 return Body ? Walker.Visit(Body) :
false;
4695bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
4702 if (F->isInlineBuiltinDeclaration())
4705 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
4710 if (
const Module *M = F->getOwningModule();
4711 M && M->getTopLevelModule()->isNamedModule() &&
4712 getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
4722 if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
4727 if (F->hasAttr<NoInlineAttr>())
4730 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
4732 DLLImportFunctionVisitor Visitor;
4733 Visitor.TraverseFunctionDecl(
const_cast<FunctionDecl*
>(F));
4734 if (!Visitor.SafeToInline)
4737 if (
const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
4740 for (
const Decl *
Member : Dtor->getParent()->decls())
4744 for (
const CXXBaseSpecifier &B : Dtor->getParent()->bases())
4755 return !isTriviallyRecursive(F);
4758bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
4759 return CodeGenOpts.OptimizationLevel > 0;
4762void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
4763 llvm::GlobalValue *GV) {
4767 auto *Spec = FD->
getAttr<CPUSpecificAttr>();
4768 for (
unsigned I = 0; I < Spec->cpus_size(); ++I)
4770 }
else if (
auto *TC = FD->
getAttr<TargetClonesAttr>()) {
4771 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I)
4772 if (TC->isFirstOfVersion(I))
4775 EmitGlobalFunctionDefinition(GD, GV);
4781 AddDeferredMultiVersionResolverToEmit(GD);
4783 GetOrCreateMultiVersionResolver(GD);
4787void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
4790 PrettyStackTraceDecl CrashInfo(
const_cast<ValueDecl *
>(D), D->
getLocation(),
4791 Context.getSourceManager(),
4792 "Generating code for declaration");
4794 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
4797 if (!shouldEmitFunction(GD))
4800 llvm::TimeTraceScope TimeScope(
"CodeGen Function", [&]() {
4802 llvm::raw_string_ostream
OS(Name);
4808 if (
const auto *
Method = dyn_cast<CXXMethodDecl>(D)) {
4812 ABI->emitCXXStructor(GD);
4814 EmitMultiVersionFunctionDefinition(GD, GV);
4816 EmitGlobalFunctionDefinition(GD, GV);
4825 return EmitMultiVersionFunctionDefinition(GD, GV);
4826 return EmitGlobalFunctionDefinition(GD, GV);
4829 if (
const auto *VD = dyn_cast<VarDecl>(D))
4830 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
4832 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
4836 llvm::Function *NewFn);
4852static llvm::GlobalValue::LinkageTypes
4856 return llvm::GlobalValue::InternalLinkage;
4857 return llvm::GlobalValue::WeakODRLinkage;
4860void CodeGenModule::emitMultiVersionFunctions() {
4861 std::vector<GlobalDecl> MVFuncsToEmit;
4862 MultiVersionFuncs.swap(MVFuncsToEmit);
4863 for (GlobalDecl GD : MVFuncsToEmit) {
4865 assert(FD &&
"Expected a FunctionDecl");
4867 auto createFunction = [&](
const FunctionDecl *
Decl,
unsigned MVIdx = 0) {
4868 GlobalDecl CurGD{
Decl->isDefined() ?
Decl->getDefinition() :
Decl, MVIdx};
4872 if (
Decl->isDefined()) {
4873 EmitGlobalFunctionDefinition(CurGD,
nullptr);
4881 assert(
Func &&
"This should have just been created");
4889 bool ShouldEmitResolver = !
getTriple().isAArch64();
4890 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
4891 llvm::DenseMap<llvm::Function *, const FunctionDecl *> DeclMap;
4894 FD, [&](
const FunctionDecl *CurFD) {
4895 llvm::SmallVector<StringRef, 8> Feats;
4898 if (
const auto *TA = CurFD->
getAttr<TargetAttr>()) {
4900 TA->getX86AddedFeatures(Feats);
4901 llvm::Function *
Func = createFunction(CurFD);
4902 DeclMap.insert({
Func, CurFD});
4903 Options.emplace_back(
Func, Feats, TA->getX86Architecture());
4904 }
else if (
const auto *TVA = CurFD->
getAttr<TargetVersionAttr>()) {
4905 if (TVA->isDefaultVersion() && IsDefined)
4906 ShouldEmitResolver =
true;
4907 llvm::Function *
Func = createFunction(CurFD);
4908 DeclMap.insert({
Func, CurFD});
4910 TVA->getFeatures(Feats, Delim);
4911 Options.emplace_back(
Func, Feats);
4912 }
else if (
const auto *TC = CurFD->
getAttr<TargetClonesAttr>()) {
4913 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
4914 if (!TC->isFirstOfVersion(I))
4916 if (TC->isDefaultVersion(I) && IsDefined)
4917 ShouldEmitResolver =
true;
4918 llvm::Function *
Func = createFunction(CurFD, I);
4919 DeclMap.insert({
Func, CurFD});
4922 TC->getX86Feature(Feats, I);
4923 Options.emplace_back(
Func, Feats, TC->getX86Architecture(I));
4926 TC->getFeatures(Feats, I, Delim);
4927 Options.emplace_back(
Func, Feats);
4931 llvm_unreachable(
"unexpected MultiVersionKind");
4934 if (!ShouldEmitResolver)
4937 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
4938 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
4939 ResolverConstant = IFunc->getResolver();
4944 *
this, GD, FD,
true);
4951 auto *Alias = llvm::GlobalAlias::create(
4953 MangledName +
".ifunc", IFunc, &
getModule());
4962 Options, [&TI](
const CodeGenFunction::FMVResolverOption &LHS,
4963 const CodeGenFunction::FMVResolverOption &RHS) {
4969 for (
auto I = Options.begin() + 1, E = Options.end(); I != E; ++I) {
4970 llvm::APInt RHS = llvm::AArch64::getCpuSupportsMask(I->Features);
4971 if (std::any_of(Options.begin(), I, [RHS](
auto RO) {
4972 llvm::APInt LHS = llvm::AArch64::getCpuSupportsMask(RO.Features);
4973 return LHS.isSubsetOf(RHS);
4975 Diags.Report(DeclMap[I->Function]->getLocation(),
4976 diag::warn_unreachable_version)
4977 << I->Function->getName();
4978 assert(I->Function->user_empty() &&
"unexpected users");
4979 I->Function->eraseFromParent();
4980 I->Function =
nullptr;
4984 CodeGenFunction CGF(*
this);
4985 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4987 setMultiVersionResolverAttributes(ResolverFunc, GD);
4989 ResolverFunc->setComdat(
4990 getModule().getOrInsertComdat(ResolverFunc->getName()));
4996 if (!MVFuncsToEmit.empty())
5001 if (!MultiVersionFuncs.empty())
5002 emitMultiVersionFunctions();
5012 llvm::GlobalValue *DS = TheModule.getNamedValue(DSName);
5014 DS =
new llvm::GlobalVariable(TheModule,
Int8Ty,
false,
5015 llvm::GlobalVariable::ExternalWeakLinkage,
5017 DS->setVisibility(llvm::GlobalValue::HiddenVisibility);
5022void CodeGenModule::emitPFPFieldsWithEvaluatedOffset() {
5023 llvm::Constant *Nop = llvm::ConstantExpr::getIntToPtr(
5025 for (
auto *FD :
getContext().PFPFieldsWithEvaluatedOffset) {
5027 llvm::GlobalValue *OldDS = TheModule.getNamedValue(DSName);
5028 llvm::GlobalValue *DS = llvm::GlobalAlias::create(
5029 Int8Ty, 0, llvm::GlobalValue::ExternalLinkage, DSName, Nop, &TheModule);
5030 DS->setVisibility(llvm::GlobalValue::HiddenVisibility);
5032 DS->takeName(OldDS);
5033 OldDS->replaceAllUsesWith(DS);
5034 OldDS->eraseFromParent();
5040 llvm::Constant *
New) {
5043 Old->replaceAllUsesWith(
New);
5044 Old->eraseFromParent();
5047void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
5049 assert(FD &&
"Not a FunctionDecl?");
5051 const auto *DD = FD->
getAttr<CPUDispatchAttr>();
5052 assert(DD &&
"Not a cpu_dispatch Function?");
5058 UpdateMultiVersionNames(GD, FD, ResolverName);
5060 llvm::Type *ResolverType;
5061 GlobalDecl ResolverGD;
5063 ResolverType = llvm::FunctionType::get(
5074 ResolverName, ResolverType, ResolverGD,
false));
5077 ResolverFunc->setComdat(
5078 getModule().getOrInsertComdat(ResolverFunc->getName()));
5080 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
5083 for (
const IdentifierInfo *II : DD->cpus()) {
5091 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
5094 EmitGlobalFunctionDefinition(ExistingDecl,
nullptr);
5100 Func = GetOrCreateLLVMFunction(
5101 MangledName, DeclTy, ExistingDecl,
5107 llvm::SmallVector<StringRef, 32> Features;
5108 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
5109 llvm::transform(Features, Features.begin(),
5110 [](StringRef Str) { return Str.substr(1); });
5111 llvm::erase_if(Features, [&Target](StringRef Feat) {
5112 return !Target.validateCpuSupports(Feat);
5118 llvm::stable_sort(Options, [](
const CodeGenFunction::FMVResolverOption &LHS,
5119 const CodeGenFunction::FMVResolverOption &RHS) {
5120 return llvm::X86::getCpuSupportsMask(LHS.
Features) >
5121 llvm::X86::getCpuSupportsMask(RHS.
Features);
5128 while (Options.size() > 1 && llvm::all_of(llvm::X86::getCpuSupportsMask(
5129 (Options.end() - 2)->Features),
5130 [](
auto X) { return X == 0; })) {
5131 StringRef LHSName = (Options.end() - 2)->Function->getName();
5132 StringRef RHSName = (Options.end() - 1)->Function->getName();
5133 if (LHSName.compare(RHSName) < 0)
5134 Options.erase(Options.end() - 2);
5136 Options.erase(Options.end() - 1);
5139 CodeGenFunction CGF(*
this);
5140 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
5141 setMultiVersionResolverAttributes(ResolverFunc, GD);
5146 unsigned AS = IFunc->getType()->getPointerAddressSpace();
5151 auto *GI = llvm::GlobalIFunc::create(DeclTy, AS,
Linkage,
"",
5158 *
this, GD, FD,
true);
5161 auto *GA = llvm::GlobalAlias::create(DeclTy, AS,
Linkage, AliasName,
5169void CodeGenModule::AddDeferredMultiVersionResolverToEmit(GlobalDecl GD) {
5171 assert(FD &&
"Not a FunctionDecl?");
5174 std::string MangledName =
5176 if (!DeferredResolversToEmit.insert(MangledName).second)
5179 MultiVersionFuncs.push_back(GD);
5185llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
5187 assert(FD &&
"Not a FunctionDecl?");
5189 std::string MangledName =
5194 std::string ResolverName = MangledName;
5198 llvm_unreachable(
"unexpected MultiVersionKind::None for resolver");
5202 ResolverName +=
".ifunc";
5209 ResolverName +=
".resolver";
5212 bool ShouldReturnIFunc =
5231 AddDeferredMultiVersionResolverToEmit(GD);
5235 if (ShouldReturnIFunc) {
5237 llvm::Type *ResolverType = llvm::FunctionType::get(
5239 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
5240 MangledName +
".resolver", ResolverType, GlobalDecl{},
5248 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(DeclTy, AS,
Linkage,
"",
5250 GIF->setName(ResolverName);
5257 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
5258 ResolverName, DeclTy, GlobalDecl{},
false);
5260 "Resolver should be created for the first time");
5265void CodeGenModule::setMultiVersionResolverAttributes(llvm::Function *Resolver,
5267 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(GD.
getDecl());
5280 Resolver->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
5291bool CodeGenModule::shouldDropDLLAttribute(
const Decl *D,
5292 const llvm::GlobalValue *GV)
const {
5293 auto SC = GV->getDLLStorageClass();
5294 if (SC == llvm::GlobalValue::DefaultStorageClass)
5297 return (((SC == llvm::GlobalValue::DLLImportStorageClass &&
5298 !MRD->
hasAttr<DLLImportAttr>()) ||
5299 (SC == llvm::GlobalValue::DLLExportStorageClass &&
5300 !MRD->
hasAttr<DLLExportAttr>())) &&
5311llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
5312 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD,
bool ForVTable,
5313 bool DontDefer,
bool IsThunk, llvm::AttributeList ExtraAttrs,
5317 std::string NameWithoutMultiVersionMangling;
5318 if (
const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
5320 if (
getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
5321 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->
isDefined() &&
5322 !DontDefer && !IsForDefinition) {
5325 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
5327 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
5330 GDDef = GlobalDecl(FDDef);
5338 UpdateMultiVersionNames(GD, FD, MangledName);
5339 if (!IsForDefinition) {
5345 AddDeferredMultiVersionResolverToEmit(GD);
5347 *
this, GD, FD,
true);
5356 *
this, GD, FD,
true);
5358 return GetOrCreateMultiVersionResolver(GD);
5363 if (!NameWithoutMultiVersionMangling.empty())
5364 MangledName = NameWithoutMultiVersionMangling;
5369 if (WeakRefReferences.erase(Entry)) {
5370 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
5371 if (FD && !FD->
hasAttr<WeakAttr>())
5372 Entry->setLinkage(llvm::Function::ExternalLinkage);
5376 if (D && shouldDropDLLAttribute(D, Entry)) {
5377 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5383 if (IsForDefinition && !Entry->isDeclaration()) {
5390 DiagnosedConflictingDefinitions.insert(GD).second) {
5394 diag::note_previous_definition);
5399 (Entry->getValueType() == Ty)) {
5406 if (!IsForDefinition)
5413 bool IsIncompleteFunction =
false;
5415 llvm::FunctionType *FTy;
5419 FTy = llvm::FunctionType::get(
VoidTy,
false);
5420 IsIncompleteFunction =
true;
5424 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
5425 Entry ? StringRef() : MangledName, &
getModule());
5429 if (D && D->
hasAttr<AnnotateAttr>())
5447 if (!Entry->use_empty()) {
5449 Entry->removeDeadConstantUsers();
5455 assert(F->getName() == MangledName &&
"name was uniqued!");
5457 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
5458 if (ExtraAttrs.hasFnAttrs()) {
5459 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
5467 if (isa_and_nonnull<CXXDestructorDecl>(D) &&
5470 addDeferredDeclToEmit(GD);
5475 auto DDI = DeferredDecls.find(MangledName);
5476 if (DDI != DeferredDecls.end()) {
5480 addDeferredDeclToEmit(DDI->second);
5481 DeferredDecls.erase(DDI);
5509 if (!IsIncompleteFunction) {
5510 assert(F->getFunctionType() == Ty);
5528 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
5538 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(GD.
getDecl())) {
5541 DD->getParent()->getNumVBases() == 0)
5546 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
5547 false, llvm::AttributeList(),
5550 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
5554 if (IsForDefinition)
5562 llvm::GlobalValue *F =
5565 return llvm::NoCFIValue::get(F);
5575 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
5578 if (!
C.getLangOpts().CPlusPlus)
5583 (Name ==
"_ZSt9terminatev" || Name ==
"?terminate@@YAXXZ")
5584 ?
C.Idents.get(
"terminate")
5585 :
C.Idents.get(Name);
5587 for (
const auto &N : {
"__cxxabiv1",
"std"}) {
5591 if (
auto *LSD = dyn_cast<LinkageSpecDecl>(
Result))
5592 for (
const auto *
Result : LSD->lookup(&NS))
5593 if ((ND = dyn_cast<NamespaceDecl>(
Result)))
5598 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
5607 llvm::Function *F, StringRef Name) {
5613 if (!Local && CGM.
getTriple().isWindowsItaniumEnvironment() &&
5616 if (!FD || FD->
hasAttr<DLLImportAttr>()) {
5617 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
5618 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
5625 llvm::AttributeList ExtraAttrs,
bool Local,
bool AssumeConvergent) {
5626 if (AssumeConvergent) {
5628 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5631 QualType FTy = Context.getFunctionType(ReturnTy, ArgTys,
5636 llvm::Constant *
C = GetOrCreateLLVMFunction(
5638 false,
false, ExtraAttrs);
5640 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
5656 llvm::AttributeList ExtraAttrs,
bool Local,
5657 bool AssumeConvergent) {
5658 if (AssumeConvergent) {
5660 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5664 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
5668 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
5677 markRegisterParameterAttributes(F);
5703 if (WeakRefReferences.erase(Entry)) {
5704 if (D && !D->
hasAttr<WeakAttr>())
5705 Entry->setLinkage(llvm::Function::ExternalLinkage);
5709 if (D && shouldDropDLLAttribute(D, Entry))
5710 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5712 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
5715 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
5720 if (IsForDefinition && !Entry->isDeclaration()) {
5728 (OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
5730 DiagnosedConflictingDefinitions.insert(D).second) {
5734 diag::note_previous_definition);
5739 if (Entry->getType()->getAddressSpace() != TargetAS)
5740 return llvm::ConstantExpr::getAddrSpaceCast(
5741 Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
5745 if (!IsForDefinition)
5751 auto *GV =
new llvm::GlobalVariable(
5752 getModule(), Ty,
false, llvm::GlobalValue::ExternalLinkage,
nullptr,
5753 MangledName,
nullptr, llvm::GlobalVariable::NotThreadLocal,
5754 getContext().getTargetAddressSpace(DAddrSpace));
5759 GV->takeName(Entry);
5761 if (!Entry->use_empty()) {
5762 Entry->replaceAllUsesWith(GV);
5765 Entry->eraseFromParent();
5771 auto DDI = DeferredDecls.find(MangledName);
5772 if (DDI != DeferredDecls.end()) {
5775 addDeferredDeclToEmit(DDI->second);
5776 DeferredDecls.erase(DDI);
5781 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
5788 GV->setAlignment(
getContext().getDeclAlign(D).getAsAlign());
5794 CXXThreadLocals.push_back(D);
5802 if (
getContext().isMSStaticDataMemberInlineDefinition(D)) {
5803 EmitGlobalVarDefinition(D);
5808 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>())
5809 GV->setSection(SA->getName());
5813 if (
getTriple().getArch() == llvm::Triple::xcore &&
5817 GV->setSection(
".cp.rodata");
5820 if (
const auto *CMA = D->
getAttr<CodeModelAttr>())
5821 GV->setCodeModel(CMA->getModel());
5826 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
5830 Context.getBaseElementType(D->
getType())->getAsCXXRecordDecl();
5831 bool HasMutableFields =
Record &&
Record->hasMutableFields();
5832 if (!HasMutableFields) {
5839 auto *InitType =
Init->getType();
5840 if (GV->getValueType() != InitType) {
5845 GV->setName(StringRef());
5850 ->stripPointerCasts());
5853 GV->eraseFromParent();
5856 GV->setInitializer(
Init);
5857 GV->setConstant(
true);
5858 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
5878 SanitizerMD->reportGlobal(GV, *D);
5883 assert(
getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
5884 if (DAddrSpace != ExpectedAS)
5897 false, IsForDefinition);
5918 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes
Linkage,
5919 llvm::Align Alignment) {
5920 llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
5921 llvm::GlobalVariable *OldGV =
nullptr;
5925 if (GV->getValueType() == Ty)
5930 assert(GV->isDeclaration() &&
"Declaration has wrong type!");
5935 GV =
new llvm::GlobalVariable(
getModule(), Ty,
true,
5940 GV->takeName(OldGV);
5942 if (!OldGV->use_empty()) {
5943 OldGV->replaceAllUsesWith(GV);
5946 OldGV->eraseFromParent();
5950 !GV->hasAvailableExternallyLinkage())
5951 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5953 GV->setAlignment(Alignment);
5990 assert(!D->
getInit() &&
"Cannot emit definite definitions here!");
5998 if (GV && !GV->isDeclaration())
6003 if (!MustBeEmitted(D) && !GV) {
6004 DeferredDecls[MangledName] = D;
6009 EmitGlobalVarDefinition(D);
6014 if (
auto const *CD = dyn_cast<const CXXConstructorDecl>(D))
6016 else if (
auto const *DD = dyn_cast<const CXXDestructorDecl>(D))
6031 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(
Addr)) {
6035 if (
const auto *VD = dyn_cast<VarDecl>(D)) {
6038 }
else if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
6040 if (!Fn->getSubprogram())
6046 return Context.toCharUnitsFromBits(
6051 if (LangOpts.OpenCL) {
6062 if (LangOpts.SYCLIsDevice &&
6066 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
6068 if (D->
hasAttr<CUDAConstantAttr>())
6070 if (D->
hasAttr<CUDASharedAttr>())
6072 if (D->
hasAttr<CUDADeviceAttr>())
6080 if (LangOpts.OpenMP) {
6082 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
6090 if (LangOpts.OpenCL)
6092 if (LangOpts.SYCLIsDevice)
6094 if (LangOpts.HIP && LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())
6102 if (
auto AS =
getTarget().getConstantAddressSpace())
6115static llvm::Constant *
6117 llvm::GlobalVariable *GV) {
6118 llvm::Constant *Cast = GV;
6123 GV, llvm::PointerType::get(
6130template<
typename SomeDecl>
6132 llvm::GlobalValue *GV) {
6147 const SomeDecl *
First = D->getFirstDecl();
6148 if (
First->getDeclContext()->isRecord() || !
First->isInExternCContext())
6154 std::pair<StaticExternCMap::iterator, bool> R =
6155 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
6160 R.first->second =
nullptr;
6167 if (D.
hasAttr<SelectAnyAttr>())
6171 if (
auto *VD = dyn_cast<VarDecl>(&D))
6185 llvm_unreachable(
"No such linkage");
6193 llvm::GlobalObject &GO) {
6196 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
6204void CodeGenModule::EmitGlobalVarDefinition(
const VarDecl *D,
6219 if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
6220 OpenMPRuntime->emitTargetGlobalVariable(D))
6223 llvm::TrackingVH<llvm::Constant>
Init;
6224 bool NeedsGlobalCtor =
false;
6228 bool IsDefinitionAvailableExternally =
6230 bool NeedsGlobalDtor =
6231 !IsDefinitionAvailableExternally &&
6238 if (IsDefinitionAvailableExternally &&
6249 std::optional<ConstantEmitter> emitter;
6254 bool IsCUDASharedVar =
6259 bool IsCUDAShadowVar =
6261 (D->
hasAttr<CUDAConstantAttr>() || D->
hasAttr<CUDADeviceAttr>() ||
6262 D->
hasAttr<CUDASharedAttr>());
6263 bool IsCUDADeviceShadowVar =
6268 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) {
6269 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
6273 Init = llvm::PoisonValue::get(
getTypes().ConvertType(ASTTy));
6276 }
else if (D->
hasAttr<LoaderUninitializedAttr>()) {
6277 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
6278 }
else if (!InitExpr) {
6291 initializedGlobalDecl = GlobalDecl(D);
6292 emitter.emplace(*
this);
6293 llvm::Constant *
Initializer = emitter->tryEmitForInitializer(*InitDecl);
6295 QualType T = InitExpr->
getType();
6301 if (!IsDefinitionAvailableExternally)
6302 NeedsGlobalCtor =
true;
6306 NeedsGlobalCtor =
false;
6310 Init = llvm::PoisonValue::get(
getTypes().ConvertType(T));
6318 DelayedCXXInitPosition.erase(D);
6325 assert(VarSize == CstSize &&
"Emitted constant has unexpected size");
6330 llvm::Type* InitType =
Init->getType();
6331 llvm::Constant *Entry =
6335 Entry = Entry->stripPointerCasts();
6338 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
6349 if (!GV || GV->getValueType() != InitType ||
6350 GV->getType()->getAddressSpace() !=
6354 Entry->setName(StringRef());
6359 ->stripPointerCasts());
6362 llvm::Constant *NewPtrForOldDecl =
6363 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
6365 Entry->replaceAllUsesWith(NewPtrForOldDecl);
6373 if (D->
hasAttr<AnnotateAttr>())
6386 if (LangOpts.CUDA) {
6387 if (LangOpts.CUDAIsDevice) {
6390 (D->
hasAttr<CUDADeviceAttr>() || D->
hasAttr<CUDAConstantAttr>() ||
6393 GV->setExternallyInitialized(
true);
6400 if (LangOpts.HLSL &&
6405 GV->setExternallyInitialized(
true);
6407 GV->setInitializer(
Init);
6414 emitter->finalize(GV);
6417 GV->setConstant((D->
hasAttr<CUDAConstantAttr>() && LangOpts.CUDAIsDevice) ||
6418 (!NeedsGlobalCtor && !NeedsGlobalDtor &&
6422 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>()) {
6423 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
6425 GV->setConstant(
true);
6430 if (std::optional<CharUnits> AlignValFromAllocate =
6432 AlignVal = *AlignValFromAllocate;
6450 Linkage == llvm::GlobalValue::ExternalLinkage &&
6451 Context.getTargetInfo().getTriple().isOSDarwin() &&
6453 Linkage = llvm::GlobalValue::InternalLinkage;
6458 if (LangOpts.HLSL &&
6460 Linkage = llvm::GlobalValue::ExternalLinkage;
6463 if (D->
hasAttr<DLLImportAttr>())
6464 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
6465 else if (D->
hasAttr<DLLExportAttr>())
6466 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
6468 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6470 if (
Linkage == llvm::GlobalVariable::CommonLinkage) {
6472 GV->setConstant(
false);
6477 if (!GV->getInitializer()->isNullValue())
6478 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
6481 setNonAliasAttributes(D, GV);
6483 if (D->
getTLSKind() && !GV->isThreadLocal()) {
6485 CXXThreadLocals.push_back(D);
6492 if (NeedsGlobalCtor || NeedsGlobalDtor)
6493 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
6495 SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
6500 DI->EmitGlobalVariable(GV, D);
6508 if ((NoCommon || D->
hasAttr<NoCommonAttr>()) && !D->
hasAttr<CommonAttr>())
6519 if (D->
hasAttr<SectionAttr>())
6525 if (D->
hasAttr<PragmaClangBSSSectionAttr>() ||
6526 D->
hasAttr<PragmaClangDataSectionAttr>() ||
6527 D->
hasAttr<PragmaClangRelroSectionAttr>() ||
6528 D->
hasAttr<PragmaClangRodataSectionAttr>())
6536 if (D->
hasAttr<WeakImportAttr>())
6545 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6546 if (D->
hasAttr<AlignedAttr>())
6549 if (Context.isAlignmentRequired(VarType))
6553 for (
const FieldDecl *FD : RD->fields()) {
6554 if (FD->isBitField())
6556 if (FD->
hasAttr<AlignedAttr>())
6558 if (Context.isAlignmentRequired(FD->
getType()))
6570 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
6571 Context.getTypeAlignIfKnown(D->
getType()) >
6578llvm::GlobalValue::LinkageTypes
6582 return llvm::Function::InternalLinkage;
6585 return llvm::GlobalVariable::WeakAnyLinkage;
6589 return llvm::GlobalVariable::LinkOnceAnyLinkage;
6594 return llvm::GlobalValue::AvailableExternallyLinkage;
6608 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
6609 : llvm::Function::InternalLinkage;
6623 return llvm::Function::ExternalLinkage;
6626 return D->
hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
6627 : llvm::Function::InternalLinkage;
6628 return llvm::Function::WeakODRLinkage;
6635 CodeGenOpts.NoCommon))
6636 return llvm::GlobalVariable::CommonLinkage;
6642 if (D->
hasAttr<SelectAnyAttr>())
6643 return llvm::GlobalVariable::WeakODRLinkage;
6647 return llvm::GlobalVariable::ExternalLinkage;
6650llvm::GlobalValue::LinkageTypes
6659 llvm::Function *newFn) {
6661 if (old->use_empty())
6664 llvm::Type *newRetTy = newFn->getReturnType();
6669 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
6671 llvm::User *user = ui->getUser();
6675 if (
auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
6676 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
6682 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
6685 if (!callSite->isCallee(&*ui))
6690 if (callSite->getType() != newRetTy && !callSite->use_empty())
6695 llvm::AttributeList oldAttrs = callSite->getAttributes();
6698 unsigned newNumArgs = newFn->arg_size();
6699 if (callSite->arg_size() < newNumArgs)
6705 bool dontTransform =
false;
6706 for (llvm::Argument &A : newFn->args()) {
6707 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
6708 dontTransform =
true;
6713 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
6721 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
6725 callSite->getOperandBundlesAsDefs(newBundles);
6727 llvm::CallBase *newCall;
6729 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles,
"",
6730 callSite->getIterator());
6733 newCall = llvm::InvokeInst::Create(
6734 newFn, oldInvoke->getNormalDest(), oldInvoke->getUnwindDest(),
6735 newArgs, newBundles,
"", callSite->getIterator());
6739 if (!newCall->getType()->isVoidTy())
6740 newCall->takeName(callSite);
6741 newCall->setAttributes(
6742 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
6743 oldAttrs.getRetAttrs(), newArgAttrs));
6744 newCall->setCallingConv(callSite->getCallingConv());
6747 if (!callSite->use_empty())
6748 callSite->replaceAllUsesWith(newCall);
6751 if (callSite->getDebugLoc())
6752 newCall->setDebugLoc(callSite->getDebugLoc());
6754 callSitesToBeRemovedFromParent.push_back(callSite);
6757 for (
auto *callSite : callSitesToBeRemovedFromParent) {
6758 callSite->eraseFromParent();
6772 llvm::Function *NewFn) {
6782 (LangOpts.CUDA && !shouldEmitCUDAGlobalVar(VD)))
6794void CodeGenModule::EmitGlobalFunctionDefinition(
GlobalDecl GD,
6795 llvm::GlobalValue *GV) {
6803 if (!GV || (GV->getValueType() != Ty))
6809 if (!GV->isDeclaration())
6819 if (
getTriple().isOSAIX() && D->isTargetClonesMultiVersion())
6820 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
6831 setNonAliasAttributes(GD, Fn);
6833 bool ShouldAddOptNone = !CodeGenOpts.DisableO0ImplyOptNone &&
6834 (CodeGenOpts.OptimizationLevel == 0) &&
6837 if (DeviceKernelAttr::isOpenCLSpelling(D->
getAttr<DeviceKernelAttr>())) {
6839 !D->
hasAttr<NoInlineAttr>() &&
6840 !Fn->hasFnAttribute(llvm::Attribute::NoInline) &&
6841 !D->
hasAttr<OptimizeNoneAttr>() &&
6842 !Fn->hasFnAttribute(llvm::Attribute::OptimizeNone) &&
6843 !ShouldAddOptNone) {
6844 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
6850 auto GetPriority = [
this](
const auto *
Attr) ->
int {
6855 return Attr->DefaultPriority;
6858 if (
const ConstructorAttr *CA = D->
getAttr<ConstructorAttr>())
6860 if (
const DestructorAttr *DA = D->
getAttr<DestructorAttr>())
6866void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
6868 const AliasAttr *AA = D->
getAttr<AliasAttr>();
6869 assert(AA &&
"Not an alias?");
6873 if (AA->getAliasee() == MangledName) {
6874 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6881 if (Entry && !Entry->isDeclaration())
6884 Aliases.push_back(GD);
6890 llvm::Constant *Aliasee;
6891 llvm::GlobalValue::LinkageTypes
LT;
6893 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
6899 if (
const auto *VD = dyn_cast<VarDecl>(GD.
getDecl()))
6906 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
6908 llvm::GlobalAlias::create(DeclTy, AS, LT,
"", Aliasee, &
getModule());
6911 if (GA->getAliasee() == Entry) {
6912 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6916 assert(Entry->isDeclaration());
6925 GA->takeName(Entry);
6927 Entry->replaceAllUsesWith(GA);
6928 Entry->eraseFromParent();
6930 GA->setName(MangledName);
6938 GA->setLinkage(llvm::Function::WeakAnyLinkage);
6941 if (
const auto *VD = dyn_cast<VarDecl>(D))
6942 if (VD->getTLSKind())
6953void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
6955 const IFuncAttr *IFA = D->
getAttr<IFuncAttr>();
6956 assert(IFA &&
"Not an ifunc?");
6960 if (IFA->getResolver() == MangledName) {
6961 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6967 if (Entry && !Entry->isDeclaration()) {
6970 DiagnosedConflictingDefinitions.insert(GD).second) {
6971 Diags.Report(D->
getLocation(), diag::err_duplicate_mangled_name)
6974 diag::note_previous_definition);
6979 Aliases.push_back(GD);
6985 llvm::Constant *Resolver =
6986 GetOrCreateLLVMFunction(IFA->getResolver(),
VoidTy, {},
6990 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
6991 DeclTy, AS, llvm::Function::ExternalLinkage,
"", Resolver, &
getModule());
6993 if (GIF->getResolver() == Entry) {
6994 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6997 assert(Entry->isDeclaration());
7006 GIF->takeName(Entry);
7008 Entry->replaceAllUsesWith(GIF);
7009 Entry->eraseFromParent();
7011 GIF->setName(MangledName);
7017 return llvm::Intrinsic::getOrInsertDeclaration(&
getModule(),
7018 (llvm::Intrinsic::ID)IID, Tys);
7021static llvm::StringMapEntry<llvm::GlobalVariable *> &
7024 bool &IsUTF16,
unsigned &StringLength) {
7025 StringRef String = Literal->getString();
7026 unsigned NumBytes = String.size();
7029 if (!Literal->containsNonAsciiOrNull()) {
7030 StringLength = NumBytes;
7031 return *Map.insert(std::make_pair(String,
nullptr)).first;
7038 const llvm::UTF8 *FromPtr = (
const llvm::UTF8 *)String.data();
7039 llvm::UTF16 *ToPtr = &ToBuf[0];
7041 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
7042 ToPtr + NumBytes, llvm::strictConversion);
7045 StringLength = ToPtr - &ToBuf[0];
7049 return *Map.insert(std::make_pair(
7050 StringRef(
reinterpret_cast<const char *
>(ToBuf.data()),
7051 (StringLength + 1) * 2),
7057 unsigned StringLength = 0;
7058 bool isUTF16 =
false;
7059 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
7064 if (
auto *
C = Entry.second)
7069 const llvm::Triple &Triple =
getTriple();
7072 const bool IsSwiftABI =
7073 static_cast<unsigned>(CFRuntime) >=
7078 if (!CFConstantStringClassRef) {
7079 const char *CFConstantStringClassName =
"__CFConstantStringClassReference";
7081 Ty = llvm::ArrayType::get(Ty, 0);
7083 switch (CFRuntime) {
7087 CFConstantStringClassName =
7088 Triple.isOSDarwin() ?
"$s15SwiftFoundation19_NSCFConstantStringCN"
7089 :
"$s10Foundation19_NSCFConstantStringCN";
7093 CFConstantStringClassName =
7094 Triple.isOSDarwin() ?
"$S15SwiftFoundation19_NSCFConstantStringCN"
7095 :
"$S10Foundation19_NSCFConstantStringCN";
7099 CFConstantStringClassName =
7100 Triple.isOSDarwin() ?
"__T015SwiftFoundation19_NSCFConstantStringCN"
7101 :
"__T010Foundation19_NSCFConstantStringCN";
7108 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
7109 llvm::GlobalValue *GV =
nullptr;
7111 if ((GV = dyn_cast<llvm::GlobalValue>(
C))) {
7118 if ((VD = dyn_cast<VarDecl>(
Result)))
7121 if (Triple.isOSBinFormatELF()) {
7123 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
7125 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
7126 if (!VD || !VD->
hasAttr<DLLExportAttr>())
7127 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
7129 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
7137 CFConstantStringClassRef =
7138 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(
C, Ty) :
C;
7141 QualType CFTy = Context.getCFConstantStringType();
7146 auto Fields = Builder.beginStruct(STy);
7155 Fields.addInt(
IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
7156 Fields.addInt(
Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
7158 Fields.addInt(
IntTy, isUTF16 ? 0x07d0 : 0x07C8);
7162 llvm::Constant *
C =
nullptr;
7165 reinterpret_cast<uint16_t *
>(
const_cast<char *
>(Entry.first().data())),
7166 Entry.first().size() / 2);
7167 C = llvm::ConstantDataArray::get(VMContext, Arr);
7169 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
7175 new llvm::GlobalVariable(
getModule(),
C->getType(),
true,
7176 llvm::GlobalValue::PrivateLinkage,
C,
".str");
7177 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
7180 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
7181 : Context.getTypeAlignInChars(Context.CharTy);
7187 if (Triple.isOSBinFormatMachO())
7188 GV->setSection(isUTF16 ?
"__TEXT,__ustring"
7189 :
"__TEXT,__cstring,cstring_literals");
7192 else if (Triple.isOSBinFormatELF())
7193 GV->setSection(
".rodata");
7199 llvm::IntegerType *LengthTy =
7209 Fields.addInt(LengthTy, StringLength);
7217 GV = Fields.finishAndCreateGlobal(
"_unnamed_cfstring_", Alignment,
7219 llvm::GlobalVariable::PrivateLinkage);
7220 GV->addAttribute(
"objc_arc_inert");
7221 switch (Triple.getObjectFormat()) {
7222 case llvm::Triple::UnknownObjectFormat:
7223 llvm_unreachable(
"unknown file format");
7224 case llvm::Triple::DXContainer:
7225 case llvm::Triple::GOFF:
7226 case llvm::Triple::SPIRV:
7227 case llvm::Triple::XCOFF:
7228 llvm_unreachable(
"unimplemented");
7229 case llvm::Triple::COFF:
7230 case llvm::Triple::ELF:
7231 case llvm::Triple::Wasm:
7232 GV->setSection(
"cfstring");
7234 case llvm::Triple::MachO:
7235 GV->setSection(
"__DATA,__cfstring");
7244 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
7248 if (ObjCFastEnumerationStateType.isNull()) {
7249 RecordDecl *D = Context.buildImplicitRecord(
"__objcFastEnumerationState");
7253 Context.UnsignedLongTy, Context.getPointerType(Context.getObjCIdType()),
7254 Context.getPointerType(Context.UnsignedLongTy),
7255 Context.getConstantArrayType(Context.UnsignedLongTy, llvm::APInt(32, 5),
7258 for (
size_t i = 0; i < 4; ++i) {
7263 FieldTypes[i],
nullptr,
7272 ObjCFastEnumerationStateType = Context.getCanonicalTagType(D);
7275 return ObjCFastEnumerationStateType;
7289 assert(CAT &&
"String literal not of constant array type!");
7291 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
7295 llvm::Type *ElemTy = AType->getElementType();
7296 unsigned NumElements = AType->getNumElements();
7299 if (ElemTy->getPrimitiveSizeInBits() == 16) {
7301 Elements.reserve(NumElements);
7303 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
7305 Elements.resize(NumElements);
7306 return llvm::ConstantDataArray::get(VMContext, Elements);
7309 assert(ElemTy->getPrimitiveSizeInBits() == 32);
7311 Elements.reserve(NumElements);
7313 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
7315 Elements.resize(NumElements);
7316 return llvm::ConstantDataArray::get(VMContext, Elements);
7319static llvm::GlobalVariable *
7328 auto *GV =
new llvm::GlobalVariable(
7329 M,
C->getType(), !CGM.
getLangOpts().WritableStrings, LT,
C, GlobalName,
7330 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
7332 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
7333 if (GV->isWeakForLinker()) {
7334 assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
7335 GV->setComdat(M.getOrInsertComdat(GV->getName()));
7351 llvm::GlobalVariable **Entry =
nullptr;
7352 if (!LangOpts.WritableStrings) {
7353 Entry = &ConstantStringMap[
C];
7354 if (
auto GV = *Entry) {
7355 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
7358 GV->getValueType(), Alignment);
7363 StringRef GlobalVariableName;
7364 llvm::GlobalValue::LinkageTypes LT;
7369 if (
getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
7370 !LangOpts.WritableStrings) {
7371 llvm::raw_svector_ostream Out(MangledNameBuffer);
7373 LT = llvm::GlobalValue::LinkOnceODRLinkage;
7374 GlobalVariableName = MangledNameBuffer;
7376 LT = llvm::GlobalValue::PrivateLinkage;
7377 GlobalVariableName = Name;
7389 SanitizerMD->reportGlobal(GV, S->
getStrTokenLoc(0),
"<string literal>");
7392 GV->getValueType(), Alignment);
7409 StringRef GlobalName) {
7410 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
7415 llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
7418 llvm::GlobalVariable **Entry =
nullptr;
7419 if (!LangOpts.WritableStrings) {
7420 Entry = &ConstantStringMap[
C];
7421 if (
auto GV = *Entry) {
7422 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
7425 GV->getValueType(), Alignment);
7431 GlobalName, Alignment);
7436 GV->getValueType(), Alignment);
7454 MaterializedType = E->
getType();
7458 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E,
nullptr});
7459 if (!InsertResult.second) {
7462 if (!InsertResult.first->second) {
7467 InsertResult.first->second =
new llvm::GlobalVariable(
7468 getModule(),
Type,
false, llvm::GlobalVariable::InternalLinkage,
7472 llvm::cast<llvm::GlobalVariable>(
7473 InsertResult.first->second->stripPointerCasts())
7482 llvm::raw_svector_ostream Out(Name);
7504 std::optional<ConstantEmitter> emitter;
7505 llvm::Constant *InitialValue =
nullptr;
7510 emitter.emplace(*
this);
7511 InitialValue = emitter->emitForInitializer(*
Value, AddrSpace,
7516 Type = InitialValue->getType();
7525 if (
Linkage == llvm::GlobalVariable::ExternalLinkage) {
7527 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
7531 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
7535 Linkage = llvm::GlobalVariable::InternalLinkage;
7539 auto *GV =
new llvm::GlobalVariable(
7541 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
7542 if (emitter) emitter->finalize(GV);
7544 if (!llvm::GlobalValue::isLocalLinkage(
Linkage)) {
7546 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
7548 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
7552 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
7553 if (VD->getTLSKind())
7555 llvm::Constant *CV = GV;
7558 GV, llvm::PointerType::get(
7564 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
7566 Entry->replaceAllUsesWith(CV);
7567 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
7576void CodeGenModule::EmitObjCPropertyImplementations(
const
7589 if (!Getter || Getter->isSynthesizedAccessorStub())
7592 auto *Setter = PID->getSetterMethodDecl();
7593 if (!PD->
isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
7604 if (ivar->getType().isDestructedType())
7625void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
7638 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod,
false);
7653 getContext().getObjCIdType(),
nullptr, D,
true,
7659 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod,
true);
7664void CodeGenModule::EmitLinkageSpec(
const LinkageSpecDecl *LSD) {
7671 EmitDeclContext(LSD);
7674void CodeGenModule::EmitTopLevelStmt(
const TopLevelStmtDecl *D) {
7676 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7679 std::unique_ptr<CodeGenFunction> &CurCGF =
7680 GlobalTopLevelStmtBlockInFlight.first;
7684 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
7692 std::string Name =
"__stmts__" + llvm::utostr(CXXGlobalInits.size());
7693 FunctionArgList Args;
7695 const CGFunctionInfo &FnInfo =
7698 llvm::Function *
Fn = llvm::Function::Create(
7699 FnTy, llvm::GlobalValue::InternalLinkage, Name, &
getModule());
7701 CurCGF.reset(
new CodeGenFunction(*
this));
7702 GlobalTopLevelStmtBlockInFlight.second = D;
7703 CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
7705 CXXGlobalInits.push_back(Fn);
7708 CurCGF->EmitStmt(D->
getStmt());
7711void CodeGenModule::EmitDeclContext(
const DeclContext *DC) {
7712 for (
auto *I : DC->
decls()) {
7718 if (
auto *OID = dyn_cast<ObjCImplDecl>(I)) {
7719 for (
auto *M : OID->methods())
7738 case Decl::CXXConversion:
7739 case Decl::CXXMethod:
7740 case Decl::Function:
7747 case Decl::CXXDeductionGuide:
7752 case Decl::Decomposition:
7753 case Decl::VarTemplateSpecialization:
7755 if (
auto *DD = dyn_cast<DecompositionDecl>(D))
7756 for (
auto *B : DD->flat_bindings())
7757 if (
auto *HD = B->getHoldingVar())
7764 case Decl::IndirectField:
7768 case Decl::Namespace:
7771 case Decl::ClassTemplateSpecialization: {
7774 if (Spec->getSpecializationKind() ==
7776 Spec->hasDefinition())
7777 DI->completeTemplateDefinition(*Spec);
7779 case Decl::CXXRecord: {
7783 DI->EmitAndRetainType(
7787 DI->completeUnusedClass(*CRD);
7790 for (
auto *I : CRD->
decls())
7796 case Decl::UsingShadow:
7797 case Decl::ClassTemplate:
7798 case Decl::VarTemplate:
7800 case Decl::VarTemplatePartialSpecialization:
7801 case Decl::FunctionTemplate:
7802 case Decl::TypeAliasTemplate:
7811 case Decl::UsingEnum:
7815 case Decl::NamespaceAlias:
7819 case Decl::UsingDirective:
7823 case Decl::CXXConstructor:
7826 case Decl::CXXDestructor:
7830 case Decl::StaticAssert:
7831 case Decl::ExplicitInstantiation:
7838 case Decl::ObjCInterface:
7839 case Decl::ObjCCategory:
7842 case Decl::ObjCProtocol: {
7844 if (Proto->isThisDeclarationADefinition())
7845 ObjCRuntime->GenerateProtocol(Proto);
7849 case Decl::ObjCCategoryImpl:
7855 case Decl::ObjCImplementation: {
7857 EmitObjCPropertyImplementations(OMD);
7858 EmitObjCIvarInitializations(OMD);
7859 ObjCRuntime->GenerateClass(OMD);
7863 DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
7864 OMD->getClassInterface()), OMD->getLocation());
7867 case Decl::ObjCMethod: {
7874 case Decl::ObjCCompatibleAlias:
7878 case Decl::PragmaComment: {
7880 switch (PCD->getCommentKind()) {
7882 llvm_unreachable(
"unexpected pragma comment kind");
7897 case Decl::PragmaDetectMismatch: {
7903 case Decl::LinkageSpec:
7907 case Decl::FileScopeAsm: {
7909 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7912 if (LangOpts.OpenMPIsTargetDevice)
7915 if (LangOpts.SYCLIsDevice)
7918 getModule().appendModuleInlineAsm(AD->getAsmString());
7922 case Decl::TopLevelStmt:
7926 case Decl::Import: {
7930 if (!ImportedModules.insert(Import->getImportedModule()))
7934 if (!Import->getImportedOwningModule()) {
7936 DI->EmitImportDecl(*Import);
7942 if (CXX20ModuleInits && Import->getImportedModule() &&
7943 Import->getImportedModule()->isNamedModule())
7952 Visited.insert(Import->getImportedModule());
7953 Stack.push_back(Import->getImportedModule());
7955 while (!Stack.empty()) {
7957 if (!EmittedModuleInitializers.insert(Mod).second)
7960 for (
auto *D : Context.getModuleInitializers(Mod))
7967 if (Submodule->IsExplicit)
7970 if (Visited.insert(Submodule).second)
7971 Stack.push_back(Submodule);
7981 case Decl::OMPThreadPrivate:
7985 case Decl::OMPAllocate:
7989 case Decl::OMPDeclareReduction:
7993 case Decl::OMPDeclareMapper:
7997 case Decl::OMPRequires:
8002 case Decl::TypeAlias:
8004 DI->EmitAndRetainType(
getContext().getTypedefType(
8012 DI->EmitAndRetainType(
8019 DI->EmitAndRetainType(
8023 case Decl::HLSLRootSignature:
8026 case Decl::HLSLBuffer:
8030 case Decl::OpenACCDeclare:
8033 case Decl::OpenACCRoutine:
8048 if (!CodeGenOpts.CoverageMapping)
8051 case Decl::CXXConversion:
8052 case Decl::CXXMethod:
8053 case Decl::Function:
8054 case Decl::ObjCMethod:
8055 case Decl::CXXConstructor:
8056 case Decl::CXXDestructor: {
8065 DeferredEmptyCoverageMappingDecls.try_emplace(D,
true);
8075 if (!CodeGenOpts.CoverageMapping)
8077 if (
const auto *Fn = dyn_cast<FunctionDecl>(D)) {
8078 if (Fn->isTemplateInstantiation())
8081 DeferredEmptyCoverageMappingDecls.insert_or_assign(D,
false);
8089 for (
const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
8092 const Decl *D = Entry.first;
8094 case Decl::CXXConversion:
8095 case Decl::CXXMethod:
8096 case Decl::Function:
8097 case Decl::ObjCMethod: {
8104 case Decl::CXXConstructor: {
8111 case Decl::CXXDestructor: {
8128 if (llvm::Function *F =
getModule().getFunction(
"main")) {
8129 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
8130 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
8131 auto *GA = llvm::GlobalAlias::create(
"__main_void", F);
8132 GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
8141 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
8142 return llvm::ConstantInt::get(i64, PtrInt);
8146 llvm::NamedMDNode *&GlobalMetadata,
8148 llvm::GlobalValue *
Addr) {
8149 if (!GlobalMetadata)
8151 CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
8154 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(
Addr),
8157 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
8160bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
8161 llvm::GlobalValue *CppFunc) {
8163 llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
8166 llvm::SmallVector<llvm::ConstantExpr *> CEs;
8169 if (Elem == CppFunc)
8175 for (llvm::User *User : Elem->users()) {
8179 if (
auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
8180 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
8183 for (llvm::User *CEUser : ConstExpr->users()) {
8184 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
8185 IFuncs.push_back(IFunc);
8190 CEs.push_back(ConstExpr);
8191 }
else if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
8192 IFuncs.push_back(IFunc);
8204 for (llvm::GlobalIFunc *IFunc : IFuncs)
8205 IFunc->setResolver(
nullptr);
8206 for (llvm::ConstantExpr *ConstExpr : CEs)
8207 ConstExpr->destroyConstant();
8211 Elem->eraseFromParent();
8213 for (llvm::GlobalIFunc *IFunc : IFuncs) {
8218 llvm::FunctionType::get(IFunc->getType(),
false);
8219 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
8220 CppFunc->getName(), ResolverTy, {},
false);
8221 IFunc->setResolver(Resolver);
8231void CodeGenModule::EmitStaticExternCAliases() {
8234 for (
auto &I : StaticExternCValues) {
8235 const IdentifierInfo *Name = I.first;
8236 llvm::GlobalValue *Val = I.second;
8244 llvm::GlobalValue *ExistingElem =
8249 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
8256 auto Res = Manglings.find(MangledName);
8257 if (Res == Manglings.end())
8259 Result = Res->getValue();
8270void CodeGenModule::EmitDeclMetadata() {
8271 llvm::NamedMDNode *GlobalMetadata =
nullptr;
8273 for (
auto &I : MangledDeclNames) {
8274 llvm::GlobalValue *
Addr =
getModule().getNamedValue(I.second);
8284void CodeGenFunction::EmitDeclMetadata() {
8285 if (LocalDeclMap.empty())
return;
8290 unsigned DeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
8292 llvm::NamedMDNode *GlobalMetadata =
nullptr;
8294 for (
auto &I : LocalDeclMap) {
8295 const Decl *D = I.first;
8296 llvm::Value *
Addr = I.second.emitRawPointer(*
this);
8297 if (
auto *Alloca = dyn_cast<llvm::AllocaInst>(
Addr)) {
8299 Alloca->setMetadata(
8300 DeclPtrKind, llvm::MDNode::get(
8301 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
8302 }
else if (
auto *GV = dyn_cast<llvm::GlobalValue>(
Addr)) {
8309void CodeGenModule::EmitVersionIdentMetadata() {
8310 llvm::NamedMDNode *IdentMetadata =
8311 TheModule.getOrInsertNamedMetadata(
"llvm.ident");
8313 llvm::LLVMContext &Ctx = TheModule.getContext();
8315 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
8316 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
8319void CodeGenModule::EmitCommandLineMetadata() {
8320 llvm::NamedMDNode *CommandLineMetadata =
8321 TheModule.getOrInsertNamedMetadata(
"llvm.commandline");
8323 llvm::LLVMContext &Ctx = TheModule.getContext();
8325 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
8326 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
8329void CodeGenModule::EmitCoverageFile() {
8330 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu");
8334 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
8335 llvm::LLVMContext &Ctx = TheModule.getContext();
8336 auto *CoverageDataFile =
8338 auto *CoverageNotesFile =
8340 for (
int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
8341 llvm::MDNode *CU = CUNode->getOperand(i);
8342 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
8343 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
8356 LangOpts.ObjCRuntime.isGNUFamily())
8357 return ObjCRuntime->GetEHType(Ty);
8364 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
8366 for (
auto RefExpr : D->
varlist()) {
8369 VD->getAnyInitializer() &&
8370 !VD->getAnyInitializer()->isConstantInitializer(
getContext());
8376 VD,
Addr, RefExpr->getBeginLoc(), PerformInit))
8377 CXXGlobalInits.push_back(InitFunction);
8382CodeGenModule::CreateMetadataIdentifierImpl(
QualType T, MetadataTypeMap &Map,
8386 FnType->getReturnType(), FnType->getParamTypes(),
8387 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
8389 llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
8394 std::string OutName;
8395 llvm::raw_string_ostream Out(OutName);
8400 Out <<
".normalized";
8423 return CreateMetadataIdentifierImpl(T, MetadataIdMap,
"");
8428 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap,
".virtual");
8432 return CreateMetadataIdentifierImpl(T, GeneralizedMetadataIdMap,
8440 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
8441 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
8442 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
8443 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
8444 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
8445 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
8446 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
8447 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
8455 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8457 if (CodeGenOpts.SanitizeCfiCrossDso)
8459 VTable->addTypeMetadata(Offset.getQuantity(),
8460 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
8463 llvm::Metadata *MD = llvm::MDString::get(
getLLVMContext(),
"all-vtables");
8464 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8470 SanStats = std::make_unique<llvm::SanitizerStatReport>(&
getModule());
8480 auto *FTy = llvm::FunctionType::get(SamplerT, {
C->getType()},
false);
8495 bool forPointeeType) {
8506 if (
auto Align = TT->getDecl()->getMaxAlignment()) {
8513 bool AlignForArray = T->isArrayType();
8519 if (T->isIncompleteType()) {
8536 if (T.getQualifiers().hasUnaligned()) {
8538 }
else if (forPointeeType && !AlignForArray &&
8539 (RD = T->getAsCXXRecordDecl())) {
8550 if (
unsigned MaxAlign =
getLangOpts().MaxTypeAlign) {
8563 if (NumAutoVarInit >= StopAfter) {
8566 if (!NumAutoVarInit) {
8580 const Decl *D)
const {
8584 OS << (isa<VarDecl>(D) ?
".static." :
".intern.");
8586 OS << (isa<VarDecl>(D) ?
"__static__" :
"__intern__");
8592 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
8596 llvm::MD5::MD5Result
Result;
8597 for (
const auto &Arg : PreprocessorOpts.Macros)
8598 Hash.update(Arg.first);
8602 llvm::sys::fs::UniqueID ID;
8606 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
8610 SM.getDiagnostics().Report(diag::err_cannot_open_file)
8611 << PLoc.
getFilename() << Status.getError().message();
8613 ID = Status->getUniqueID();
8615 OS << llvm::format(
"%x", ID.getFile()) << llvm::format(
"%x", ID.getDevice())
8616 <<
"_" << llvm::utohexstr(
Result.low(),
true, 8);
8623 assert(DeferredDeclsToEmit.empty() &&
8624 "Should have emitted all decls deferred to emit.");
8625 assert(NewBuilder->DeferredDecls.empty() &&
8626 "Newly created module should not have deferred decls");
8627 NewBuilder->DeferredDecls = std::move(DeferredDecls);
8628 assert(EmittedDeferredDecls.empty() &&
8629 "Still have (unmerged) EmittedDeferredDecls deferred decls");
8631 assert(NewBuilder->DeferredVTables.empty() &&
8632 "Newly created module should not have deferred vtables");
8633 NewBuilder->DeferredVTables = std::move(DeferredVTables);
8635 assert(NewBuilder->MangledDeclNames.empty() &&
8636 "Newly created module should not have mangled decl names");
8637 assert(NewBuilder->Manglings.empty() &&
8638 "Newly created module should not have manglings");
8639 NewBuilder->Manglings = std::move(Manglings);
8641 NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
8643 NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
8647 std::string OutName;
8648 llvm::raw_string_ostream Out(OutName);
8656 if (!Context.getTargetInfo().emitVectorDeletingDtors(Context.getLangOpts()))
8665 return RequireVectorDeletingDtor.count(RD);
8669 if (!Context.getTargetInfo().emitVectorDeletingDtors(Context.getLangOpts()))
8671 RequireVectorDeletingDtor.insert(RD);
8685 if (Entry && !Entry->isDeclaration()) {
8690 auto *NewFn = llvm::Function::Create(
8692 llvm::Function::ExternalLinkage, VDName, &
getModule());
8693 SetFunctionAttributes(VectorDtorGD, NewFn,
false,
8695 NewFn->takeName(VDEntry);
8696 VDEntry->replaceAllUsesWith(NewFn);
8697 VDEntry->eraseFromParent();
8698 Entry->replaceAllUsesWith(NewFn);
8699 Entry->eraseFromParent();
8704 addDeferredDeclToEmit(VectorDtorGD);
Defines the clang::ASTContext interface.
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 bool shouldAssumeDSOLocal(const CIRGenModule &cgm, cir::CIRGlobalValueInterface gv)
static bool shouldBeInCOMDAT(CIRGenModule &cgm, const Decl &d)
static bool hasUnwindExceptions(const LangOptions &langOpts)
Determines whether the language options require us to model unwind exceptions.
static void setWindowsItaniumDLLImport(CIRGenModule &cgm, bool isLocal, cir::FuncOp funcOp, StringRef name)
static std::string getMangledNameImpl(CIRGenModule &cgm, GlobalDecl gd, const NamedDecl *nd)
static bool hasImplicitAttr(const ValueDecl *decl)
static std::vector< std::string > getFeatureDeltaFromDefault(const CIRGenModule &cgm, llvm::StringRef targetCPU, llvm::StringMap< bool > &featureMap)
Get the feature delta from the default feature map for the given target CPU.
static CIRGenCXXABI * createCXXABI(CIRGenModule &cgm)
static bool isVarDeclStrongDefinition(const ASTContext &astContext, CIRGenModule &cgm, const VarDecl *vd, bool noCommon)
static void setLinkageForGV(cir::GlobalOp &gv, const NamedDecl *nd)
static void emitUsed(CIRGenModule &cgm, StringRef name, std::vector< cir::CIRGlobalValueInterface > &list)
static bool hasExistingGeneralizedTypeMD(llvm::Function *F)
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 GlobalDecl getBaseVariantGlobalDecl(const NamedDecl *D)
static void checkAliasForTocData(llvm::GlobalVariable *GVar, const CodeGenOptions &CodeGenOpts, DiagnosticsEngine &Diags, SourceLocation Location)
static const char PFPDeactivationSymbolPrefix[]
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 QualType GeneralizeTransparentUnion(QualType Ty)
static std::string getCPUSpecificMangling(const CodeGenModule &CGM, StringRef Name)
static const char AnnotationSection[]
static bool isUniqueInternalLinkageDecl(GlobalDecl GD, CodeGenModule &CGM)
static bool allowKCFIIdentifier(StringRef Name)
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 void checkDataLayoutConsistency(const TargetInfo &Target, llvm::LLVMContext &Context, const LangOptions &Opts)
static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty, bool GeneralizePointers)
static bool needsDestructMethod(ObjCImplementationDecl *impl)
static bool isStackProtectorOn(const LangOptions &LangOpts, const llvm::Triple &Triple, clang::LangOptions::StackProtectorMode Mode)
static void removeImageAccessQualifier(std::string &TyName)
static llvm::StringMapEntry< llvm::GlobalVariable * > & GetConstantCFStringEntry(llvm::StringMap< llvm::GlobalVariable * > &Map, const StringLiteral *Literal, bool TargetIsLSB, bool &IsUTF16, unsigned &StringLength)
static void setLLVMVisibility(llvm::GlobalValue &GV, std::optional< llvm::GlobalValue::VisibilityTypes > V)
static llvm::GlobalVariable * GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, CodeGenModule &CGM, StringRef GlobalName, CharUnits Alignment)
static llvm::APInt getFMVPriority(const TargetInfo &TI, const CodeGenFunction::FMVResolverOption &RO)
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 QualType GeneralizeType(ASTContext &Ctx, QualType Ty, bool GeneralizePointers)
static bool shouldSkipAliasEmission(const CodeGenModule &CGM, const ValueDecl *Global)
static constexpr auto ErrnoTBAAMDName
static unsigned ArgInfoAddressSpace(LangAS AS)
static void replaceDeclarationWith(llvm::GlobalValue *Old, llvm::Constant *New)
static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, llvm::Function *NewFn)
ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we implement a function with...
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.
Result
Implement __builtin_bit_cast and related operations.
llvm::MachO::Target Target
llvm::MachO::Record Record
Defines the clang::Module class, which describes a module in the source code.
Maps Clang QualType instances to corresponding LLVM ABI type representations.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
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()
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
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()'.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
const XRayFunctionFilter & getXRayFilter() const
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
StringRef getCUIDHash() const
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.
const NoSanitizeList & getNoSanitizeList() const
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
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
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
DiagnosticsEngine & getDiagnostics() const
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.
CanQualType getCanonicalTagType(const TagDecl *TD) const
unsigned getTargetAddressSpace(LangAS AS) const
Module * getCurrentNamedModule() const
Get module under construction, nullptr if this is not a C++20 module.
Attr - This represents one attribute.
Represents a block literal declaration, which is like an unnamed FunctionDecl.
bool isLibFunction(unsigned ID) const
Return true if this is a builtin for a libc/libm function, with a "__builtin_" prefix (e....
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Represents a base class of a C++ class.
CXXTemporary * getTemporary()
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Represents a C++ base or member initializer.
Expr * getInit() const
Get the initializer.
FunctionDecl * getOperatorDelete() const
Represents a C++ destructor within a class.
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
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.
FunctionDecl * getOperatorNew() const
Represents a C++ struct/union/class.
unsigned getNumBases() const
Retrieves the number of base classes of this class.
bool hasDefinition() const
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
const CXXDestructorDecl * getDestructor() const
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
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 MSSecureHotPatchFunctionsFile
The name of a file that contains functions which will be compiled for hotpatching.
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::vector< std::string > TocDataVarsUserSpecified
List of global variables explicitly specified by the user as toc-data.
PointerAuthOptions PointerAuth
Configuration for pointer-signing.
std::vector< std::string > MSSecureHotPatchFunctionsList
A list of functions which will be compiled for hotpatching.
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 EmitGlobalAlias(const llvm::GlobalValue *GV, const GlobalDecl Decl)
Emit information about global variable alias.
void EmitExternalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl)
Emit information about an external variable.
void EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc, QualType FnType, llvm::Function *Fn=nullptr)
Emit debug info for a function declaration.
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 addRootSignature(const HLSLRootSignatureDecl *D)
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...
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
void EmitCfiCheckFail()
Emit a cross-DSO CFI failure handling function.
void GenerateObjCGetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCGetter - Synthesize an Objective-C property getter function.
void EmitCfiCheckStub()
Emit a stub for the cross-DSO CFI check function.
void GenerateObjCMethod(const ObjCMethodDecl *OMD)
Generate an Objective-C method.
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.
llvm::LLVMContext & getLLVMContext()
bool isTrivialInitializer(const Expr *Init)
Determine whether the given initializer is trivial in the sense that it requires no code to be genera...
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
std::optional< llvm::Attribute::AttrKind > StackProtectorAttribute(const Decl *D) const
llvm::GlobalValue * getPFPDeactivationSymbol(const FieldDecl *FD)
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.
llvm::ConstantInt * CreateKCFITypeId(QualType T, StringRef Salt)
Generate a KCFI type identifier for T.
CGDebugInfo * getModuleDebugInfo()
llvm::Constant * performAddrSpaceCast(llvm::Constant *Src, llvm::Type *DestTy)
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.
void createFunctionTypeMetadataForIcall(const FunctionDecl *FD, llvm::Function *F)
Create and attach type metadata to the given function.
bool getExpressionLocationsEnabled() const
Return true if we should emit location information for expressions.
void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C)
bool classNeedsVectorDestructor(const CXXRecordDecl *RD)
Check that class need vector deleting destructor body.
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 IntrusiveRefCntPtr< llvm::vfs::FileSystem > & getFileSystem() 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.
void EmitOpenACCDeclare(const OpenACCDeclareDecl *D, CodeGenFunction *CGF=nullptr)
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 createIndirectFunctionTypeMD(const FunctionDecl *FD, llvm::Function *F)
Create and attach type metadata if the function is a potential indirect call target to support call g...
void AppendLinkerOptions(StringRef Opts)
Appends Opts to the "llvm.linker.options" metadata value.
void createCalleeTypeMetadataForIcall(const QualType &QT, llvm::CallBase *CB)
Create and attach type metadata to the given call.
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.
void requireVectorDestructorDefinition(const CXXRecordDecl *RD)
Record that new[] was called for the class, transform vector deleting destructor definition in a form...
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.
std::string getPFPFieldName(const FieldDecl *FD)
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.
SanitizerMetadata * getSanitizerMetadata()
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...
const llvm::abi::TargetInfo & getLLVMABITargetInfo(llvm::abi::TypeBuilder &TB)
Lazily build and return the LLVMABI library's TargetInfo for the current target.
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)
AtomicOptions getAtomicOpts()
Get the current Atomic options.
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.
bool shouldUseLLVMABILowering() const
True when -fexperimental-abi-lowering is in effect AND the active target has an LLVMABI implementatio...
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 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 EmitOpenACCRoutine(const OpenACCRoutineDecl *D, CodeGenFunction *CGF=nullptr)
void addReplacement(StringRef Name, llvm::Constant *C)
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.
llvm::Metadata * CreateMetadataIdentifierForFnType(QualType T)
Create a metadata identifier for the given function type.
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, StringRef GlobalName=".str")
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 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.
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.
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.
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.
void addDecl(Decl *D)
Add the declaration D into this context.
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
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.
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
SourceLocation getLocation() const
SourceLocation getBeginLoc() const LLVM_READONLY
TranslationUnitDecl * getTranslationUnitDecl()
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
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.
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Represents a member of a struct/union/class.
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
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 isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
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 * 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.
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 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.
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
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.
@ FPE_Ignore
Assume that floating-point exceptions are masked.
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...
clang::ObjCRuntime ObjCRuntime
CoreFoundationABI CFRuntime
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
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.
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
unsigned getManglingNumber() const
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.
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.
llvm::SmallVector< ModuleRef, 2 > Imports
The set of modules imported by this module, and on which this module depends.
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.
bool isExternallyVisible() const
Represent a C++ namespace.
This represents 'pragma omp threadprivate ...' directive.
ObjCEncodeExpr, used for @encode in Objective-C.
QualType getEncodedType() const
propimpl_range property_impls() const
const ObjCInterfaceDecl * getClassInterface() const
void addInstanceMethod(ObjCMethodDecl *method)
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
init_iterator init_end()
init_end() - Retrieve an iterator past the last initializer.
CXXCtorInitializer ** init_iterator
init_iterator - Iterates through the ivar initializer list.
init_iterator init_begin()
init_begin() - Retrieve an iterator to the first initializer.
unsigned getNumIvarInitializers() const
getNumArgs - Number of ivars which must be initialized.
void setHasDestructors(bool val)
void setHasNonZeroConstructors(bool val)
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()
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?
@ 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.
bool isAddressDiscriminated() const
uint16_t getConstantDiscrimination() const
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
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.
ExclusionType getDefault(llvm::driver::ProfileInstrKind Kind) const
std::optional< ExclusionType > isFunctionExcluded(StringRef FunctionName, llvm::driver::ProfileInstrKind Kind) const
std::optional< ExclusionType > isFileExcluded(StringRef FileName, llvm::driver::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.
std::optional< ExclusionType > isLocationExcluded(SourceLocation Loc, llvm::driver::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.
bool isConstant(const ASTContext &Ctx) const
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
virtual void completeDefinition()
Note that the definition of this type is now complete.
Selector getSelector(unsigned NumArgs, const IdentifierInfo **IIV)
Can create any sort of selector.
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.
Stmt - This represents one statement.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
SourceLocation getBeginLoc() const LLVM_READONLY
StringLiteral - This represents a string literal expression, e.g.
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
unsigned getLength() const
uint32_t getCodeUnit(size_t i) const
StringRef getString() const
unsigned getCharByteWidth() const
Represents the declaration of a struct/union/class/enum.
void startDefinition()
Starts the definition of this tag declaration.
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.
virtual llvm::APInt getFMVPriority(ArrayRef< StringRef > Features) const
bool supportsIFunc() const
Identify whether this target supports IFuncs.
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
virtual bool initFeatureMap(llvm::StringMap< bool > &Features, DiagnosticsEngine &Diags, StringRef CPU, const std::vector< std::string > &FeatureVec) const
Initialize the map with the default set of target features for the CPU this should include all legal ...
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 RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
bool isPointerType() const
const T * castAs() const
Member-template castAs<specific type>.
bool isReferenceType() const
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.
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
bool isHLSLResourceRecord() const
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
bool isHLSLResourceRecordArray() 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.
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
TLSKind getTLSKind() const
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
bool hasFlexibleArrayInit(const ASTContext &Ctx) const
Whether this variable has a flexible array member initialized with one or more elements.
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
const Expr * getInit() const
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
@ TLS_Dynamic
TLS with a dynamic initializer.
@ DeclarationOnly
This declaration is only a declaration.
@ Definition
This declaration is definitely a definition.
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
StorageClass getStorageClass() const
Returns the storage class as written in the source.
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
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 > 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)
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
constexpr bool isInitializedByPipeline(LangAS AS)
bool LT(InterpState &S, CodePtr OpPC)
llvm::PointerUnion< const Decl *, const Expr * > DeclTy
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
CXXCtorType
C++ constructor types.
@ Ctor_Base
Base object ctor.
@ Ctor_Complete
Complete object ctor.
bool isa(CodeGen::Address addr)
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)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
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...
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
@ 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_VectorDeleting
Vector deleting dtor.
@ Dtor_Base
Base object dtor.
@ Dtor_Complete
Complete object dtor.
@ Dtor_Deleting
Deleting dtor.
LangAS
Defines the address space values used by the address space qualifier of QualType.
@ FirstTargetAddressSpace
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::vfs::FileSystem &VFS, DiagnosticsEngine &Diags)
static const char * getCFBranchLabelSchemeFlagVal(const CFBranchLabelSchemeKind Scheme)
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.
U cast(CodeGen::Address addr)
@ None
No keyword precedes the qualified type name.
@ 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
int const char * function
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
std::optional< StringRef > Architecture
llvm::SmallVector< StringRef, 8 > Features
llvm::CallingConv::ID RuntimeCC
llvm::PointerType * VoidPtrTy
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
llvm::PointerType * ProgramPtrTy
Pointer in program address space.
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
Return true if the evaluated expression has side effects.
Extra information about a function prototype.
static const LangStandard & getLangStandardForKind(Kind K)
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.
PointerAuthSchema InitFiniPointers
The ABI for function addresses in .init_array and .fini_array.
Describes how types, statements, expressions, and declarations should be printed.