54#include "llvm/ABI/IRTypeMapper.h"
55#include "llvm/ABI/TargetInfo.h"
56#include "llvm/ADT/APFloat.h"
57#include "llvm/ADT/ArrayRef.h"
58#include "llvm/ADT/STLExtras.h"
59#include "llvm/ADT/StringExtras.h"
60#include "llvm/ADT/StringSwitch.h"
61#include "llvm/Analysis/TargetLibraryInfo.h"
62#include "llvm/BinaryFormat/ELF.h"
63#include "llvm/IR/AttributeMask.h"
64#include "llvm/IR/CallingConv.h"
65#include "llvm/IR/DataLayout.h"
66#include "llvm/IR/Intrinsics.h"
67#include "llvm/IR/LLVMContext.h"
68#include "llvm/IR/Module.h"
69#include "llvm/IR/ProfileSummary.h"
70#include "llvm/ProfileData/InstrProfReader.h"
71#include "llvm/ProfileData/SampleProf.h"
72#include "llvm/Support/ARMBuildAttributes.h"
73#include "llvm/Support/CRC.h"
74#include "llvm/Support/CodeGen.h"
75#include "llvm/Support/CommandLine.h"
76#include "llvm/Support/ConvertUTF.h"
77#include "llvm/Support/ErrorHandling.h"
78#include "llvm/Support/TimeProfiler.h"
79#include "llvm/Support/VirtualFileSystem.h"
80#include "llvm/TargetParser/AArch64TargetParser.h"
81#include "llvm/TargetParser/RISCVISAInfo.h"
82#include "llvm/TargetParser/Triple.h"
83#include "llvm/TargetParser/X86TargetParser.h"
84#include "llvm/Transforms/Instrumentation/KCFI.h"
85#include "llvm/Transforms/Utils/BuildLibCalls.h"
86#include "llvm/Transforms/Utils/KCFIHash.h"
87#include "llvm/Transforms/Utils/ModuleUtils.h"
95 "limited-coverage-experimental", llvm::cl::Hidden,
96 llvm::cl::desc(
"Emit limited coverage mapping information (experimental)"));
103 case TargetCXXABI::AppleARM64:
104 case TargetCXXABI::Fuchsia:
105 case TargetCXXABI::GenericAArch64:
106 case TargetCXXABI::GenericARM:
107 case TargetCXXABI::iOS:
108 case TargetCXXABI::WatchOS:
109 case TargetCXXABI::GenericMIPS:
110 case TargetCXXABI::GenericItanium:
111 case TargetCXXABI::WebAssembly:
112 case TargetCXXABI::XL:
114 case TargetCXXABI::Microsoft:
118 llvm_unreachable(
"invalid C++ ABI kind");
121static std::unique_ptr<TargetCodeGenInfo>
124 const llvm::Triple &Triple =
Target.getTriple();
127 switch (Triple.getArch()) {
131 case llvm::Triple::m68k:
133 case llvm::Triple::mips:
134 case llvm::Triple::mipsel:
135 if (Triple.getOS() == llvm::Triple::Win32)
139 case llvm::Triple::mips64:
140 case llvm::Triple::mips64el:
143 case llvm::Triple::avr: {
147 unsigned NPR =
Target.getABI() ==
"avrtiny" ? 6 : 18;
148 unsigned NRR =
Target.getABI() ==
"avrtiny" ? 4 : 8;
152 case llvm::Triple::aarch64:
153 case llvm::Triple::aarch64_32:
154 case llvm::Triple::aarch64_be: {
156 if (
Target.getABI() ==
"darwinpcs")
157 Kind = AArch64ABIKind::DarwinPCS;
158 else if (Triple.isOSWindowsOrUEFI())
160 else if (
Target.getABI() ==
"aapcs-soft")
161 Kind = AArch64ABIKind::AAPCSSoft;
166 case llvm::Triple::wasm32:
167 case llvm::Triple::wasm64: {
169 if (
Target.getABI() ==
"experimental-mv")
170 Kind = WebAssemblyABIKind::ExperimentalMV;
174 case llvm::Triple::arm:
175 case llvm::Triple::armeb:
176 case llvm::Triple::thumb:
177 case llvm::Triple::thumbeb: {
178 if (Triple.getOS() == llvm::Triple::Win32)
182 StringRef ABIStr =
Target.getABI();
183 if (ABIStr ==
"apcs-gnu")
184 Kind = ARMABIKind::APCS;
185 else if (ABIStr ==
"aapcs16")
186 Kind = ARMABIKind::AAPCS16_VFP;
187 else if (CodeGenOpts.
FloatABI ==
"hard" ||
188 (CodeGenOpts.
FloatABI !=
"soft" && Triple.isHardFloatABI()))
189 Kind = ARMABIKind::AAPCS_VFP;
194 case llvm::Triple::ppc: {
195 if (Triple.isOSAIX())
202 case llvm::Triple::ppcle: {
207 case llvm::Triple::ppc64:
208 if (Triple.isOSAIX())
211 if (Triple.isOSBinFormatELF()) {
213 if (
Target.getABI() ==
"elfv2")
214 Kind = PPC64_SVR4_ABIKind::ELFv2;
215 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
220 case llvm::Triple::ppc64le: {
221 assert(Triple.isOSBinFormatELF() &&
"PPC64 LE non-ELF not supported!");
223 if (
Target.getABI() ==
"elfv1")
224 Kind = PPC64_SVR4_ABIKind::ELFv1;
225 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
230 case llvm::Triple::nvptx:
231 case llvm::Triple::nvptx64:
234 case llvm::Triple::msp430:
237 case llvm::Triple::riscv32:
238 case llvm::Triple::riscv64:
239 case llvm::Triple::riscv32be:
240 case llvm::Triple::riscv64be: {
241 StringRef ABIStr =
Target.getABI();
243 unsigned ABIFLen = 0;
244 if (ABIStr.ends_with(
"f"))
246 else if (ABIStr.ends_with(
"d"))
248 bool EABI = ABIStr.ends_with(
"e");
252 case llvm::Triple::systemz: {
253 bool SoftFloat = CodeGenOpts.
FloatABI ==
"soft";
254 bool HasVector = !SoftFloat &&
Target.getABI() ==
"vector";
255 if (Triple.getOS() == llvm::Triple::ZOS)
260 case llvm::Triple::tce:
261 case llvm::Triple::tcele:
262 case llvm::Triple::tcele64:
265 case llvm::Triple::x86: {
266 bool IsDarwinVectorABI = Triple.isOSDarwin();
267 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
269 if (Triple.getOS() == llvm::Triple::Win32) {
271 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
272 CodeGenOpts.NumRegisterParameters);
275 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
276 CodeGenOpts.NumRegisterParameters, CodeGenOpts.
FloatABI ==
"soft");
279 case llvm::Triple::x86_64: {
280 StringRef ABI =
Target.getABI();
281 X86AVXABILevel AVXLevel = (ABI ==
"avx512" ? X86AVXABILevel::AVX512
282 : ABI ==
"avx" ? X86AVXABILevel::AVX
283 : X86AVXABILevel::None);
285 switch (Triple.getOS()) {
286 case llvm::Triple::UEFI:
287 case llvm::Triple::Win32:
293 case llvm::Triple::hexagon:
295 case llvm::Triple::lanai:
297 case llvm::Triple::r600:
299 case llvm::Triple::amdgpu:
301 case llvm::Triple::sparc:
303 case llvm::Triple::sparcv9:
305 case llvm::Triple::xcore:
307 case llvm::Triple::arc:
309 case llvm::Triple::spir:
310 case llvm::Triple::spir64:
312 case llvm::Triple::spirv32:
313 case llvm::Triple::spirv64:
314 case llvm::Triple::spirv:
316 case llvm::Triple::dxil:
318 case llvm::Triple::ve:
320 case llvm::Triple::csky: {
321 bool IsSoftFloat = !
Target.hasFeature(
"hard-float-abi");
323 Target.hasFeature(
"fpuv2_df") ||
Target.hasFeature(
"fpuv3_df");
328 case llvm::Triple::bpfeb:
329 case llvm::Triple::bpfel:
331 case llvm::Triple::loongarch32:
332 case llvm::Triple::loongarch64: {
333 StringRef ABIStr =
Target.getABI();
334 unsigned ABIFRLen = 0;
335 if (ABIStr.ends_with(
"f"))
337 else if (ABIStr.ends_with(
"d"))
342 case llvm::Triple::xtensa:
348 if (!TheTargetCodeGenInfo)
350 return *TheTargetCodeGenInfo;
356 return T.isAMDGCN() || (
T.isSPIRV() &&
T.getVendor() == llvm::Triple::AMD);
360 if (!CodeGenOpts.ExperimentalABILowering)
374 if (
T.getArch() == llvm::Triple::aarch64 ||
375 T.getArch() == llvm::Triple::aarch64_32 ||
376 T.getArch() == llvm::Triple::aarch64_be)
379 if (
T.getArch() == llvm::Triple::x86_64 && !
T.isOSWindows() && !
T.isUEFI() &&
380 !
T.isOSDarwin() && !
T.isOSCygMing()) {
382 case llvm::CallingConv::Win64:
383 case llvm::CallingConv::X86_RegCall:
384 case llvm::CallingConv::X86_FastCall:
385 case llvm::CallingConv::X86_VectorCall:
386 case llvm::CallingConv::X86_StdCall:
387 case llvm::CallingConv::X86_ThisCall:
391 case llvm::CallingConv::Intel_OCL_BI:
392 case llvm::CallingConv::PreserveMost:
393 case llvm::CallingConv::PreserveAll:
394 case llvm::CallingConv::PreserveNone:
405 CompatInfo.IsMatrixHA = Compat > LangOptions::ClangABI::Ver23;
409 const llvm::Triple &
T,
413 CompatInfo.ClassifyIntegerMMXAsSSE = Compat > LangOptions::ClangABI::Ver3_8 &&
414 !
T.isOSDarwin() && !
T.isPS() &&
416 CompatInfo.HonorsRevision98 = !
T.isOSDarwin();
417 CompatInfo.PassInt128VectorsInMem =
418 Compat > LangOptions::ClangABI::Ver9 && (
T.isOSLinux() ||
T.isOSNetBSD());
420 CompatInfo.ReturnCXXRecordGreaterThan128InMem =
421 Compat > LangOptions::ClangABI::Ver20 && !
T.isPS();
422 CompatInfo.Clang11Compat = Compat <= LangOptions::ClangABI::Ver11 ||
T.isPS();
423 CompatInfo.ClassifyUnnamedBitFields =
424 Compat > LangOptions::ClangABI::Ver23 && !
T.isPS();
425 if (
T.isOSDarwin() ||
T.isPS()) {
426 CompatInfo.SmallIntABICompat = llvm::abi::SmallIntABICompatKind::Clang23;
428 switch (CGOpts.getSmallIntABICompat()) {
430 CompatInfo.SmallIntABICompat = llvm::abi::SmallIntABICompatKind::Platform;
433 CompatInfo.SmallIntABICompat = llvm::abi::SmallIntABICompatKind::Clang23;
436 CompatInfo.SmallIntABICompat = llvm::abi::SmallIntABICompatKind::Both;
442const llvm::abi::TargetInfo &
444 if (TheLLVMABITargetInfo)
445 return *TheLLVMABITargetInfo;
450 llvm::abi::AMDGPUABIOptions Opts;
451 Opts.PrivateAddrSpace =
453 Opts.ConstantAddrSpace =
456 Opts.CoerceGenericPtrArgToGlobal =
458 TheLLVMABITargetInfo = llvm::abi::createAMDGPUTargetInfo(TB, Opts);
459 return *TheLLVMABITargetInfo;
462 switch (
T.getArch()) {
464 llvm_unreachable(
"LLVMABI lowering requested for an unsupported target");
466 case llvm::Triple::aarch64:
467 case llvm::Triple::aarch64_32:
468 case llvm::Triple::aarch64_be: {
469 llvm::abi::AArch64ABIOptions Opts;
471 if (ABI ==
"darwinpcs")
472 Opts.Kind = llvm::abi::AArch64ABIKind::DarwinPCS;
473 else if (
T.isOSWindows())
474 Opts.Kind = llvm::abi::AArch64ABIKind::Win64;
475 else if (ABI ==
"aapcs-soft")
476 Opts.Kind = llvm::abi::AArch64ABIKind::AAPCSSoft;
478 Opts.Kind = llvm::abi::AArch64ABIKind::AAPCS;
480 Opts.IsILP32 =
T.getArch() == llvm::Triple::aarch64_32;
482 Opts.IsMachO =
T.isOSBinFormatMachO();
483 Opts.IsAndroidOrOHOS =
T.isAndroid() ||
T.isOHOSFamily();
484 Opts.IsWindowsArm64EC =
T.isWindowsArm64EC();
486 Opts.IsBigEndian = !
T.isLittleEndian();
491 TheLLVMABITargetInfo = llvm::abi::createAArch64TargetInfo(TB, Opts);
492 return *TheLLVMABITargetInfo;
495 case llvm::Triple::spirv:
496 case llvm::Triple::spirv32:
497 case llvm::Triple::spirv64:
498 TheLLVMABITargetInfo = llvm::abi::createSPIRVTargetInfo(
501 return *TheLLVMABITargetInfo;
503 case llvm::Triple::bpfeb:
504 case llvm::Triple::bpfel:
506 TheLLVMABITargetInfo = llvm::abi::createBPFTargetInfo(TB);
507 return *TheLLVMABITargetInfo;
509 case llvm::Triple::x86_64: {
511 llvm::abi::X86AVXABILevel AVXLevel =
512 ABI ==
"avx512" ? llvm::abi::X86AVXABILevel::AVX512
513 : ABI ==
"avx" ? llvm::abi::X86AVXABILevel::AVX
514 : llvm::abi::X86AVXABILevel::None;
516 llvm::abi::X86ABICompatInfo CompatInfo;
522 TheLLVMABITargetInfo = llvm::abi::createX86_64TargetInfo(
523 TB, AVXLevel, Has64BitPointers, CompatInfo);
524 return *TheLLVMABITargetInfo;
530 llvm::LLVMContext &Context,
534 if (Opts.AlignDouble || Opts.OpenCL)
537 llvm::Triple Triple =
Target.getTriple();
538 llvm::DataLayout DL(
Target.getDataLayoutString());
539 auto Check = [&](
const char *Name, llvm::Type *Ty,
unsigned Alignment) {
540 llvm::Align DLAlign = DL.getABITypeAlign(Ty);
541 llvm::Align ClangAlign(Alignment / 8);
542 if (DLAlign != ClangAlign) {
543 llvm::errs() <<
"For target " << Triple.str() <<
" type " << Name
544 <<
" mapping to " << *Ty <<
" has data layout alignment "
545 << DLAlign.value() <<
" while clang specifies "
546 << ClangAlign.value() <<
"\n";
551 Check(
"bool", llvm::Type::getIntNTy(Context,
Target.BoolWidth),
553 Check(
"short", llvm::Type::getIntNTy(Context,
Target.ShortWidth),
555 Check(
"int", llvm::Type::getIntNTy(Context,
Target.IntWidth),
557 Check(
"long", llvm::Type::getIntNTy(Context,
Target.LongWidth),
560 if (Triple.getArch() != llvm::Triple::m68k)
561 Check(
"long long", llvm::Type::getIntNTy(Context,
Target.LongLongWidth),
564 if (
Target.hasInt128Type() && !
Target.getTargetOpts().ForceEnableInt128 &&
565 !Triple.isAMDGPU() && !Triple.isSPIRV() &&
566 Triple.getArch() != llvm::Triple::ve)
567 Check(
"__int128", llvm::Type::getIntNTy(Context, 128),
Target.Int128Align);
569 if (
Target.hasFloat16Type())
570 Check(
"half", llvm::Type::getFloatingPointTy(Context, *
Target.HalfFormat),
572 if (
Target.hasBFloat16Type())
573 Check(
"bfloat", llvm::Type::getBFloatTy(Context),
Target.BFloat16Align);
574 Check(
"float", llvm::Type::getFloatingPointTy(Context, *
Target.FloatFormat),
576 Check(
"double", llvm::Type::getFloatingPointTy(Context, *
Target.DoubleFormat),
579 llvm::Type::getFloatingPointTy(Context, *
Target.LongDoubleFormat),
581 if (
Target.hasFloat128Type())
582 Check(
"__float128", llvm::Type::getFP128Ty(Context),
Target.Float128Align);
583 if (
Target.hasIbm128Type())
584 Check(
"__ibm128", llvm::Type::getPPC_FP128Ty(Context),
Target.Ibm128Align);
586 Check(
"void*", llvm::PointerType::getUnqual(Context),
Target.PointerAlign);
588 if (
Target.vectorsAreElementAligned() != DL.vectorsAreElementAligned()) {
589 llvm::errs() <<
"Datalayout for target " << Triple.str()
590 <<
" sets element-aligned vectors to '"
591 <<
Target.vectorsAreElementAligned()
592 <<
"' but clang specifies '" << DL.vectorsAreElementAligned()
606 : Context(
C), LangOpts(
C.
getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
607 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
609 VMContext(M.
getContext()), VTables(*this), StackHandler(diags),
613 AbiMapper = std::make_unique<QualTypeMapper>(
C, M.getDataLayout(), AbiAlloc);
614 AbiReverseMapper = std::make_unique<llvm::abi::IRTypeMapper>(
615 M.getContext(), M.getDataLayout());
619 llvm::LLVMContext &LLVMContext = M.getContext();
620 VoidTy = llvm::Type::getVoidTy(LLVMContext);
621 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
622 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
623 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
624 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
625 HalfTy = llvm::Type::getHalfTy(LLVMContext);
626 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
627 FloatTy = llvm::Type::getFloatTy(LLVMContext);
628 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
634 C.toCharUnitsFromBits(
C.getTargetInfo().getMaxPointerWidth()).getQuantity();
636 C.toCharUnitsFromBits(
C.getTargetInfo().getIntAlign()).getQuantity();
638 llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getCharWidth());
639 IntTy = llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getIntWidth());
640 IntPtrTy = llvm::IntegerType::get(LLVMContext,
641 C.getTargetInfo().getMaxPointerWidth());
642 Int8PtrTy = llvm::PointerType::get(LLVMContext,
644 const llvm::DataLayout &DL = M.getDataLayout();
646 llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
648 llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
650 llvm::PointerType::get(LLVMContext, DL.getProgramAddressSpace());
666 createOpenCLRuntime();
668 createOpenMPRuntime();
675 if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Thread | SanitizerKind::Type) ||
676 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
682 if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
683 CodeGenOpts.CoverageNotesFile.size() ||
684 CodeGenOpts.CoverageDataFile.size())
692 Block.GlobalUniqueCount = 0;
694 if (
C.getLangOpts().ObjC)
697 if (CodeGenOpts.hasProfileClangUse()) {
698 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
699 CodeGenOpts.ProfileInstrumentUsePath, *FS,
700 CodeGenOpts.ProfileRemappingFile);
701 if (
auto E = ReaderOrErr.takeError()) {
702 llvm::handleAllErrors(std::move(E), [&](
const llvm::ErrorInfoBase &EI) {
703 Diags.Report(diag::err_reading_profile)
704 << CodeGenOpts.ProfileInstrumentUsePath << EI.message();
708 PGOReader = std::move(ReaderOrErr.get());
713 if (CodeGenOpts.CoverageMapping)
717 if (CodeGenOpts.UniqueInternalLinkageNames &&
718 !
getModule().getSourceFileName().empty()) {
722 Context.getTargetInfo());
723 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path);
727 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
728 getModule().addModuleFlag(llvm::Module::Error,
"NumRegisterParameters",
729 CodeGenOpts.NumRegisterParameters);
738 const llvm::MemoryBuffer &FileBuffer = **BufOrErr;
739 for (llvm::line_iterator I(FileBuffer.getMemBufferRef(),
true), E;
741 this->MSHotPatchFunctions.push_back(std::string{*I});
743 auto &DE = Context.getDiagnostics();
744 DE.Report(diag::err_open_hotpatch_file_failed)
746 << BufOrErr.getError().message();
751 this->MSHotPatchFunctions.push_back(FuncName);
753 llvm::sort(this->MSHotPatchFunctions);
756 if (!Context.getAuxTargetInfo())
762void CodeGenModule::createObjCRuntime() {
779 llvm_unreachable(
"bad runtime kind");
782void CodeGenModule::createOpenCLRuntime() {
786void CodeGenModule::createOpenMPRuntime() {
787 if (!LangOpts.OMPHostIRFile.empty() && !FS->exists(LangOpts.OMPHostIRFile))
788 Diags.Report(diag::err_omp_host_ir_file_not_found)
789 << LangOpts.OMPHostIRFile;
794 case llvm::Triple::nvptx:
795 case llvm::Triple::nvptx64:
796 case llvm::Triple::amdgpu:
797 case llvm::Triple::spirv64:
800 "OpenMP AMDGPU/NVPTX/SPIRV is only prepared to deal with device code.");
801 OpenMPRuntime.reset(
new CGOpenMPRuntimeGPU(*
this));
804 if (LangOpts.OpenMPSimd)
805 OpenMPRuntime.reset(
new CGOpenMPSIMDRuntime(*
this));
807 OpenMPRuntime.reset(
new CGOpenMPRuntime(*
this));
812void CodeGenModule::createCUDARuntime() {
816void CodeGenModule::createHLSLRuntime() {
817 HLSLRuntime.reset(
new CGHLSLRuntime(*
this));
821 Replacements[Name] =
C;
824void CodeGenModule::applyReplacements() {
825 for (
auto &I : Replacements) {
826 StringRef MangledName = I.first;
827 llvm::Constant *Replacement = I.second;
832 auto *NewF = dyn_cast<llvm::Function>(Replacement);
834 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
835 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
838 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
839 CE->getOpcode() == llvm::Instruction::GetElementPtr);
840 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
845 OldF->replaceAllUsesWith(Replacement);
847 NewF->removeFromParent();
848 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
851 OldF->eraseFromParent();
856 GlobalValReplacements.push_back(std::make_pair(GV,
C));
859void CodeGenModule::applyGlobalValReplacements() {
860 for (
auto &I : GlobalValReplacements) {
861 llvm::GlobalValue *GV = I.first;
862 llvm::Constant *
C = I.second;
864 GV->replaceAllUsesWith(
C);
865 GV->eraseFromParent();
872 const llvm::Constant *
C;
873 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
874 C = GA->getAliasee();
875 else if (
auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
876 C = GI->getResolver();
880 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(
C->stripPointerCasts());
884 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
893 bool IsIFunc,
const llvm::GlobalValue *Alias,
const llvm::GlobalValue *&GV,
894 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
898 Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
902 if (GV->hasCommonLinkage()) {
903 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
904 if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
905 Diags.
Report(Location, diag::err_alias_to_common);
910 if (GV->isDeclaration()) {
911 Diags.
Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
912 Diags.
Report(Location, diag::note_alias_requires_mangled_name)
913 << IsIFunc << IsIFunc;
916 for (
const auto &[
Decl, Name] : MangledDeclNames) {
917 if (
const auto *ND = dyn_cast<NamedDecl>(
Decl.getDecl())) {
919 if (II && II->
getName() == GV->getName()) {
920 Diags.
Report(Location, diag::note_alias_mangled_name_alternative)
924 (Twine(IsIFunc ?
"ifunc" :
"alias") +
"(\"" + Name +
"\")")
934 const auto *F = dyn_cast<llvm::Function>(GV);
936 Diags.
Report(Location, diag::err_alias_to_undefined)
937 << IsIFunc << IsIFunc;
941 llvm::FunctionType *FTy = F->getFunctionType();
942 if (!FTy->getReturnType()->isPointerTy()) {
943 Diags.
Report(Location, diag::err_ifunc_resolver_return);
957 if (GVar->hasAttribute(
"toc-data")) {
958 auto GVId = GVar->getName();
961 Diags.
Report(Location, diag::warn_toc_unsupported_type)
962 << GVId <<
"the variable has an alias";
964 llvm::AttributeSet CurrAttributes = GVar->getAttributes();
965 llvm::AttributeSet NewAttributes =
966 CurrAttributes.removeAttribute(GVar->getContext(),
"toc-data");
967 GVar->setAttributes(NewAttributes);
971void CodeGenModule::checkAliases() {
976 DiagnosticsEngine &Diags =
getDiags();
977 for (
const GlobalDecl &GD : Aliases) {
979 SourceLocation Location;
981 bool IsIFunc = D->hasAttr<IFuncAttr>();
982 if (
const Attr *A = D->getDefiningAttr()) {
983 Location = A->getLocation();
984 Range = A->getRange();
986 llvm_unreachable(
"Not an alias or ifunc?");
990 const llvm::GlobalValue *GV =
nullptr;
992 MangledDeclNames, Range)) {
998 GlobalDecl AliaseeGD;
1001 Diags.Report(Location, diag::err_alias_to_undefined)
1002 << IsIFunc << IsIFunc;
1011 if (AliasIsFuncDecl != AliaseeIsFunc) {
1012 Diags.Report(Location, diag::err_alias_between_function_and_variable)
1015 diag::note_aliasee_declaration);
1022 if (AliasIsFuncDecl && AliaseeIsFunc) {
1023 QualType AliasTy = D->getType();
1025 auto shouldReportTypeMismatch = [&]() {
1026 const auto *AliasFTy =
1028 const auto *AliaseeFTy =
1030 assert(AliasFTy && AliaseeFTy);
1031 if (!Context.typesAreCompatible(AliasFTy->getReturnType(),
1034 const auto *AliasFPTy = dyn_cast<FunctionProtoType>(AliasFTy);
1035 const auto *AliaseeFPTy = dyn_cast<FunctionProtoType>(AliaseeFTy);
1037 if ((AliasFPTy && AliasFPTy->isVariadic() && !AliaseeFPTy) ||
1038 (AliaseeFPTy && AliaseeFPTy->isVariadic() && !AliasFPTy))
1041 if (!AliasFPTy || !AliaseeFPTy)
1045 if (AliasFPTy->getNumParams() != AliaseeFPTy->getNumParams() ||
1046 AliasFPTy->isVariadic() != AliaseeFPTy->isVariadic())
1048 for (
unsigned i = 0; i < AliasFPTy->getNumParams(); ++i)
1049 if (!Context.typesAreCompatible(AliasFPTy->getParamType(i),
1050 AliaseeFPTy->getParamType(i)))
1054 if (shouldReportTypeMismatch()) {
1055 Diags.Report(Location, diag::warn_alias_type_mismatch)
1056 << AliasTy << AliaseeTy;
1058 diag::note_aliasee_declaration);
1064 if (
const llvm::GlobalVariable *GVar =
1065 dyn_cast<const llvm::GlobalVariable>(GV))
1069 llvm::Constant *Aliasee =
1073 llvm::GlobalValue *AliaseeGV;
1074 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
1079 if (
const SectionAttr *SA = D->getAttr<SectionAttr>()) {
1080 StringRef AliasSection = SA->getName();
1081 if (AliasSection != AliaseeGV->getSection())
1082 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
1083 << AliasSection << IsIFunc << IsIFunc;
1091 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
1092 if (GA->isInterposable()) {
1093 Diags.Report(Location, diag::warn_alias_to_weak_alias)
1094 << GV->getName() << GA->getName() << IsIFunc;
1095 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1096 GA->getAliasee(), Alias->getType());
1108 llvm::Attribute::DisableSanitizerInstrumentation);
1113 for (
const GlobalDecl &GD : Aliases) {
1116 Alias->replaceAllUsesWith(llvm::PoisonValue::get(Alias->getType()));
1117 Alias->eraseFromParent();
1122 DeferredDeclsToEmit.clear();
1123 EmittedDeferredDecls.clear();
1124 DeferredAnnotations.clear();
1126 OpenMPRuntime->clear();
1130 StringRef MainFile) {
1133 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
1134 if (MainFile.empty())
1135 MainFile =
"<stdin>";
1136 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
1139 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
1142 Diags.
Report(diag::warn_profile_data_missing) << Visited << Missing;
1146static std::optional<llvm::GlobalValue::VisibilityTypes>
1151 return std::nullopt;
1153 return llvm::GlobalValue::DefaultVisibility;
1155 return llvm::GlobalValue::HiddenVisibility;
1157 return llvm::GlobalValue::ProtectedVisibility;
1159 llvm_unreachable(
"unknown option value!");
1164 std::optional<llvm::GlobalValue::VisibilityTypes>
V) {
1173 GV.setDSOLocal(
false);
1174 GV.setVisibility(*
V);
1179 if (!LO.VisibilityFromDLLStorageClass)
1182 std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
1185 std::optional<llvm::GlobalValue::VisibilityTypes>
1186 NoDLLStorageClassVisibility =
1189 std::optional<llvm::GlobalValue::VisibilityTypes>
1190 ExternDeclDLLImportVisibility =
1193 std::optional<llvm::GlobalValue::VisibilityTypes>
1194 ExternDeclNoDLLStorageClassVisibility =
1197 for (llvm::GlobalValue &GV : M.global_values()) {
1198 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
1201 if (GV.isDeclarationForLinker())
1203 llvm::GlobalValue::DLLImportStorageClass
1204 ? ExternDeclDLLImportVisibility
1205 : ExternDeclNoDLLStorageClassVisibility);
1208 llvm::GlobalValue::DLLExportStorageClass
1209 ? DLLExportVisibility
1210 : NoDLLStorageClassVisibility);
1212 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1217 const llvm::Triple &Triple,
1221 return LangOpts.getStackProtector() == Mode;
1224std::optional<llvm::Attribute::AttrKind>
1226 if (D && D->
hasAttr<NoStackProtectorAttr>())
1228 else if (D && D->
hasAttr<StrictGuardStackCheckAttr>() &&
1230 return llvm::Attribute::StackProtectStrong;
1232 return llvm::Attribute::StackProtect;
1234 return llvm::Attribute::StackProtectStrong;
1236 return llvm::Attribute::StackProtectReq;
1237 return std::nullopt;
1243 EmitModuleInitializers(Primary);
1245 DeferredDecls.insert_range(EmittedDeferredDecls);
1246 EmittedDeferredDecls.clear();
1247 EmitVTablesOpportunistically();
1248 applyGlobalValReplacements();
1249 applyReplacements();
1250 emitMultiVersionFunctions();
1251 emitPFPFieldsWithEvaluatedOffset();
1254 if (Context.getLangOpts().IncrementalExtensions &&
1255 GlobalTopLevelStmtBlockInFlight.first) {
1257 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->
getEndLoc());
1258 GlobalTopLevelStmtBlockInFlight = {
nullptr,
nullptr};
1264 EmitCXXModuleInitFunc(Primary);
1266 EmitCXXGlobalInitFunc();
1267 EmitCXXGlobalCleanUpFunc();
1268 registerGlobalDtorsWithAtExit();
1269 EmitCXXThreadLocalInitFunc();
1271 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
1273 if (Context.getLangOpts().CUDA && CUDARuntime) {
1274 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
1277 if (LangOpts.SYCLIsHost && !CodeGenOpts.OffloadBinaryToEmbedFile.empty()) {
1278 if (llvm::Function *SYCLCtorFunction = embedSYCLDeviceBinary())
1283 if (OpenMPRuntime) {
1284 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
1285 OpenMPRuntime->clear();
1289 PGOReader->getSummary(
false).getMD(VMContext),
1290 llvm::ProfileSummary::PSK_Instr);
1291 if (PGOStats.hasDiagnostics())
1297 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
1298 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
1300 EmitStaticExternCAliases();
1305 if (CoverageMapping)
1306 CoverageMapping->emit();
1307 if (CodeGenOpts.SanitizeCfiCrossDso) {
1311 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
1313 emitAtAvailableLinkGuard();
1314 if (Context.getTargetInfo().getTriple().isWasm())
1321 if (
getTarget().getTargetOpts().CodeObjectVersion !=
1322 llvm::CodeObjectVersionKind::COV_None) {
1323 getModule().addModuleFlag(llvm::Module::Error,
1324 "amdhsa_code_object_version",
1325 getTarget().getTargetOpts().CodeObjectVersion);
1330 auto *MDStr = llvm::MDString::get(
1335 getModule().addModuleFlag(llvm::Module::Error,
"amdgpu_printf_kind",
1345 llvm::Module::Error,
"amdgpu.xnack",
1346 llvm::ConstantInt::get(
1354 llvm::Module::Error,
"amdgpu.sramecc",
1355 llvm::ConstantInt::get(
1365 if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) {
1367 for (
auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) {
1369 if (
auto *FD = dyn_cast<FunctionDecl>(D))
1373 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1377 llvm::ArrayType *ATy = llvm::ArrayType::get(
Int8PtrTy, UsedArray.size());
1379 auto *GV =
new llvm::GlobalVariable(
1380 getModule(), ATy,
false, llvm::GlobalValue::InternalLinkage,
1381 llvm::ConstantArray::get(ATy, UsedArray),
"__clang_gpu_used_external");
1388 if (LangOpts.HIP && !LangOpts.IncrementalExtensions) {
1391 auto *GV =
new llvm::GlobalVariable(
1393 llvm::Constant::getNullValue(
Int8Ty),
1402 if (CodeGenOpts.Autolink &&
1403 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
1404 EmitModuleLinkOptions();
1419 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
1420 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.dependent-libraries");
1421 for (
auto *MD : ELFDependentLibraries)
1422 NMD->addOperand(MD);
1425 if (CodeGenOpts.DwarfVersion) {
1426 getModule().addModuleFlag(llvm::Module::Max,
"Dwarf Version",
1427 CodeGenOpts.DwarfVersion);
1430 if (CodeGenOpts.Dwarf64)
1431 getModule().addModuleFlag(llvm::Module::Max,
"DWARF64", 1);
1433 if (Context.getLangOpts().SemanticInterposition)
1435 getModule().setSemanticInterposition(
true);
1437 if (CodeGenOpts.EmitCodeView) {
1439 getModule().addModuleFlag(llvm::Module::Warning,
"CodeView", 1);
1441 if (CodeGenOpts.CodeViewGHash) {
1442 getModule().addModuleFlag(llvm::Module::Warning,
"CodeViewGHash", 1);
1444 if (CodeGenOpts.ControlFlowGuard) {
1447 llvm::Module::Warning,
"cfguard",
1448 static_cast<unsigned>(llvm::ControlFlowGuardMode::Enabled));
1449 }
else if (CodeGenOpts.ControlFlowGuardNoChecks) {
1452 llvm::Module::Warning,
"cfguard",
1453 static_cast<unsigned>(llvm::ControlFlowGuardMode::TableOnly));
1455 if (CodeGenOpts.getWinControlFlowGuardMechanism() !=
1456 llvm::ControlFlowGuardMechanism::Automatic) {
1459 llvm::Module::Warning,
"cfguard-mechanism",
1460 static_cast<unsigned>(CodeGenOpts.getWinControlFlowGuardMechanism()));
1462 if (CodeGenOpts.EHContGuard) {
1464 getModule().addModuleFlag(llvm::Module::Warning,
"ehcontguard", 1);
1466 if (Context.getLangOpts().Kernel) {
1468 getModule().addModuleFlag(llvm::Module::Warning,
"ms-kernel", 1);
1470 if (CodeGenOpts.HotPatch) {
1473 getModule().addModuleFlag(llvm::Module::Min,
"ms-hotpatch", 1);
1475 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
1480 getModule().addModuleFlag(llvm::Module::Error,
"StrictVTablePointers",1);
1482 llvm::Metadata *Ops[2] = {
1483 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
1484 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1485 llvm::Type::getInt32Ty(VMContext), 1))};
1487 getModule().addModuleFlag(llvm::Module::Require,
1488 "StrictVTablePointersRequirement",
1489 llvm::MDNode::get(VMContext, Ops));
1495 getModule().addModuleFlag(llvm::Module::Warning,
"Debug Info Version",
1496 llvm::DEBUG_METADATA_VERSION);
1501 uint64_t WCharWidth =
1502 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
1503 if (WCharWidth !=
getTriple().getDefaultWCharSize())
1504 getModule().addModuleFlag(llvm::Module::Error,
"wchar_size",
1505 static_cast<uint32_t
>(WCharWidth));
1509 llvm::FloatABI::ABIType FloatABI =
1510 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
1511 .Cases({
"soft",
"softfp"}, llvm::FloatABI::Soft)
1512 .Case(
"hard", llvm::FloatABI::Hard)
1513 .Default(llvm::FloatABI::Default);
1514 if (FloatABI != llvm::FloatABI::Default &&
1515 FloatABI !=
getTriple().getDefaultFloatABI()) {
1517 llvm::Module::Error,
"float-abi",
1519 llvm::FloatABI::getABITypeName(FloatABI)));
1524 llvm::ThreadModel ThreadModel =
1526 ? llvm::ThreadModel::Single
1527 : llvm::ThreadModel::POSIX;
1528 if (ThreadModel !=
getTriple().getDefaultThreadModel())
1529 getModule().setThreadModel(ThreadModel);
1531 if (
getTypes().isLongDoubleReferenced()) {
1534 std::optional<llvm::LongDoubleFormat> Format;
1535 if (flt == &llvm::APFloat::IEEEquad())
1536 Format = llvm::LongDoubleFormat::IEEEquad;
1537 else if (flt == &llvm::APFloat::IEEEdouble())
1538 Format = llvm::LongDoubleFormat::IEEEdouble;
1539 else if (flt == &llvm::APFloat::PPCDoubleDouble())
1540 Format = llvm::LongDoubleFormat::PPCDoubleDouble;
1541 else if (flt == &llvm::APFloat::x87DoubleExtended())
1542 Format = llvm::LongDoubleFormat::X87DoubleExtended;
1543 else if (flt == &llvm::APFloat::IEEEsingle())
1544 Format = llvm::LongDoubleFormat::IEEEsingle;
1547 getModule().setLongDoubleFormat(*Format);
1554 llvm::ExceptionHandling ExceptionModel =
1556 if (ExceptionModel != llvm::ExceptionHandling::Default) {
1558 llvm::Module::Error,
"exception-model",
1560 llvm::getExceptionModelName(ExceptionModel)));
1563 if (CodeGenOpts.getDebuggerTuning() != llvm::DebuggerKind::Default)
1564 getModule().setDebuggerTuning(CodeGenOpts.getDebuggerTuning());
1567 getModule().addModuleFlag(llvm::Module::Warning,
1568 "zos_product_major_version",
1570 getModule().addModuleFlag(llvm::Module::Warning,
1571 "zos_product_minor_version",
1573 getModule().addModuleFlag(llvm::Module::Warning,
"zos_product_patchlevel",
1574 uint32_t(CLANG_VERSION_PATCHLEVEL));
1576 getModule().addModuleFlag(llvm::Module::Error,
"zos_product_id",
1577 llvm::MDString::get(VMContext, ProductId));
1582 getModule().addModuleFlag(llvm::Module::Error,
"zos_cu_language",
1583 llvm::MDString::get(VMContext, lang_str));
1585 time_t TT = PreprocessorOpts.SourceDateEpoch
1586 ? *PreprocessorOpts.SourceDateEpoch
1587 : std::time(
nullptr);
1588 getModule().addModuleFlag(llvm::Module::Max,
"zos_translation_time",
1589 static_cast<uint64_t
>(TT));
1592 getModule().addModuleFlag(llvm::Module::Error,
"zos_le_char_mode",
1593 llvm::MDString::get(VMContext,
"ascii"));
1596 llvm::Triple
T = Context.getTargetInfo().getTriple();
1601 if (StringRef ABIStr = Target.getABI();
1602 !ABIStr.empty() && (
T.isARM() ||
T.isThumb() ||
T.isRISCV() ||
1603 T.isPPC() ||
T.isLoongArch() ||
T.isWasm())) {
1604 getModule().addModuleFlag(llvm::Module::Error,
"target-abi",
1605 llvm::MDString::get(VMContext, ABIStr));
1608 if (
T.isARM() ||
T.isThumb()) {
1610 uint32_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
1611 getModule().addModuleFlag(llvm::Module::Error,
"min_enum_size", EnumWidth);
1615 llvm::LLVMContext &Ctx = TheModule.getContext();
1620 const std::vector<std::string> &Features =
1623 llvm::RISCVISAInfo::parseFeatures(
T.isRISCV64() ? 64 : 32, Features);
1624 if (!errorToBool(ParseResult.takeError()))
1626 llvm::Module::AppendUnique,
"riscv-isa",
1628 Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString())));
1631 if (CodeGenOpts.SanitizeCfiCrossDso) {
1633 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
1636 if (CodeGenOpts.WholeProgramVTables) {
1640 getModule().addModuleFlag(llvm::Module::Error,
"Virtual Function Elim",
1641 CodeGenOpts.VirtualFunctionElimination);
1644 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
1645 getModule().addModuleFlag(llvm::Module::Override,
1646 "CFI Canonical Jump Tables",
1647 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1650 if (CodeGenOpts.SanitizeCfiICallNormalizeIntegers) {
1651 getModule().addModuleFlag(llvm::Module::Override,
"cfi-normalize-integers",
1655 if (!CodeGenOpts.UniqueSourceFileIdentifier.empty()) {
1657 llvm::Module::Append,
"Unique Source File Identifier",
1659 TheModule.getContext(),
1660 llvm::MDString::get(TheModule.getContext(),
1661 CodeGenOpts.UniqueSourceFileIdentifier)));
1664 if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) {
1665 getModule().addModuleFlag(llvm::Module::Override,
"kcfi", 1);
1668 if (CodeGenOpts.PatchableFunctionEntryOffset)
1669 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-offset",
1670 CodeGenOpts.PatchableFunctionEntryOffset);
1671 if (CodeGenOpts.SanitizeKcfiArity)
1672 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-arity", 1);
1675 llvm::Module::Override,
"kcfi-hash",
1676 llvm::MDString::get(
1678 llvm::stringifyKCFIHashAlgorithm(CodeGenOpts.SanitizeKcfiHash)));
1681 if (CodeGenOpts.CFProtectionReturn &&
1682 Target.checkCFProtectionReturnSupported(
getDiags())) {
1684 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-return",
1688 if (CodeGenOpts.CFProtectionBranch &&
1689 Target.checkCFProtectionBranchSupported(
getDiags())) {
1691 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-branch",
1694 auto Scheme = CodeGenOpts.getCFBranchLabelScheme();
1695 if (Target.checkCFBranchLabelSchemeSupported(Scheme,
getDiags())) {
1697 Scheme = Target.getDefaultCFBranchLabelScheme();
1699 llvm::Module::Error,
"cf-branch-label-scheme",
1705 if (CodeGenOpts.FunctionReturnThunks)
1706 getModule().addModuleFlag(llvm::Module::Override,
"function_return_thunk_extern", 1);
1708 if (CodeGenOpts.IndirectBranchCSPrefix)
1709 getModule().addModuleFlag(llvm::Module::Override,
"indirect_branch_cs_prefix", 1);
1711 if (
T.isARM() ||
T.isThumb() ||
T.isAArch64()) {
1719 if (LangOpts.BranchTargetEnforcement)
1720 getModule().addModuleFlag(llvm::Module::Min,
"branch-target-enforcement",
1722 if (LangOpts.BranchProtectionPAuthLR)
1723 getModule().addModuleFlag(llvm::Module::Min,
"branch-protection-pauth-lr",
1725 if (LangOpts.GuardedControlStack)
1726 getModule().addModuleFlag(llvm::Module::Min,
"guarded-control-stack", 2);
1727 if (LangOpts.hasSignReturnAddress())
1728 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address", 2);
1729 if (LangOpts.isSignReturnAddressScopeAll())
1730 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address-all",
1732 if (!LangOpts.isSignReturnAddressWithAKey())
1733 getModule().addModuleFlag(llvm::Module::Min,
1734 "sign-return-address-with-bkey", 2);
1736 if (
T.isAArch64()) {
1748 if (LangOpts.PointerAuthReturns)
1749 getModule().addModuleFlag(llvm::Module::Max,
"ptrauth-returns", 1);
1750 if (LangOpts.PointerAuthAuthTraps)
1751 getModule().addModuleFlag(llvm::Module::Max,
"ptrauth-auth-traps", 1);
1752 if (LangOpts.PointerAuthIndirectGotos)
1753 getModule().addModuleFlag(llvm::Module::Max,
"ptrauth-indirect-gotos", 1);
1754 if (LangOpts.AArch64JumpTableHardening)
1755 getModule().addModuleFlag(llvm::Module::Max,
1756 "aarch64-jump-table-hardening", 1);
1764 getModule().addModuleFlag(llvm::Module::Error,
"ptrauth-elf-got",
1765 LangOpts.PointerAuthELFGOT);
1767 getModule().addModuleFlag(llvm::Module::Error,
"ptrauth-init-fini",
1768 LangOpts.PointerAuthCalls &&
1769 LangOpts.PointerAuthInitFini);
1771 llvm::Module::Error,
"ptrauth-init-fini-address-discrimination",
1772 LangOpts.PointerAuthCalls && LangOpts.PointerAuthInitFini &&
1773 LangOpts.PointerAuthInitFiniAddressDiscrimination);
1776 if (LangOpts.hasSignReturnAddressHardening()) {
1779 llvm::Module::Error,
"sign-return-address-harden",
1785 getModule().addModuleFlag(llvm::Module::Error,
"ptrauth-sign-personality",
1786 LangOpts.PointerAuthCalls);
1789 using namespace llvm::ELF;
1790 assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST < 32);
1791 uint32_t PAuthABIVersion =
1792 (LangOpts.PointerAuthIntrinsics
1793 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS) |
1794 (LangOpts.PointerAuthCalls
1795 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS) |
1796 (LangOpts.PointerAuthReturns
1797 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS) |
1798 (LangOpts.PointerAuthAuthTraps
1799 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS) |
1800 (LangOpts.PointerAuthVTPtrAddressDiscrimination
1801 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR) |
1802 (LangOpts.PointerAuthVTPtrTypeDiscrimination
1803 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR) |
1804 (LangOpts.PointerAuthInitFini
1805 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI) |
1806 (LangOpts.PointerAuthInitFiniAddressDiscrimination
1807 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC) |
1808 (LangOpts.PointerAuthELFGOT
1809 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT) |
1810 (LangOpts.PointerAuthIndirectGotos
1811 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS) |
1812 (LangOpts.PointerAuthTypeInfoVTPtrDiscrimination
1813 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR) |
1814 (LangOpts.PointerAuthFunctionTypeDiscrimination
1815 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR);
1816 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR ==
1817 AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
1818 "Update when new enum items are defined");
1823 getModule().addModuleFlag(llvm::Module::Error,
1824 "aarch64-elf-pauthabi-platform",
1825 AARCH64_PAUTH_PLATFORM_LLVM_LINUX);
1827 llvm::Module::Error,
"aarch64-elf-pauthabi-version", PAuthABIVersion);
1830 if ((
T.isARM() ||
T.isThumb()) &&
getTriple().isTargetAEABI() &&
1832 uint32_t TagVal = 0;
1833 llvm::Module::ModFlagBehavior DenormalTagBehavior = llvm::Module::Max;
1835 llvm::DenormalMode::getPositiveZero()) {
1836 TagVal = llvm::ARMBuildAttrs::PositiveZero;
1838 llvm::DenormalMode::getIEEE()) {
1839 TagVal = llvm::ARMBuildAttrs::IEEEDenormals;
1840 DenormalTagBehavior = llvm::Module::Override;
1842 llvm::DenormalMode::getPreserveSign()) {
1843 TagVal = llvm::ARMBuildAttrs::PreserveFPSign;
1845 getModule().addModuleFlag(DenormalTagBehavior,
"arm-eabi-fp-denormal",
1850 getModule().addModuleFlag(llvm::Module::Min,
"arm-eabi-fp-exceptions",
1851 llvm::ARMBuildAttrs::Allowed);
1854 TagVal = llvm::ARMBuildAttrs::AllowIEEENormal;
1856 TagVal = llvm::ARMBuildAttrs::AllowIEEE754;
1857 getModule().addModuleFlag(llvm::Module::Min,
"arm-eabi-fp-number-model",
1861 if (CodeGenOpts.StackClashProtector)
1863 llvm::Module::Override,
"probe-stack",
1864 llvm::MDString::get(TheModule.getContext(),
"inline-asm"));
1866 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
1867 getModule().addModuleFlag(llvm::Module::Min,
"stack-probe-size",
1868 CodeGenOpts.StackProbeSize);
1870 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1871 llvm::LLVMContext &Ctx = TheModule.getContext();
1873 llvm::Module::Error,
"MemProfProfileFilename",
1874 llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
1877 if (LangOpts.CUDAIsDevice &&
getTriple().isNVPTX()) {
1881 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
1882 CodeGenOpts.FP32DenormalMode.Output !=
1883 llvm::DenormalMode::IEEE);
1886 if (LangOpts.EHAsynch)
1887 getModule().addModuleFlag(llvm::Module::Warning,
"eh-asynch", 1);
1890 if (CodeGenOpts.ImportCallOptimization)
1891 getModule().addModuleFlag(llvm::Module::Warning,
"import-call-optimization",
1901 auto UnwindMode = CodeGenOpts.getWinX64EHUnwind();
1902 if (UnwindMode == llvm::WinX64EHUnwindMode::Default) {
1903 if (
T.isOSWindows() &&
T.isX86_64() &&
1904 Context.getTargetInfo().hasFeature(
"egpr"))
1905 UnwindMode = llvm::WinX64EHUnwindMode::V3;
1907 UnwindMode = llvm::WinX64EHUnwindMode::V1;
1909 if (UnwindMode != llvm::WinX64EHUnwindMode::V1)
1910 getModule().addModuleFlag(llvm::Module::Warning,
"winx64-eh-unwind",
1911 static_cast<unsigned>(UnwindMode));
1915 getModule().addModuleFlag(llvm::Module::Max,
"openmp", LangOpts.OpenMP);
1917 getModule().addModuleFlag(llvm::Module::Max,
"openmp-device",
1922 (LangOpts.SYCLIsDevice || LangOpts.OpenMPIsTargetDevice))
1923 getModule().addModuleFlag(llvm::Module::Max,
"spirv-dynamic-local-memory",
1927 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())) {
1928 EmitOpenCLMetadata();
1935 auto Version = LangOpts.getOpenCLCompatibleVersion();
1936 llvm::Metadata *SPIRVerElts[] = {
1937 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1939 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1940 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
1941 llvm::NamedMDNode *SPIRVerMD =
1942 TheModule.getOrInsertNamedMetadata(
"opencl.spir.version");
1943 llvm::LLVMContext &Ctx = TheModule.getContext();
1944 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
1952 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
1953 assert(PLevel < 3 &&
"Invalid PIC Level");
1954 getModule().setPICLevel(
static_cast<llvm::PICLevel::Level
>(PLevel));
1955 if (Context.getLangOpts().PIE)
1956 getModule().setPIELevel(
static_cast<llvm::PIELevel::Level
>(PLevel));
1960 unsigned CM = llvm::StringSwitch<unsigned>(
getCodeGenOpts().CodeModel)
1961 .Case(
"tiny", llvm::CodeModel::Tiny)
1962 .Case(
"small", llvm::CodeModel::Small)
1963 .Case(
"kernel", llvm::CodeModel::Kernel)
1964 .Case(
"medium", llvm::CodeModel::Medium)
1965 .Case(
"large", llvm::CodeModel::Large)
1968 llvm::CodeModel::Model codeModel =
static_cast<llvm::CodeModel::Model
>(CM);
1971 if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
1972 Context.getTargetInfo().getTriple().getArch() ==
1973 llvm::Triple::x86_64) {
1979 if (CodeGenOpts.NoPLT)
1982 CodeGenOpts.DirectAccessExternalData !=
1983 getModule().getDirectAccessExternalData()) {
1984 getModule().setDirectAccessExternalData(
1985 CodeGenOpts.DirectAccessExternalData);
1987 if (CodeGenOpts.UnwindTables)
1988 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1990 switch (CodeGenOpts.getFramePointer()) {
1995 getModule().setFramePointer(llvm::FramePointerKind::Reserved);
1998 getModule().setFramePointer(llvm::FramePointerKind::NonLeafNoReserve);
2001 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
2004 getModule().setFramePointer(llvm::FramePointerKind::All);
2008 SimplifyPersonality();
2021 EmitVersionIdentMetadata();
2024 EmitCommandLineMetadata();
2032 getModule().setStackProtectorGuardSymbol(
2035 getModule().setStackProtectorGuardOffset(
2038 getModule().setStackProtectorGuardValueWidth(
2041 if (
getModule().getStackProtectorGuard() !=
"global") {
2042 Diags.Report(diag::err_opt_not_valid_without_opt)
2043 <<
"-mstack-protector-guard-record"
2044 <<
"-mstack-protector-guard=global";
2046 getModule().setStackProtectorGuardRecord(
true);
2051 getModule().addModuleFlag(llvm::Module::Override,
"SkipRaxSetup", 1);
2053 getModule().addModuleFlag(llvm::Module::Override,
"RegCallv4", 1);
2055 if (
getContext().getTargetInfo().getMaxTLSAlign())
2056 getModule().addModuleFlag(llvm::Module::Error,
"MaxTLSAlign",
2057 getContext().getTargetInfo().getMaxTLSAlign());
2075 if (!MustTailCallUndefinedGlobals.empty()) {
2077 for (
auto &I : MustTailCallUndefinedGlobals) {
2078 if (!I.first->isDefined())
2079 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
2083 if (!Entry || Entry->isWeakForLinker() ||
2084 Entry->isDeclarationForLinker())
2085 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
2089 for (
auto &I : MustTailCallUndefinedGlobals) {
2098 if (Entry->isDeclarationForLinker()) {
2101 Entry->hasHiddenVisibility() || Entry->hasProtectedVisibility();
2103 CalleeIsLocal = Entry->isDSOLocal();
2107 getDiags().
Report(I.second, diag::err_mips_impossible_musttail) << 1;
2120 llvm::MDBuilder MDB(TheModule.getContext());
2121 uint64_t Size = Context.getTypeSizeInChars(Context.IntTy).getQuantity();
2122 llvm::MDNode *StructNode =
2123 CodeGenOpts.NewStructPathTBAA
2124 ? MDB.createTBAATypeNode(TBAA->getChar(), Size,
2125 MDB.createString(
"__libc_errno"),
2126 {{0, Size, IntegerNode}})
2127 : MDB.createTBAAStructTypeNode(
"__libc_errno",
2128 {{IntegerNode, 0}});
2131 auto *ErrnoTBAAMD = TheModule.getOrInsertNamedMetadata(
ErrnoTBAAMDName);
2132 ErrnoTBAAMD->addOperand(StructTagNode);
2137void CodeGenModule::EmitOpenCLMetadata() {
2142 unsigned CLVersion =
2145 auto EmitVersion = [
this](StringRef MDName,
int Version) {
2146 llvm::Metadata *OCLVerElts[] = {
2147 llvm::ConstantAsMetadata::get(
2148 llvm::ConstantInt::get(
Int32Ty, Version / 100)),
2149 llvm::ConstantAsMetadata::get(
2150 llvm::ConstantInt::get(
Int32Ty, (Version % 100) / 10))};
2151 llvm::NamedMDNode *OCLVerMD = TheModule.getOrInsertNamedMetadata(MDName);
2152 llvm::LLVMContext &Ctx = TheModule.getContext();
2153 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
2156 EmitVersion(
"opencl.ocl.version", CLVersion);
2157 if (LangOpts.OpenCLCPlusPlus) {
2159 EmitVersion(
"opencl.cxx.version", LangOpts.OpenCLCPlusPlusVersion);
2163void CodeGenModule::EmitBackendOptionsMetadata(
2164 const CodeGenOptions &CodeGenOpts) {
2166 getModule().addModuleFlag(llvm::Module::Min,
"SmallDataLimit",
2167 CodeGenOpts.SmallDataLimit);
2171 if (LangOpts.AllocTokenMode) {
2172 StringRef S = llvm::getAllocTokenModeAsString(*LangOpts.AllocTokenMode);
2173 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-mode",
2174 llvm::MDString::get(VMContext, S));
2176 if (LangOpts.AllocTokenMax)
2178 llvm::Module::Error,
"alloc-token-max",
2179 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
2180 *LangOpts.AllocTokenMax));
2181 if (CodeGenOpts.SanitizeAllocTokenFastABI)
2182 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-fast-abi", 1);
2183 if (CodeGenOpts.SanitizeAllocTokenExtended)
2184 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-extended", 1);
2200 return TBAA->getTypeInfo(QTy);
2219 return TBAA->getAccessInfo(AccessType);
2226 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
2232 return TBAA->getTBAAStructInfo(QTy);
2238 return TBAA->getBaseTypeInfo(QTy);
2244 return TBAA->getAccessTagInfo(Info);
2251 return TBAA->mergeTBAAInfoForCast(SourceInfo,
TargetInfo);
2259 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
2267 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
2273 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
2278 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
2290 std::string Msg =
Type;
2292 diag::err_codegen_unsupported)
2298 diag::err_codegen_unsupported)
2305 std::string Msg =
Type;
2307 diag::err_codegen_unsupported)
2312 llvm::function_ref<
void()> Fn) {
2313 StackHandler.runWithSufficientStackSpace(Loc, Fn);
2323 if (GV->hasLocalLinkage()) {
2324 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2337 if (Context.getLangOpts().OpenMP &&
2338 Context.getLangOpts().OpenMPIsTargetDevice &&
isa<VarDecl>(D) &&
2339 D->
hasAttr<OMPDeclareTargetDeclAttr>() &&
2340 D->
getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
2341 OMPDeclareTargetDeclAttr::DT_NoHost &&
2343 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
2350 if (Context.getLangOpts().CUDAIsDevice &&
2352 !D->
hasAttr<OMPDeclareTargetDeclAttr>()) {
2353 bool NeedsProtected =
false;
2357 else if (
const auto *VD = dyn_cast<VarDecl>(D))
2358 NeedsProtected = VD->hasAttr<CUDADeviceAttr>() ||
2359 VD->hasAttr<CUDAConstantAttr>() ||
2360 VD->getType()->isCUDADeviceBuiltinSurfaceType() ||
2361 VD->getType()->isCUDADeviceBuiltinTextureType();
2362 if (NeedsProtected) {
2363 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
2369 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
2373 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
2377 if (GV->hasDLLExportStorageClass()) {
2380 diag::err_hidden_visibility_dllexport);
2383 diag::err_non_default_visibility_dllimport);
2389 !GV->isDeclarationForLinker())
2394 llvm::GlobalValue *GV) {
2395 if (GV->hasLocalLinkage())
2398 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
2402 if (GV->hasDLLImportStorageClass())
2405 const llvm::Triple &TT = CGM.
getTriple();
2407 if (TT.isOSCygMing()) {
2425 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
2433 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
2437 if (!TT.isOSBinFormatELF())
2443 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
2451 return !(CGM.
getLangOpts().SemanticInterposition ||
2456 if (!GV->isDeclarationForLinker())
2462 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
2469 if (CGOpts.DirectAccessExternalData) {
2475 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
2476 if (!Var->isThreadLocal())
2501 const auto *D = dyn_cast<NamedDecl>(GD.
getDecl());
2503 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
2513 if (D->
hasAttr<DLLImportAttr>())
2514 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2515 else if ((D->
hasAttr<DLLExportAttr>() ||
2517 !GV->isDeclarationForLinker())
2518 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2538 GV->setPartition(CodeGenOpts.SymbolPartition);
2542 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
2543 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
2544 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
2545 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
2546 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
2549llvm::GlobalVariable::ThreadLocalMode
2551 switch (CodeGenOpts.getDefaultTLSModel()) {
2553 return llvm::GlobalVariable::GeneralDynamicTLSModel;
2555 return llvm::GlobalVariable::LocalDynamicTLSModel;
2557 return llvm::GlobalVariable::InitialExecTLSModel;
2559 return llvm::GlobalVariable::LocalExecTLSModel;
2561 llvm_unreachable(
"Invalid TLS model!");
2565 assert(D.
getTLSKind() &&
"setting TLS mode on non-TLS var!");
2567 llvm::GlobalValue::ThreadLocalMode TLM;
2571 if (
const TLSModelAttr *
Attr = D.
getAttr<TLSModelAttr>()) {
2575 GV->setThreadLocalMode(TLM);
2581 return (Twine(
'.') + Twine(
Target.CPUSpecificManglingCharacter(Name))).str();
2585 const CPUSpecificAttr *
Attr,
2602 !D->
hasAttr<AsmLabelAttr>() &&
2608 bool OmitMultiVersionMangling =
false,
2609 bool IgnoreAsmLabel =
false) {
2611 llvm::raw_svector_ostream Out(Buffer);
2615 bool ShouldMangle = !IgnoreAsmLabel
2619 if (!IgnoreAsmLabel)
2625 assert(II &&
"Attempt to mangle unnamed decl.");
2626 const auto *FD = dyn_cast<FunctionDecl>(ND);
2631 Out <<
"__regcall4__" << II->
getName();
2633 Out <<
"__regcall3__" << II->
getName();
2634 }
else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
2636 Out <<
"__device_stub__" << II->
getName();
2638 DeviceKernelAttr::isOpenCLSpelling(
2639 FD->getAttr<DeviceKernelAttr>()) &&
2641 Out <<
"__clang_ocl_kern_imp_" << II->
getName();
2657 "Hash computed when not explicitly requested");
2661 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
2662 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
2663 switch (FD->getMultiVersionKind()) {
2667 FD->getAttr<CPUSpecificAttr>(),
2671 auto *
Attr = FD->getAttr<TargetAttr>();
2672 assert(
Attr &&
"Expected TargetAttr to be present "
2673 "for attribute mangling");
2679 auto *
Attr = FD->getAttr<TargetVersionAttr>();
2680 assert(
Attr &&
"Expected TargetVersionAttr to be present "
2681 "for attribute mangling");
2687 auto *
Attr = FD->getAttr<TargetClonesAttr>();
2688 assert(
Attr &&
"Expected TargetClonesAttr to be present "
2689 "for attribute mangling");
2696 llvm_unreachable(
"None multiversion type isn't valid here");
2706 return std::string(Out.str());
2709void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
2710 const FunctionDecl *FD,
2711 StringRef &CurName) {
2718 std::string NonTargetName =
2726 "Other GD should now be a multiversioned function");
2736 if (OtherName != NonTargetName) {
2739 const auto ExistingRecord = Manglings.find(NonTargetName);
2740 if (ExistingRecord != std::end(Manglings))
2741 Manglings.remove(&(*ExistingRecord));
2742 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
2747 CurName = OtherNameRef;
2749 Entry->setName(OtherName);
2759 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
2773 auto FoundName = MangledDeclNames.find(CanonicalGD);
2774 if (FoundName != MangledDeclNames.end())
2775 return FoundName->second;
2812 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
2813 return MangledDeclNames[CanonicalGD] =
Result.first->first();
2818 std::string MangledName =
2830 llvm::raw_svector_ostream Out(Buffer);
2833 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
2834 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(D))
2836 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(D))
2841 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
2842 return Result.first->first();
2846 auto it = MangledDeclNames.begin();
2847 while (it != MangledDeclNames.end()) {
2848 if (it->second == Name)
2863 llvm::Constant *AssociatedData) {
2865 GlobalCtors.push_back(
Structor(Priority, LexOrder, Ctor, AssociatedData));
2871 bool IsDtorAttrFunc) {
2872 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2874 DtorsUsingAtExit[Priority].push_back(Dtor);
2879 GlobalDtors.push_back(
Structor(Priority, ~0
U, Dtor,
nullptr));
2882void CodeGenModule::EmitCtorList(CtorList &Fns,
const char *GlobalName) {
2883 if (Fns.empty())
return;
2886 llvm::PointerType *PtrTy = llvm::PointerType::get(
2887 getLLVMContext(), TheModule.getDataLayout().getProgramAddressSpace());
2890 llvm::StructType *CtorStructTy = llvm::StructType::get(
Int32Ty, PtrTy, PtrTy);
2894 auto Ctors = Builder.beginArray(CtorStructTy);
2895 for (
const auto &I : Fns) {
2896 auto Ctor = Ctors.beginStruct(CtorStructTy);
2897 Ctor.addInt(
Int32Ty, I.Priority);
2898 Ctor.add(I.Initializer);
2899 if (I.AssociatedData)
2900 Ctor.add(I.AssociatedData);
2902 Ctor.addNullPointer(PtrTy);
2903 Ctor.finishAndAddTo(Ctors);
2906 auto List = Ctors.finishAndCreateGlobal(GlobalName,
getPointerAlign(),
2908 llvm::GlobalValue::AppendingLinkage);
2912 List->setAlignment(std::nullopt);
2917llvm::GlobalValue::LinkageTypes
2923 if (
const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
2930 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2931 if (!MDS)
return nullptr;
2933 return llvm::ConstantInt::get(
Int64Ty, llvm::MD5Hash(MDS->getString()));
2941 if (!UD->
hasAttr<TransparentUnionAttr>())
2943 if (!UD->
fields().empty())
2944 return UD->
fields().begin()->getType();
2953 bool GeneralizePointers) {
2966 bool GeneralizePointers) {
2969 for (
auto &Param : FnType->param_types())
2970 GeneralizedParams.push_back(
2974 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers),
2975 GeneralizedParams, FnType->getExtProtoInfo());
2980 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers));
2982 llvm_unreachable(
"Encountered unknown FunctionType");
2990 FnType->getReturnType(), FnType->getParamTypes(),
2991 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
2993 std::string OutName;
2994 llvm::raw_string_ostream Out(OutName);
3002 Out <<
".normalized";
3004 Out <<
".generalized";
3006 return llvm::ConstantInt::get(
3012 llvm::Function *F,
bool IsThunk) {
3014 llvm::AttributeList PAL;
3017 if (
CallingConv == llvm::CallingConv::X86_VectorCall &&
3021 Loc = D->getLocation();
3023 Error(Loc,
"__vectorcall calling convention is not currently supported");
3025 F->setAttributes(PAL);
3026 F->setCallingConv(
static_cast<llvm::CallingConv::ID
>(
CallingConv));
3030 std::string ReadOnlyQual(
"__read_only");
3031 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
3032 if (ReadOnlyPos != std::string::npos)
3034 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
3036 std::string WriteOnlyQual(
"__write_only");
3037 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
3038 if (WriteOnlyPos != std::string::npos)
3039 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
3041 std::string ReadWriteQual(
"__read_write");
3042 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
3043 if (ReadWritePos != std::string::npos)
3044 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
3077 assert(((FD && CGF) || (!FD && !CGF)) &&
3078 "Incorrect use - FD and CGF should either be both null or not!");
3104 for (
unsigned i = 0, e = FD->
getNumParams(); i != e; ++i) {
3107 argNames.push_back(llvm::MDString::get(VMContext, parm->
getName()));
3112 std::string typeQuals;
3116 const Decl *PDecl = parm;
3118 PDecl = TD->getDecl();
3119 const OpenCLAccessAttr *A = PDecl->
getAttr<OpenCLAccessAttr>();
3120 if (A && A->isWriteOnly())
3121 accessQuals.push_back(llvm::MDString::get(VMContext,
"write_only"));
3122 else if (A && A->isReadWrite())
3123 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_write"));
3125 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_only"));
3127 accessQuals.push_back(llvm::MDString::get(VMContext,
"none"));
3129 auto getTypeSpelling = [&](
QualType Ty) {
3130 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
3132 if (Ty.isCanonical()) {
3133 StringRef typeNameRef = typeName;
3135 if (typeNameRef.consume_front(
"unsigned "))
3136 return std::string(
"u") + typeNameRef.str();
3137 if (typeNameRef.consume_front(
"signed "))
3138 return typeNameRef.str();
3148 addressQuals.push_back(
3149 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(
3153 std::string typeName = getTypeSpelling(pointeeTy) +
"*";
3154 std::string baseTypeName =
3156 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
3157 argBaseTypeNames.push_back(
3158 llvm::MDString::get(VMContext, baseTypeName));
3162 typeQuals =
"restrict";
3165 typeQuals += typeQuals.empty() ?
"const" :
" const";
3167 typeQuals += typeQuals.empty() ?
"volatile" :
" volatile";
3169 uint32_t AddrSpc = 0;
3174 addressQuals.push_back(
3175 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(AddrSpc)));
3179 std::string typeName = getTypeSpelling(ty);
3191 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
3192 argBaseTypeNames.push_back(
3193 llvm::MDString::get(VMContext, baseTypeName));
3198 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
3202 Fn->setMetadata(
"kernel_arg_addr_space",
3203 llvm::MDNode::get(VMContext, addressQuals));
3204 Fn->setMetadata(
"kernel_arg_access_qual",
3205 llvm::MDNode::get(VMContext, accessQuals));
3206 Fn->setMetadata(
"kernel_arg_type",
3207 llvm::MDNode::get(VMContext, argTypeNames));
3208 Fn->setMetadata(
"kernel_arg_base_type",
3209 llvm::MDNode::get(VMContext, argBaseTypeNames));
3210 Fn->setMetadata(
"kernel_arg_type_qual",
3211 llvm::MDNode::get(VMContext, argTypeQuals));
3215 Fn->setMetadata(
"kernel_arg_name",
3216 llvm::MDNode::get(VMContext, argNames));
3232SmallVector<const CXXRecordDecl *, 0>
3234 llvm::SetVector<const CXXRecordDecl *> MostBases;
3239 MostBases.insert(RD);
3241 CollectMostBases(B.getType()->getAsCXXRecordDecl());
3243 CollectMostBases(RD);
3244 return MostBases.takeVector();
3248 llvm::Function *F) {
3249 llvm::AttrBuilder B(F->getContext());
3251 if ((!D || !D->
hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
3252 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
3254 if (CodeGenOpts.StackClashProtector)
3255 B.addAttribute(
"probe-stack",
"inline-asm");
3257 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
3258 B.addAttribute(
"stack-probe-size",
3259 std::to_string(CodeGenOpts.StackProbeSize));
3262 B.addAttribute(llvm::Attribute::NoUnwind);
3264 if (std::optional<llvm::Attribute::AttrKind>
Attr =
3266 B.addAttribute(*
Attr);
3271 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline))
3272 B.addAttribute(llvm::Attribute::AlwaysInline);
3276 else if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
3278 B.addAttribute(llvm::Attribute::NoInline);
3286 if (D->
hasAttr<ArmLocallyStreamingAttr>())
3287 B.addAttribute(
"aarch64_pstate_sm_body");
3290 if (
Attr->isNewZA())
3291 B.addAttribute(
"aarch64_new_za");
3292 if (
Attr->isNewZT0())
3293 B.addAttribute(
"aarch64_new_zt0");
3298 bool ShouldAddOptNone =
3299 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
3301 ShouldAddOptNone &= !D->
hasAttr<MinSizeAttr>();
3302 ShouldAddOptNone &= !D->
hasAttr<AlwaysInlineAttr>();
3305 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline) &&
3306 !D->
hasAttr<NoInlineAttr>()) {
3307 B.addAttribute(llvm::Attribute::AlwaysInline);
3308 }
else if ((ShouldAddOptNone || D->
hasAttr<OptimizeNoneAttr>()) &&
3309 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
3311 B.addAttribute(llvm::Attribute::OptimizeNone);
3314 B.addAttribute(llvm::Attribute::NoInline);
3319 B.addAttribute(llvm::Attribute::Naked);
3322 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
3323 F->removeFnAttr(llvm::Attribute::MinSize);
3324 }
else if (D->
hasAttr<NakedAttr>()) {
3326 B.addAttribute(llvm::Attribute::Naked);
3327 B.addAttribute(llvm::Attribute::NoInline);
3328 }
else if (D->
hasAttr<NoDuplicateAttr>()) {
3329 B.addAttribute(llvm::Attribute::NoDuplicate);
3330 }
else if (D->
hasAttr<NoInlineAttr>() &&
3331 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
3333 B.addAttribute(llvm::Attribute::NoInline);
3334 }
else if (D->
hasAttr<AlwaysInlineAttr>() &&
3335 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
3337 B.addAttribute(llvm::Attribute::AlwaysInline);
3341 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
3342 B.addAttribute(llvm::Attribute::NoInline);
3346 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
3349 auto CheckRedeclForInline = [](
const FunctionDecl *Redecl) {
3350 return Redecl->isInlineSpecified();
3352 if (any_of(FD->
redecls(), CheckRedeclForInline))
3357 return any_of(Pattern->
redecls(), CheckRedeclForInline);
3359 if (CheckForInline(FD)) {
3360 B.addAttribute(llvm::Attribute::InlineHint);
3361 }
else if (CodeGenOpts.getInlining() ==
3364 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
3365 B.addAttribute(llvm::Attribute::NoInline);
3372 if (!D->
hasAttr<OptimizeNoneAttr>()) {
3374 if (!ShouldAddOptNone)
3375 B.addAttribute(llvm::Attribute::OptimizeForSize);
3376 B.addAttribute(llvm::Attribute::Cold);
3379 B.addAttribute(llvm::Attribute::Hot);
3380 if (D->
hasAttr<MinSizeAttr>())
3381 B.addAttribute(llvm::Attribute::MinSize);
3386 if (CodeGenOpts.DisableOutlining || D->
hasAttr<NoOutlineAttr>())
3387 B.addAttribute(llvm::Attribute::NoOutline);
3392 if (CodeGenOpts.ModuleLocalHints) {
3393 const auto *FD = dyn_cast<FunctionDecl>(D);
3401 B.addAttribute(llvm::Attribute::LikelyModuleLocal);
3406 llvm::MaybeAlign ExplicitAlignment;
3407 if (
unsigned alignment = D->
getMaxAlignment() / Context.getCharWidth())
3408 ExplicitAlignment = llvm::Align(alignment);
3409 else if (LangOpts.FunctionAlignment)
3410 ExplicitAlignment = llvm::Align::fromLog2(LangOpts.FunctionAlignment);
3412 if (ExplicitAlignment) {
3413 F->setAlignment(ExplicitAlignment);
3414 F->setPreferredAlignment(ExplicitAlignment);
3415 }
else if (LangOpts.PreferredFunctionAlignment) {
3416 F->setPreferredAlignment(llvm::Align(LangOpts.PreferredFunctionAlignment));
3425 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
3430 if (CodeGenOpts.SanitizeCfiCrossDso &&
3431 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
3432 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
3440 if (CodeGenOpts.CallGraphSection) {
3441 if (
auto *FD = dyn_cast<FunctionDecl>(D))
3448 auto *MD = dyn_cast<CXXMethodDecl>(D);
3451 llvm::Metadata *Id =
3453 MD->getType(), std::nullopt,
Base));
3454 F->addTypeMetadata(0, Id);
3461 if (
const auto *FD = dyn_cast<FunctionDecl>(D))
3462 if (FD->
hasAttr<SYCLExternalAttr>())
3463 addSYCLModuleIdAttr(F);
3467void CodeGenModule::addSYCLModuleIdAttr(llvm::Function *Fn) {
3469 Fn->addFnAttr(
"sycl-module-id",
getModule().getModuleIdentifier());
3477 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FD))
3479 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(FD))
3493 Linkage != llvm::GlobalValue::AvailableExternallyLinkage;
3498 if (isa_and_nonnull<NamedDecl>(D))
3501 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
3503 if (D && D->
hasAttr<UsedAttr>())
3506 if (
const auto *VD = dyn_cast_if_present<VarDecl>(D);
3508 ((CodeGenOpts.KeepPersistentStorageVariables &&
3509 (VD->getStorageDuration() ==
SD_Static ||
3510 VD->getStorageDuration() ==
SD_Thread)) ||
3511 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
3512 VD->getType().isConstQualified())))
3515 if (CodeGenOpts.KeepInlineFunctions)
3516 if (
const auto *FD = dyn_cast_if_present<FunctionDecl>(D))
3522static std::vector<std::string>
3524 const llvm::StringMap<bool> &FeatureMap) {
3525 llvm::StringMap<bool> DefaultFeatureMap;
3529 std::vector<std::string> Delta;
3530 for (
const auto &[K,
V] : FeatureMap) {
3531 auto DefaultIt = DefaultFeatureMap.find(K);
3532 if (DefaultIt == DefaultFeatureMap.end() || DefaultIt->getValue() !=
V)
3533 Delta.push_back((
V ?
"+" :
"-") + K.str());
3539bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
3540 llvm::AttrBuilder &Attrs,
3541 bool SetTargetFeatures) {
3547 std::vector<std::string> Features;
3548 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.
getDecl());
3551 const auto *TV = FD ? FD->
getAttr<TargetVersionAttr>() :
nullptr;
3552 assert((!TD || !TV) &&
"both target_version and target specified");
3555 bool AddedAttr =
false;
3556 auto GetTargetFeaturesAttr = [&](llvm::ArrayRef<std::string> Features) {
3557 llvm::SmallVector<StringRef, 16> CanonicalFeatures;
3558 for (StringRef
Feature : Features)
3560 CanonicalFeatures.push_back(
Feature);
3561 if (CanonicalFeatures.empty())
3562 return llvm::Attribute();
3563 llvm::sort(CanonicalFeatures);
3565 llvm::join(CanonicalFeatures,
","));
3567 if (TD || TV || SD || TC) {
3574 StringRef FeatureStr = TD ? TD->getFeaturesStr() : StringRef();
3577 if (!FeatureStr.empty()) {
3578 ParsedTargetAttr ParsedAttr = Target.parseTargetAttr(FeatureStr);
3579 if (!ParsedAttr.
CPU.empty() &&
3581 TargetCPU = ParsedAttr.
CPU;
3584 if (!ParsedAttr.
Tune.empty() &&
3586 TuneCPU = ParsedAttr.
Tune;
3602 for (
const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
3603 Features.push_back((Entry.getValue() ?
"+" :
"-") +
3604 Entry.getKey().str());
3617 }
else if (SetTargetFeatures) {
3618 if (!DefaultTargetFeatures)
3619 DefaultTargetFeatures =
3620 GetTargetFeaturesAttr(
getTarget().getTargetOpts().Features);
3621 if (DefaultTargetFeatures->isValid()) {
3622 Attrs.addAttribute(*DefaultTargetFeatures);
3628 if (!TargetCPU.empty()) {
3629 Attrs.addAttribute(
"target-cpu", TargetCPU);
3632 if (!TuneCPU.empty()) {
3633 Attrs.addAttribute(
"tune-cpu", TuneCPU);
3636 if (!Features.empty() && SetTargetFeatures) {
3637 llvm::Attribute FeatureAttr = GetTargetFeaturesAttr(Features);
3638 if (FeatureAttr.isValid()) {
3639 Attrs.addAttribute(FeatureAttr);
3645 llvm::SmallVector<StringRef, 8> Feats;
3646 bool IsDefault =
false;
3648 IsDefault = TV->isDefaultVersion();
3649 TV->getFeatures(Feats);
3655 Attrs.addAttribute(
"fmv-features");
3657 }
else if (!Feats.empty()) {
3659 std::set<StringRef> OrderedFeats(Feats.begin(), Feats.end());
3660 std::string FMVFeatures;
3661 for (StringRef F : OrderedFeats)
3662 FMVFeatures.append(
"," + F.str());
3663 Attrs.addAttribute(
"fmv-features", FMVFeatures.substr(1));
3670void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
3671 llvm::GlobalObject *GO) {
3676 if (
auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
3679 if (
auto *SA = D->
getAttr<PragmaClangBSSSectionAttr>())
3680 GV->addAttribute(
"bss-section", SA->getName());
3681 if (
auto *SA = D->
getAttr<PragmaClangDataSectionAttr>())
3682 GV->addAttribute(
"data-section", SA->getName());
3683 if (
auto *SA = D->
getAttr<PragmaClangRodataSectionAttr>())
3684 GV->addAttribute(
"rodata-section", SA->getName());
3685 if (
auto *SA = D->
getAttr<PragmaClangRelroSectionAttr>())
3686 GV->addAttribute(
"relro-section", SA->getName());
3689 if (
auto *F = dyn_cast<llvm::Function>(GO)) {
3692 if (
auto *SA = D->
getAttr<PragmaClangTextSectionAttr>())
3693 if (!D->
getAttr<SectionAttr>())
3694 F->setSection(SA->getName());
3696 llvm::AttrBuilder Attrs(F->getContext());
3697 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
3701 llvm::AttributeMask RemoveAttrs;
3702 RemoveAttrs.addAttribute(
"target-cpu");
3703 RemoveAttrs.addAttribute(
"target-features");
3704 RemoveAttrs.addAttribute(
"fmv-features");
3705 RemoveAttrs.addAttribute(
"tune-cpu");
3706 F->removeFnAttrs(RemoveAttrs);
3707 F->addFnAttrs(Attrs);
3711 if (
const auto *CSA = D->
getAttr<CodeSegAttr>())
3712 GO->setSection(CSA->getName());
3713 else if (
const auto *SA = D->
getAttr<SectionAttr>())
3714 GO->setSection(SA->getName());
3727 F->setLinkage(llvm::Function::InternalLinkage);
3729 setNonAliasAttributes(GD, F);
3740 GV->
setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
3744 llvm::Function *F) {
3747 if (!F->hasLocalLinkage() ||
3748 F->getFunction().hasAddressTaken(
nullptr,
true,
3752 bool HasBody = FD->
hasBody(Def);
3753 if (!HasBody || !Def)
3770 ParamTypes.push_back(P->getType());
3778 llvm::LLVMContext::MD_callgraph,
3785 llvm::Function *F) {
3787 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
3797 F->addTypeMetadata(0, MD);
3803 if (CodeGenOpts.SanitizeCfiCrossDso)
3805 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
3809 llvm::CallBase *CB) {
3811 if (!CodeGenOpts.CallGraphSection || !CB->isIndirectCall())
3815 llvm::MDTuple *TypeTuple = llvm::MDTuple::get(
getLLVMContext(), {TypeIdMD});
3816 llvm::MDTuple *MDN = llvm::MDNode::get(
getLLVMContext(), {TypeTuple});
3817 CB->setMetadata(llvm::LLVMContext::MD_callee_type, MDN);
3821 llvm::LLVMContext &Ctx = F->getContext();
3822 llvm::MDBuilder MDB(Ctx);
3823 llvm::StringRef Salt;
3826 if (
const auto &Info = FP->getExtraAttributeInfo())
3827 Salt = Info.CFISalt;
3829 F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
3838 return llvm::all_of(Name, [](
const char &
C) {
3839 return llvm::isAlnum(
C) ||
C ==
'_' ||
C ==
'.';
3845 for (
auto &F : M.functions()) {
3847 bool AddressTaken = F.hasAddressTaken();
3848 if (!AddressTaken && F.hasLocalLinkage())
3849 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
3854 if (!AddressTaken || !F.isDeclaration())
3857 const llvm::ConstantInt *
Type;
3858 if (
const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
3859 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
3863 StringRef Name = F.getName();
3867 std::string
Asm = (
".weak __kcfi_typeid_" + Name +
"\n.set __kcfi_typeid_" +
3868 Name +
", " + Twine(
Type->getZExtValue()) +
" /* " +
3869 Twine(
Type->getSExtValue()) +
" */\n")
3871 M.appendModuleInlineAsm(
Asm);
3875void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
3876 bool IsIncompleteFunction,
3879 if (F->getIntrinsicID() != llvm::Intrinsic::not_intrinsic) {
3887 if (!IsIncompleteFunction)
3894 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
3896 assert(!F->arg_empty() &&
3897 F->arg_begin()->getType()
3898 ->canLosslesslyBitCastTo(F->getReturnType()) &&
3899 "unexpected this return");
3900 F->addParamAttr(0, llvm::Attribute::Returned);
3910 if (!IsIncompleteFunction && F->isDeclaration())
3913 if (
const auto *CSA = FD->
getAttr<CodeSegAttr>())
3914 F->setSection(CSA->getName());
3915 else if (
const auto *SA = FD->
getAttr<SectionAttr>())
3916 F->setSection(SA->getName());
3918 if (
const auto *EA = FD->
getAttr<ErrorAttr>()) {
3920 F->addFnAttr(
"dontcall-error", EA->getUserDiagnostic());
3921 else if (EA->isWarning())
3922 F->addFnAttr(
"dontcall-warn", EA->getUserDiagnostic());
3927 const FunctionDecl *FDBody;
3928 bool HasBody = FD->
hasBody(FDBody);
3930 assert(HasBody &&
"Inline builtin declarations should always have an "
3932 if (shouldEmitFunction(FDBody))
3933 F->addFnAttr(llvm::Attribute::NoBuiltin);
3939 F->addFnAttr(llvm::Attribute::NoBuiltin);
3943 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3944 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
3945 if (MD->isVirtual())
3946 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3952 if (!CodeGenOpts.SanitizeCfiCrossDso ||
3953 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
3956 if (CodeGenOpts.CallGraphSection)
3959 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
3965 if (CodeGenOpts.InlineMaxStackSize !=
UINT_MAX)
3966 F->addFnAttr(
"inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
3968 if (
const auto *CB = FD->
getAttr<CallbackAttr>()) {
3972 llvm::LLVMContext &Ctx = F->getContext();
3973 llvm::MDBuilder MDB(Ctx);
3977 int CalleeIdx = *CB->encoding_begin();
3978 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
3979 F->addMetadata(llvm::LLVMContext::MD_callback,
3980 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
3981 CalleeIdx, PayloadIndices,
3988 "Only globals with definition can force usage.");
3989 LLVMUsed.emplace_back(GV);
3993 assert(!GV->isDeclaration() &&
3994 "Only globals with definition can force usage.");
3995 LLVMCompilerUsed.emplace_back(GV);
4000 "Only globals with definition can force usage.");
4002 LLVMCompilerUsed.emplace_back(GV);
4004 LLVMUsed.emplace_back(GV);
4008 std::vector<llvm::WeakTrackingVH> &List) {
4018 UsedArray.reserve(List.size());
4019 for (
const llvm::WeakTrackingVH &VH : List) {
4020 if (llvm::Value *
V = VH)
4021 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
4025 if (UsedArray.empty())
4027 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
4029 auto *GV =
new llvm::GlobalVariable(
4030 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
4031 llvm::ConstantArray::get(ATy, UsedArray), Name);
4033 GV->setSection(
"llvm.metadata");
4036void CodeGenModule::emitLLVMUsed() {
4037 emitUsed(*
this,
"llvm.used", LLVMUsed);
4038 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
4043 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
4052 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
4058 ELFDependentLibraries.push_back(
4059 llvm::MDNode::get(
C, llvm::MDString::get(
C, Lib)));
4066 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
C, MDOpts));
4073void CodeGenModule::ProcessPragmaCommentCopyright(StringRef Comment,
4074 bool isFromASTFile) {
4076 "pragma comment copyright is supported only when targeting AIX");
4089 assert(!LoadTimeCommentGlobal &&
4090 "Only one copyright pragma allowed per translation unit.");
4095 uint64_t Hash = xxh3_64bits(Comment);
4096 std::string GlobalName =
4097 (
"__loadtime_comment_str_" + Twine::utohexstr(Hash)).str();
4100 llvm::Constant *StrInit =
4101 llvm::ConstantDataArray::getString(
C, Comment,
true);
4104 auto *GV =
new llvm::GlobalVariable(
getModule(), StrInit->getType(),
4106 llvm::GlobalValue::WeakODRLinkage,
4107 StrInit, GlobalName);
4109 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4110 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4111 GV->setAlignment(llvm::Align(1));
4117 GV->setSection(
"__loadtime_comment");
4120 GV->setMetadata(
"loadtime_comment", llvm::MDNode::get(
C, {}));
4123 llvm::appendToCompilerUsed(
getModule(), {GV});
4125 LoadTimeCommentGlobal = GV;
4134 if (Mod->
Parent && Visited.insert(Mod->
Parent).second) {
4140 if (Visited.insert(Import).second)
4157 if (LL.IsFramework) {
4158 llvm::Metadata *Args[2] = {llvm::MDString::get(Context,
"-framework"),
4159 llvm::MDString::get(Context, LL.Library)};
4161 Metadata.push_back(llvm::MDNode::get(Context, Args));
4167 llvm::Metadata *Args[2] = {
4168 llvm::MDString::get(Context,
"lib"),
4169 llvm::MDString::get(Context, LL.Library),
4171 Metadata.push_back(llvm::MDNode::get(Context, Args));
4175 auto *OptString = llvm::MDString::get(Context, Opt);
4176 Metadata.push_back(llvm::MDNode::get(Context, OptString));
4181void CodeGenModule::EmitModuleInitializers(
clang::Module *Primary) {
4183 "We should only emit module initializers for named modules.");
4191 assert(
isa<VarDecl>(D) &&
"GMF initializer decl is not a var?");
4208 assert(
isa<VarDecl>(D) &&
"PMF initializer decl is not a var?");
4214void CodeGenModule::EmitModuleLinkOptions() {
4218 llvm::SetVector<clang::Module *> LinkModules;
4219 llvm::SmallPtrSet<clang::Module *, 16> Visited;
4220 SmallVector<clang::Module *, 16> Stack;
4223 for (
Module *M : ImportedModules) {
4226 if (M->getTopLevelModuleName() ==
getLangOpts().CurrentModule &&
4229 if (Visited.insert(M).second)
4235 while (!Stack.empty()) {
4238 bool AnyChildren =
false;
4247 if (Visited.insert(SM).second) {
4248 Stack.push_back(SM);
4256 LinkModules.insert(Mod);
4263 SmallVector<llvm::MDNode *, 16> MetadataArgs;
4265 for (
Module *M : LinkModules)
4266 if (Visited.insert(M).second)
4268 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
4269 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
4272 if (!LinkerOptionsMetadata.empty()) {
4273 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.linker.options");
4274 for (
auto *MD : LinkerOptionsMetadata)
4275 NMD->addOperand(MD);
4279void CodeGenModule::EmitDeferred() {
4288 if (!DeferredVTables.empty()) {
4289 EmitDeferredVTables();
4294 assert(DeferredVTables.empty());
4301 llvm::append_range(DeferredDeclsToEmit,
4305 if (DeferredDeclsToEmit.empty())
4310 std::vector<GlobalDecl> CurDeclsToEmit;
4311 CurDeclsToEmit.swap(DeferredDeclsToEmit);
4313 for (GlobalDecl &D : CurDeclsToEmit) {
4319 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>() &&
4323 if (!FD->
getAttr<SYCLKernelEntryPointAttr>()->isInvalidAttr()) {
4344 if (GV && !GV->isDeclaration()) {
4345 GlobalDecl ExistingGD;
4368 if (!GV->isDeclaration())
4372 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
4376 EmitGlobalDefinition(D, GV);
4381 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
4383 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
4388void CodeGenModule::EmitVTablesOpportunistically() {
4394 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
4395 &&
"Only emit opportunistic vtables with optimizations");
4397 for (
const CXXRecordDecl *RD : OpportunisticVTables) {
4399 "This queue should only contain external vtables");
4400 if (
getCXXABI().canSpeculativelyEmitVTable(RD))
4401 VTables.GenerateClassData(RD);
4403 OpportunisticVTables.clear();
4407 for (
const auto& [MangledName, VD] : DeferredAnnotations) {
4412 DeferredAnnotations.clear();
4414 if (Annotations.empty())
4418 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
4419 Annotations[0]->
getType(), Annotations.size()), Annotations);
4420 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
4421 llvm::GlobalValue::AppendingLinkage,
4422 Array,
"llvm.global.annotations");
4427 llvm::Constant *&AStr = AnnotationStrings[Str];
4432 llvm::Constant *s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
4433 auto *gv =
new llvm::GlobalVariable(
4434 getModule(), s->getType(),
true, llvm::GlobalValue::PrivateLinkage, s,
4435 ".str",
nullptr, llvm::GlobalValue::NotThreadLocal,
4438 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4456 return llvm::ConstantInt::get(
Int32Ty, LineNo);
4464 llvm::FoldingSetNodeID ID;
4465 for (
Expr *E : Exprs) {
4468 llvm::Constant *&Lookup = AnnotationArgs[ID.computeHash()];
4473 LLVMArgs.reserve(Exprs.size());
4475 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](
const Expr *E) {
4477 return ConstEmiter.
emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
4480 auto *
Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
4481 auto *GV =
new llvm::GlobalVariable(
getModule(),
Struct->getType(),
true,
4482 llvm::GlobalValue::PrivateLinkage,
Struct,
4485 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4492 const AnnotateAttr *AA,
4500 llvm::Constant *GVInGlobalsAS = GV;
4501 if (GV->getAddressSpace() !=
4503 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
4505 llvm::PointerType::get(
4506 GV->getContext(),
getDataLayout().getDefaultGlobalsAddressSpace()));
4510 llvm::Constant *Fields[] = {
4511 GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
4513 return llvm::ConstantStruct::getAnon(Fields);
4517 llvm::GlobalValue *GV) {
4518 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
4528 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
4531 auto &SM = Context.getSourceManager();
4532 FileEntryRef MainFile = *SM.getFileEntryRefForID(SM.getMainFileID());
4533 if (NoSanitizeL.containsMainFile(Kind, MainFile.
getName()))
4538 return NoSanitizeL.containsLocation(Kind, Loc);
4541 return NoSanitizeL.containsFile(Kind, MainFile.
getName());
4545 llvm::GlobalVariable *GV,
4547 StringRef Category)
const {
4549 if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
4551 auto &SM = Context.getSourceManager();
4552 if (NoSanitizeL.containsMainFile(
4553 Kind, SM.getFileEntryRefForID(SM.getMainFileID())->getName(),
4556 if (NoSanitizeL.containsLocation(Kind, Loc, Category))
4563 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
4564 Ty = AT->getElementType();
4569 if (NoSanitizeL.containsType(Kind, TypeStr, Category))
4577 StringRef Category)
const {
4580 auto Attr = ImbueAttr::NONE;
4582 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
4583 if (
Attr == ImbueAttr::NONE)
4584 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
4586 case ImbueAttr::NONE:
4588 case ImbueAttr::ALWAYS:
4589 Fn->addFnAttr(
"function-instrument",
"xray-always");
4591 case ImbueAttr::ALWAYS_ARG1:
4592 Fn->addFnAttr(
"function-instrument",
"xray-always");
4593 Fn->addFnAttr(
"xray-log-args",
"1");
4595 case ImbueAttr::NEVER:
4596 Fn->addFnAttr(
"function-instrument",
"xray-never");
4609 llvm::driver::ProfileInstrKind Kind =
getCodeGenOpts().getProfileInstr();
4619 auto &SM = Context.getSourceManager();
4620 if (
auto MainFile = SM.getFileEntryRefForID(SM.getMainFileID()))
4634 if (NumGroups > 1) {
4635 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
4644 if (LangOpts.EmitAllDecls)
4647 const auto *VD = dyn_cast<VarDecl>(
Global);
4649 ((CodeGenOpts.KeepPersistentStorageVariables &&
4650 (VD->getStorageDuration() ==
SD_Static ||
4651 VD->getStorageDuration() ==
SD_Thread)) ||
4652 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
4653 VD->getType().isConstQualified())))
4656 if (CodeGenOpts.KeepInlineFunctions)
4657 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global))
4678 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
4679 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
4680 OMPDeclareTargetDeclAttr::getActiveAttr(
Global);
4681 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (
unsigned)-1)
4685 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
4695 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>())
4702 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
4703 if (Context.getInlineVariableDefinitionKind(VD) ==
4708 if (CXX20ModuleInits && VD->getOwningModule() &&
4709 !VD->getOwningModule()->isModuleMapModule()) {
4718 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
4721 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
Global))
4734 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
4738 llvm::Constant *
Init;
4741 if (!
V.isAbsent()) {
4752 llvm::Constant *Fields[4] = {
4756 llvm::ConstantDataArray::getRaw(
4757 StringRef(
reinterpret_cast<char *
>(Parts.
Part4And5), 8), 8,
4759 Init = llvm::ConstantStruct::getAnon(Fields);
4762 auto *GV =
new llvm::GlobalVariable(
4764 true, llvm::GlobalValue::LinkOnceODRLinkage,
Init, Name);
4766 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4769 if (!
V.isAbsent()) {
4782 llvm::GlobalVariable **Entry =
nullptr;
4783 Entry = &UnnamedGlobalConstantDeclMap[GCD];
4788 llvm::Constant *
Init;
4792 assert(!
V.isAbsent());
4796 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
4798 llvm::GlobalValue::PrivateLinkage,
Init,
4800 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4815 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
4819 llvm::Constant *
Init =
Emitter.emitForInitializer(
4827 llvm::GlobalValue::LinkageTypes
Linkage =
4829 ? llvm::GlobalValue::LinkOnceODRLinkage
4830 : llvm::GlobalValue::InternalLinkage;
4831 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
4835 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4842 const AliasAttr *AA = VD->
getAttr<AliasAttr>();
4843 assert(AA &&
"No alias?");
4853 llvm::Constant *Aliasee;
4855 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
4863 F->setLinkage(llvm::Function::ExternalWeakLinkage);
4864 WeakRefReferences.insert(F);
4872 if (!LangOpts.OpenMPIsTargetDevice && !LangOpts.CUDA)
4875 const auto *AA =
Global->getAttr<AliasAttr>();
4883 const auto *AliaseeDecl = dyn_cast<ValueDecl>(AliaseeGD.getDecl());
4884 if (LangOpts.OpenMPIsTargetDevice)
4885 return !AliaseeDecl ||
4886 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(AliaseeDecl);
4889 const bool HasDeviceAttr =
Global->hasAttr<CUDADeviceAttr>();
4890 const bool AliaseeHasDeviceAttr =
4891 AliaseeDecl && AliaseeDecl->hasAttr<CUDADeviceAttr>();
4893 if (LangOpts.CUDAIsDevice)
4894 return !HasDeviceAttr || !AliaseeHasDeviceAttr;
4905 if (
Global->hasAttr<WeakRefAttr>())
4910 if (
Global->hasAttr<AliasAttr>()) {
4913 return EmitAliasDefinition(GD);
4917 if (
Global->hasAttr<IFuncAttr>())
4918 return emitIFuncDefinition(GD);
4921 if (
Global->hasAttr<CPUDispatchAttr>())
4922 return emitCPUDispatchDefinition(GD);
4928 if (LangOpts.OpenMP) {
4930 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
4932 if (
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(
Global)) {
4933 if (MustBeEmitted(
Global))
4937 if (
auto *DMD = dyn_cast<OMPDeclareMapperDecl>(
Global)) {
4938 if (MustBeEmitted(
Global))
4945 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
4946 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
4952 if (FD->
hasAttr<AnnotateAttr>()) {
4955 DeferredAnnotations[MangledName.str()] = FD;
4970 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
4976 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
4978 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
4979 if (LangOpts.OpenMP) {
4981 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
4982 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
4986 if (VD->hasExternalStorage() &&
4987 Res != OMPDeclareTargetDeclAttr::MT_Link)
4990 bool UnifiedMemoryEnabled =
4992 if (*Res == OMPDeclareTargetDeclAttr::MT_Local ||
4993 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4994 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4995 !UnifiedMemoryEnabled)) {
4998 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
4999 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
5000 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
5001 UnifiedMemoryEnabled)) &&
5002 "Link clause or to clause with unified memory expected.");
5012 if (LangOpts.HLSL) {
5013 if (VD->getStorageClass() ==
SC_Extern) {
5022 if (Context.getInlineVariableDefinitionKind(VD) ==
5032 if (MustBeEmitted(
Global) && MayBeEmittedEagerly(
Global)) {
5034 EmitGlobalDefinition(GD);
5035 addEmittedDeferredDecl(GD);
5043 DelayedCXXInitPosition[
Global] = CXXGlobalInits.size();
5044 CXXGlobalInits.push_back(
nullptr);
5050 addDeferredDeclToEmit(GD);
5051 }
else if (MustBeEmitted(
Global)) {
5053 assert(!MayBeEmittedEagerly(
Global));
5054 addDeferredDeclToEmit(GD);
5059 DeferredDecls[MangledName] = GD;
5065 if (
const auto *RT =
5066 T->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
5067 if (
auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
5068 RD = RD->getDefinitionOrSelf();
5069 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
5078struct DLLImportFunctionVisitor
5079 :
public RecursiveASTVisitor<DLLImportFunctionVisitor> {
5080 bool SafeToInline =
true;
5082 bool shouldVisitImplicitCode()
const {
return true; }
5084 bool VisitVarDecl(VarDecl *VD) {
5087 SafeToInline =
false;
5088 return SafeToInline;
5095 return SafeToInline;
5098 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
5100 SafeToInline = D->
hasAttr<DLLImportAttr>();
5101 return SafeToInline;
5104 bool VisitDeclRefExpr(DeclRefExpr *E) {
5107 SafeToInline = VD->
hasAttr<DLLImportAttr>();
5108 else if (VarDecl *
V = dyn_cast<VarDecl>(VD))
5109 SafeToInline = !
V->hasGlobalStorage() ||
V->hasAttr<DLLImportAttr>();
5110 return SafeToInline;
5113 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
5115 return SafeToInline;
5118 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
5122 SafeToInline =
true;
5124 SafeToInline = M->
hasAttr<DLLImportAttr>();
5126 return SafeToInline;
5129 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
5131 return SafeToInline;
5134 bool VisitCXXNewExpr(CXXNewExpr *E) {
5136 return SafeToInline;
5141bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
5148 if (F->isInlineBuiltinDeclaration())
5151 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
5156 if (
const Module *M = F->getOwningModule();
5157 M && M->getTopLevelModule()->isNamedModule() &&
5158 getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
5168 if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
5173 if (F->hasAttr<NoInlineAttr>())
5176 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
5178 DLLImportFunctionVisitor Visitor;
5179 Visitor.TraverseFunctionDecl(
const_cast<FunctionDecl*
>(F));
5180 if (!Visitor.SafeToInline)
5183 if (
const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
5190 for (
const CXXBaseSpecifier &B :
Dtor->getParent()->bases())
5204bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
5205 return CodeGenOpts.OptimizationLevel > 0;
5208void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
5209 llvm::GlobalValue *GV) {
5213 auto *Spec = FD->
getAttr<CPUSpecificAttr>();
5214 for (
unsigned I = 0; I < Spec->cpus_size(); ++I)
5216 }
else if (
auto *TC = FD->
getAttr<TargetClonesAttr>()) {
5217 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I)
5218 if (TC->isFirstOfVersion(I))
5221 EmitGlobalFunctionDefinition(GD, GV);
5227 AddDeferredMultiVersionResolverToEmit(GD);
5229 GetOrCreateMultiVersionResolver(GD);
5233void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
5236 PrettyStackTraceDecl CrashInfo(
const_cast<ValueDecl *
>(D), D->
getLocation(),
5237 Context.getSourceManager(),
5238 "Generating code for declaration");
5240 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
5243 if (!shouldEmitFunction(GD))
5246 llvm::TimeTraceScope TimeScope(
"CodeGen Function", [&]() {
5248 llvm::raw_string_ostream
OS(Name);
5254 if (
const auto *
Method = dyn_cast<CXXMethodDecl>(D)) {
5258 ABI->emitCXXStructor(GD);
5260 EmitMultiVersionFunctionDefinition(GD, GV);
5262 EmitGlobalFunctionDefinition(GD, GV);
5271 return EmitMultiVersionFunctionDefinition(GD, GV);
5272 return EmitGlobalFunctionDefinition(GD, GV);
5275 if (
const auto *VD = dyn_cast<VarDecl>(D))
5276 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
5278 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
5282 llvm::Function *NewFn);
5298static llvm::GlobalValue::LinkageTypes
5302 return llvm::GlobalValue::InternalLinkage;
5303 return llvm::GlobalValue::WeakODRLinkage;
5306void CodeGenModule::emitMultiVersionFunctions() {
5307 std::vector<GlobalDecl> MVFuncsToEmit;
5308 MultiVersionFuncs.swap(MVFuncsToEmit);
5309 for (GlobalDecl GD : MVFuncsToEmit) {
5311 assert(FD &&
"Expected a FunctionDecl");
5313 auto createFunction = [&](
const FunctionDecl *
Decl,
unsigned MVIdx = 0) {
5314 GlobalDecl CurGD{
Decl->isDefined() ?
Decl->getDefinition() :
Decl, MVIdx};
5318 if (
Decl->isDefined()) {
5319 EmitGlobalFunctionDefinition(CurGD,
nullptr);
5327 assert(
Func &&
"This should have just been created");
5335 bool ShouldEmitResolver = !
getTriple().isAArch64();
5336 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
5337 llvm::DenseMap<llvm::Function *, const FunctionDecl *> DeclMap;
5340 FD, [&](
const FunctionDecl *CurFD) {
5341 llvm::SmallVector<StringRef, 8> Feats;
5344 if (
const auto *TA = CurFD->
getAttr<TargetAttr>()) {
5346 TA->getX86AddedFeatures(Feats);
5347 llvm::Function *
Func = createFunction(CurFD);
5348 DeclMap.insert({
Func, CurFD});
5349 Options.emplace_back(
Func, Feats, TA->getX86Architecture());
5350 }
else if (
const auto *TVA = CurFD->
getAttr<TargetVersionAttr>()) {
5351 if (TVA->isDefaultVersion() && IsDefined)
5352 ShouldEmitResolver =
true;
5353 llvm::Function *
Func = createFunction(CurFD);
5354 DeclMap.insert({
Func, CurFD});
5356 TVA->getFeatures(Feats, Delim);
5357 Options.emplace_back(
Func, Feats);
5358 }
else if (
const auto *TC = CurFD->
getAttr<TargetClonesAttr>()) {
5359 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
5360 if (!TC->isFirstOfVersion(I))
5362 if (TC->isDefaultVersion(I) && IsDefined)
5363 ShouldEmitResolver =
true;
5364 llvm::Function *
Func = createFunction(CurFD, I);
5365 DeclMap.insert({
Func, CurFD});
5368 TC->getX86Feature(Feats, I);
5369 Options.emplace_back(
Func, Feats, TC->getX86Architecture(I));
5372 TC->getFeatures(Feats, I, Delim);
5373 Options.emplace_back(
Func, Feats);
5377 llvm_unreachable(
"unexpected MultiVersionKind");
5380 if (!ShouldEmitResolver)
5383 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
5384 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
5385 ResolverConstant = IFunc->getResolver();
5390 *
this, GD, FD,
true);
5397 auto *Alias = llvm::GlobalAlias::create(
5399 MangledName +
".ifunc", IFunc, &
getModule());
5408 Options, [&TI](
const CodeGenFunction::FMVResolverOption &LHS,
5409 const CodeGenFunction::FMVResolverOption &RHS) {
5415 for (
auto I = Options.begin() + 1, E = Options.end(); I != E; ++I) {
5416 llvm::APInt RHS = llvm::AArch64::getCpuSupportsMask(I->Features);
5417 if (std::any_of(Options.begin(), I, [RHS](
auto RO) {
5418 llvm::APInt LHS = llvm::AArch64::getCpuSupportsMask(RO.Features);
5419 return LHS.isSubsetOf(RHS);
5421 Diags.Report(DeclMap[I->Function]->getLocation(),
5422 diag::warn_unreachable_version)
5423 << I->Function->getName();
5424 assert(I->Function->user_empty() &&
"unexpected users");
5425 I->Function->eraseFromParent();
5426 I->Function =
nullptr;
5430 CodeGenFunction CGF(*
this);
5431 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
5433 setMultiVersionResolverAttributes(ResolverFunc, GD);
5435 ResolverFunc->setComdat(
5436 getModule().getOrInsertComdat(ResolverFunc->getName()));
5442 if (!MVFuncsToEmit.empty())
5447 if (!MultiVersionFuncs.empty())
5448 emitMultiVersionFunctions();
5458 llvm::GlobalValue *DS = TheModule.getNamedValue(DSName);
5460 DS =
new llvm::GlobalVariable(TheModule,
Int8Ty,
false,
5461 llvm::GlobalVariable::ExternalWeakLinkage,
5463 DS->setVisibility(llvm::GlobalValue::HiddenVisibility);
5468void CodeGenModule::emitPFPFieldsWithEvaluatedOffset() {
5469 llvm::Constant *Nop = llvm::ConstantExpr::getIntToPtr(
5471 for (
auto *FD :
getContext().PFPFieldsWithEvaluatedOffset) {
5473 llvm::GlobalValue *OldDS = TheModule.getNamedValue(DSName);
5474 llvm::GlobalValue *DS = llvm::GlobalAlias::create(
5475 Int8Ty, 0, llvm::GlobalValue::ExternalLinkage, DSName, Nop, &TheModule);
5476 DS->setVisibility(llvm::GlobalValue::HiddenVisibility);
5478 DS->takeName(OldDS);
5479 OldDS->replaceAllUsesWith(DS);
5480 OldDS->eraseFromParent();
5486 llvm::Constant *
New) {
5489 Old->replaceAllUsesWith(
New);
5490 Old->eraseFromParent();
5493void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
5495 assert(FD &&
"Not a FunctionDecl?");
5497 const auto *DD = FD->
getAttr<CPUDispatchAttr>();
5498 assert(DD &&
"Not a cpu_dispatch Function?");
5504 UpdateMultiVersionNames(GD, FD, ResolverName);
5506 llvm::Type *ResolverType;
5507 GlobalDecl ResolverGD;
5509 ResolverType = llvm::FunctionType::get(
5515 ResolverType = DeclTy;
5520 ResolverName, ResolverType, ResolverGD,
false));
5523 ResolverFunc->setComdat(
5524 getModule().getOrInsertComdat(ResolverFunc->getName()));
5526 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
5529 for (
const IdentifierInfo *II : DD->cpus()) {
5537 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
5540 EmitGlobalFunctionDefinition(ExistingDecl,
nullptr);
5546 Func = GetOrCreateLLVMFunction(
5547 MangledName, DeclTy, ExistingDecl,
5553 llvm::SmallVector<StringRef, 32> Features;
5554 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
5555 llvm::transform(Features, Features.begin(),
5556 [](StringRef Str) { return Str.substr(1); });
5557 llvm::erase_if(Features, [&Target](StringRef Feat) {
5558 return !Target.validateCpuSupports(Feat);
5564 llvm::stable_sort(Options, [](
const CodeGenFunction::FMVResolverOption &LHS,
5565 const CodeGenFunction::FMVResolverOption &RHS) {
5566 return llvm::X86::getCpuSupportsMask(LHS.
Features) >
5567 llvm::X86::getCpuSupportsMask(RHS.
Features);
5574 while (Options.size() > 1 && llvm::all_of(llvm::X86::getCpuSupportsMask(
5575 (Options.end() - 2)->Features),
5576 [](
auto X) { return X == 0; })) {
5577 StringRef LHSName = (Options.end() - 2)->Function->getName();
5578 StringRef RHSName = (Options.end() - 1)->Function->getName();
5579 if (LHSName.compare(RHSName) < 0)
5580 Options.erase(Options.end() - 2);
5582 Options.erase(Options.end() - 1);
5585 CodeGenFunction CGF(*
this);
5586 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
5587 setMultiVersionResolverAttributes(ResolverFunc, GD);
5592 unsigned AS = IFunc->getType()->getPointerAddressSpace();
5597 auto *GI = llvm::GlobalIFunc::create(DeclTy, AS,
Linkage,
"",
5603 std::string AliasName =
5607 auto *GA = llvm::GlobalAlias::create(DeclTy, AS,
Linkage, AliasName,
5615void CodeGenModule::AddDeferredMultiVersionResolverToEmit(GlobalDecl GD) {
5617 assert(FD &&
"Not a FunctionDecl?");
5620 std::string MangledName =
5622 if (!DeferredResolversToEmit.insert(MangledName).second)
5625 MultiVersionFuncs.push_back(GD);
5631llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
5633 assert(FD &&
"Not a FunctionDecl?");
5635 std::string MangledName =
5640 std::string ResolverName = MangledName;
5644 llvm_unreachable(
"unexpected MultiVersionKind::None for resolver");
5648 ResolverName +=
".ifunc";
5655 ResolverName +=
".resolver";
5658 bool ShouldReturnIFunc =
5677 AddDeferredMultiVersionResolverToEmit(GD);
5681 if (ShouldReturnIFunc) {
5683 llvm::Type *ResolverType = llvm::FunctionType::get(
5685 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
5686 MangledName +
".resolver", ResolverType, GlobalDecl{},
5694 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(DeclTy, AS,
Linkage,
"",
5696 GIF->setName(ResolverName);
5703 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
5704 ResolverName, DeclTy, GlobalDecl{},
false);
5706 "Resolver should be created for the first time");
5711void CodeGenModule::setMultiVersionResolverAttributes(llvm::Function *Resolver,
5713 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(GD.
getDecl());
5726 Resolver->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
5737bool CodeGenModule::shouldDropDLLAttribute(
const Decl *D,
5738 const llvm::GlobalValue *GV)
const {
5739 auto SC = GV->getDLLStorageClass();
5740 if (SC == llvm::GlobalValue::DefaultStorageClass)
5743 return (((SC == llvm::GlobalValue::DLLImportStorageClass &&
5744 !MRD->
hasAttr<DLLImportAttr>()) ||
5745 (SC == llvm::GlobalValue::DLLExportStorageClass &&
5746 !MRD->
hasAttr<DLLExportAttr>())) &&
5757llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
5758 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD,
bool ForVTable,
5759 bool DontDefer,
bool IsThunk, llvm::AttributeList ExtraAttrs,
5763 std::string NameWithoutMultiVersionMangling;
5764 if (
const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
5766 if (
getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
5767 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->
isDefined() &&
5768 !DontDefer && !IsForDefinition) {
5771 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
5773 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
5776 GDDef = GlobalDecl(FDDef);
5784 UpdateMultiVersionNames(GD, FD, MangledName);
5785 if (!IsForDefinition) {
5791 AddDeferredMultiVersionResolverToEmit(GD);
5793 *
this, GD, FD,
true);
5802 *
this, GD, FD,
true);
5804 return GetOrCreateMultiVersionResolver(GD);
5809 if (!NameWithoutMultiVersionMangling.empty())
5810 MangledName = NameWithoutMultiVersionMangling;
5815 if (WeakRefReferences.erase(Entry)) {
5816 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
5817 if (FD && !FD->
hasAttr<WeakAttr>())
5818 Entry->setLinkage(llvm::Function::ExternalLinkage);
5822 if (D && shouldDropDLLAttribute(D, Entry)) {
5823 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5829 if (IsForDefinition && !Entry->isDeclaration()) {
5836 DiagnosedConflictingDefinitions.insert(GD).second) {
5840 diag::note_previous_definition);
5845 (Entry->getValueType() == Ty)) {
5852 if (!IsForDefinition)
5859 bool IsIncompleteFunction =
false;
5861 llvm::FunctionType *FTy;
5865 FTy = llvm::FunctionType::get(
VoidTy,
false);
5866 IsIncompleteFunction =
true;
5870 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
5871 Entry ? StringRef() : MangledName, &
getModule());
5875 if (D && D->
hasAttr<AnnotateAttr>())
5893 if (!Entry->use_empty()) {
5895 Entry->removeDeadConstantUsers();
5901 assert(F->getName() == MangledName &&
"name was uniqued!");
5903 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
5904 if (ExtraAttrs.hasFnAttrs()) {
5905 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
5913 if (isa_and_nonnull<CXXDestructorDecl>(D) &&
5916 addDeferredDeclToEmit(GD);
5921 auto DDI = DeferredDecls.find(MangledName);
5922 if (DDI != DeferredDecls.end()) {
5926 addDeferredDeclToEmit(DDI->second);
5927 DeferredDecls.erase(DDI);
5955 if (!IsIncompleteFunction) {
5956 assert(F->getFunctionType() == Ty);
5974 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
5984 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(GD.
getDecl())) {
5987 DD->getParent()->getNumVBases() == 0)
5992 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
5993 false, llvm::AttributeList(),
5996 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
6000 if (IsForDefinition)
6008 llvm::GlobalValue *F =
6011 return llvm::NoCFIValue::get(F);
6021 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
6024 if (!
C.getLangOpts().CPlusPlus)
6029 (Name ==
"_ZSt9terminatev" || Name ==
"?terminate@@YAXXZ")
6030 ?
C.Idents.get(
"terminate")
6031 :
C.Idents.get(Name);
6033 for (
const auto &N : {
"__cxxabiv1",
"std"}) {
6037 if (
auto *LSD = dyn_cast<LinkageSpecDecl>(
Result))
6038 for (
const auto *
Result : LSD->lookup(&NS))
6039 if ((ND = dyn_cast<NamespaceDecl>(
Result)))
6044 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
6053 llvm::Function *F, StringRef Name) {
6062 if (!FD || FD->
hasAttr<DLLImportAttr>()) {
6063 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
6064 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
6071 llvm::AttributeList ExtraAttrs,
bool Local,
bool AssumeConvergent) {
6072 if (AssumeConvergent) {
6074 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
6077 QualType FTy = Context.getFunctionType(ReturnTy, ArgTys,
6082 llvm::Constant *
C = GetOrCreateLLVMFunction(
6084 false,
false, ExtraAttrs);
6086 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
6102 llvm::AttributeList ExtraAttrs,
bool Local,
6103 bool AssumeConvergent) {
6104 if (AssumeConvergent) {
6106 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
6110 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
6114 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
6123 markRegisterParameterAttributes(F);
6149 if (WeakRefReferences.erase(Entry)) {
6150 if (D && !D->
hasAttr<WeakAttr>())
6151 Entry->setLinkage(llvm::Function::ExternalLinkage);
6155 if (D && shouldDropDLLAttribute(D, Entry))
6156 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
6158 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
6161 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
6166 if (IsForDefinition && !Entry->isDeclaration()) {
6174 (OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
6176 DiagnosedConflictingDefinitions.insert(D).second) {
6180 diag::note_previous_definition);
6185 if (Entry->getType()->getAddressSpace() != TargetAS &&
6187 return llvm::ConstantExpr::getAddrSpaceCast(
6188 Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
6192 if (!IsForDefinition)
6198 auto *GV =
new llvm::GlobalVariable(
6199 getModule(), Ty,
false, llvm::GlobalValue::ExternalLinkage,
nullptr,
6200 MangledName,
nullptr, llvm::GlobalVariable::NotThreadLocal,
6201 getContext().getTargetAddressSpace(DAddrSpace));
6206 GV->takeName(Entry);
6208 if (!Entry->use_empty()) {
6209 Entry->replaceAllUsesWith(GV);
6212 Entry->eraseFromParent();
6218 auto DDI = DeferredDecls.find(MangledName);
6219 if (DDI != DeferredDecls.end()) {
6222 addDeferredDeclToEmit(DDI->second);
6223 DeferredDecls.erase(DDI);
6228 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
6235 GV->setAlignment(
getContext().getDeclAlign(D).getAsAlign());
6241 CXXThreadLocals.push_back(D);
6249 if (
getContext().isMSStaticDataMemberInlineDefinition(D)) {
6250 EmitGlobalVarDefinition(D);
6255 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>())
6256 GV->setSection(SA->getName());
6260 if (
getTriple().getArch() == llvm::Triple::xcore &&
6264 GV->setSection(
".cp.rodata");
6267 if (
const auto *CMA = D->
getAttr<CodeModelAttr>())
6268 GV->setCodeModel(CMA->getModel());
6273 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
6277 Context.getBaseElementType(D->
getType())->getAsCXXRecordDecl();
6278 bool HasMutableFields =
Record &&
Record->hasMutableFields();
6279 if (!HasMutableFields) {
6286 auto *InitType =
Init->getType();
6287 if (GV->getValueType() != InitType) {
6292 GV->setName(StringRef());
6297 ->stripPointerCasts());
6300 GV->eraseFromParent();
6303 GV->setInitializer(
Init);
6304 GV->setConstant(
true);
6305 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
6325 SanitizerMD->reportGlobal(GV, *D);
6330 assert(
getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
6344 false, IsForDefinition);
6365 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes
Linkage,
6366 llvm::Align Alignment) {
6367 llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
6368 llvm::GlobalVariable *OldGV =
nullptr;
6372 if (GV->getValueType() == Ty)
6377 assert(GV->isDeclaration() &&
"Declaration has wrong type!");
6382 GV =
new llvm::GlobalVariable(
getModule(), Ty,
true,
6387 GV->takeName(OldGV);
6389 if (!OldGV->use_empty()) {
6390 OldGV->replaceAllUsesWith(GV);
6393 OldGV->eraseFromParent();
6397 !GV->hasAvailableExternallyLinkage())
6398 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
6400 GV->setAlignment(Alignment);
6437 assert(!D->
getInit() &&
"Cannot emit definite definitions here!");
6445 if (GV && !GV->isDeclaration())
6450 if (!MustBeEmitted(D) && !GV) {
6451 DeferredDecls[MangledName] = D;
6456 EmitGlobalVarDefinition(D);
6461 if (
auto const *CD = dyn_cast<const CXXConstructorDecl>(D))
6463 else if (
auto const *DD = dyn_cast<const CXXDestructorDecl>(D))
6478 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(
Addr)) {
6482 if (
const auto *VD = dyn_cast<VarDecl>(D)) {
6485 }
else if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
6487 if (!Fn->getSubprogram())
6493 return Context.toCharUnitsFromBits(
6498 if (LangOpts.OpenCL) {
6509 if (LangOpts.SYCLIsDevice &&
6513 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
6518 if (D->
hasAttr<CUDAConstantAttr>())
6520 if (D->
hasAttr<CUDASharedAttr>())
6522 if (D->
hasAttr<CUDADeviceAttr>())
6530 if (LangOpts.OpenMP) {
6532 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
6550static llvm::Constant *
6552 llvm::GlobalVariable *GV) {
6553 llvm::Constant *Cast = GV;
6558 GV, llvm::PointerType::get(
6565template<
typename SomeDecl>
6567 llvm::GlobalValue *GV) {
6582 const SomeDecl *
First = D->getFirstDecl();
6583 if (
First->getDeclContext()->isRecord() || !
First->isInExternCContext())
6589 std::pair<StaticExternCMap::iterator, bool> R =
6590 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
6595 R.first->second =
nullptr;
6603 llvm::GlobalObject &GO) {
6606 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
6614void CodeGenModule::EmitGlobalVarDefinition(
const VarDecl *D,
6636 if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
6637 OpenMPRuntime->emitTargetGlobalVariable(D))
6640 llvm::TrackingVH<llvm::Constant>
Init;
6641 bool NeedsGlobalCtor =
false;
6645 bool IsDefinitionAvailableExternally =
6647 bool NeedsGlobalDtor =
6648 !IsDefinitionAvailableExternally &&
6655 if (IsDefinitionAvailableExternally &&
6666 std::optional<ConstantEmitter> emitter;
6671 bool IsCUDASharedVar =
6676 bool IsCUDAShadowVar =
6678 (D->
hasAttr<CUDAConstantAttr>() || D->
hasAttr<CUDADeviceAttr>() ||
6679 D->
hasAttr<CUDASharedAttr>());
6680 bool IsCUDADeviceShadowVar =
6685 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) {
6686 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
6690 Init = llvm::PoisonValue::get(
getTypes().ConvertType(ASTTy));
6693 }
else if (D->
hasAttr<LoaderUninitializedAttr>()) {
6694 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
6695 }
else if (!InitExpr) {
6708 initializedGlobalDecl = GlobalDecl(D);
6709 emitter.emplace(*
this);
6710 llvm::Constant *
Initializer = emitter->tryEmitForInitializer(*InitDecl);
6718 if (!IsDefinitionAvailableExternally)
6719 NeedsGlobalCtor =
true;
6723 NeedsGlobalCtor =
false;
6735 DelayedCXXInitPosition.erase(D);
6742 assert(VarSize == CstSize &&
"Emitted constant has unexpected size");
6747 llvm::Type* InitType =
Init->getType();
6748 llvm::Constant *Entry =
6752 Entry = Entry->stripPointerCasts();
6755 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
6766 if (!GV || GV->getValueType() != InitType ||
6767 GV->getType()->getAddressSpace() !=
6771 Entry->setName(StringRef());
6776 ->stripPointerCasts());
6779 llvm::Constant *NewPtrForOldDecl =
6780 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
6782 Entry->replaceAllUsesWith(NewPtrForOldDecl);
6790 if (D->
hasAttr<AnnotateAttr>())
6803 if (LangOpts.CUDA) {
6804 if (LangOpts.CUDAIsDevice) {
6807 (D->
hasAttr<CUDADeviceAttr>() || D->
hasAttr<CUDAConstantAttr>() ||
6810 GV->setExternallyInitialized(
true);
6817 if (LangOpts.HLSL &&
6822 GV->setExternallyInitialized(
true);
6824 GV->setInitializer(
Init);
6831 emitter->finalize(GV);
6834 GV->setConstant((D->
hasAttr<CUDAConstantAttr>() && LangOpts.CUDAIsDevice) ||
6835 (!NeedsGlobalCtor && !NeedsGlobalDtor &&
6839 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>()) {
6840 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
6842 GV->setConstant(
true);
6847 if (std::optional<CharUnits> AlignValFromAllocate =
6849 AlignVal = *AlignValFromAllocate;
6867 Linkage == llvm::GlobalValue::ExternalLinkage &&
6868 Context.getTargetInfo().getTriple().isOSDarwin() &&
6870 Linkage = llvm::GlobalValue::InternalLinkage;
6875 if (LangOpts.HLSL &&
6877 Linkage = llvm::GlobalValue::ExternalLinkage;
6880 if (D->
hasAttr<DLLImportAttr>())
6881 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
6882 else if (D->
hasAttr<DLLExportAttr>())
6883 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
6885 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6887 if (
Linkage == llvm::GlobalVariable::CommonLinkage) {
6889 GV->setConstant(
false);
6894 if (!GV->getInitializer()->isNullValue())
6895 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
6898 setNonAliasAttributes(D, GV);
6900 if (D->
getTLSKind() && !GV->isThreadLocal()) {
6902 CXXThreadLocals.push_back(D);
6909 if (NeedsGlobalCtor || NeedsGlobalDtor)
6910 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
6912 SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
6917 DI->EmitGlobalVariable(GV, D);
6920llvm::GlobalValue::LinkageTypes
6924 return llvm::Function::InternalLinkage;
6927 return llvm::GlobalVariable::WeakAnyLinkage;
6931 return llvm::GlobalVariable::LinkOnceAnyLinkage;
6936 return llvm::GlobalValue::AvailableExternallyLinkage;
6950 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
6951 : llvm::Function::InternalLinkage;
6965 return llvm::Function::ExternalLinkage;
6968 return D->
hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
6969 : llvm::Function::InternalLinkage;
6970 return llvm::Function::WeakODRLinkage;
6977 CodeGenOpts.NoCommon))
6978 return llvm::GlobalVariable::CommonLinkage;
6984 if (D->
hasAttr<SelectAnyAttr>())
6985 return llvm::GlobalVariable::WeakODRLinkage;
6989 return llvm::GlobalVariable::ExternalLinkage;
6992llvm::GlobalValue::LinkageTypes
7001 llvm::Function *newFn) {
7003 if (old->use_empty())
7006 llvm::Type *newRetTy = newFn->getReturnType();
7011 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
7013 llvm::User *user = ui->getUser();
7017 if (
auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
7018 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
7024 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
7027 if (!callSite->isCallee(&*ui))
7032 if (callSite->getType() != newRetTy && !callSite->use_empty())
7037 llvm::AttributeList oldAttrs = callSite->getAttributes();
7040 unsigned newNumArgs = newFn->arg_size();
7041 if (callSite->arg_size() < newNumArgs)
7047 bool dontTransform =
false;
7048 for (llvm::Argument &A : newFn->args()) {
7049 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
7050 dontTransform =
true;
7055 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
7063 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
7067 callSite->getOperandBundlesAsDefs(newBundles);
7069 llvm::CallBase *newCall;
7071 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles,
"",
7072 callSite->getIterator());
7075 newCall = llvm::InvokeInst::Create(
7076 newFn, oldInvoke->getNormalDest(), oldInvoke->getUnwindDest(),
7077 newArgs, newBundles,
"", callSite->getIterator());
7081 if (!newCall->getType()->isVoidTy())
7082 newCall->takeName(callSite);
7083 newCall->setAttributes(
7084 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
7085 oldAttrs.getRetAttrs(), newArgAttrs));
7086 newCall->setCallingConv(callSite->getCallingConv());
7089 if (!callSite->use_empty())
7090 callSite->replaceAllUsesWith(newCall);
7093 if (callSite->getDebugLoc())
7094 newCall->setDebugLoc(callSite->getDebugLoc());
7096 callSitesToBeRemovedFromParent.push_back(callSite);
7099 for (
auto *callSite : callSitesToBeRemovedFromParent) {
7100 callSite->eraseFromParent();
7114 llvm::Function *NewFn) {
7124 (LangOpts.CUDA && !
getContext().shouldEmitCUDADecl(VD)))
7136void CodeGenModule::EmitGlobalFunctionDefinition(
GlobalDecl GD,
7137 llvm::GlobalValue *GV) {
7145 if (!GV || (GV->getValueType() != Ty))
7151 if (!GV->isDeclaration())
7161 if (
getTriple().isOSAIX() && D->isTargetClonesMultiVersion())
7162 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
7174 setNonAliasAttributes(GD, Fn);
7176 bool ShouldAddOptNone = !CodeGenOpts.DisableO0ImplyOptNone &&
7177 (CodeGenOpts.OptimizationLevel == 0) &&
7180 if (DeviceKernelAttr::isOpenCLSpelling(D->
getAttr<DeviceKernelAttr>())) {
7182 !D->
hasAttr<NoInlineAttr>() &&
7183 !Fn->hasFnAttribute(llvm::Attribute::NoInline) &&
7184 !D->
hasAttr<OptimizeNoneAttr>() &&
7185 !Fn->hasFnAttribute(llvm::Attribute::OptimizeNone) &&
7186 !ShouldAddOptNone) {
7187 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
7197 auto UnwindMode = CodeGenOpts.getWinX64EHUnwind();
7198 if (UnwindMode != llvm::WinX64EHUnwindMode::Default &&
7199 UnwindMode != llvm::WinX64EHUnwindMode::V3 &&
7200 Fn->needsUnwindTableEntry()) {
7201 bool HasEGPR =
false;
7202 if (Fn->hasFnAttribute(
"target-features")) {
7204 Fn->getFnAttribute(
"target-features").getValueAsString();
7206 Feats.split(Tokens,
',', -1,
false);
7207 for (StringRef
Tok : Tokens) {
7210 else if (
Tok ==
"-egpr")
7214 HasEGPR = Context.getTargetInfo().hasFeature(
"egpr");
7217 unsigned DiagID = Diags.getCustomDiagID(
7219 "EGPR target feature requires unwind version 3");
7225 auto GetPriority = [
this](
const auto *Attr) ->
int {
7226 Expr *E = Attr->getPriority();
7230 return Attr->DefaultPriority;
7233 if (
const ConstructorAttr *CA = D->
getAttr<ConstructorAttr>())
7235 if (
const DestructorAttr *DA = D->
getAttr<DestructorAttr>())
7241void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
7243 const AliasAttr *AA = D->
getAttr<AliasAttr>();
7244 assert(AA &&
"Not an alias?");
7248 if (AA->getAliasee() == MangledName) {
7249 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
7256 if (Entry && !Entry->isDeclaration())
7259 Aliases.push_back(GD);
7265 llvm::Constant *Aliasee;
7266 llvm::GlobalValue::LinkageTypes
LT;
7268 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
7274 if (
const auto *VD = dyn_cast<VarDecl>(GD.
getDecl()))
7281 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
7283 llvm::GlobalAlias::create(DeclTy, AS, LT,
"", Aliasee, &
getModule());
7286 if (GA->getAliasee() == Entry) {
7287 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
7291 assert(Entry->isDeclaration());
7300 GA->takeName(Entry);
7302 Entry->replaceAllUsesWith(GA);
7303 Entry->eraseFromParent();
7305 GA->setName(MangledName);
7313 GA->setLinkage(llvm::Function::WeakAnyLinkage);
7316 if (
const auto *VD = dyn_cast<VarDecl>(D))
7317 if (VD->getTLSKind())
7328void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
7330 const IFuncAttr *IFA = D->
getAttr<IFuncAttr>();
7331 assert(IFA &&
"Not an ifunc?");
7335 if (IFA->getResolver() == MangledName) {
7336 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
7342 if (Entry && !Entry->isDeclaration()) {
7345 DiagnosedConflictingDefinitions.insert(GD).second) {
7346 Diags.Report(D->
getLocation(), diag::err_duplicate_mangled_name)
7349 diag::note_previous_definition);
7354 Aliases.push_back(GD);
7360 llvm::Constant *Resolver =
7361 GetOrCreateLLVMFunction(IFA->getResolver(),
VoidTy, {},
7365 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
7366 DeclTy, AS, llvm::Function::ExternalLinkage,
"", Resolver, &
getModule());
7368 if (GIF->getResolver() == Entry) {
7369 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
7372 assert(Entry->isDeclaration());
7381 GIF->takeName(Entry);
7383 Entry->replaceAllUsesWith(GIF);
7384 Entry->eraseFromParent();
7386 GIF->setName(MangledName);
7392 return llvm::Intrinsic::getOrInsertDeclaration(&
getModule(),
7393 (llvm::Intrinsic::ID)IID, Tys);
7396static llvm::StringMapEntry<llvm::GlobalVariable *> &
7399 bool &IsUTF16,
unsigned &StringLength) {
7400 StringRef String = Literal->getString();
7401 unsigned NumBytes = String.size();
7404 if (!Literal->containsNonAsciiOrNull()) {
7405 StringLength = NumBytes;
7406 return *Map.insert(std::make_pair(String,
nullptr)).first;
7413 const llvm::UTF8 *FromPtr = (
const llvm::UTF8 *)String.data();
7414 llvm::UTF16 *ToPtr = &ToBuf[0];
7416 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
7417 ToPtr + NumBytes, llvm::strictConversion);
7420 StringLength = ToPtr - &ToBuf[0];
7424 return *Map.insert(std::make_pair(
7425 StringRef(
reinterpret_cast<const char *
>(ToBuf.data()),
7426 (StringLength + 1) * 2),
7432 unsigned StringLength = 0;
7433 bool isUTF16 =
false;
7434 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
7439 if (
auto *
C = Entry.second)
7444 const llvm::Triple &Triple =
getTriple();
7447 const bool IsSwiftABI =
7448 static_cast<unsigned>(CFRuntime) >=
7453 if (!CFConstantStringClassRef) {
7454 const char *CFConstantStringClassName =
"__CFConstantStringClassReference";
7456 Ty = llvm::ArrayType::get(Ty, 0);
7458 switch (CFRuntime) {
7462 CFConstantStringClassName =
7463 Triple.isOSDarwin() ?
"$s15SwiftFoundation19_NSCFConstantStringCN"
7464 :
"$s10Foundation19_NSCFConstantStringCN";
7468 CFConstantStringClassName =
7469 Triple.isOSDarwin() ?
"$S15SwiftFoundation19_NSCFConstantStringCN"
7470 :
"$S10Foundation19_NSCFConstantStringCN";
7474 CFConstantStringClassName =
7475 Triple.isOSDarwin() ?
"__T015SwiftFoundation19_NSCFConstantStringCN"
7476 :
"__T010Foundation19_NSCFConstantStringCN";
7483 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
7484 llvm::GlobalValue *GV =
nullptr;
7486 if ((GV = dyn_cast<llvm::GlobalValue>(
C))) {
7493 if ((VD = dyn_cast<VarDecl>(
Result)))
7496 if (Triple.isOSBinFormatELF()) {
7498 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
7500 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
7501 if (!VD || !VD->
hasAttr<DLLExportAttr>())
7502 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
7504 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
7512 CFConstantStringClassRef =
7513 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(
C, Ty) :
C;
7516 QualType CFTy = Context.getCFConstantStringType();
7521 auto Fields = Builder.beginStruct(STy);
7530 Fields.addInt(
IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
7531 Fields.addInt(
Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
7533 Fields.addInt(
IntTy, isUTF16 ? 0x07d0 : 0x07C8);
7537 llvm::Constant *
C =
nullptr;
7540 reinterpret_cast<uint16_t *
>(
const_cast<char *
>(Entry.first().data())),
7541 Entry.first().size() / 2);
7542 C = llvm::ConstantDataArray::get(VMContext, Arr);
7544 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
7550 new llvm::GlobalVariable(
getModule(),
C->getType(),
true,
7551 llvm::GlobalValue::PrivateLinkage,
C,
".str");
7552 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
7555 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
7556 : Context.getTypeAlignInChars(Context.CharTy);
7562 if (Triple.isOSBinFormatMachO())
7563 GV->setSection(isUTF16 ?
"__TEXT,__ustring"
7564 :
"__TEXT,__cstring,cstring_literals");
7567 else if (Triple.isOSBinFormatELF())
7568 GV->setSection(
".rodata");
7574 llvm::IntegerType *LengthTy =
7584 Fields.addInt(LengthTy, StringLength);
7592 GV = Fields.finishAndCreateGlobal(
"_unnamed_cfstring_", Alignment,
7594 llvm::GlobalVariable::PrivateLinkage);
7595 GV->addAttribute(
"objc_arc_inert");
7596 switch (Triple.getObjectFormat()) {
7597 case llvm::Triple::UnknownObjectFormat:
7598 llvm_unreachable(
"unknown file format");
7599 case llvm::Triple::DXContainer:
7600 case llvm::Triple::GOFF:
7601 case llvm::Triple::SPIRV:
7602 case llvm::Triple::XCOFF:
7603 llvm_unreachable(
"unimplemented");
7604 case llvm::Triple::COFF:
7605 case llvm::Triple::ELF:
7606 case llvm::Triple::Wasm:
7607 GV->setSection(
"cfstring");
7609 case llvm::Triple::MachO:
7610 GV->setSection(
"__DATA,__cfstring");
7619 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
7623 if (ObjCFastEnumerationStateType.isNull()) {
7624 RecordDecl *D = Context.buildImplicitRecord(
"__objcFastEnumerationState");
7628 Context.UnsignedLongTy, Context.getPointerType(Context.getObjCIdType()),
7629 Context.getPointerType(Context.UnsignedLongTy),
7630 Context.getConstantArrayType(Context.UnsignedLongTy, llvm::APInt(32, 5),
7633 for (
size_t i = 0; i < 4; ++i) {
7638 FieldTypes[i],
nullptr,
7647 ObjCFastEnumerationStateType = Context.getCanonicalTagType(D);
7650 return ObjCFastEnumerationStateType;
7664 assert(CAT &&
"String literal not of constant array type!");
7666 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
7670 llvm::Type *ElemTy = AType->getElementType();
7671 unsigned NumElements = AType->getNumElements();
7674 if (ElemTy->getPrimitiveSizeInBits() == 16) {
7676 Elements.reserve(NumElements);
7678 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
7680 Elements.resize(NumElements);
7681 return llvm::ConstantDataArray::get(VMContext, Elements);
7684 assert(ElemTy->getPrimitiveSizeInBits() == 32);
7686 Elements.reserve(NumElements);
7688 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
7690 Elements.resize(NumElements);
7691 return llvm::ConstantDataArray::get(VMContext, Elements);
7694static llvm::GlobalVariable *
7703 auto *GV =
new llvm::GlobalVariable(
7704 M,
C->getType(), !CGM.
getLangOpts().WritableStrings, LT,
C, GlobalName,
7705 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
7707 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
7708 if (GV->isWeakForLinker()) {
7709 assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
7710 GV->setComdat(M.getOrInsertComdat(GV->getName()));
7726 llvm::GlobalVariable **Entry =
nullptr;
7727 if (!LangOpts.WritableStrings) {
7728 Entry = &ConstantStringMap[
C];
7729 if (
auto GV = *Entry) {
7730 if (Alignment.
getAsAlign() > GV->getAlign().valueOrOne())
7733 GV->getValueType(), Alignment);
7738 StringRef GlobalVariableName;
7739 llvm::GlobalValue::LinkageTypes LT;
7744 if (
getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
7745 !LangOpts.WritableStrings) {
7746 llvm::raw_svector_ostream Out(MangledNameBuffer);
7748 LT = llvm::GlobalValue::LinkOnceODRLinkage;
7749 GlobalVariableName = MangledNameBuffer;
7751 LT = llvm::GlobalValue::PrivateLinkage;
7752 GlobalVariableName = Name;
7764 SanitizerMD->reportGlobal(GV, S->
getStrTokenLoc(0),
"<string literal>");
7767 GV->getValueType(), Alignment);
7784 StringRef GlobalName) {
7785 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
7790 llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
7793 llvm::GlobalVariable **Entry =
nullptr;
7794 if (!LangOpts.WritableStrings) {
7795 Entry = &ConstantStringMap[
C];
7796 if (
auto GV = *Entry) {
7797 if (Alignment.
getAsAlign() > GV->getAlign().valueOrOne())
7800 GV->getValueType(), Alignment);
7806 GlobalName, Alignment);
7811 GV->getValueType(), Alignment);
7829 MaterializedType = E->
getType();
7833 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E,
nullptr});
7834 if (!InsertResult.second) {
7837 if (!InsertResult.first->second) {
7842 InsertResult.first->second =
new llvm::GlobalVariable(
7843 getModule(),
Type,
false, llvm::GlobalVariable::InternalLinkage,
7847 llvm::cast<llvm::GlobalVariable>(
7848 InsertResult.first->second->stripPointerCasts())
7857 llvm::raw_svector_ostream Out(Name);
7879 std::optional<ConstantEmitter> emitter;
7880 llvm::Constant *InitialValue =
nullptr;
7885 emitter.emplace(*
this);
7886 InitialValue = emitter->emitForInitializer(*
Value, AddrSpace,
7891 Type = InitialValue->getType();
7900 if (
Linkage == llvm::GlobalVariable::ExternalLinkage) {
7902 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
7906 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
7910 Linkage = llvm::GlobalVariable::InternalLinkage;
7914 auto *GV =
new llvm::GlobalVariable(
7916 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
7917 if (emitter) emitter->finalize(GV);
7919 if (!llvm::GlobalValue::isLocalLinkage(
Linkage)) {
7921 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
7923 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
7927 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
7928 if (VD->getTLSKind())
7930 llvm::Constant *CV = GV;
7933 GV, llvm::PointerType::get(
7939 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
7941 Entry->replaceAllUsesWith(CV);
7942 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
7951void CodeGenModule::EmitObjCPropertyImplementations(
const
7964 if (!Getter || Getter->isSynthesizedAccessorStub())
7967 auto *Setter = PID->getSetterMethodDecl();
7968 if (!PD->
isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
7979 if (ivar->getType().isDestructedType())
8000void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
8013 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod,
false);
8028 getContext().getObjCIdType(),
nullptr, D,
true,
8034 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod,
true);
8039void CodeGenModule::EmitLinkageSpec(
const LinkageSpecDecl *LSD) {
8046 EmitDeclContext(LSD);
8049void CodeGenModule::EmitTopLevelStmt(
const TopLevelStmtDecl *D) {
8051 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
8054 std::unique_ptr<CodeGenFunction> &CurCGF =
8055 GlobalTopLevelStmtBlockInFlight.first;
8059 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
8067 std::string Name =
"__stmts__" + llvm::utostr(CXXGlobalInits.size());
8068 FunctionArgList Args;
8070 const CGFunctionInfo &FnInfo =
8073 llvm::Function *
Fn = llvm::Function::Create(
8074 FnTy, llvm::GlobalValue::InternalLinkage, Name, &
getModule());
8076 CurCGF.reset(
new CodeGenFunction(*
this));
8077 GlobalTopLevelStmtBlockInFlight.second = D;
8078 CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
8080 CXXGlobalInits.push_back(Fn);
8083 CurCGF->EmitStmt(D->
getStmt());
8086void CodeGenModule::EmitDeclContext(
const DeclContext *DC) {
8087 for (
auto *I : DC->
decls()) {
8093 if (
auto *OID = dyn_cast<ObjCImplDecl>(I)) {
8094 for (
auto *M : OID->methods())
8113 case Decl::CXXConversion:
8114 case Decl::CXXMethod:
8115 case Decl::Function:
8122 case Decl::CXXDeductionGuide:
8127 case Decl::Decomposition:
8128 case Decl::VarTemplateSpecialization:
8130 if (
auto *DD = dyn_cast<DecompositionDecl>(D))
8131 for (
auto *B : DD->flat_bindings())
8132 if (
auto *HD = B->getHoldingVar())
8139 case Decl::IndirectField:
8143 case Decl::Namespace:
8146 case Decl::ClassTemplateSpecialization: {
8149 if (Spec->getSpecializationKind() ==
8151 Spec->hasDefinition())
8152 DI->completeTemplateDefinition(*Spec);
8154 case Decl::CXXRecord: {
8158 DI->EmitAndRetainType(
8162 DI->completeUnusedClass(*CRD);
8165 for (
auto *I : CRD->
decls())
8171 case Decl::UsingShadow:
8172 case Decl::ClassTemplate:
8173 case Decl::VarTemplate:
8175 case Decl::VarTemplatePartialSpecialization:
8176 case Decl::FunctionTemplate:
8177 case Decl::TypeAliasTemplate:
8186 case Decl::UsingEnum:
8190 case Decl::NamespaceAlias:
8194 case Decl::UsingDirective:
8198 case Decl::CXXConstructor:
8201 case Decl::CXXDestructor:
8205 case Decl::StaticAssert:
8206 case Decl::ExplicitInstantiation:
8213 case Decl::ObjCInterface:
8214 case Decl::ObjCCategory:
8217 case Decl::ObjCProtocol: {
8219 if (Proto->isThisDeclarationADefinition())
8220 ObjCRuntime->GenerateProtocol(Proto);
8224 case Decl::ObjCCategoryImpl:
8230 case Decl::ObjCImplementation: {
8232 EmitObjCPropertyImplementations(OMD);
8233 EmitObjCIvarInitializations(OMD);
8234 ObjCRuntime->GenerateClass(OMD);
8238 DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
8239 OMD->getClassInterface()), OMD->getLocation());
8242 case Decl::ObjCMethod: {
8249 case Decl::ObjCCompatibleAlias:
8253 case Decl::PragmaComment: {
8255 switch (PCD->getCommentKind()) {
8257 llvm_unreachable(
"unexpected pragma comment kind");
8265 ProcessPragmaCommentCopyright(PCD->getArg(), PCD->isFromASTFile());
8275 case Decl::PragmaDetectMismatch: {
8281 case Decl::LinkageSpec:
8285 case Decl::FileScopeAsm: {
8287 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
8290 if (LangOpts.OpenMPIsTargetDevice)
8293 if (LangOpts.SYCLIsDevice)
8298 llvm::Module::GlobalAsmProperties Props;
8299 Props.TargetFeatures = llvm::join(TargetOpts.
Features,
",");
8300 Props.TargetCPU = TargetOpts.
CPU;
8302 llvm::Module::GlobalAsmFragment(AD->getAsmString(), Props));
8306 case Decl::TopLevelStmt:
8310 case Decl::Import: {
8314 if (!ImportedModules.insert(Import->getImportedModule()))
8318 if (!Import->getImportedOwningModule()) {
8320 DI->EmitImportDecl(*Import);
8326 if (CXX20ModuleInits && Import->getImportedModule() &&
8327 Import->getImportedModule()->isNamedModule())
8336 Visited.insert(Import->getImportedModule());
8337 Stack.push_back(Import->getImportedModule());
8339 while (!Stack.empty()) {
8341 if (!EmittedModuleInitializers.insert(Mod).second)
8344 for (
auto *D : Context.getModuleInitializers(Mod))
8351 if (Submodule->IsExplicit)
8354 if (Visited.insert(Submodule).second)
8355 Stack.push_back(Submodule);
8365 case Decl::OMPThreadPrivate:
8369 case Decl::OMPAllocate:
8373 case Decl::OMPDeclareReduction:
8377 case Decl::OMPDeclareMapper:
8381 case Decl::OMPRequires:
8386 case Decl::TypeAlias:
8388 DI->EmitAndRetainType(
getContext().getTypedefType(
8396 DI->EmitAndRetainType(
8403 DI->EmitAndRetainType(
8407 case Decl::HLSLRootSignature:
8410 case Decl::HLSLBuffer:
8414 case Decl::OpenACCDeclare:
8417 case Decl::OpenACCRoutine:
8432 if (!CodeGenOpts.CoverageMapping)
8435 case Decl::CXXConversion:
8436 case Decl::CXXMethod:
8437 case Decl::Function:
8438 case Decl::ObjCMethod:
8439 case Decl::CXXConstructor:
8440 case Decl::CXXDestructor: {
8449 DeferredEmptyCoverageMappingDecls.try_emplace(D,
true);
8459 if (!CodeGenOpts.CoverageMapping)
8461 if (
const auto *Fn = dyn_cast<FunctionDecl>(D)) {
8462 if (Fn->isTemplateInstantiation())
8465 DeferredEmptyCoverageMappingDecls.insert_or_assign(D,
false);
8473 for (
const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
8476 const Decl *D = Entry.first;
8478 case Decl::CXXConversion:
8479 case Decl::CXXMethod:
8480 case Decl::Function:
8481 case Decl::ObjCMethod: {
8488 case Decl::CXXConstructor: {
8495 case Decl::CXXDestructor: {
8512 if (llvm::Function *F =
getModule().getFunction(
"main")) {
8513 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
8514 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
8515 auto *GA = llvm::GlobalAlias::create(
"__main_void", F);
8516 GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
8525 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
8526 return llvm::ConstantInt::get(i64, PtrInt);
8530 llvm::NamedMDNode *&GlobalMetadata,
8532 llvm::GlobalValue *
Addr) {
8533 if (!GlobalMetadata)
8535 CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
8538 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(
Addr),
8541 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
8544bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
8545 llvm::GlobalValue *CppFunc) {
8547 llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
8550 llvm::SmallVector<llvm::ConstantExpr *> CEs;
8553 if (Elem == CppFunc)
8559 for (llvm::User *User : Elem->users()) {
8563 if (
auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
8564 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
8567 for (llvm::User *CEUser : ConstExpr->users()) {
8568 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
8569 IFuncs.push_back(IFunc);
8574 CEs.push_back(ConstExpr);
8575 }
else if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
8576 IFuncs.push_back(IFunc);
8588 for (llvm::GlobalIFunc *IFunc : IFuncs)
8589 IFunc->setResolver(
nullptr);
8590 for (llvm::ConstantExpr *ConstExpr : CEs)
8591 ConstExpr->destroyConstant();
8595 Elem->eraseFromParent();
8597 for (llvm::GlobalIFunc *IFunc : IFuncs) {
8602 llvm::FunctionType::get(IFunc->getType(),
false);
8603 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
8604 CppFunc->getName(), ResolverTy, {},
false);
8605 IFunc->setResolver(Resolver);
8615void CodeGenModule::EmitStaticExternCAliases() {
8618 for (
auto &I : StaticExternCValues) {
8619 const IdentifierInfo *Name = I.first;
8620 llvm::GlobalValue *Val = I.second;
8628 llvm::GlobalValue *ExistingElem =
8633 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
8640 auto Res = Manglings.find(MangledName);
8641 if (Res == Manglings.end())
8643 Result = Res->getValue();
8654void CodeGenModule::EmitDeclMetadata() {
8655 llvm::NamedMDNode *GlobalMetadata =
nullptr;
8657 for (
auto &I : MangledDeclNames) {
8658 llvm::GlobalValue *
Addr =
getModule().getNamedValue(I.second);
8668void CodeGenFunction::EmitDeclMetadata() {
8669 if (LocalDeclMap.empty())
return;
8674 unsigned DeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
8676 llvm::NamedMDNode *GlobalMetadata =
nullptr;
8678 for (
auto &I : LocalDeclMap) {
8679 const Decl *D = I.first;
8680 llvm::Value *
Addr = I.second.emitRawPointer(*
this);
8681 if (
auto *Alloca = dyn_cast<llvm::AllocaInst>(
Addr)) {
8683 Alloca->setMetadata(
8684 DeclPtrKind, llvm::MDNode::get(
8685 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
8686 }
else if (
auto *GV = dyn_cast<llvm::GlobalValue>(
Addr)) {
8693void CodeGenModule::EmitVersionIdentMetadata() {
8694 llvm::NamedMDNode *IdentMetadata =
8695 TheModule.getOrInsertNamedMetadata(
"llvm.ident");
8697 llvm::LLVMContext &Ctx = TheModule.getContext();
8699 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
8700 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
8703void CodeGenModule::EmitCommandLineMetadata() {
8704 llvm::NamedMDNode *CommandLineMetadata =
8705 TheModule.getOrInsertNamedMetadata(
"llvm.commandline");
8707 llvm::LLVMContext &Ctx = TheModule.getContext();
8709 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
8710 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
8713void CodeGenModule::EmitCoverageFile() {
8714 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu");
8718 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
8719 llvm::LLVMContext &Ctx = TheModule.getContext();
8720 auto *CoverageDataFile =
8722 auto *CoverageNotesFile =
8724 for (
int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
8725 llvm::MDNode *CU = CUNode->getOperand(i);
8726 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
8727 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
8740 LangOpts.ObjCRuntime.isGNUFamily())
8741 return ObjCRuntime->GetEHType(Ty);
8748 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
8750 for (
auto RefExpr : D->
varlist()) {
8753 VD->getAnyInitializer() &&
8754 !VD->getAnyInitializer()->isConstantInitializer(
getContext());
8760 VD,
Addr, RefExpr->getBeginLoc(), PerformInit))
8761 CXXGlobalInits.push_back(InitFunction);
8766CodeGenModule::CreateMetadataIdentifierImpl(
QualType T, MetadataTypeMap &Map,
8767 StringRef Suffix,
bool ForceString,
8768 bool NormalizeIntegers) {
8771 FnType->getReturnType(), FnType->getParamTypes(),
8772 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
8774 llvm::Metadata *&InternalId = Map[
T.getCanonicalType()];
8779 std::string OutName;
8780 llvm::raw_string_ostream Out(OutName);
8784 if (NormalizeIntegers)
8785 Out <<
".normalized";
8800 bool GeneralizePointers) {
8801 assert(
T->isFunctionType());
8803 bool NormalizeIntegers =
getCodeGenOpts().SanitizeCfiICallNormalizeIntegers;
8804 if (GeneralizePointers)
8805 return CreateMetadataIdentifierImpl(
T, GeneralizedMetadataIdMap,
8806 ".generalized",
false,
8808 return CreateMetadataIdentifierImpl(
T, CfiICallMetadataIdMap,
"",
8809 false, NormalizeIntegers);
8819 return CreateMetadataIdentifierImpl(
T, MetadataIdMap,
"");
8824 return CreateMetadataIdentifierImpl(
T, VirtualMetadataIdMap,
".virtual");
8837 if (Context.isPromotableIntegerType(Ty))
8838 return Context.getPromotedIntegerType(Ty);
8840 if (BT->getKind() == BuiltinType::Float ||
8841 BT->getKind() == BuiltinType::Half)
8842 return Context.DoubleTy;
8850 PromotedParamTypes.reserve(ParamTypes.size());
8854 return Context.getFunctionType(FNPT->
getReturnType(), PromotedParamTypes,
8862 return CreateMetadataIdentifierImpl(
T, CallGraphMetadataIdMap,
"",
8870 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
8871 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
8872 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
8873 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
8874 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
8875 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
8876 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
8877 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
8885 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8887 if (CodeGenOpts.SanitizeCfiCrossDso)
8889 VTable->addTypeMetadata(Offset.getQuantity(),
8890 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
8893 llvm::Metadata *MD = llvm::MDString::get(
getLLVMContext(),
"all-vtables");
8894 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8900 SanStats = std::make_unique<llvm::SanitizerStatReport>(&
getModule());
8910 auto *FTy = llvm::FunctionType::get(SamplerT, {
C->getType()},
false);
8925 bool forPointeeType) {
8936 if (
auto Align = TT->getDecl()->getMaxAlignment()) {
8943 bool AlignForArray =
T->isArrayType();
8949 if (
T->isIncompleteType()) {
8966 if (
T.getQualifiers().hasUnaligned()) {
8968 }
else if (forPointeeType && !AlignForArray &&
8969 (RD =
T->getAsCXXRecordDecl())) {
8980 if (
unsigned MaxAlign =
getLangOpts().MaxTypeAlign) {
8993 if (NumAutoVarInit >= StopAfter) {
8996 if (!NumAutoVarInit) {
9010 const Decl *D)
const {
9014 OS << (isa<VarDecl>(D) ?
".static." :
".intern.");
9016 OS << (isa<VarDecl>(D) ?
"__static__" :
"__intern__");
9022 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
9026 llvm::MD5::MD5Result
Result;
9027 for (
const auto &Arg : PreprocessorOpts.Macros)
9028 Hash.update(Arg.first);
9032 llvm::sys::fs::UniqueID ID;
9036 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
9041 << PLoc.
getFilename() << Status.getError().message();
9043 ID = Status->getUniqueID();
9045 OS << llvm::format(
"%x", ID.getFile()) << llvm::format(
"%x", ID.getDevice())
9046 <<
"_" << llvm::utohexstr(
Result.low(),
true, 8);
9053 assert(DeferredDeclsToEmit.empty() &&
9054 "Should have emitted all decls deferred to emit.");
9055 assert(NewBuilder->DeferredDecls.empty() &&
9056 "Newly created module should not have deferred decls");
9057 NewBuilder->DeferredDecls = std::move(DeferredDecls);
9058 assert(EmittedDeferredDecls.empty() &&
9059 "Still have (unmerged) EmittedDeferredDecls deferred decls");
9061 assert(NewBuilder->DeferredVTables.empty() &&
9062 "Newly created module should not have deferred vtables");
9063 NewBuilder->DeferredVTables = std::move(DeferredVTables);
9065 assert(NewBuilder->EmittedVTables.empty() &&
9066 "Newly created module should not have defined vtables");
9067 NewBuilder->EmittedVTables = std::move(EmittedVTables);
9069 assert(NewBuilder->MangledDeclNames.empty() &&
9070 "Newly created module should not have mangled decl names");
9071 assert(NewBuilder->Manglings.empty() &&
9072 "Newly created module should not have manglings");
9073 NewBuilder->Manglings = std::move(Manglings);
9075 NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
9077 NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
9081 std::string OutName;
9082 llvm::raw_string_ostream Out(OutName);
9090 if (!Context.getTargetInfo().emitVectorDeletingDtors(Context.getLangOpts()))
9096 if (Dtor && Dtor->isVirtual() && Dtor->hasAttr<DLLExportAttr>())
9099 return RequireVectorDeletingDtor.count(RD);
9103 if (!Context.getTargetInfo().emitVectorDeletingDtors(Context.getLangOpts()))
9105 RequireVectorDeletingDtor.insert(RD);
9119 if (Entry && !Entry->isDeclaration()) {
9124 auto *NewFn = llvm::Function::Create(
9126 llvm::Function::ExternalLinkage, VDName, &
getModule());
9127 SetFunctionAttributes(VectorDtorGD, NewFn,
false,
9129 NewFn->takeName(VDEntry);
9130 VDEntry->replaceAllUsesWith(NewFn);
9131 VDEntry->eraseFromParent();
9132 Entry->replaceAllUsesWith(NewFn);
9133 Entry->eraseFromParent();
9138 addDeferredDeclToEmit(VectorDtorGD);
9142 llvm::GlobalAlias *GlobalDeleteAlias,
9146 PendingMSVCGlobalDeletes.insert({GlobalDeleteAlias, OperatorDeleteFD});
9168 "__global_delete wrapper is only used with the Microsoft ABI");
9170 llvm::LLVMContext &LLVMCtx = M.getContext();
9174 llvm::FunctionType *FnTy = GlobDeleteFn->getFunctionType();
9184 StringRef GlobDeleteMangledName = GlobDeleteFn->getName();
9185 StringRef Signature;
9186 const char *WrapperBase;
9187 if (GlobDeleteMangledName.starts_with(
"??3@")) {
9188 Signature = GlobDeleteMangledName.substr(4);
9189 WrapperBase =
"?__global_delete@@";
9190 }
else if (GlobDeleteMangledName.starts_with(
"??_V@")) {
9191 Signature = GlobDeleteMangledName.substr(5);
9192 WrapperBase =
"?__global_array_delete@@";
9194 llvm_unreachable(
"unexpected global operator delete mangling");
9197 std::string GlobalDeleteName = (WrapperBase + Signature).str();
9198 std::string EmptyGlobalDeleteName =
9199 (
"?__empty_global_delete@@" + Signature).str();
9203 if (llvm::GlobalValue *Existing = M.getNamedValue(GlobalDeleteName))
9212 llvm::Function *EmptyFn = M.getFunction(EmptyGlobalDeleteName);
9214 EmptyFn = llvm::Function::Create(
9215 FnTy, llvm::GlobalValue::LinkOnceODRLinkage, EmptyGlobalDeleteName, &M);
9216 EmptyFn->setComdat(M.getOrInsertComdat(EmptyGlobalDeleteName));
9217 EmptyFn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
9224 auto *BB = llvm::BasicBlock::Create(LLVMCtx,
"", EmptyFn);
9225 llvm::Function *TrapFn =
9226 llvm::Intrinsic::getOrInsertDeclaration(&M, llvm::Intrinsic::trap);
9227 llvm::CallInst::Create(TrapFn, {},
"", BB);
9228 new llvm::UnreachableInst(LLVMCtx, BB);
9242 auto *GlobalDeleteAlias = llvm::GlobalAlias::create(
9243 FnTy, GlobDeleteFn->getAddressSpace(), llvm::GlobalValue::WeakAnyLinkage,
9244 GlobalDeleteName, EmptyFn, &M);
9251 return GlobalDeleteAlias;
9263 if (!HasDirectGlobalDelete)
9266 for (
const auto &Entry : PendingMSVCGlobalDeletes) {
9267 llvm::GlobalAlias *Alias = Entry.first;
9275 llvm::Function::Create(FnTy, llvm::GlobalValue::LinkOnceODRLinkage,
9276 Alias->getAddressSpace(),
"", &
getModule());
9282 for (
auto &Arg : GlobDelFn->args())
9283 Args.push_back(&Arg);
9284 llvm::CallInst::Create(FnTy, RealDeleteFn, Args,
"", BB);
9289 Alias->replaceAllUsesWith(GlobDelFn);
9290 GlobDelFn->takeName(Alias);
9291 Alias->eraseFromParent();
9293 GlobDelFn->setComdat(
getModule().getOrInsertComdat(GlobDelFn->getName()));
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 shouldSkipAliasEmission(const CIRGenModule &cgm, const ValueDecl *global)
static void setWindowsItaniumDLLImport(CIRGenModule &cgm, bool isLocal, cir::FuncOp funcOp, StringRef name)
static std::string getMangledNameImpl(CIRGenModule &cgm, GlobalDecl gd, const NamedDecl *nd)
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 void setLinkageForGV(cir::GlobalOp &gv, const NamedDecl *nd)
static void emitUsed(CIRGenModule &cgm, StringRef name, std::vector< cir::CIRGlobalValueInterface > &list)
static bool usesAMDGPUABI(const llvm::Triple &T)
AMDGCN, and the AMDGCN-flavoured SPIR-V that lowers to it, share one classifier.
static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, const CPUSpecificAttr *Attr, unsigned CPUIndex, raw_ostream &Out)
static void initializeCommonABICompatInfo(llvm::abi::ABICompatInfo &CompatInfo, const LangOptions::ClangABI Compat)
static bool AllTrivialInitializers(CodeGenModule &CGM, ObjCImplementationDecl *D)
static const FunctionDecl * GetRuntimeFunctionDecl(ASTContext &C, StringRef Name)
static bool shouldKeepInlineFunction(llvm::GlobalValue::LinkageTypes Linkage, const FunctionDecl *FD)
static GlobalDecl getBaseVariantGlobalDecl(const NamedDecl *D)
static void checkAliasForTocData(llvm::GlobalVariable *GVar, const CodeGenOptions &CodeGenOpts, DiagnosticsEngine &Diags, SourceLocation Location)
static void initializeX86ABICompatInfo(llvm::abi::X86ABICompatInfo &CompatInfo, const llvm::Triple &T, const LangOptions::ClangABI Compat, const CodeGenOptions &CGOpts)
static const char PFPDeactivationSymbolPrefix[]
static GlobalDecl getGlobalDeclForLinkage(const FunctionDecl *FD)
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 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.
Defines the clang::Preprocessor interface.
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.
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()
const llvm::StringMap< bool > & getFunctionFeatureMap(const FunctionDecl *FD) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
@ Strong
Strong definition.
@ WeakUnknown
Weak for now, might become strong later in this TU.
const ProfileList & getProfileList() const
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.
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.
This class is used for builtin types like 'int'.
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
This is an opaque type for sizes expressed in character units.
llvm::Align getAsAlign() const
Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit bytes.
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
static CharUnits One()
Construct a CharUnits quantity of one.
static CharUnits fromQuantity(QuantityType Quantity)
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.
static llvm::ExceptionHandling toExceptionHandling(ExceptionHandlingKind Kind)
Translate a clang ExceptionHandlingKind into the corresponding LLVM ExceptionHandling model.
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.
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.
llvm::Metadata * CreateMetadataIdentifierForCallGraphType(QualType T)
Create a metadata identifier for the Call Graph Section.
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.
llvm::Constant * getOrCreateMSVCGlobalDeleteWrapper(const FunctionDecl *GlobOD)
Get or create the MSVC-compatible __global_delete wrapper for the given global operator delete,...
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 callgraph metadata if the function is a potential indirect call target to support c...
void AppendLinkerOptions(StringRef Opts)
Appends Opts to the "llvm.linker.options" metadata value.
void createCalleeTypeMetadataForIcall(const QualType &QT, llvm::CallBase *CB)
Create and attach callee_type metadata to the given call.
bool tryEmitCUDADeviceInvalidFunctionBody(GlobalDecl GD, llvm::Function *Fn)
Emit a trap stub body for functions in ASTContext::CUDADeviceInvalidFuncs.
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
QualType GetCallGraphPromotedType(QualType Ty) const
Applies C default argument promotions to a parameter type for Call Graph Section type reconstruction.
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)
void addPendingGlobalDelete(llvm::GlobalAlias *GlobalDeleteAlias, const FunctionDecl *OperatorDeleteFD)
Record a pending __global_delete variant that may need a forwarding body.
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()
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)
void noteDirectGlobalDelete()
Note that global operator delete is directly used in this TU.
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.
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.
QualType ReconstructCallGraphPrototype(const FunctionNoProtoType *FNPT, ArrayRef< QualType > ParamTypes) const
Reconstructs a FunctionProtoType for an unprototyped function type (FunctionNoProtoType) using the gi...
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...
std::string getMangledNameIgnoringAsmLabel(GlobalDecl GD, const NamedDecl *ND)
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 emitGlobalDeleteForwardingBodies()
Emit __global_delete forwarding bodies for any pending variants, if this TU directly uses global oper...
void addReplacement(StringRef Name, llvm::Constant *C)
void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535, unsigned LexOrder=~0U, llvm::Constant *AssociatedData=nullptr)
AddGlobalCtor - Add a function to the list that will be called before main() runs.
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
llvm::Metadata * CreateMetadataIdentifierForVirtualMemPtrType(QualType T)
Create a metadata identifier that is intended to be used to check virtual calls via a member function...
bool shouldUseLLVMABILowering(unsigned CallingConv) const
True when -fexperimental-abi-lowering is in effect AND the active target has an LLVMABI implementatio...
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::Metadata * CreateMetadataIdentifierForCFIFnType(QualType T, bool GeneralizePointers)
Create a metadata identifier for the given function type for CFI icall.
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 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 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).
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Represents a ValueDecl that came out of a declarator.
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
This represents one expression.
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
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
bool isImmediateFunction() const
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
ArrayRef< ParmVarDecl * > parameters() const
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:
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
bool isInlineBuiltinDeclaration() const
Determine if this function provides an inline implementation of a builtin.
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.
bool isImplicitHDExplicitInstantiation() const
True if both host and device are implicit attributes and this is (or is a member of) an explicit temp...
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
QualType getReturnType() 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.
@ 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.
@ Single
Single Threaded Environment.
@ 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.
ClangABI
Clang versions with different platform ABI conformance.
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
bool isTargetDevice() const
True when compiling for an offloading target device.
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 isTriviallyRecursive(const FunctionDecl *FD)
Return true if FD's body contains a direct call back to the symbol it links as, through an asm label ...
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
void mangleNameIgnoringAsmLabel(GlobalDecl GD, raw_ostream &)
ManglerKind getKind() const
virtual void needsUniqueInternalLinkageNames()
virtual void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber, raw_ostream &)=0
bool shouldMangleDeclNameIgnoringAsmLabel(const NamedDecl *D)
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.
@ 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.
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
static void processPathForFileMacro(SmallVectorImpl< char > &Path, const LangOptions &LangOpts, const TargetInfo &TI)
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.
RecordDecl * getDefinitionOrSelf() const
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.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
DiagnosticsEngine & getDiagnostics() const
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
StringRef getBufferName(SourceLocation Loc, bool *Invalid=nullptr) const
Return the filename or buffer identifier of the buffer the location is in.
FileID getMainFileID() const
Returns the FileID of the main source file.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
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
Return the code unit at the given position.
StringRef getString() const
unsigned getCharByteWidth() const
Represents the declaration of a struct/union/class/enum.
void startDefinition()
Starts the definition of this tag declaration.
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
const char * getSignReturnAddressHardeningStr() const
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.
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
virtual llvm::APInt getFMVPriority(ArrayRef< StringRef > Features) const
bool supportsIFunc() const
Identify whether this target supports IFuncs.
const llvm::fltSemantics & getLongDoubleFormat() const
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
virtual StringRef getABI() const
Get the ABI currently in use.
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 ...
Options for controlling the target.
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
AMDGPUFeatureState AMDGPUSramEccState
AMDGPU sramecc setting from -msramecc/-mno-sramecc.
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.
AMDGPUFeatureState AMDGPUXnackState
AMDGPU xnack setting from -mxnack/-mno-xnack.
@ Enabled
Feature explicitly enabled.
@ Any
Feature state not specified and should generate most compatible code.
@ 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.
bool isPointerType() const
const T * castAs() const
Member-template castAs<specific type>.
bool isReferenceType() const
bool isAMDGPUNamedBarrierTypeOrWrapper() const
Check if the type is the AMDGPU named barrier type/a RecordType of a named barrier wrapper,...
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
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.
@ TLS_None
Not a TLS variable.
@ 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.
LangAS getGlobalConstantAddressSpace(const LangOptions &LangOpts, const TargetInfo &Target)
Determines whether the language options require us to model unwind exceptions.
bool isVarDeclStrongDefinition(const ASTContext &Ctx, const VarDecl *D, bool NoCommon)
Check whether D is a strong definition, and thus must not be given common linkage.
bool hasUnwindExceptions(const LangOptions &LangOpts)
bool shouldBeInCOMDAT(const ASTContext &Ctx, const Decl &D)
Check whether D should be emitted into a COMDAT group.
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 > createXtensaTargetCodeGenInfo(CodeGenModule &CGM)
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)
std::unique_ptr< TargetCodeGenInfo > createSystemZ_ZOS_TargetCodeGenInfo(CodeGenModule &CGM, bool HasVector, 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,...
bool isStructOrArrayOfWithResources(QualType Ty)
constexpr bool isInitializedByPipeline(LangAS AS)
bool LT(InterpState &S, CodePtr OpPC)
Top level wrappers for InstallAPI frontend operations.
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.
@ Result
The result type of a method or function.
const FunctionProtoType * T
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
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.
Describes how types, statements, expressions, and declarations should be printed.