52#include "llvm/ABI/IRTypeMapper.h"
53#include "llvm/ABI/TargetInfo.h"
54#include "llvm/ADT/STLExtras.h"
55#include "llvm/ADT/StringExtras.h"
56#include "llvm/ADT/StringSwitch.h"
57#include "llvm/Analysis/TargetLibraryInfo.h"
58#include "llvm/BinaryFormat/ELF.h"
59#include "llvm/IR/AttributeMask.h"
60#include "llvm/IR/CallingConv.h"
61#include "llvm/IR/DataLayout.h"
62#include "llvm/IR/Intrinsics.h"
63#include "llvm/IR/LLVMContext.h"
64#include "llvm/IR/Module.h"
65#include "llvm/IR/ProfileSummary.h"
66#include "llvm/ProfileData/InstrProfReader.h"
67#include "llvm/ProfileData/SampleProf.h"
68#include "llvm/Support/ARMBuildAttributes.h"
69#include "llvm/Support/CRC.h"
70#include "llvm/Support/CodeGen.h"
71#include "llvm/Support/CommandLine.h"
72#include "llvm/Support/ConvertUTF.h"
73#include "llvm/Support/ErrorHandling.h"
74#include "llvm/Support/TimeProfiler.h"
75#include "llvm/TargetParser/AArch64TargetParser.h"
76#include "llvm/TargetParser/RISCVISAInfo.h"
77#include "llvm/TargetParser/Triple.h"
78#include "llvm/TargetParser/X86TargetParser.h"
79#include "llvm/Transforms/Instrumentation/KCFI.h"
80#include "llvm/Transforms/Utils/BuildLibCalls.h"
81#include "llvm/Transforms/Utils/KCFIHash.h"
89 "limited-coverage-experimental", llvm::cl::Hidden,
90 llvm::cl::desc(
"Emit limited coverage mapping information (experimental)"));
97 case TargetCXXABI::AppleARM64:
98 case TargetCXXABI::Fuchsia:
99 case TargetCXXABI::GenericAArch64:
100 case TargetCXXABI::GenericARM:
101 case TargetCXXABI::iOS:
102 case TargetCXXABI::WatchOS:
103 case TargetCXXABI::GenericMIPS:
104 case TargetCXXABI::GenericItanium:
105 case TargetCXXABI::WebAssembly:
106 case TargetCXXABI::XL:
108 case TargetCXXABI::Microsoft:
112 llvm_unreachable(
"invalid C++ ABI kind");
115static std::unique_ptr<TargetCodeGenInfo>
118 const llvm::Triple &Triple =
Target.getTriple();
121 switch (Triple.getArch()) {
125 case llvm::Triple::m68k:
127 case llvm::Triple::mips:
128 case llvm::Triple::mipsel:
129 if (Triple.getOS() == llvm::Triple::Win32)
133 case llvm::Triple::mips64:
134 case llvm::Triple::mips64el:
137 case llvm::Triple::avr: {
141 unsigned NPR =
Target.getABI() ==
"avrtiny" ? 6 : 18;
142 unsigned NRR =
Target.getABI() ==
"avrtiny" ? 4 : 8;
146 case llvm::Triple::aarch64:
147 case llvm::Triple::aarch64_32:
148 case llvm::Triple::aarch64_be: {
150 if (
Target.getABI() ==
"darwinpcs")
151 Kind = AArch64ABIKind::DarwinPCS;
152 else if (Triple.isOSWindows())
154 else if (
Target.getABI() ==
"aapcs-soft")
155 Kind = AArch64ABIKind::AAPCSSoft;
160 case llvm::Triple::wasm32:
161 case llvm::Triple::wasm64: {
163 if (
Target.getABI() ==
"experimental-mv")
164 Kind = WebAssemblyABIKind::ExperimentalMV;
168 case llvm::Triple::arm:
169 case llvm::Triple::armeb:
170 case llvm::Triple::thumb:
171 case llvm::Triple::thumbeb: {
172 if (Triple.getOS() == llvm::Triple::Win32)
176 StringRef ABIStr =
Target.getABI();
177 if (ABIStr ==
"apcs-gnu")
178 Kind = ARMABIKind::APCS;
179 else if (ABIStr ==
"aapcs16")
180 Kind = ARMABIKind::AAPCS16_VFP;
181 else if (CodeGenOpts.
FloatABI ==
"hard" ||
182 (CodeGenOpts.
FloatABI !=
"soft" && Triple.isHardFloatABI()))
183 Kind = ARMABIKind::AAPCS_VFP;
188 case llvm::Triple::ppc: {
189 if (Triple.isOSAIX())
196 case llvm::Triple::ppcle: {
201 case llvm::Triple::ppc64:
202 if (Triple.isOSAIX())
205 if (Triple.isOSBinFormatELF()) {
207 if (
Target.getABI() ==
"elfv2")
208 Kind = PPC64_SVR4_ABIKind::ELFv2;
209 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
214 case llvm::Triple::ppc64le: {
215 assert(Triple.isOSBinFormatELF() &&
"PPC64 LE non-ELF not supported!");
217 if (
Target.getABI() ==
"elfv1")
218 Kind = PPC64_SVR4_ABIKind::ELFv1;
219 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
224 case llvm::Triple::nvptx:
225 case llvm::Triple::nvptx64:
228 case llvm::Triple::msp430:
231 case llvm::Triple::riscv32:
232 case llvm::Triple::riscv64:
233 case llvm::Triple::riscv32be:
234 case llvm::Triple::riscv64be: {
235 StringRef ABIStr =
Target.getABI();
237 unsigned ABIFLen = 0;
238 if (ABIStr.ends_with(
"f"))
240 else if (ABIStr.ends_with(
"d"))
242 bool EABI = ABIStr.ends_with(
"e");
246 case llvm::Triple::systemz: {
247 bool SoftFloat = CodeGenOpts.
FloatABI ==
"soft";
248 bool HasVector = !SoftFloat &&
Target.getABI() ==
"vector";
249 if (Triple.getOS() == llvm::Triple::ZOS)
254 case llvm::Triple::tce:
255 case llvm::Triple::tcele:
256 case llvm::Triple::tcele64:
259 case llvm::Triple::x86: {
260 bool IsDarwinVectorABI = Triple.isOSDarwin();
261 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
263 if (Triple.getOS() == llvm::Triple::Win32) {
265 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
266 CodeGenOpts.NumRegisterParameters);
269 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
270 CodeGenOpts.NumRegisterParameters, CodeGenOpts.
FloatABI ==
"soft");
273 case llvm::Triple::x86_64: {
274 StringRef ABI =
Target.getABI();
275 X86AVXABILevel AVXLevel = (ABI ==
"avx512" ? X86AVXABILevel::AVX512
276 : ABI ==
"avx" ? X86AVXABILevel::AVX
277 : X86AVXABILevel::None);
279 switch (Triple.getOS()) {
280 case llvm::Triple::UEFI:
281 case llvm::Triple::Win32:
287 case llvm::Triple::hexagon:
289 case llvm::Triple::lanai:
291 case llvm::Triple::r600:
293 case llvm::Triple::amdgcn:
295 case llvm::Triple::sparc:
297 case llvm::Triple::sparcv9:
299 case llvm::Triple::xcore:
301 case llvm::Triple::arc:
303 case llvm::Triple::spir:
304 case llvm::Triple::spir64:
306 case llvm::Triple::spirv32:
307 case llvm::Triple::spirv64:
308 case llvm::Triple::spirv:
310 case llvm::Triple::dxil:
312 case llvm::Triple::ve:
314 case llvm::Triple::csky: {
315 bool IsSoftFloat = !
Target.hasFeature(
"hard-float-abi");
317 Target.hasFeature(
"fpuv2_df") ||
Target.hasFeature(
"fpuv3_df");
322 case llvm::Triple::bpfeb:
323 case llvm::Triple::bpfel:
325 case llvm::Triple::loongarch32:
326 case llvm::Triple::loongarch64: {
327 StringRef ABIStr =
Target.getABI();
328 unsigned ABIFRLen = 0;
329 if (ABIStr.ends_with(
"f"))
331 else if (ABIStr.ends_with(
"d"))
340 if (!TheTargetCodeGenInfo)
342 return *TheTargetCodeGenInfo;
346 if (!CodeGenOpts.ExperimentalABILowering)
353const llvm::abi::TargetInfo &
355 if (TheLLVMABITargetInfo)
356 return *TheLLVMABITargetInfo;
359 "LLVMABI lowering requested for an unsupported target");
360 TheLLVMABITargetInfo = llvm::abi::createBPFTargetInfo(TB);
361 return *TheLLVMABITargetInfo;
365 llvm::LLVMContext &Context,
369 if (Opts.AlignDouble || Opts.OpenCL)
372 llvm::Triple Triple =
Target.getTriple();
373 llvm::DataLayout DL(
Target.getDataLayoutString());
374 auto Check = [&](
const char *Name, llvm::Type *Ty,
unsigned Alignment) {
375 llvm::Align DLAlign = DL.getABITypeAlign(Ty);
376 llvm::Align ClangAlign(Alignment / 8);
377 if (DLAlign != ClangAlign) {
378 llvm::errs() <<
"For target " << Triple.str() <<
" type " << Name
379 <<
" mapping to " << *Ty <<
" has data layout alignment "
380 << DLAlign.value() <<
" while clang specifies "
381 << ClangAlign.value() <<
"\n";
386 Check(
"bool", llvm::Type::getIntNTy(Context,
Target.BoolWidth),
388 Check(
"short", llvm::Type::getIntNTy(Context,
Target.ShortWidth),
390 Check(
"int", llvm::Type::getIntNTy(Context,
Target.IntWidth),
392 Check(
"long", llvm::Type::getIntNTy(Context,
Target.LongWidth),
395 if (Triple.getArch() != llvm::Triple::m68k)
396 Check(
"long long", llvm::Type::getIntNTy(Context,
Target.LongLongWidth),
399 if (
Target.hasInt128Type() && !
Target.getTargetOpts().ForceEnableInt128 &&
400 !Triple.isAMDGPU() && !Triple.isSPIRV() &&
401 Triple.getArch() != llvm::Triple::ve)
402 Check(
"__int128", llvm::Type::getIntNTy(Context, 128),
Target.Int128Align);
404 if (
Target.hasFloat16Type())
405 Check(
"half", llvm::Type::getFloatingPointTy(Context, *
Target.HalfFormat),
407 if (
Target.hasBFloat16Type())
408 Check(
"bfloat", llvm::Type::getBFloatTy(Context),
Target.BFloat16Align);
409 Check(
"float", llvm::Type::getFloatingPointTy(Context, *
Target.FloatFormat),
411 Check(
"double", llvm::Type::getFloatingPointTy(Context, *
Target.DoubleFormat),
414 llvm::Type::getFloatingPointTy(Context, *
Target.LongDoubleFormat),
416 if (
Target.hasFloat128Type())
417 Check(
"__float128", llvm::Type::getFP128Ty(Context),
Target.Float128Align);
418 if (
Target.hasIbm128Type())
419 Check(
"__ibm128", llvm::Type::getPPC_FP128Ty(Context),
Target.Ibm128Align);
421 Check(
"void*", llvm::PointerType::getUnqual(Context),
Target.PointerAlign);
423 if (
Target.vectorsAreElementAligned() != DL.vectorsAreElementAligned()) {
424 llvm::errs() <<
"Datalayout for target " << Triple.str()
425 <<
" sets element-aligned vectors to '"
426 <<
Target.vectorsAreElementAligned()
427 <<
"' but clang specifies '" << DL.vectorsAreElementAligned()
441 : Context(
C), LangOpts(
C.
getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
442 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
444 VMContext(M.
getContext()), VTables(*this), StackHandler(diags),
448 AbiMapper = std::make_unique<QualTypeMapper>(
C, M.getDataLayout(), AbiAlloc);
449 AbiReverseMapper = std::make_unique<llvm::abi::IRTypeMapper>(
450 M.getContext(), M.getDataLayout());
454 llvm::LLVMContext &LLVMContext = M.getContext();
455 VoidTy = llvm::Type::getVoidTy(LLVMContext);
456 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
457 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
458 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
459 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
460 HalfTy = llvm::Type::getHalfTy(LLVMContext);
461 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
462 FloatTy = llvm::Type::getFloatTy(LLVMContext);
463 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
469 C.toCharUnitsFromBits(
C.getTargetInfo().getMaxPointerWidth()).getQuantity();
471 C.toCharUnitsFromBits(
C.getTargetInfo().getIntAlign()).getQuantity();
473 llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getCharWidth());
474 IntTy = llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getIntWidth());
475 IntPtrTy = llvm::IntegerType::get(LLVMContext,
476 C.getTargetInfo().getMaxPointerWidth());
477 Int8PtrTy = llvm::PointerType::get(LLVMContext,
479 const llvm::DataLayout &DL = M.getDataLayout();
481 llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
483 llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
485 llvm::PointerType::get(LLVMContext, DL.getProgramAddressSpace());
501 createOpenCLRuntime();
503 createOpenMPRuntime();
510 if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Thread | SanitizerKind::Type) ||
511 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
517 if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
518 CodeGenOpts.CoverageNotesFile.size() ||
519 CodeGenOpts.CoverageDataFile.size())
527 Block.GlobalUniqueCount = 0;
529 if (
C.getLangOpts().ObjC)
532 if (CodeGenOpts.hasProfileClangUse()) {
533 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
534 CodeGenOpts.ProfileInstrumentUsePath, *FS,
535 CodeGenOpts.ProfileRemappingFile);
536 if (
auto E = ReaderOrErr.takeError()) {
537 llvm::handleAllErrors(std::move(E), [&](
const llvm::ErrorInfoBase &EI) {
538 Diags.Report(diag::err_reading_profile)
539 << CodeGenOpts.ProfileInstrumentUsePath << EI.message();
543 PGOReader = std::move(ReaderOrErr.get());
548 if (CodeGenOpts.CoverageMapping)
552 if (CodeGenOpts.UniqueInternalLinkageNames &&
553 !
getModule().getSourceFileName().empty()) {
557 Context.getTargetInfo());
558 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path);
562 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
563 getModule().addModuleFlag(llvm::Module::Error,
"NumRegisterParameters",
564 CodeGenOpts.NumRegisterParameters);
573 const llvm::MemoryBuffer &FileBuffer = **BufOrErr;
574 for (llvm::line_iterator I(FileBuffer.getMemBufferRef(),
true), E;
576 this->MSHotPatchFunctions.push_back(std::string{*I});
578 auto &DE = Context.getDiagnostics();
579 DE.Report(diag::err_open_hotpatch_file_failed)
581 << BufOrErr.getError().message();
586 this->MSHotPatchFunctions.push_back(FuncName);
588 llvm::sort(this->MSHotPatchFunctions);
591 if (!Context.getAuxTargetInfo())
597void CodeGenModule::createObjCRuntime() {
614 llvm_unreachable(
"bad runtime kind");
617void CodeGenModule::createOpenCLRuntime() {
621void CodeGenModule::createOpenMPRuntime() {
622 if (!LangOpts.OMPHostIRFile.empty() && !FS->exists(LangOpts.OMPHostIRFile))
623 Diags.Report(diag::err_omp_host_ir_file_not_found)
624 << LangOpts.OMPHostIRFile;
629 case llvm::Triple::nvptx:
630 case llvm::Triple::nvptx64:
631 case llvm::Triple::amdgcn:
632 case llvm::Triple::spirv64:
635 "OpenMP AMDGPU/NVPTX/SPIRV is only prepared to deal with device code.");
636 OpenMPRuntime.reset(
new CGOpenMPRuntimeGPU(*
this));
639 if (LangOpts.OpenMPSimd)
640 OpenMPRuntime.reset(
new CGOpenMPSIMDRuntime(*
this));
642 OpenMPRuntime.reset(
new CGOpenMPRuntime(*
this));
647void CodeGenModule::createCUDARuntime() {
651void CodeGenModule::createHLSLRuntime() {
652 HLSLRuntime.reset(
new CGHLSLRuntime(*
this));
656 Replacements[Name] =
C;
659void CodeGenModule::applyReplacements() {
660 for (
auto &I : Replacements) {
661 StringRef MangledName = I.first;
662 llvm::Constant *Replacement = I.second;
667 auto *NewF = dyn_cast<llvm::Function>(Replacement);
669 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
670 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
673 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
674 CE->getOpcode() == llvm::Instruction::GetElementPtr);
675 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
680 OldF->replaceAllUsesWith(Replacement);
682 NewF->removeFromParent();
683 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
686 OldF->eraseFromParent();
691 GlobalValReplacements.push_back(std::make_pair(GV,
C));
694void CodeGenModule::applyGlobalValReplacements() {
695 for (
auto &I : GlobalValReplacements) {
696 llvm::GlobalValue *GV = I.first;
697 llvm::Constant *
C = I.second;
699 GV->replaceAllUsesWith(
C);
700 GV->eraseFromParent();
707 const llvm::Constant *
C;
708 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
709 C = GA->getAliasee();
710 else if (
auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
711 C = GI->getResolver();
715 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(
C->stripPointerCasts());
719 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
728 bool IsIFunc,
const llvm::GlobalValue *Alias,
const llvm::GlobalValue *&GV,
729 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
733 Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
737 if (GV->hasCommonLinkage()) {
738 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
739 if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
740 Diags.
Report(Location, diag::err_alias_to_common);
745 if (GV->isDeclaration()) {
746 Diags.
Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
747 Diags.
Report(Location, diag::note_alias_requires_mangled_name)
748 << IsIFunc << IsIFunc;
751 for (
const auto &[
Decl, Name] : MangledDeclNames) {
752 if (
const auto *ND = dyn_cast<NamedDecl>(
Decl.getDecl())) {
754 if (II && II->
getName() == GV->getName()) {
755 Diags.
Report(Location, diag::note_alias_mangled_name_alternative)
759 (Twine(IsIFunc ?
"ifunc" :
"alias") +
"(\"" + Name +
"\")")
769 const auto *F = dyn_cast<llvm::Function>(GV);
771 Diags.
Report(Location, diag::err_alias_to_undefined)
772 << IsIFunc << IsIFunc;
776 llvm::FunctionType *FTy = F->getFunctionType();
777 if (!FTy->getReturnType()->isPointerTy()) {
778 Diags.
Report(Location, diag::err_ifunc_resolver_return);
792 if (GVar->hasAttribute(
"toc-data")) {
793 auto GVId = GVar->getName();
796 Diags.
Report(Location, diag::warn_toc_unsupported_type)
797 << GVId <<
"the variable has an alias";
799 llvm::AttributeSet CurrAttributes = GVar->getAttributes();
800 llvm::AttributeSet NewAttributes =
801 CurrAttributes.removeAttribute(GVar->getContext(),
"toc-data");
802 GVar->setAttributes(NewAttributes);
806void CodeGenModule::checkAliases() {
811 DiagnosticsEngine &Diags =
getDiags();
812 for (
const GlobalDecl &GD : Aliases) {
814 SourceLocation Location;
816 bool IsIFunc = D->hasAttr<IFuncAttr>();
817 if (
const Attr *A = D->getDefiningAttr()) {
818 Location = A->getLocation();
819 Range = A->getRange();
821 llvm_unreachable(
"Not an alias or ifunc?");
825 const llvm::GlobalValue *GV =
nullptr;
827 MangledDeclNames, Range)) {
833 GlobalDecl AliaseeGD;
836 Diags.Report(Location, diag::err_alias_to_undefined)
837 << IsIFunc << IsIFunc;
846 if (AliasIsFuncDecl != AliaseeIsFunc) {
847 Diags.Report(Location, diag::err_alias_between_function_and_variable)
850 diag::note_aliasee_declaration);
857 if (AliasIsFuncDecl && AliaseeIsFunc) {
858 QualType AliasTy = D->getType();
860 auto shouldReportTypeMismatch = [&]() {
861 const auto *AliasFTy =
863 const auto *AliaseeFTy =
865 assert(AliasFTy && AliaseeFTy);
866 if (!Context.typesAreCompatible(AliasFTy->getReturnType(),
869 const auto *AliasFPTy = dyn_cast<FunctionProtoType>(AliasFTy);
870 const auto *AliaseeFPTy = dyn_cast<FunctionProtoType>(AliaseeFTy);
872 if ((AliasFPTy && AliasFPTy->isVariadic() && !AliaseeFPTy) ||
873 (AliaseeFPTy && AliaseeFPTy->isVariadic() && !AliasFPTy))
876 if (!AliasFPTy || !AliaseeFPTy)
880 if (AliasFPTy->getNumParams() != AliaseeFPTy->getNumParams() ||
881 AliasFPTy->isVariadic() != AliaseeFPTy->isVariadic())
883 for (
unsigned i = 0; i < AliasFPTy->getNumParams(); ++i)
884 if (!Context.typesAreCompatible(AliasFPTy->getParamType(i),
885 AliaseeFPTy->getParamType(i)))
889 if (shouldReportTypeMismatch()) {
890 Diags.Report(Location, diag::warn_alias_type_mismatch)
891 << AliasTy << AliaseeTy;
893 diag::note_aliasee_declaration);
899 if (
const llvm::GlobalVariable *GVar =
900 dyn_cast<const llvm::GlobalVariable>(GV))
904 llvm::Constant *Aliasee =
908 llvm::GlobalValue *AliaseeGV;
909 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
914 if (
const SectionAttr *SA = D->getAttr<SectionAttr>()) {
915 StringRef AliasSection = SA->getName();
916 if (AliasSection != AliaseeGV->getSection())
917 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
918 << AliasSection << IsIFunc << IsIFunc;
926 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
927 if (GA->isInterposable()) {
928 Diags.Report(Location, diag::warn_alias_to_weak_alias)
929 << GV->getName() << GA->getName() << IsIFunc;
930 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
931 GA->getAliasee(), Alias->getType());
943 llvm::Attribute::DisableSanitizerInstrumentation);
948 for (
const GlobalDecl &GD : Aliases) {
951 Alias->replaceAllUsesWith(llvm::PoisonValue::get(Alias->getType()));
952 Alias->eraseFromParent();
957 DeferredDeclsToEmit.clear();
958 EmittedDeferredDecls.clear();
959 DeferredAnnotations.clear();
961 OpenMPRuntime->clear();
965 StringRef MainFile) {
968 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
969 if (MainFile.empty())
970 MainFile =
"<stdin>";
971 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
974 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
977 Diags.
Report(diag::warn_profile_data_missing) << Visited << Missing;
981static std::optional<llvm::GlobalValue::VisibilityTypes>
988 return llvm::GlobalValue::DefaultVisibility;
990 return llvm::GlobalValue::HiddenVisibility;
992 return llvm::GlobalValue::ProtectedVisibility;
994 llvm_unreachable(
"unknown option value!");
999 std::optional<llvm::GlobalValue::VisibilityTypes>
V) {
1008 GV.setDSOLocal(
false);
1009 GV.setVisibility(*
V);
1014 if (!LO.VisibilityFromDLLStorageClass)
1017 std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
1020 std::optional<llvm::GlobalValue::VisibilityTypes>
1021 NoDLLStorageClassVisibility =
1024 std::optional<llvm::GlobalValue::VisibilityTypes>
1025 ExternDeclDLLImportVisibility =
1028 std::optional<llvm::GlobalValue::VisibilityTypes>
1029 ExternDeclNoDLLStorageClassVisibility =
1032 for (llvm::GlobalValue &GV : M.global_values()) {
1033 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
1036 if (GV.isDeclarationForLinker())
1038 llvm::GlobalValue::DLLImportStorageClass
1039 ? ExternDeclDLLImportVisibility
1040 : ExternDeclNoDLLStorageClassVisibility);
1043 llvm::GlobalValue::DLLExportStorageClass
1044 ? DLLExportVisibility
1045 : NoDLLStorageClassVisibility);
1047 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1052 const llvm::Triple &Triple,
1056 return LangOpts.getStackProtector() == Mode;
1059std::optional<llvm::Attribute::AttrKind>
1061 if (D && D->
hasAttr<NoStackProtectorAttr>())
1063 else if (D && D->
hasAttr<StrictGuardStackCheckAttr>() &&
1065 return llvm::Attribute::StackProtectStrong;
1067 return llvm::Attribute::StackProtect;
1069 return llvm::Attribute::StackProtectStrong;
1071 return llvm::Attribute::StackProtectReq;
1072 return std::nullopt;
1078 EmitModuleInitializers(Primary);
1080 DeferredDecls.insert_range(EmittedDeferredDecls);
1081 EmittedDeferredDecls.clear();
1082 EmitVTablesOpportunistically();
1083 applyGlobalValReplacements();
1084 applyReplacements();
1085 emitMultiVersionFunctions();
1086 emitPFPFieldsWithEvaluatedOffset();
1088 if (Context.getLangOpts().IncrementalExtensions &&
1089 GlobalTopLevelStmtBlockInFlight.first) {
1091 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->
getEndLoc());
1092 GlobalTopLevelStmtBlockInFlight = {
nullptr,
nullptr};
1098 EmitCXXModuleInitFunc(Primary);
1100 EmitCXXGlobalInitFunc();
1101 EmitCXXGlobalCleanUpFunc();
1102 registerGlobalDtorsWithAtExit();
1103 EmitCXXThreadLocalInitFunc();
1105 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
1107 if (Context.getLangOpts().CUDA && CUDARuntime) {
1108 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
1111 if (OpenMPRuntime) {
1112 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
1113 OpenMPRuntime->clear();
1117 PGOReader->getSummary(
false).getMD(VMContext),
1118 llvm::ProfileSummary::PSK_Instr);
1119 if (PGOStats.hasDiagnostics())
1125 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
1126 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
1128 EmitStaticExternCAliases();
1133 if (CoverageMapping)
1134 CoverageMapping->emit();
1135 if (CodeGenOpts.SanitizeCfiCrossDso) {
1139 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
1141 emitAtAvailableLinkGuard();
1142 if (Context.getTargetInfo().getTriple().isWasm())
1149 if (
getTarget().getTargetOpts().CodeObjectVersion !=
1150 llvm::CodeObjectVersionKind::COV_None) {
1151 getModule().addModuleFlag(llvm::Module::Error,
1152 "amdhsa_code_object_version",
1153 getTarget().getTargetOpts().CodeObjectVersion);
1158 auto *MDStr = llvm::MDString::get(
1163 getModule().addModuleFlag(llvm::Module::Error,
"amdgpu_printf_kind",
1172 if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) {
1174 for (
auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) {
1176 if (
auto *FD = dyn_cast<FunctionDecl>(D))
1180 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1184 llvm::ArrayType *ATy = llvm::ArrayType::get(
Int8PtrTy, UsedArray.size());
1186 auto *GV =
new llvm::GlobalVariable(
1187 getModule(), ATy,
false, llvm::GlobalValue::InternalLinkage,
1188 llvm::ConstantArray::get(ATy, UsedArray),
"__clang_gpu_used_external");
1194 auto *GV =
new llvm::GlobalVariable(
1196 llvm::Constant::getNullValue(
Int8Ty),
1205 if (CodeGenOpts.Autolink &&
1206 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
1207 EmitModuleLinkOptions();
1222 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
1223 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.dependent-libraries");
1224 for (
auto *MD : ELFDependentLibraries)
1225 NMD->addOperand(MD);
1228 if (CodeGenOpts.DwarfVersion) {
1229 getModule().addModuleFlag(llvm::Module::Max,
"Dwarf Version",
1230 CodeGenOpts.DwarfVersion);
1233 if (CodeGenOpts.Dwarf64)
1234 getModule().addModuleFlag(llvm::Module::Max,
"DWARF64", 1);
1236 if (Context.getLangOpts().SemanticInterposition)
1238 getModule().setSemanticInterposition(
true);
1240 if (CodeGenOpts.EmitCodeView) {
1242 getModule().addModuleFlag(llvm::Module::Warning,
"CodeView", 1);
1244 if (CodeGenOpts.CodeViewGHash) {
1245 getModule().addModuleFlag(llvm::Module::Warning,
"CodeViewGHash", 1);
1247 if (CodeGenOpts.ControlFlowGuard) {
1250 llvm::Module::Warning,
"cfguard",
1251 static_cast<unsigned>(llvm::ControlFlowGuardMode::Enabled));
1252 }
else if (CodeGenOpts.ControlFlowGuardNoChecks) {
1255 llvm::Module::Warning,
"cfguard",
1256 static_cast<unsigned>(llvm::ControlFlowGuardMode::TableOnly));
1258 if (CodeGenOpts.getWinControlFlowGuardMechanism() !=
1259 llvm::ControlFlowGuardMechanism::Automatic) {
1262 llvm::Module::Warning,
"cfguard-mechanism",
1263 static_cast<unsigned>(CodeGenOpts.getWinControlFlowGuardMechanism()));
1265 if (CodeGenOpts.EHContGuard) {
1267 getModule().addModuleFlag(llvm::Module::Warning,
"ehcontguard", 1);
1269 if (Context.getLangOpts().Kernel) {
1271 getModule().addModuleFlag(llvm::Module::Warning,
"ms-kernel", 1);
1273 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
1278 getModule().addModuleFlag(llvm::Module::Error,
"StrictVTablePointers",1);
1280 llvm::Metadata *Ops[2] = {
1281 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
1282 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1283 llvm::Type::getInt32Ty(VMContext), 1))};
1285 getModule().addModuleFlag(llvm::Module::Require,
1286 "StrictVTablePointersRequirement",
1287 llvm::MDNode::get(VMContext, Ops));
1293 getModule().addModuleFlag(llvm::Module::Warning,
"Debug Info Version",
1294 llvm::DEBUG_METADATA_VERSION);
1299 uint64_t WCharWidth =
1300 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
1301 if (WCharWidth !=
getTriple().getDefaultWCharSize())
1302 getModule().addModuleFlag(llvm::Module::Error,
"wchar_size", WCharWidth);
1305 getModule().addModuleFlag(llvm::Module::Warning,
1306 "zos_product_major_version",
1307 uint32_t(CLANG_VERSION_MAJOR));
1308 getModule().addModuleFlag(llvm::Module::Warning,
1309 "zos_product_minor_version",
1310 uint32_t(CLANG_VERSION_MINOR));
1311 getModule().addModuleFlag(llvm::Module::Warning,
"zos_product_patchlevel",
1312 uint32_t(CLANG_VERSION_PATCHLEVEL));
1314 getModule().addModuleFlag(llvm::Module::Error,
"zos_product_id",
1315 llvm::MDString::get(VMContext, ProductId));
1320 getModule().addModuleFlag(llvm::Module::Error,
"zos_cu_language",
1321 llvm::MDString::get(VMContext, lang_str));
1323 time_t TT = PreprocessorOpts.SourceDateEpoch
1324 ? *PreprocessorOpts.SourceDateEpoch
1325 : std::time(
nullptr);
1326 getModule().addModuleFlag(llvm::Module::Max,
"zos_translation_time",
1327 static_cast<uint64_t
>(TT));
1330 getModule().addModuleFlag(llvm::Module::Error,
"zos_le_char_mode",
1331 llvm::MDString::get(VMContext,
"ascii"));
1334 llvm::Triple T = Context.getTargetInfo().getTriple();
1335 if (T.isARM() || T.isThumb()) {
1337 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
1338 getModule().addModuleFlag(llvm::Module::Error,
"min_enum_size", EnumWidth);
1342 StringRef ABIStr = Target.getABI();
1343 llvm::LLVMContext &Ctx = TheModule.getContext();
1344 getModule().addModuleFlag(llvm::Module::Error,
"target-abi",
1345 llvm::MDString::get(Ctx, ABIStr));
1350 const std::vector<std::string> &Features =
1353 llvm::RISCVISAInfo::parseFeatures(T.isRISCV64() ? 64 : 32, Features);
1354 if (!errorToBool(ParseResult.takeError()))
1356 llvm::Module::AppendUnique,
"riscv-isa",
1358 Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString())));
1361 if (CodeGenOpts.SanitizeCfiCrossDso) {
1363 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
1366 if (CodeGenOpts.WholeProgramVTables) {
1370 getModule().addModuleFlag(llvm::Module::Error,
"Virtual Function Elim",
1371 CodeGenOpts.VirtualFunctionElimination);
1374 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
1375 getModule().addModuleFlag(llvm::Module::Override,
1376 "CFI Canonical Jump Tables",
1377 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1380 if (CodeGenOpts.SanitizeCfiICallNormalizeIntegers) {
1381 getModule().addModuleFlag(llvm::Module::Override,
"cfi-normalize-integers",
1385 if (!CodeGenOpts.UniqueSourceFileIdentifier.empty()) {
1387 llvm::Module::Append,
"Unique Source File Identifier",
1389 TheModule.getContext(),
1390 llvm::MDString::get(TheModule.getContext(),
1391 CodeGenOpts.UniqueSourceFileIdentifier)));
1394 if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) {
1395 getModule().addModuleFlag(llvm::Module::Override,
"kcfi", 1);
1398 if (CodeGenOpts.PatchableFunctionEntryOffset)
1399 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-offset",
1400 CodeGenOpts.PatchableFunctionEntryOffset);
1401 if (CodeGenOpts.SanitizeKcfiArity)
1402 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-arity", 1);
1405 llvm::Module::Override,
"kcfi-hash",
1406 llvm::MDString::get(
1408 llvm::stringifyKCFIHashAlgorithm(CodeGenOpts.SanitizeKcfiHash)));
1411 if (CodeGenOpts.CFProtectionReturn &&
1412 Target.checkCFProtectionReturnSupported(
getDiags())) {
1414 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-return",
1418 if (CodeGenOpts.CFProtectionBranch &&
1419 Target.checkCFProtectionBranchSupported(
getDiags())) {
1421 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-branch",
1424 auto Scheme = CodeGenOpts.getCFBranchLabelScheme();
1425 if (Target.checkCFBranchLabelSchemeSupported(Scheme,
getDiags())) {
1427 Scheme = Target.getDefaultCFBranchLabelScheme();
1429 llvm::Module::Error,
"cf-branch-label-scheme",
1435 if (CodeGenOpts.FunctionReturnThunks)
1436 getModule().addModuleFlag(llvm::Module::Override,
"function_return_thunk_extern", 1);
1438 if (CodeGenOpts.IndirectBranchCSPrefix)
1439 getModule().addModuleFlag(llvm::Module::Override,
"indirect_branch_cs_prefix", 1);
1450 if (Context.getTargetInfo().hasFeature(
"ptrauth") &&
1451 LangOpts.getSignReturnAddressScope() !=
1453 getModule().addModuleFlag(llvm::Module::Override,
1454 "sign-return-address-buildattr", 1);
1455 if (LangOpts.Sanitize.has(SanitizerKind::MemtagStack))
1456 getModule().addModuleFlag(llvm::Module::Override,
1457 "tag-stack-memory-buildattr", 1);
1459 if (T.isARM() || T.isThumb() || T.isAArch64()) {
1467 if (LangOpts.BranchTargetEnforcement)
1468 getModule().addModuleFlag(llvm::Module::Min,
"branch-target-enforcement",
1470 if (LangOpts.BranchProtectionPAuthLR)
1471 getModule().addModuleFlag(llvm::Module::Min,
"branch-protection-pauth-lr",
1473 if (LangOpts.GuardedControlStack)
1474 getModule().addModuleFlag(llvm::Module::Min,
"guarded-control-stack", 2);
1475 if (LangOpts.hasSignReturnAddress())
1476 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address", 2);
1477 if (LangOpts.isSignReturnAddressScopeAll())
1478 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address-all",
1480 if (!LangOpts.isSignReturnAddressWithAKey())
1481 getModule().addModuleFlag(llvm::Module::Min,
1482 "sign-return-address-with-bkey", 2);
1484 if (LangOpts.PointerAuthELFGOT)
1485 getModule().addModuleFlag(llvm::Module::Error,
"ptrauth-elf-got", 1);
1488 if (LangOpts.PointerAuthCalls)
1489 getModule().addModuleFlag(llvm::Module::Error,
1490 "ptrauth-sign-personality", 1);
1492 using namespace llvm::ELF;
1493 uint64_t PAuthABIVersion =
1494 (LangOpts.PointerAuthIntrinsics
1495 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS) |
1496 (LangOpts.PointerAuthCalls
1497 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS) |
1498 (LangOpts.PointerAuthReturns
1499 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS) |
1500 (LangOpts.PointerAuthAuthTraps
1501 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS) |
1502 (LangOpts.PointerAuthVTPtrAddressDiscrimination
1503 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR) |
1504 (LangOpts.PointerAuthVTPtrTypeDiscrimination
1505 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR) |
1506 (LangOpts.PointerAuthInitFini
1507 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI) |
1508 (LangOpts.PointerAuthInitFiniAddressDiscrimination
1509 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC) |
1510 (LangOpts.PointerAuthELFGOT
1511 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT) |
1512 (LangOpts.PointerAuthIndirectGotos
1513 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS) |
1514 (LangOpts.PointerAuthTypeInfoVTPtrDiscrimination
1515 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR) |
1516 (LangOpts.PointerAuthFunctionTypeDiscrimination
1517 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR);
1518 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR ==
1519 AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
1520 "Update when new enum items are defined");
1521 if (PAuthABIVersion != 0) {
1522 getModule().addModuleFlag(llvm::Module::Error,
1523 "aarch64-elf-pauthabi-platform",
1524 AARCH64_PAUTH_PLATFORM_LLVM_LINUX);
1525 getModule().addModuleFlag(llvm::Module::Error,
1526 "aarch64-elf-pauthabi-version",
1531 if ((T.isARM() || T.isThumb()) &&
getTriple().isTargetAEABI() &&
1533 uint32_t TagVal = 0;
1534 llvm::Module::ModFlagBehavior DenormalTagBehavior = llvm::Module::Max;
1536 llvm::DenormalMode::getPositiveZero()) {
1537 TagVal = llvm::ARMBuildAttrs::PositiveZero;
1539 llvm::DenormalMode::getIEEE()) {
1540 TagVal = llvm::ARMBuildAttrs::IEEEDenormals;
1541 DenormalTagBehavior = llvm::Module::Override;
1543 llvm::DenormalMode::getPreserveSign()) {
1544 TagVal = llvm::ARMBuildAttrs::PreserveFPSign;
1546 getModule().addModuleFlag(DenormalTagBehavior,
"arm-eabi-fp-denormal",
1551 getModule().addModuleFlag(llvm::Module::Min,
"arm-eabi-fp-exceptions",
1552 llvm::ARMBuildAttrs::Allowed);
1555 TagVal = llvm::ARMBuildAttrs::AllowIEEENormal;
1557 TagVal = llvm::ARMBuildAttrs::AllowIEEE754;
1558 getModule().addModuleFlag(llvm::Module::Min,
"arm-eabi-fp-number-model",
1562 if (CodeGenOpts.StackClashProtector)
1564 llvm::Module::Override,
"probe-stack",
1565 llvm::MDString::get(TheModule.getContext(),
"inline-asm"));
1567 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
1568 getModule().addModuleFlag(llvm::Module::Min,
"stack-probe-size",
1569 CodeGenOpts.StackProbeSize);
1571 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1572 llvm::LLVMContext &Ctx = TheModule.getContext();
1574 llvm::Module::Error,
"MemProfProfileFilename",
1575 llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
1578 if (LangOpts.CUDAIsDevice &&
getTriple().isNVPTX()) {
1582 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
1583 CodeGenOpts.FP32DenormalMode.Output !=
1584 llvm::DenormalMode::IEEE);
1587 if (LangOpts.EHAsynch)
1588 getModule().addModuleFlag(llvm::Module::Warning,
"eh-asynch", 1);
1591 if (CodeGenOpts.ImportCallOptimization)
1592 getModule().addModuleFlag(llvm::Module::Warning,
"import-call-optimization",
1596 if (CodeGenOpts.getWinX64EHUnwindV2() != llvm::WinX64EHUnwindV2Mode::Disabled)
1598 llvm::Module::Warning,
"winx64-eh-unwindv2",
1599 static_cast<unsigned>(CodeGenOpts.getWinX64EHUnwindV2()));
1603 getModule().addModuleFlag(llvm::Module::Max,
"openmp", LangOpts.OpenMP);
1605 getModule().addModuleFlag(llvm::Module::Max,
"openmp-device",
1609 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())) {
1610 EmitOpenCLMetadata();
1617 auto Version = LangOpts.getOpenCLCompatibleVersion();
1618 llvm::Metadata *SPIRVerElts[] = {
1619 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1621 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1622 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
1623 llvm::NamedMDNode *SPIRVerMD =
1624 TheModule.getOrInsertNamedMetadata(
"opencl.spir.version");
1625 llvm::LLVMContext &Ctx = TheModule.getContext();
1626 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
1634 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
1635 assert(PLevel < 3 &&
"Invalid PIC Level");
1636 getModule().setPICLevel(
static_cast<llvm::PICLevel::Level
>(PLevel));
1637 if (Context.getLangOpts().PIE)
1638 getModule().setPIELevel(
static_cast<llvm::PIELevel::Level
>(PLevel));
1642 unsigned CM = llvm::StringSwitch<unsigned>(
getCodeGenOpts().CodeModel)
1643 .Case(
"tiny", llvm::CodeModel::Tiny)
1644 .Case(
"small", llvm::CodeModel::Small)
1645 .Case(
"kernel", llvm::CodeModel::Kernel)
1646 .Case(
"medium", llvm::CodeModel::Medium)
1647 .Case(
"large", llvm::CodeModel::Large)
1650 llvm::CodeModel::Model codeModel =
static_cast<llvm::CodeModel::Model
>(CM);
1653 if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
1654 Context.getTargetInfo().getTriple().getArch() ==
1655 llvm::Triple::x86_64) {
1661 if (CodeGenOpts.NoPLT)
1664 CodeGenOpts.DirectAccessExternalData !=
1665 getModule().getDirectAccessExternalData()) {
1666 getModule().setDirectAccessExternalData(
1667 CodeGenOpts.DirectAccessExternalData);
1669 if (CodeGenOpts.UnwindTables)
1670 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1672 switch (CodeGenOpts.getFramePointer()) {
1677 getModule().setFramePointer(llvm::FramePointerKind::Reserved);
1680 getModule().setFramePointer(llvm::FramePointerKind::NonLeafNoReserve);
1683 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1686 getModule().setFramePointer(llvm::FramePointerKind::All);
1690 SimplifyPersonality();
1703 EmitVersionIdentMetadata();
1706 EmitCommandLineMetadata();
1714 getModule().setStackProtectorGuardSymbol(
1717 getModule().setStackProtectorGuardOffset(
1720 getModule().setStackProtectorGuardValueWidth(
1723 if (
getModule().getStackProtectorGuard() !=
"global") {
1724 Diags.Report(diag::err_opt_not_valid_without_opt)
1725 <<
"-mstack-protector-guard-record"
1726 <<
"-mstack-protector-guard=global";
1728 getModule().setStackProtectorGuardRecord(
true);
1733 getModule().addModuleFlag(llvm::Module::Override,
"SkipRaxSetup", 1);
1735 getModule().addModuleFlag(llvm::Module::Override,
"RegCallv4", 1);
1737 if (
getContext().getTargetInfo().getMaxTLSAlign())
1738 getModule().addModuleFlag(llvm::Module::Error,
"MaxTLSAlign",
1739 getContext().getTargetInfo().getMaxTLSAlign());
1757 if (!MustTailCallUndefinedGlobals.empty()) {
1759 for (
auto &I : MustTailCallUndefinedGlobals) {
1760 if (!I.first->isDefined())
1761 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1765 if (!Entry || Entry->isWeakForLinker() ||
1766 Entry->isDeclarationForLinker())
1767 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1771 for (
auto &I : MustTailCallUndefinedGlobals) {
1780 if (Entry->isDeclarationForLinker()) {
1783 Entry->hasHiddenVisibility() || Entry->hasProtectedVisibility();
1785 CalleeIsLocal = Entry->isDSOLocal();
1789 getDiags().
Report(I.second, diag::err_mips_impossible_musttail) << 1;
1800 auto *ErrnoTBAAMD = TheModule.getOrInsertNamedMetadata(
ErrnoTBAAMDName);
1801 ErrnoTBAAMD->addOperand(IntegerNode);
1806void CodeGenModule::EmitOpenCLMetadata() {
1812 auto EmitVersion = [
this](StringRef MDName,
int Version) {
1813 llvm::Metadata *OCLVerElts[] = {
1814 llvm::ConstantAsMetadata::get(
1815 llvm::ConstantInt::get(
Int32Ty, Version / 100)),
1816 llvm::ConstantAsMetadata::get(
1817 llvm::ConstantInt::get(
Int32Ty, (Version % 100) / 10))};
1818 llvm::NamedMDNode *OCLVerMD = TheModule.getOrInsertNamedMetadata(MDName);
1819 llvm::LLVMContext &Ctx = TheModule.getContext();
1820 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
1823 EmitVersion(
"opencl.ocl.version", CLVersion);
1824 if (LangOpts.OpenCLCPlusPlus) {
1826 EmitVersion(
"opencl.cxx.version", LangOpts.OpenCLCPlusPlusVersion);
1830void CodeGenModule::EmitBackendOptionsMetadata(
1831 const CodeGenOptions &CodeGenOpts) {
1833 getModule().addModuleFlag(llvm::Module::Min,
"SmallDataLimit",
1834 CodeGenOpts.SmallDataLimit);
1838 if (LangOpts.AllocTokenMode) {
1839 StringRef S = llvm::getAllocTokenModeAsString(*LangOpts.AllocTokenMode);
1840 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-mode",
1841 llvm::MDString::get(VMContext, S));
1843 if (LangOpts.AllocTokenMax)
1845 llvm::Module::Error,
"alloc-token-max",
1846 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1847 *LangOpts.AllocTokenMax));
1848 if (CodeGenOpts.SanitizeAllocTokenFastABI)
1849 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-fast-abi", 1);
1850 if (CodeGenOpts.SanitizeAllocTokenExtended)
1851 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-extended", 1);
1867 return TBAA->getTypeInfo(QTy);
1886 return TBAA->getAccessInfo(AccessType);
1893 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
1899 return TBAA->getTBAAStructInfo(QTy);
1905 return TBAA->getBaseTypeInfo(QTy);
1911 return TBAA->getAccessTagInfo(Info);
1918 return TBAA->mergeTBAAInfoForCast(SourceInfo,
TargetInfo);
1926 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
1934 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
1940 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
1945 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
1957 std::string Msg =
Type;
1959 diag::err_codegen_unsupported)
1965 diag::err_codegen_unsupported)
1972 std::string Msg =
Type;
1974 diag::err_codegen_unsupported)
1979 llvm::function_ref<
void()> Fn) {
1980 StackHandler.runWithSufficientStackSpace(Loc, Fn);
1990 if (GV->hasLocalLinkage()) {
1991 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2004 if (Context.getLangOpts().OpenMP &&
2005 Context.getLangOpts().OpenMPIsTargetDevice &&
isa<VarDecl>(D) &&
2006 D->
hasAttr<OMPDeclareTargetDeclAttr>() &&
2007 D->
getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
2008 OMPDeclareTargetDeclAttr::DT_NoHost &&
2010 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
2017 if (Context.getLangOpts().CUDAIsDevice &&
2019 !D->
hasAttr<OMPDeclareTargetDeclAttr>()) {
2020 bool NeedsProtected =
false;
2024 else if (
const auto *VD = dyn_cast<VarDecl>(D))
2025 NeedsProtected = VD->hasAttr<CUDADeviceAttr>() ||
2026 VD->hasAttr<CUDAConstantAttr>() ||
2027 VD->getType()->isCUDADeviceBuiltinSurfaceType() ||
2028 VD->getType()->isCUDADeviceBuiltinTextureType();
2029 if (NeedsProtected) {
2030 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
2036 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
2040 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
2044 if (GV->hasDLLExportStorageClass()) {
2047 diag::err_hidden_visibility_dllexport);
2050 diag::err_non_default_visibility_dllimport);
2056 !GV->isDeclarationForLinker())
2061 llvm::GlobalValue *GV) {
2062 if (GV->hasLocalLinkage())
2065 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
2069 if (GV->hasDLLImportStorageClass())
2072 const llvm::Triple &TT = CGM.
getTriple();
2074 if (TT.isOSCygMing()) {
2092 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
2100 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
2104 if (!TT.isOSBinFormatELF())
2110 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
2118 return !(CGM.
getLangOpts().SemanticInterposition ||
2123 if (!GV->isDeclarationForLinker())
2129 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
2136 if (CGOpts.DirectAccessExternalData) {
2142 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
2143 if (!Var->isThreadLocal())
2168 const auto *D = dyn_cast<NamedDecl>(GD.
getDecl());
2170 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
2180 if (D->
hasAttr<DLLImportAttr>())
2181 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2182 else if ((D->
hasAttr<DLLExportAttr>() ||
2184 !GV->isDeclarationForLinker())
2185 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2205 GV->setPartition(CodeGenOpts.SymbolPartition);
2209 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
2210 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
2211 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
2212 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
2213 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
2216llvm::GlobalVariable::ThreadLocalMode
2218 switch (CodeGenOpts.getDefaultTLSModel()) {
2220 return llvm::GlobalVariable::GeneralDynamicTLSModel;
2222 return llvm::GlobalVariable::LocalDynamicTLSModel;
2224 return llvm::GlobalVariable::InitialExecTLSModel;
2226 return llvm::GlobalVariable::LocalExecTLSModel;
2228 llvm_unreachable(
"Invalid TLS model!");
2232 assert(D.
getTLSKind() &&
"setting TLS mode on non-TLS var!");
2234 llvm::GlobalValue::ThreadLocalMode TLM;
2238 if (
const TLSModelAttr *
Attr = D.
getAttr<TLSModelAttr>()) {
2242 GV->setThreadLocalMode(TLM);
2248 return (Twine(
'.') + Twine(
Target.CPUSpecificManglingCharacter(Name))).str();
2252 const CPUSpecificAttr *
Attr,
2269 !D->
hasAttr<AsmLabelAttr>() &&
2275 bool OmitMultiVersionMangling =
false) {
2277 llvm::raw_svector_ostream Out(Buffer);
2286 assert(II &&
"Attempt to mangle unnamed decl.");
2287 const auto *FD = dyn_cast<FunctionDecl>(ND);
2292 Out <<
"__regcall4__" << II->
getName();
2294 Out <<
"__regcall3__" << II->
getName();
2295 }
else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
2297 Out <<
"__device_stub__" << II->
getName();
2299 DeviceKernelAttr::isOpenCLSpelling(
2300 FD->getAttr<DeviceKernelAttr>()) &&
2302 Out <<
"__clang_ocl_kern_imp_" << II->
getName();
2318 "Hash computed when not explicitly requested");
2322 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
2323 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
2324 switch (FD->getMultiVersionKind()) {
2328 FD->getAttr<CPUSpecificAttr>(),
2332 auto *
Attr = FD->getAttr<TargetAttr>();
2333 assert(
Attr &&
"Expected TargetAttr to be present "
2334 "for attribute mangling");
2340 auto *
Attr = FD->getAttr<TargetVersionAttr>();
2341 assert(
Attr &&
"Expected TargetVersionAttr to be present "
2342 "for attribute mangling");
2348 auto *
Attr = FD->getAttr<TargetClonesAttr>();
2349 assert(
Attr &&
"Expected TargetClonesAttr to be present "
2350 "for attribute mangling");
2357 llvm_unreachable(
"None multiversion type isn't valid here");
2367 return std::string(Out.str());
2370void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
2371 const FunctionDecl *FD,
2372 StringRef &CurName) {
2379 std::string NonTargetName =
2387 "Other GD should now be a multiversioned function");
2397 if (OtherName != NonTargetName) {
2400 const auto ExistingRecord = Manglings.find(NonTargetName);
2401 if (ExistingRecord != std::end(Manglings))
2402 Manglings.remove(&(*ExistingRecord));
2403 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
2408 CurName = OtherNameRef;
2410 Entry->setName(OtherName);
2420 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
2434 auto FoundName = MangledDeclNames.find(CanonicalGD);
2435 if (FoundName != MangledDeclNames.end())
2436 return FoundName->second;
2473 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
2474 return MangledDeclNames[CanonicalGD] =
Result.first->first();
2483 llvm::raw_svector_ostream Out(Buffer);
2486 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
2487 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(D))
2489 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(D))
2494 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
2495 return Result.first->first();
2499 auto it = MangledDeclNames.begin();
2500 while (it != MangledDeclNames.end()) {
2501 if (it->second == Name)
2516 llvm::Constant *AssociatedData) {
2518 GlobalCtors.push_back(
Structor(Priority, LexOrder, Ctor, AssociatedData));
2524 bool IsDtorAttrFunc) {
2525 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2527 DtorsUsingAtExit[Priority].push_back(Dtor);
2532 GlobalDtors.push_back(
Structor(Priority, ~0
U, Dtor,
nullptr));
2535void CodeGenModule::EmitCtorList(CtorList &Fns,
const char *GlobalName) {
2536 if (Fns.empty())
return;
2542 llvm::PointerType *PtrTy = llvm::PointerType::get(
2543 getLLVMContext(), TheModule.getDataLayout().getProgramAddressSpace());
2546 llvm::StructType *CtorStructTy = llvm::StructType::get(
Int32Ty, PtrTy, PtrTy);
2550 auto Ctors = Builder.beginArray(CtorStructTy);
2551 for (
const auto &I : Fns) {
2552 auto Ctor = Ctors.beginStruct(CtorStructTy);
2553 Ctor.addInt(
Int32Ty, I.Priority);
2554 if (InitFiniAuthSchema) {
2555 llvm::Constant *StorageAddress =
2557 ? llvm::ConstantExpr::getIntToPtr(
2558 llvm::ConstantInt::get(
2560 llvm::ConstantPtrAuth::AddrDiscriminator_CtorsDtors),
2564 I.Initializer, InitFiniAuthSchema.
getKey(), StorageAddress,
2565 llvm::ConstantInt::get(
2567 Ctor.add(SignedCtorPtr);
2569 Ctor.add(I.Initializer);
2571 if (I.AssociatedData)
2572 Ctor.add(I.AssociatedData);
2574 Ctor.addNullPointer(PtrTy);
2575 Ctor.finishAndAddTo(Ctors);
2578 auto List = Ctors.finishAndCreateGlobal(GlobalName,
getPointerAlign(),
2580 llvm::GlobalValue::AppendingLinkage);
2584 List->setAlignment(std::nullopt);
2589llvm::GlobalValue::LinkageTypes
2595 if (
const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
2602 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2603 if (!MDS)
return nullptr;
2605 return llvm::ConstantInt::get(
Int64Ty, llvm::MD5Hash(MDS->getString()));
2613 if (!UD->
hasAttr<TransparentUnionAttr>())
2615 if (!UD->
fields().empty())
2616 return UD->
fields().begin()->getType();
2625 bool GeneralizePointers) {
2638 bool GeneralizePointers) {
2641 for (
auto &Param : FnType->param_types())
2642 GeneralizedParams.push_back(
2646 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers),
2647 GeneralizedParams, FnType->getExtProtoInfo());
2652 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers));
2654 llvm_unreachable(
"Encountered unknown FunctionType");
2662 FnType->getReturnType(), FnType->getParamTypes(),
2663 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
2665 std::string OutName;
2666 llvm::raw_string_ostream Out(OutName);
2674 Out <<
".normalized";
2676 Out <<
".generalized";
2678 return llvm::ConstantInt::get(
2684 llvm::Function *F,
bool IsThunk) {
2686 llvm::AttributeList PAL;
2689 if (
CallingConv == llvm::CallingConv::X86_VectorCall &&
2693 Loc = D->getLocation();
2695 Error(Loc,
"__vectorcall calling convention is not currently supported");
2697 F->setAttributes(PAL);
2698 F->setCallingConv(
static_cast<llvm::CallingConv::ID
>(
CallingConv));
2702 std::string ReadOnlyQual(
"__read_only");
2703 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2704 if (ReadOnlyPos != std::string::npos)
2706 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2708 std::string WriteOnlyQual(
"__write_only");
2709 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2710 if (WriteOnlyPos != std::string::npos)
2711 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2713 std::string ReadWriteQual(
"__read_write");
2714 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2715 if (ReadWritePos != std::string::npos)
2716 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2749 assert(((FD && CGF) || (!FD && !CGF)) &&
2750 "Incorrect use - FD and CGF should either be both null or not!");
2776 for (
unsigned i = 0, e = FD->
getNumParams(); i != e; ++i) {
2779 argNames.push_back(llvm::MDString::get(VMContext, parm->
getName()));
2784 std::string typeQuals;
2788 const Decl *PDecl = parm;
2790 PDecl = TD->getDecl();
2791 const OpenCLAccessAttr *A = PDecl->
getAttr<OpenCLAccessAttr>();
2792 if (A && A->isWriteOnly())
2793 accessQuals.push_back(llvm::MDString::get(VMContext,
"write_only"));
2794 else if (A && A->isReadWrite())
2795 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_write"));
2797 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_only"));
2799 accessQuals.push_back(llvm::MDString::get(VMContext,
"none"));
2801 auto getTypeSpelling = [&](
QualType Ty) {
2802 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2804 if (Ty.isCanonical()) {
2805 StringRef typeNameRef = typeName;
2807 if (typeNameRef.consume_front(
"unsigned "))
2808 return std::string(
"u") + typeNameRef.str();
2809 if (typeNameRef.consume_front(
"signed "))
2810 return typeNameRef.str();
2820 addressQuals.push_back(
2821 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(
2825 std::string typeName = getTypeSpelling(pointeeTy) +
"*";
2826 std::string baseTypeName =
2828 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2829 argBaseTypeNames.push_back(
2830 llvm::MDString::get(VMContext, baseTypeName));
2834 typeQuals =
"restrict";
2837 typeQuals += typeQuals.empty() ?
"const" :
" const";
2839 typeQuals += typeQuals.empty() ?
"volatile" :
" volatile";
2841 uint32_t AddrSpc = 0;
2846 addressQuals.push_back(
2847 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(AddrSpc)));
2851 std::string typeName = getTypeSpelling(ty);
2863 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2864 argBaseTypeNames.push_back(
2865 llvm::MDString::get(VMContext, baseTypeName));
2870 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
2874 Fn->setMetadata(
"kernel_arg_addr_space",
2875 llvm::MDNode::get(VMContext, addressQuals));
2876 Fn->setMetadata(
"kernel_arg_access_qual",
2877 llvm::MDNode::get(VMContext, accessQuals));
2878 Fn->setMetadata(
"kernel_arg_type",
2879 llvm::MDNode::get(VMContext, argTypeNames));
2880 Fn->setMetadata(
"kernel_arg_base_type",
2881 llvm::MDNode::get(VMContext, argBaseTypeNames));
2882 Fn->setMetadata(
"kernel_arg_type_qual",
2883 llvm::MDNode::get(VMContext, argTypeQuals));
2887 Fn->setMetadata(
"kernel_arg_name",
2888 llvm::MDNode::get(VMContext, argNames));
2898 if (!LangOpts.Exceptions)
return false;
2901 if (LangOpts.CXXExceptions)
return true;
2904 if (LangOpts.ObjCExceptions) {
2924SmallVector<const CXXRecordDecl *, 0>
2926 llvm::SetVector<const CXXRecordDecl *> MostBases;
2931 MostBases.insert(RD);
2933 CollectMostBases(B.getType()->getAsCXXRecordDecl());
2935 CollectMostBases(RD);
2936 return MostBases.takeVector();
2940 llvm::Function *F) {
2941 llvm::AttrBuilder B(F->getContext());
2943 if ((!D || !D->
hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2944 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2946 if (CodeGenOpts.StackClashProtector)
2947 B.addAttribute(
"probe-stack",
"inline-asm");
2949 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
2950 B.addAttribute(
"stack-probe-size",
2951 std::to_string(CodeGenOpts.StackProbeSize));
2954 B.addAttribute(llvm::Attribute::NoUnwind);
2956 if (std::optional<llvm::Attribute::AttrKind>
Attr =
2958 B.addAttribute(*
Attr);
2963 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline))
2964 B.addAttribute(llvm::Attribute::AlwaysInline);
2968 else if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2970 B.addAttribute(llvm::Attribute::NoInline);
2978 if (D->
hasAttr<ArmLocallyStreamingAttr>())
2979 B.addAttribute(
"aarch64_pstate_sm_body");
2982 if (
Attr->isNewZA())
2983 B.addAttribute(
"aarch64_new_za");
2984 if (
Attr->isNewZT0())
2985 B.addAttribute(
"aarch64_new_zt0");
2990 bool ShouldAddOptNone =
2991 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
2993 ShouldAddOptNone &= !D->
hasAttr<MinSizeAttr>();
2994 ShouldAddOptNone &= !D->
hasAttr<AlwaysInlineAttr>();
2997 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline) &&
2998 !D->
hasAttr<NoInlineAttr>()) {
2999 B.addAttribute(llvm::Attribute::AlwaysInline);
3000 }
else if ((ShouldAddOptNone || D->
hasAttr<OptimizeNoneAttr>()) &&
3001 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
3003 B.addAttribute(llvm::Attribute::OptimizeNone);
3006 B.addAttribute(llvm::Attribute::NoInline);
3011 B.addAttribute(llvm::Attribute::Naked);
3014 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
3015 F->removeFnAttr(llvm::Attribute::MinSize);
3016 }
else if (D->
hasAttr<NakedAttr>()) {
3018 B.addAttribute(llvm::Attribute::Naked);
3019 B.addAttribute(llvm::Attribute::NoInline);
3020 }
else if (D->
hasAttr<NoDuplicateAttr>()) {
3021 B.addAttribute(llvm::Attribute::NoDuplicate);
3022 }
else if (D->
hasAttr<NoInlineAttr>() &&
3023 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
3025 B.addAttribute(llvm::Attribute::NoInline);
3026 }
else if (D->
hasAttr<AlwaysInlineAttr>() &&
3027 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
3029 B.addAttribute(llvm::Attribute::AlwaysInline);
3033 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
3034 B.addAttribute(llvm::Attribute::NoInline);
3038 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
3041 auto CheckRedeclForInline = [](
const FunctionDecl *Redecl) {
3042 return Redecl->isInlineSpecified();
3044 if (any_of(FD->
redecls(), CheckRedeclForInline))
3049 return any_of(Pattern->
redecls(), CheckRedeclForInline);
3051 if (CheckForInline(FD)) {
3052 B.addAttribute(llvm::Attribute::InlineHint);
3053 }
else if (CodeGenOpts.getInlining() ==
3056 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
3057 B.addAttribute(llvm::Attribute::NoInline);
3064 if (!D->
hasAttr<OptimizeNoneAttr>()) {
3066 if (!ShouldAddOptNone)
3067 B.addAttribute(llvm::Attribute::OptimizeForSize);
3068 B.addAttribute(llvm::Attribute::Cold);
3071 B.addAttribute(llvm::Attribute::Hot);
3072 if (D->
hasAttr<MinSizeAttr>())
3073 B.addAttribute(llvm::Attribute::MinSize);
3078 if (CodeGenOpts.DisableOutlining || D->
hasAttr<NoOutlineAttr>())
3079 B.addAttribute(llvm::Attribute::NoOutline);
3083 llvm::MaybeAlign ExplicitAlignment;
3084 if (
unsigned alignment = D->
getMaxAlignment() / Context.getCharWidth())
3085 ExplicitAlignment = llvm::Align(alignment);
3086 else if (LangOpts.FunctionAlignment)
3087 ExplicitAlignment = llvm::Align(1ull << LangOpts.FunctionAlignment);
3089 if (ExplicitAlignment) {
3090 F->setAlignment(ExplicitAlignment);
3091 F->setPreferredAlignment(ExplicitAlignment);
3092 }
else if (LangOpts.PreferredFunctionAlignment) {
3093 F->setPreferredAlignment(llvm::Align(LangOpts.PreferredFunctionAlignment));
3102 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
3107 if (CodeGenOpts.SanitizeCfiCrossDso &&
3108 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
3109 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
3117 if (CodeGenOpts.CallGraphSection) {
3118 if (
auto *FD = dyn_cast<FunctionDecl>(D))
3125 auto *MD = dyn_cast<CXXMethodDecl>(D);
3128 llvm::Metadata *Id =
3130 MD->getType(), std::nullopt,
Base));
3131 F->addTypeMetadata(0, Id);
3138 if (
const auto *FD = dyn_cast<FunctionDecl>(D))
3139 if (FD->
hasAttr<SYCLExternalAttr>())
3140 addSYCLModuleIdAttr(F);
3144void CodeGenModule::addSYCLModuleIdAttr(llvm::Function *Fn) {
3146 Fn->addFnAttr(
"sycl-module-id",
getModule().getModuleIdentifier());
3151 if (isa_and_nonnull<NamedDecl>(D))
3154 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
3156 if (D && D->
hasAttr<UsedAttr>())
3159 if (
const auto *VD = dyn_cast_if_present<VarDecl>(D);
3161 ((CodeGenOpts.KeepPersistentStorageVariables &&
3162 (VD->getStorageDuration() ==
SD_Static ||
3163 VD->getStorageDuration() ==
SD_Thread)) ||
3164 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
3165 VD->getType().isConstQualified())))
3170static std::vector<std::string>
3172 llvm::StringMap<bool> &FeatureMap) {
3173 llvm::StringMap<bool> DefaultFeatureMap;
3177 std::vector<std::string> Delta;
3178 for (
const auto &[K,
V] : FeatureMap) {
3179 auto DefaultIt = DefaultFeatureMap.find(K);
3180 if (DefaultIt == DefaultFeatureMap.end() || DefaultIt->getValue() !=
V)
3181 Delta.push_back((
V ?
"+" :
"-") + K.str());
3187bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
3188 llvm::AttrBuilder &Attrs,
3189 bool SetTargetFeatures) {
3195 std::vector<std::string> Features;
3196 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.
getDecl());
3199 const auto *TV = FD ? FD->
getAttr<TargetVersionAttr>() :
nullptr;
3200 assert((!TD || !TV) &&
"both target_version and target specified");
3203 bool AddedAttr =
false;
3204 if (TD || TV || SD || TC) {
3205 llvm::StringMap<bool> FeatureMap;
3212 StringRef FeatureStr = TD ? TD->getFeaturesStr() : StringRef();
3215 if (!FeatureStr.empty()) {
3216 ParsedTargetAttr ParsedAttr = Target.parseTargetAttr(FeatureStr);
3217 if (!ParsedAttr.
CPU.empty() &&
3219 TargetCPU = ParsedAttr.
CPU;
3222 if (!ParsedAttr.
Tune.empty() &&
3224 TuneCPU = ParsedAttr.
Tune;
3240 for (
const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
3241 Features.push_back((Entry.getValue() ?
"+" :
"-") +
3242 Entry.getKey().str());
3248 llvm::StringMap<bool> FeatureMap;
3262 if (!TargetCPU.empty()) {
3263 Attrs.addAttribute(
"target-cpu", TargetCPU);
3266 if (!TuneCPU.empty()) {
3267 Attrs.addAttribute(
"tune-cpu", TuneCPU);
3270 if (!Features.empty() && SetTargetFeatures) {
3271 llvm::erase_if(Features, [&](
const std::string& F) {
3274 llvm::sort(Features);
3275 Attrs.addAttribute(
"target-features", llvm::join(Features,
","));
3280 llvm::SmallVector<StringRef, 8> Feats;
3281 bool IsDefault =
false;
3283 IsDefault = TV->isDefaultVersion();
3284 TV->getFeatures(Feats);
3290 Attrs.addAttribute(
"fmv-features");
3292 }
else if (!Feats.empty()) {
3294 std::set<StringRef> OrderedFeats(Feats.begin(), Feats.end());
3295 std::string FMVFeatures;
3296 for (StringRef F : OrderedFeats)
3297 FMVFeatures.append(
"," + F.str());
3298 Attrs.addAttribute(
"fmv-features", FMVFeatures.substr(1));
3305void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
3306 llvm::GlobalObject *GO) {
3311 if (
auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
3314 if (
auto *SA = D->
getAttr<PragmaClangBSSSectionAttr>())
3315 GV->addAttribute(
"bss-section", SA->getName());
3316 if (
auto *SA = D->
getAttr<PragmaClangDataSectionAttr>())
3317 GV->addAttribute(
"data-section", SA->getName());
3318 if (
auto *SA = D->
getAttr<PragmaClangRodataSectionAttr>())
3319 GV->addAttribute(
"rodata-section", SA->getName());
3320 if (
auto *SA = D->
getAttr<PragmaClangRelroSectionAttr>())
3321 GV->addAttribute(
"relro-section", SA->getName());
3324 if (
auto *F = dyn_cast<llvm::Function>(GO)) {
3327 if (
auto *SA = D->
getAttr<PragmaClangTextSectionAttr>())
3328 if (!D->
getAttr<SectionAttr>())
3329 F->setSection(SA->getName());
3331 llvm::AttrBuilder Attrs(F->getContext());
3332 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
3336 llvm::AttributeMask RemoveAttrs;
3337 RemoveAttrs.addAttribute(
"target-cpu");
3338 RemoveAttrs.addAttribute(
"target-features");
3339 RemoveAttrs.addAttribute(
"fmv-features");
3340 RemoveAttrs.addAttribute(
"tune-cpu");
3341 F->removeFnAttrs(RemoveAttrs);
3342 F->addFnAttrs(Attrs);
3346 if (
const auto *CSA = D->
getAttr<CodeSegAttr>())
3347 GO->setSection(CSA->getName());
3348 else if (
const auto *SA = D->
getAttr<SectionAttr>())
3349 GO->setSection(SA->getName());
3362 F->setLinkage(llvm::Function::InternalLinkage);
3364 setNonAliasAttributes(GD, F);
3375 GV->
setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
3379 llvm::MDNode *MD = F->getMetadata(llvm::LLVMContext::MD_type);
3380 return MD && MD->hasGeneralizedMDString();
3384 llvm::Function *F) {
3391 if (!F->hasLocalLinkage() ||
3392 F->getFunction().hasAddressTaken(
nullptr,
true,
3399 llvm::Function *F) {
3401 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
3412 F->addTypeMetadata(0, MD);
3421 if (CodeGenOpts.SanitizeCfiCrossDso)
3423 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
3427 llvm::CallBase *CB) {
3432 if (!CodeGenOpts.CallGraphSection || !CB->isIndirectCall() ||
3437 llvm::MDTuple *TypeTuple = llvm::MDTuple::get(
3438 getLLVMContext(), {llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
3441 llvm::MDTuple *MDN = llvm::MDNode::get(
getLLVMContext(), {TypeTuple});
3442 CB->setMetadata(llvm::LLVMContext::MD_callee_type, MDN);
3446 llvm::LLVMContext &Ctx = F->getContext();
3447 llvm::MDBuilder MDB(Ctx);
3448 llvm::StringRef Salt;
3451 if (
const auto &Info = FP->getExtraAttributeInfo())
3452 Salt = Info.CFISalt;
3454 F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
3463 return llvm::all_of(Name, [](
const char &
C) {
3464 return llvm::isAlnum(
C) ||
C ==
'_' ||
C ==
'.';
3470 for (
auto &F : M.functions()) {
3472 bool AddressTaken = F.hasAddressTaken();
3473 if (!AddressTaken && F.hasLocalLinkage())
3474 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
3479 if (!AddressTaken || !F.isDeclaration())
3482 const llvm::ConstantInt *
Type;
3483 if (
const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
3484 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
3488 StringRef Name = F.getName();
3492 std::string
Asm = (
".weak __kcfi_typeid_" + Name +
"\n.set __kcfi_typeid_" +
3493 Name +
", " + Twine(
Type->getZExtValue()) +
" /* " +
3494 Twine(
Type->getSExtValue()) +
" */\n")
3496 M.appendModuleInlineAsm(
Asm);
3500void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
3501 bool IsIncompleteFunction,
3504 if (F->getIntrinsicID() != llvm::Intrinsic::not_intrinsic) {
3512 if (!IsIncompleteFunction)
3519 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
3521 assert(!F->arg_empty() &&
3522 F->arg_begin()->getType()
3523 ->canLosslesslyBitCastTo(F->getReturnType()) &&
3524 "unexpected this return");
3525 F->addParamAttr(0, llvm::Attribute::Returned);
3535 if (!IsIncompleteFunction && F->isDeclaration())
3538 if (
const auto *CSA = FD->
getAttr<CodeSegAttr>())
3539 F->setSection(CSA->getName());
3540 else if (
const auto *SA = FD->
getAttr<SectionAttr>())
3541 F->setSection(SA->getName());
3543 if (
const auto *EA = FD->
getAttr<ErrorAttr>()) {
3545 F->addFnAttr(
"dontcall-error", EA->getUserDiagnostic());
3546 else if (EA->isWarning())
3547 F->addFnAttr(
"dontcall-warn", EA->getUserDiagnostic());
3552 const FunctionDecl *FDBody;
3553 bool HasBody = FD->
hasBody(FDBody);
3555 assert(HasBody &&
"Inline builtin declarations should always have an "
3557 if (shouldEmitFunction(FDBody))
3558 F->addFnAttr(llvm::Attribute::NoBuiltin);
3564 F->addFnAttr(llvm::Attribute::NoBuiltin);
3568 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3569 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
3570 if (MD->isVirtual())
3571 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3577 if (!CodeGenOpts.SanitizeCfiCrossDso ||
3578 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
3581 if (CodeGenOpts.CallGraphSection)
3584 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
3590 if (CodeGenOpts.InlineMaxStackSize !=
UINT_MAX)
3591 F->addFnAttr(
"inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
3593 if (
const auto *CB = FD->
getAttr<CallbackAttr>()) {
3597 llvm::LLVMContext &Ctx = F->getContext();
3598 llvm::MDBuilder MDB(Ctx);
3602 int CalleeIdx = *CB->encoding_begin();
3603 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
3604 F->addMetadata(llvm::LLVMContext::MD_callback,
3605 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
3606 CalleeIdx, PayloadIndices,
3613 "Only globals with definition can force usage.");
3614 LLVMUsed.emplace_back(GV);
3618 assert(!GV->isDeclaration() &&
3619 "Only globals with definition can force usage.");
3620 LLVMCompilerUsed.emplace_back(GV);
3625 "Only globals with definition can force usage.");
3627 LLVMCompilerUsed.emplace_back(GV);
3629 LLVMUsed.emplace_back(GV);
3633 std::vector<llvm::WeakTrackingVH> &List) {
3640 UsedArray.resize(List.size());
3641 for (
unsigned i = 0, e = List.size(); i != e; ++i) {
3643 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3647 if (UsedArray.empty())
3649 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
3651 auto *GV =
new llvm::GlobalVariable(
3652 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
3653 llvm::ConstantArray::get(ATy, UsedArray), Name);
3655 GV->setSection(
"llvm.metadata");
3658void CodeGenModule::emitLLVMUsed() {
3659 emitUsed(*
this,
"llvm.used", LLVMUsed);
3660 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
3665 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3674 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3680 ELFDependentLibraries.push_back(
3681 llvm::MDNode::get(
C, llvm::MDString::get(
C, Lib)));
3688 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
C, MDOpts));
3697 if (Mod->
Parent && Visited.insert(Mod->
Parent).second) {
3703 if (Visited.insert(Import).second)
3720 if (LL.IsFramework) {
3721 llvm::Metadata *Args[2] = {llvm::MDString::get(Context,
"-framework"),
3722 llvm::MDString::get(Context, LL.Library)};
3724 Metadata.push_back(llvm::MDNode::get(Context, Args));
3730 llvm::Metadata *Args[2] = {
3731 llvm::MDString::get(Context,
"lib"),
3732 llvm::MDString::get(Context, LL.Library),
3734 Metadata.push_back(llvm::MDNode::get(Context, Args));
3738 auto *OptString = llvm::MDString::get(Context, Opt);
3739 Metadata.push_back(llvm::MDNode::get(Context, OptString));
3744void CodeGenModule::EmitModuleInitializers(
clang::Module *Primary) {
3746 "We should only emit module initializers for named modules.");
3754 assert(
isa<VarDecl>(D) &&
"GMF initializer decl is not a var?");
3771 assert(
isa<VarDecl>(D) &&
"PMF initializer decl is not a var?");
3777void CodeGenModule::EmitModuleLinkOptions() {
3781 llvm::SetVector<clang::Module *> LinkModules;
3782 llvm::SmallPtrSet<clang::Module *, 16> Visited;
3783 SmallVector<clang::Module *, 16> Stack;
3786 for (
Module *M : ImportedModules) {
3789 if (M->getTopLevelModuleName() ==
getLangOpts().CurrentModule &&
3792 if (Visited.insert(M).second)
3798 while (!Stack.empty()) {
3801 bool AnyChildren =
false;
3810 if (Visited.insert(
SM).second) {
3811 Stack.push_back(
SM);
3819 LinkModules.insert(Mod);
3826 SmallVector<llvm::MDNode *, 16> MetadataArgs;
3828 for (
Module *M : LinkModules)
3829 if (Visited.insert(M).second)
3831 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
3832 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
3835 if (!LinkerOptionsMetadata.empty()) {
3836 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.linker.options");
3837 for (
auto *MD : LinkerOptionsMetadata)
3838 NMD->addOperand(MD);
3842void CodeGenModule::EmitDeferred() {
3851 if (!DeferredVTables.empty()) {
3852 EmitDeferredVTables();
3857 assert(DeferredVTables.empty());
3864 llvm::append_range(DeferredDeclsToEmit,
3868 if (DeferredDeclsToEmit.empty())
3873 std::vector<GlobalDecl> CurDeclsToEmit;
3874 CurDeclsToEmit.swap(DeferredDeclsToEmit);
3876 for (GlobalDecl &D : CurDeclsToEmit) {
3882 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>() &&
3886 if (!FD->
getAttr<SYCLKernelEntryPointAttr>()->isInvalidAttr()) {
3902 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
3920 if (!GV->isDeclaration())
3924 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
3928 EmitGlobalDefinition(D, GV);
3933 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
3935 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
3940void CodeGenModule::EmitVTablesOpportunistically() {
3946 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
3947 &&
"Only emit opportunistic vtables with optimizations");
3949 for (
const CXXRecordDecl *RD : OpportunisticVTables) {
3951 "This queue should only contain external vtables");
3952 if (
getCXXABI().canSpeculativelyEmitVTable(RD))
3953 VTables.GenerateClassData(RD);
3955 OpportunisticVTables.clear();
3959 for (
const auto& [MangledName, VD] : DeferredAnnotations) {
3964 DeferredAnnotations.clear();
3966 if (Annotations.empty())
3970 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
3971 Annotations[0]->
getType(), Annotations.size()), Annotations);
3972 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
3973 llvm::GlobalValue::AppendingLinkage,
3974 Array,
"llvm.global.annotations");
3979 llvm::Constant *&AStr = AnnotationStrings[Str];
3984 llvm::Constant *s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
3985 auto *gv =
new llvm::GlobalVariable(
3986 getModule(), s->getType(),
true, llvm::GlobalValue::PrivateLinkage, s,
3987 ".str",
nullptr, llvm::GlobalValue::NotThreadLocal,
3990 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4007 SM.getExpansionLineNumber(L);
4008 return llvm::ConstantInt::get(
Int32Ty, LineNo);
4016 llvm::FoldingSetNodeID ID;
4017 for (
Expr *E : Exprs) {
4020 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
4025 LLVMArgs.reserve(Exprs.size());
4027 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](
const Expr *E) {
4029 return ConstEmiter.
emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
4032 auto *
Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
4033 auto *GV =
new llvm::GlobalVariable(
getModule(),
Struct->getType(),
true,
4034 llvm::GlobalValue::PrivateLinkage,
Struct,
4037 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4044 const AnnotateAttr *AA,
4052 llvm::Constant *GVInGlobalsAS = GV;
4053 if (GV->getAddressSpace() !=
4055 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
4057 llvm::PointerType::get(
4058 GV->getContext(),
getDataLayout().getDefaultGlobalsAddressSpace()));
4062 llvm::Constant *Fields[] = {
4063 GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
4065 return llvm::ConstantStruct::getAnon(Fields);
4069 llvm::GlobalValue *GV) {
4070 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
4080 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
4083 auto &
SM = Context.getSourceManager();
4085 if (NoSanitizeL.containsMainFile(Kind, MainFile.
getName()))
4090 return NoSanitizeL.containsLocation(Kind, Loc);
4093 return NoSanitizeL.containsFile(Kind, MainFile.
getName());
4097 llvm::GlobalVariable *GV,
4099 StringRef Category)
const {
4101 if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
4103 auto &
SM = Context.getSourceManager();
4104 if (NoSanitizeL.containsMainFile(
4105 Kind,
SM.getFileEntryRefForID(
SM.getMainFileID())->getName(),
4108 if (NoSanitizeL.containsLocation(Kind, Loc, Category))
4115 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
4116 Ty = AT->getElementType();
4121 if (NoSanitizeL.containsType(Kind, TypeStr, Category))
4129 StringRef Category)
const {
4132 auto Attr = ImbueAttr::NONE;
4134 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
4135 if (
Attr == ImbueAttr::NONE)
4136 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
4138 case ImbueAttr::NONE:
4140 case ImbueAttr::ALWAYS:
4141 Fn->addFnAttr(
"function-instrument",
"xray-always");
4143 case ImbueAttr::ALWAYS_ARG1:
4144 Fn->addFnAttr(
"function-instrument",
"xray-always");
4145 Fn->addFnAttr(
"xray-log-args",
"1");
4147 case ImbueAttr::NEVER:
4148 Fn->addFnAttr(
"function-instrument",
"xray-never");
4161 llvm::driver::ProfileInstrKind Kind =
getCodeGenOpts().getProfileInstr();
4171 auto &
SM = Context.getSourceManager();
4172 if (
auto MainFile =
SM.getFileEntryRefForID(
SM.getMainFileID()))
4186 if (NumGroups > 1) {
4187 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
4196 if (LangOpts.EmitAllDecls)
4199 const auto *VD = dyn_cast<VarDecl>(
Global);
4201 ((CodeGenOpts.KeepPersistentStorageVariables &&
4202 (VD->getStorageDuration() ==
SD_Static ||
4203 VD->getStorageDuration() ==
SD_Thread)) ||
4204 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
4205 VD->getType().isConstQualified())))
4218 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
4219 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
4220 OMPDeclareTargetDeclAttr::getActiveAttr(
Global);
4221 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (
unsigned)-1)
4225 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
4235 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>())
4242 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
4243 if (Context.getInlineVariableDefinitionKind(VD) ==
4248 if (CXX20ModuleInits && VD->getOwningModule() &&
4249 !VD->getOwningModule()->isModuleMapModule()) {
4258 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
4261 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
Global))
4274 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
4278 llvm::Constant *
Init;
4281 if (!
V.isAbsent()) {
4292 llvm::Constant *Fields[4] = {
4296 llvm::ConstantDataArray::getRaw(
4297 StringRef(
reinterpret_cast<char *
>(Parts.
Part4And5), 8), 8,
4299 Init = llvm::ConstantStruct::getAnon(Fields);
4302 auto *GV =
new llvm::GlobalVariable(
4304 true, llvm::GlobalValue::LinkOnceODRLinkage,
Init, Name);
4306 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4309 if (!
V.isAbsent()) {
4322 llvm::GlobalVariable **Entry =
nullptr;
4323 Entry = &UnnamedGlobalConstantDeclMap[GCD];
4328 llvm::Constant *
Init;
4332 assert(!
V.isAbsent());
4336 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
4338 llvm::GlobalValue::PrivateLinkage,
Init,
4340 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4354 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
4358 llvm::Constant *
Init =
Emitter.emitForInitializer(
4366 llvm::GlobalValue::LinkageTypes
Linkage =
4368 ? llvm::GlobalValue::LinkOnceODRLinkage
4369 : llvm::GlobalValue::InternalLinkage;
4370 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
4374 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4381 const AliasAttr *AA = VD->
getAttr<AliasAttr>();
4382 assert(AA &&
"No alias?");
4392 llvm::Constant *Aliasee;
4394 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
4402 F->setLinkage(llvm::Function::ExternalWeakLinkage);
4403 WeakRefReferences.insert(F);
4411 if (
auto *A = D->
getAttr<AttrT>())
4412 return A->isImplicit();
4419 if (!LangOpts.OpenMPIsTargetDevice && !LangOpts.CUDA)
4422 const auto *AA =
Global->getAttr<AliasAttr>();
4430 const auto *AliaseeDecl = dyn_cast<ValueDecl>(AliaseeGD.getDecl());
4431 if (LangOpts.OpenMPIsTargetDevice)
4432 return !AliaseeDecl ||
4433 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(AliaseeDecl);
4436 const bool HasDeviceAttr =
Global->hasAttr<CUDADeviceAttr>();
4437 const bool AliaseeHasDeviceAttr =
4438 AliaseeDecl && AliaseeDecl->hasAttr<CUDADeviceAttr>();
4440 if (LangOpts.CUDAIsDevice)
4441 return !HasDeviceAttr || !AliaseeHasDeviceAttr;
4448bool CodeGenModule::shouldEmitCUDAGlobalVar(
const VarDecl *
Global)
const {
4449 assert(LangOpts.CUDA &&
"Should not be called by non-CUDA languages");
4454 return !LangOpts.CUDAIsDevice ||
Global->hasAttr<CUDADeviceAttr>() ||
4455 Global->hasAttr<CUDAConstantAttr>() ||
4456 Global->hasAttr<CUDASharedAttr>() ||
4457 Global->getType()->isCUDADeviceBuiltinSurfaceType() ||
4458 Global->getType()->isCUDADeviceBuiltinTextureType();
4465 if (
Global->hasAttr<WeakRefAttr>())
4470 if (
Global->hasAttr<AliasAttr>()) {
4473 return EmitAliasDefinition(GD);
4477 if (
Global->hasAttr<IFuncAttr>())
4478 return emitIFuncDefinition(GD);
4481 if (
Global->hasAttr<CPUDispatchAttr>())
4482 return emitCPUDispatchDefinition(GD);
4487 if (LangOpts.CUDA) {
4489 "Expected Variable or Function");
4490 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
4491 if (!shouldEmitCUDAGlobalVar(VD))
4493 }
else if (LangOpts.CUDAIsDevice) {
4494 const auto *FD = dyn_cast<FunctionDecl>(
Global);
4495 if ((!
Global->hasAttr<CUDADeviceAttr>() ||
4496 (LangOpts.OffloadImplicitHostDeviceTemplates &&
4500 !
getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
4501 !
Global->hasAttr<CUDAGlobalAttr>() &&
4503 !
Global->hasAttr<CUDAHostAttr>()))
4506 }
else if (!
Global->hasAttr<CUDAHostAttr>() &&
4507 Global->hasAttr<CUDADeviceAttr>())
4511 if (LangOpts.OpenMP) {
4513 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
4515 if (
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(
Global)) {
4516 if (MustBeEmitted(
Global))
4520 if (
auto *DMD = dyn_cast<OMPDeclareMapperDecl>(
Global)) {
4521 if (MustBeEmitted(
Global))
4528 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
4529 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
4535 if (FD->
hasAttr<AnnotateAttr>()) {
4538 DeferredAnnotations[MangledName] = FD;
4553 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
4559 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
4561 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
4562 if (LangOpts.OpenMP) {
4564 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
4565 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
4569 if (VD->hasExternalStorage() &&
4570 Res != OMPDeclareTargetDeclAttr::MT_Link)
4573 bool UnifiedMemoryEnabled =
4575 if (*Res == OMPDeclareTargetDeclAttr::MT_Local ||
4576 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4577 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4578 !UnifiedMemoryEnabled)) {
4581 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
4582 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4583 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4584 UnifiedMemoryEnabled)) &&
4585 "Link clause or to clause with unified memory expected.");
4595 if (LangOpts.HLSL) {
4596 if (VD->getStorageClass() ==
SC_Extern) {
4605 if (Context.getInlineVariableDefinitionKind(VD) ==
4615 if (MustBeEmitted(
Global) && MayBeEmittedEagerly(
Global)) {
4617 EmitGlobalDefinition(GD);
4618 addEmittedDeferredDecl(GD);
4626 DelayedCXXInitPosition[
Global] = CXXGlobalInits.size();
4627 CXXGlobalInits.push_back(
nullptr);
4633 addDeferredDeclToEmit(GD);
4634 }
else if (MustBeEmitted(
Global)) {
4636 assert(!MayBeEmittedEagerly(
Global));
4637 addDeferredDeclToEmit(GD);
4642 DeferredDecls[MangledName] = GD;
4648 if (
const auto *RT =
4649 T->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
4650 if (
auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
4651 RD = RD->getDefinitionOrSelf();
4652 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
4660 struct FunctionIsDirectlyRecursive
4661 :
public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
4662 const StringRef Name;
4663 const Builtin::Context &BI;
4664 FunctionIsDirectlyRecursive(StringRef N,
const Builtin::Context &
C)
4667 bool VisitCallExpr(
const CallExpr *E) {
4671 AsmLabelAttr *Attr = FD->
getAttr<AsmLabelAttr>();
4672 if (Attr && Name == Attr->getLabel())
4677 std::string BuiltinNameStr = BI.
getName(BuiltinID);
4678 StringRef BuiltinName = BuiltinNameStr;
4679 return BuiltinName.consume_front(
"__builtin_") && Name == BuiltinName;
4682 bool VisitStmt(
const Stmt *S) {
4683 for (
const Stmt *Child : S->
children())
4684 if (Child && this->Visit(Child))
4691 struct DLLImportFunctionVisitor
4692 :
public RecursiveASTVisitor<DLLImportFunctionVisitor> {
4693 bool SafeToInline =
true;
4695 bool shouldVisitImplicitCode()
const {
return true; }
4697 bool VisitVarDecl(VarDecl *VD) {
4700 SafeToInline =
false;
4701 return SafeToInline;
4708 return SafeToInline;
4711 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
4713 SafeToInline = D->
hasAttr<DLLImportAttr>();
4714 return SafeToInline;
4717 bool VisitDeclRefExpr(DeclRefExpr *E) {
4720 SafeToInline = VD->
hasAttr<DLLImportAttr>();
4721 else if (VarDecl *
V = dyn_cast<VarDecl>(VD))
4722 SafeToInline = !
V->hasGlobalStorage() ||
V->hasAttr<DLLImportAttr>();
4723 return SafeToInline;
4726 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
4728 return SafeToInline;
4731 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4735 SafeToInline =
true;
4737 SafeToInline = M->
hasAttr<DLLImportAttr>();
4739 return SafeToInline;
4742 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
4744 return SafeToInline;
4747 bool VisitCXXNewExpr(CXXNewExpr *E) {
4749 return SafeToInline;
4758CodeGenModule::isTriviallyRecursive(
const FunctionDecl *FD) {
4760 if (
getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
4762 AsmLabelAttr *Attr = FD->
getAttr<AsmLabelAttr>();
4765 Name = Attr->getLabel();
4770 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
4771 const Stmt *Body = FD->
getBody();
4772 return Body ? Walker.Visit(Body) :
false;
4775bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
4782 if (F->isInlineBuiltinDeclaration())
4785 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
4790 if (
const Module *M = F->getOwningModule();
4791 M && M->getTopLevelModule()->isNamedModule() &&
4792 getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
4802 if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
4807 if (F->hasAttr<NoInlineAttr>())
4810 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
4812 DLLImportFunctionVisitor Visitor;
4813 Visitor.TraverseFunctionDecl(
const_cast<FunctionDecl*
>(F));
4814 if (!Visitor.SafeToInline)
4817 if (
const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
4820 for (
const Decl *
Member : Dtor->getParent()->decls())
4824 for (
const CXXBaseSpecifier &B : Dtor->getParent()->bases())
4835 return !isTriviallyRecursive(F);
4838bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
4839 return CodeGenOpts.OptimizationLevel > 0;
4842void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
4843 llvm::GlobalValue *GV) {
4847 auto *Spec = FD->
getAttr<CPUSpecificAttr>();
4848 for (
unsigned I = 0; I < Spec->cpus_size(); ++I)
4850 }
else if (
auto *TC = FD->
getAttr<TargetClonesAttr>()) {
4851 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I)
4852 if (TC->isFirstOfVersion(I))
4855 EmitGlobalFunctionDefinition(GD, GV);
4861 AddDeferredMultiVersionResolverToEmit(GD);
4863 GetOrCreateMultiVersionResolver(GD);
4867void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
4870 PrettyStackTraceDecl CrashInfo(
const_cast<ValueDecl *
>(D), D->
getLocation(),
4871 Context.getSourceManager(),
4872 "Generating code for declaration");
4874 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
4877 if (!shouldEmitFunction(GD))
4880 llvm::TimeTraceScope TimeScope(
"CodeGen Function", [&]() {
4882 llvm::raw_string_ostream
OS(Name);
4888 if (
const auto *
Method = dyn_cast<CXXMethodDecl>(D)) {
4892 ABI->emitCXXStructor(GD);
4894 EmitMultiVersionFunctionDefinition(GD, GV);
4896 EmitGlobalFunctionDefinition(GD, GV);
4905 return EmitMultiVersionFunctionDefinition(GD, GV);
4906 return EmitGlobalFunctionDefinition(GD, GV);
4909 if (
const auto *VD = dyn_cast<VarDecl>(D))
4910 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
4912 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
4916 llvm::Function *NewFn);
4932static llvm::GlobalValue::LinkageTypes
4936 return llvm::GlobalValue::InternalLinkage;
4937 return llvm::GlobalValue::WeakODRLinkage;
4940void CodeGenModule::emitMultiVersionFunctions() {
4941 std::vector<GlobalDecl> MVFuncsToEmit;
4942 MultiVersionFuncs.swap(MVFuncsToEmit);
4943 for (GlobalDecl GD : MVFuncsToEmit) {
4945 assert(FD &&
"Expected a FunctionDecl");
4947 auto createFunction = [&](
const FunctionDecl *
Decl,
unsigned MVIdx = 0) {
4948 GlobalDecl CurGD{
Decl->isDefined() ?
Decl->getDefinition() :
Decl, MVIdx};
4952 if (
Decl->isDefined()) {
4953 EmitGlobalFunctionDefinition(CurGD,
nullptr);
4961 assert(
Func &&
"This should have just been created");
4969 bool ShouldEmitResolver = !
getTriple().isAArch64();
4970 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
4971 llvm::DenseMap<llvm::Function *, const FunctionDecl *> DeclMap;
4974 FD, [&](
const FunctionDecl *CurFD) {
4975 llvm::SmallVector<StringRef, 8> Feats;
4978 if (
const auto *TA = CurFD->
getAttr<TargetAttr>()) {
4980 TA->getX86AddedFeatures(Feats);
4981 llvm::Function *
Func = createFunction(CurFD);
4982 DeclMap.insert({
Func, CurFD});
4983 Options.emplace_back(
Func, Feats, TA->getX86Architecture());
4984 }
else if (
const auto *TVA = CurFD->
getAttr<TargetVersionAttr>()) {
4985 if (TVA->isDefaultVersion() && IsDefined)
4986 ShouldEmitResolver =
true;
4987 llvm::Function *
Func = createFunction(CurFD);
4988 DeclMap.insert({
Func, CurFD});
4990 TVA->getFeatures(Feats, Delim);
4991 Options.emplace_back(
Func, Feats);
4992 }
else if (
const auto *TC = CurFD->
getAttr<TargetClonesAttr>()) {
4993 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
4994 if (!TC->isFirstOfVersion(I))
4996 if (TC->isDefaultVersion(I) && IsDefined)
4997 ShouldEmitResolver =
true;
4998 llvm::Function *
Func = createFunction(CurFD, I);
4999 DeclMap.insert({
Func, CurFD});
5002 TC->getX86Feature(Feats, I);
5003 Options.emplace_back(
Func, Feats, TC->getX86Architecture(I));
5006 TC->getFeatures(Feats, I, Delim);
5007 Options.emplace_back(
Func, Feats);
5011 llvm_unreachable(
"unexpected MultiVersionKind");
5014 if (!ShouldEmitResolver)
5017 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
5018 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
5019 ResolverConstant = IFunc->getResolver();
5024 *
this, GD, FD,
true);
5031 auto *Alias = llvm::GlobalAlias::create(
5033 MangledName +
".ifunc", IFunc, &
getModule());
5042 Options, [&TI](
const CodeGenFunction::FMVResolverOption &LHS,
5043 const CodeGenFunction::FMVResolverOption &RHS) {
5049 for (
auto I = Options.begin() + 1, E = Options.end(); I != E; ++I) {
5050 llvm::APInt RHS = llvm::AArch64::getCpuSupportsMask(I->Features);
5051 if (std::any_of(Options.begin(), I, [RHS](
auto RO) {
5052 llvm::APInt LHS = llvm::AArch64::getCpuSupportsMask(RO.Features);
5053 return LHS.isSubsetOf(RHS);
5055 Diags.Report(DeclMap[I->Function]->getLocation(),
5056 diag::warn_unreachable_version)
5057 << I->Function->getName();
5058 assert(I->Function->user_empty() &&
"unexpected users");
5059 I->Function->eraseFromParent();
5060 I->Function =
nullptr;
5064 CodeGenFunction CGF(*
this);
5065 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
5067 setMultiVersionResolverAttributes(ResolverFunc, GD);
5069 ResolverFunc->setComdat(
5070 getModule().getOrInsertComdat(ResolverFunc->getName()));
5076 if (!MVFuncsToEmit.empty())
5081 if (!MultiVersionFuncs.empty())
5082 emitMultiVersionFunctions();
5092 llvm::GlobalValue *DS = TheModule.getNamedValue(DSName);
5094 DS =
new llvm::GlobalVariable(TheModule,
Int8Ty,
false,
5095 llvm::GlobalVariable::ExternalWeakLinkage,
5097 DS->setVisibility(llvm::GlobalValue::HiddenVisibility);
5102void CodeGenModule::emitPFPFieldsWithEvaluatedOffset() {
5103 llvm::Constant *Nop = llvm::ConstantExpr::getIntToPtr(
5105 for (
auto *FD :
getContext().PFPFieldsWithEvaluatedOffset) {
5107 llvm::GlobalValue *OldDS = TheModule.getNamedValue(DSName);
5108 llvm::GlobalValue *DS = llvm::GlobalAlias::create(
5109 Int8Ty, 0, llvm::GlobalValue::ExternalLinkage, DSName, Nop, &TheModule);
5110 DS->setVisibility(llvm::GlobalValue::HiddenVisibility);
5112 DS->takeName(OldDS);
5113 OldDS->replaceAllUsesWith(DS);
5114 OldDS->eraseFromParent();
5120 llvm::Constant *
New) {
5123 Old->replaceAllUsesWith(
New);
5124 Old->eraseFromParent();
5127void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
5129 assert(FD &&
"Not a FunctionDecl?");
5131 const auto *DD = FD->
getAttr<CPUDispatchAttr>();
5132 assert(DD &&
"Not a cpu_dispatch Function?");
5138 UpdateMultiVersionNames(GD, FD, ResolverName);
5140 llvm::Type *ResolverType;
5141 GlobalDecl ResolverGD;
5143 ResolverType = llvm::FunctionType::get(
5154 ResolverName, ResolverType, ResolverGD,
false));
5157 ResolverFunc->setComdat(
5158 getModule().getOrInsertComdat(ResolverFunc->getName()));
5160 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
5163 for (
const IdentifierInfo *II : DD->cpus()) {
5171 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
5174 EmitGlobalFunctionDefinition(ExistingDecl,
nullptr);
5180 Func = GetOrCreateLLVMFunction(
5181 MangledName, DeclTy, ExistingDecl,
5187 llvm::SmallVector<StringRef, 32> Features;
5188 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
5189 llvm::transform(Features, Features.begin(),
5190 [](StringRef Str) { return Str.substr(1); });
5191 llvm::erase_if(Features, [&Target](StringRef Feat) {
5192 return !Target.validateCpuSupports(Feat);
5198 llvm::stable_sort(Options, [](
const CodeGenFunction::FMVResolverOption &LHS,
5199 const CodeGenFunction::FMVResolverOption &RHS) {
5200 return llvm::X86::getCpuSupportsMask(LHS.
Features) >
5201 llvm::X86::getCpuSupportsMask(RHS.
Features);
5208 while (Options.size() > 1 && llvm::all_of(llvm::X86::getCpuSupportsMask(
5209 (Options.end() - 2)->Features),
5210 [](
auto X) { return X == 0; })) {
5211 StringRef LHSName = (Options.end() - 2)->Function->getName();
5212 StringRef RHSName = (Options.end() - 1)->Function->getName();
5213 if (LHSName.compare(RHSName) < 0)
5214 Options.erase(Options.end() - 2);
5216 Options.erase(Options.end() - 1);
5219 CodeGenFunction CGF(*
this);
5220 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
5221 setMultiVersionResolverAttributes(ResolverFunc, GD);
5226 unsigned AS = IFunc->getType()->getPointerAddressSpace();
5231 auto *GI = llvm::GlobalIFunc::create(DeclTy, AS,
Linkage,
"",
5238 *
this, GD, FD,
true);
5241 auto *GA = llvm::GlobalAlias::create(DeclTy, AS,
Linkage, AliasName,
5249void CodeGenModule::AddDeferredMultiVersionResolverToEmit(GlobalDecl GD) {
5251 assert(FD &&
"Not a FunctionDecl?");
5254 std::string MangledName =
5256 if (!DeferredResolversToEmit.insert(MangledName).second)
5259 MultiVersionFuncs.push_back(GD);
5265llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
5267 assert(FD &&
"Not a FunctionDecl?");
5269 std::string MangledName =
5274 std::string ResolverName = MangledName;
5278 llvm_unreachable(
"unexpected MultiVersionKind::None for resolver");
5282 ResolverName +=
".ifunc";
5289 ResolverName +=
".resolver";
5292 bool ShouldReturnIFunc =
5311 AddDeferredMultiVersionResolverToEmit(GD);
5315 if (ShouldReturnIFunc) {
5317 llvm::Type *ResolverType = llvm::FunctionType::get(
5319 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
5320 MangledName +
".resolver", ResolverType, GlobalDecl{},
5328 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(DeclTy, AS,
Linkage,
"",
5330 GIF->setName(ResolverName);
5337 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
5338 ResolverName, DeclTy, GlobalDecl{},
false);
5340 "Resolver should be created for the first time");
5345void CodeGenModule::setMultiVersionResolverAttributes(llvm::Function *Resolver,
5347 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(GD.
getDecl());
5360 Resolver->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
5371bool CodeGenModule::shouldDropDLLAttribute(
const Decl *D,
5372 const llvm::GlobalValue *GV)
const {
5373 auto SC = GV->getDLLStorageClass();
5374 if (SC == llvm::GlobalValue::DefaultStorageClass)
5377 return (((SC == llvm::GlobalValue::DLLImportStorageClass &&
5378 !MRD->
hasAttr<DLLImportAttr>()) ||
5379 (SC == llvm::GlobalValue::DLLExportStorageClass &&
5380 !MRD->
hasAttr<DLLExportAttr>())) &&
5391llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
5392 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD,
bool ForVTable,
5393 bool DontDefer,
bool IsThunk, llvm::AttributeList ExtraAttrs,
5397 std::string NameWithoutMultiVersionMangling;
5398 if (
const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
5400 if (
getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
5401 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->
isDefined() &&
5402 !DontDefer && !IsForDefinition) {
5405 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
5407 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
5410 GDDef = GlobalDecl(FDDef);
5418 UpdateMultiVersionNames(GD, FD, MangledName);
5419 if (!IsForDefinition) {
5425 AddDeferredMultiVersionResolverToEmit(GD);
5427 *
this, GD, FD,
true);
5436 *
this, GD, FD,
true);
5438 return GetOrCreateMultiVersionResolver(GD);
5443 if (!NameWithoutMultiVersionMangling.empty())
5444 MangledName = NameWithoutMultiVersionMangling;
5449 if (WeakRefReferences.erase(Entry)) {
5450 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
5451 if (FD && !FD->
hasAttr<WeakAttr>())
5452 Entry->setLinkage(llvm::Function::ExternalLinkage);
5456 if (D && shouldDropDLLAttribute(D, Entry)) {
5457 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5463 if (IsForDefinition && !Entry->isDeclaration()) {
5470 DiagnosedConflictingDefinitions.insert(GD).second) {
5474 diag::note_previous_definition);
5479 (Entry->getValueType() == Ty)) {
5486 if (!IsForDefinition)
5493 bool IsIncompleteFunction =
false;
5495 llvm::FunctionType *FTy;
5499 FTy = llvm::FunctionType::get(
VoidTy,
false);
5500 IsIncompleteFunction =
true;
5504 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
5505 Entry ? StringRef() : MangledName, &
getModule());
5509 if (D && D->
hasAttr<AnnotateAttr>())
5527 if (!Entry->use_empty()) {
5529 Entry->removeDeadConstantUsers();
5535 assert(F->getName() == MangledName &&
"name was uniqued!");
5537 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
5538 if (ExtraAttrs.hasFnAttrs()) {
5539 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
5547 if (isa_and_nonnull<CXXDestructorDecl>(D) &&
5550 addDeferredDeclToEmit(GD);
5555 auto DDI = DeferredDecls.find(MangledName);
5556 if (DDI != DeferredDecls.end()) {
5560 addDeferredDeclToEmit(DDI->second);
5561 DeferredDecls.erase(DDI);
5589 if (!IsIncompleteFunction) {
5590 assert(F->getFunctionType() == Ty);
5608 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
5618 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(GD.
getDecl())) {
5621 DD->getParent()->getNumVBases() == 0)
5626 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
5627 false, llvm::AttributeList(),
5630 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
5634 if (IsForDefinition)
5642 llvm::GlobalValue *F =
5645 return llvm::NoCFIValue::get(F);
5655 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
5658 if (!
C.getLangOpts().CPlusPlus)
5663 (Name ==
"_ZSt9terminatev" || Name ==
"?terminate@@YAXXZ")
5664 ?
C.Idents.get(
"terminate")
5665 :
C.Idents.get(Name);
5667 for (
const auto &N : {
"__cxxabiv1",
"std"}) {
5671 if (
auto *LSD = dyn_cast<LinkageSpecDecl>(
Result))
5672 for (
const auto *
Result : LSD->lookup(&NS))
5673 if ((ND = dyn_cast<NamespaceDecl>(
Result)))
5678 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
5687 llvm::Function *F, StringRef Name) {
5693 if (!Local && CGM.
getTriple().isWindowsItaniumEnvironment() &&
5696 if (!FD || FD->
hasAttr<DLLImportAttr>()) {
5697 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
5698 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
5705 llvm::AttributeList ExtraAttrs,
bool Local,
bool AssumeConvergent) {
5706 if (AssumeConvergent) {
5708 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5711 QualType FTy = Context.getFunctionType(ReturnTy, ArgTys,
5716 llvm::Constant *
C = GetOrCreateLLVMFunction(
5718 false,
false, ExtraAttrs);
5720 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
5736 llvm::AttributeList ExtraAttrs,
bool Local,
5737 bool AssumeConvergent) {
5738 if (AssumeConvergent) {
5740 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5744 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
5748 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
5757 markRegisterParameterAttributes(F);
5783 if (WeakRefReferences.erase(Entry)) {
5784 if (D && !D->
hasAttr<WeakAttr>())
5785 Entry->setLinkage(llvm::Function::ExternalLinkage);
5789 if (D && shouldDropDLLAttribute(D, Entry))
5790 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5792 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
5795 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
5800 if (IsForDefinition && !Entry->isDeclaration()) {
5808 (OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
5810 DiagnosedConflictingDefinitions.insert(D).second) {
5814 diag::note_previous_definition);
5819 if (Entry->getType()->getAddressSpace() != TargetAS)
5820 return llvm::ConstantExpr::getAddrSpaceCast(
5821 Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
5825 if (!IsForDefinition)
5831 auto *GV =
new llvm::GlobalVariable(
5832 getModule(), Ty,
false, llvm::GlobalValue::ExternalLinkage,
nullptr,
5833 MangledName,
nullptr, llvm::GlobalVariable::NotThreadLocal,
5834 getContext().getTargetAddressSpace(DAddrSpace));
5839 GV->takeName(Entry);
5841 if (!Entry->use_empty()) {
5842 Entry->replaceAllUsesWith(GV);
5845 Entry->eraseFromParent();
5851 auto DDI = DeferredDecls.find(MangledName);
5852 if (DDI != DeferredDecls.end()) {
5855 addDeferredDeclToEmit(DDI->second);
5856 DeferredDecls.erase(DDI);
5861 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
5868 GV->setAlignment(
getContext().getDeclAlign(D).getAsAlign());
5874 CXXThreadLocals.push_back(D);
5882 if (
getContext().isMSStaticDataMemberInlineDefinition(D)) {
5883 EmitGlobalVarDefinition(D);
5888 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>())
5889 GV->setSection(SA->getName());
5893 if (
getTriple().getArch() == llvm::Triple::xcore &&
5897 GV->setSection(
".cp.rodata");
5900 if (
const auto *CMA = D->
getAttr<CodeModelAttr>())
5901 GV->setCodeModel(CMA->getModel());
5906 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
5910 Context.getBaseElementType(D->
getType())->getAsCXXRecordDecl();
5911 bool HasMutableFields =
Record &&
Record->hasMutableFields();
5912 if (!HasMutableFields) {
5919 auto *InitType =
Init->getType();
5920 if (GV->getValueType() != InitType) {
5925 GV->setName(StringRef());
5930 ->stripPointerCasts());
5933 GV->eraseFromParent();
5936 GV->setInitializer(
Init);
5937 GV->setConstant(
true);
5938 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
5958 SanitizerMD->reportGlobal(GV, *D);
5963 assert(
getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
5964 if (DAddrSpace != ExpectedAS)
5977 false, IsForDefinition);
5998 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes
Linkage,
5999 llvm::Align Alignment) {
6000 llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
6001 llvm::GlobalVariable *OldGV =
nullptr;
6005 if (GV->getValueType() == Ty)
6010 assert(GV->isDeclaration() &&
"Declaration has wrong type!");
6015 GV =
new llvm::GlobalVariable(
getModule(), Ty,
true,
6020 GV->takeName(OldGV);
6022 if (!OldGV->use_empty()) {
6023 OldGV->replaceAllUsesWith(GV);
6026 OldGV->eraseFromParent();
6030 !GV->hasAvailableExternallyLinkage())
6031 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
6033 GV->setAlignment(Alignment);
6070 assert(!D->
getInit() &&
"Cannot emit definite definitions here!");
6078 if (GV && !GV->isDeclaration())
6083 if (!MustBeEmitted(D) && !GV) {
6084 DeferredDecls[MangledName] = D;
6089 EmitGlobalVarDefinition(D);
6094 if (
auto const *CD = dyn_cast<const CXXConstructorDecl>(D))
6096 else if (
auto const *DD = dyn_cast<const CXXDestructorDecl>(D))
6111 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(
Addr)) {
6115 if (
const auto *VD = dyn_cast<VarDecl>(D)) {
6118 }
else if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
6120 if (!Fn->getSubprogram())
6126 return Context.toCharUnitsFromBits(
6131 if (LangOpts.OpenCL) {
6142 if (LangOpts.SYCLIsDevice &&
6146 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
6148 if (D->
hasAttr<CUDAConstantAttr>())
6150 if (D->
hasAttr<CUDASharedAttr>())
6152 if (D->
hasAttr<CUDADeviceAttr>())
6160 if (LangOpts.OpenMP) {
6162 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
6170 if (LangOpts.OpenCL)
6172 if (LangOpts.SYCLIsDevice)
6174 if (LangOpts.HIP && LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())
6182 if (
auto AS =
getTarget().getConstantAddressSpace())
6195static llvm::Constant *
6197 llvm::GlobalVariable *GV) {
6198 llvm::Constant *Cast = GV;
6203 GV, llvm::PointerType::get(
6210template<
typename SomeDecl>
6212 llvm::GlobalValue *GV) {
6227 const SomeDecl *
First = D->getFirstDecl();
6228 if (
First->getDeclContext()->isRecord() || !
First->isInExternCContext())
6234 std::pair<StaticExternCMap::iterator, bool> R =
6235 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
6240 R.first->second =
nullptr;
6247 if (D.
hasAttr<SelectAnyAttr>())
6251 if (
auto *VD = dyn_cast<VarDecl>(&D))
6265 llvm_unreachable(
"No such linkage");
6273 llvm::GlobalObject &GO) {
6276 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
6284void CodeGenModule::EmitGlobalVarDefinition(
const VarDecl *D,
6299 if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
6300 OpenMPRuntime->emitTargetGlobalVariable(D))
6303 llvm::TrackingVH<llvm::Constant>
Init;
6304 bool NeedsGlobalCtor =
false;
6308 bool IsDefinitionAvailableExternally =
6310 bool NeedsGlobalDtor =
6311 !IsDefinitionAvailableExternally &&
6318 if (IsDefinitionAvailableExternally &&
6329 std::optional<ConstantEmitter> emitter;
6334 bool IsCUDASharedVar =
6339 bool IsCUDAShadowVar =
6341 (D->
hasAttr<CUDAConstantAttr>() || D->
hasAttr<CUDADeviceAttr>() ||
6342 D->
hasAttr<CUDASharedAttr>());
6343 bool IsCUDADeviceShadowVar =
6348 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) {
6349 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
6353 Init = llvm::PoisonValue::get(
getTypes().ConvertType(ASTTy));
6356 }
else if (D->
hasAttr<LoaderUninitializedAttr>()) {
6357 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
6358 }
else if (!InitExpr) {
6371 initializedGlobalDecl = GlobalDecl(D);
6372 emitter.emplace(*
this);
6373 llvm::Constant *
Initializer = emitter->tryEmitForInitializer(*InitDecl);
6375 QualType T = InitExpr->
getType();
6381 if (!IsDefinitionAvailableExternally)
6382 NeedsGlobalCtor =
true;
6386 NeedsGlobalCtor =
false;
6390 Init = llvm::PoisonValue::get(
getTypes().ConvertType(T));
6398 DelayedCXXInitPosition.erase(D);
6405 assert(VarSize == CstSize &&
"Emitted constant has unexpected size");
6410 llvm::Type* InitType =
Init->getType();
6411 llvm::Constant *Entry =
6415 Entry = Entry->stripPointerCasts();
6418 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
6429 if (!GV || GV->getValueType() != InitType ||
6430 GV->getType()->getAddressSpace() !=
6434 Entry->setName(StringRef());
6439 ->stripPointerCasts());
6442 llvm::Constant *NewPtrForOldDecl =
6443 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
6445 Entry->replaceAllUsesWith(NewPtrForOldDecl);
6453 if (D->
hasAttr<AnnotateAttr>())
6466 if (LangOpts.CUDA) {
6467 if (LangOpts.CUDAIsDevice) {
6470 (D->
hasAttr<CUDADeviceAttr>() || D->
hasAttr<CUDAConstantAttr>() ||
6473 GV->setExternallyInitialized(
true);
6480 if (LangOpts.HLSL &&
6485 GV->setExternallyInitialized(
true);
6487 GV->setInitializer(
Init);
6494 emitter->finalize(GV);
6497 GV->setConstant((D->
hasAttr<CUDAConstantAttr>() && LangOpts.CUDAIsDevice) ||
6498 (!NeedsGlobalCtor && !NeedsGlobalDtor &&
6502 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>()) {
6503 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
6505 GV->setConstant(
true);
6510 if (std::optional<CharUnits> AlignValFromAllocate =
6512 AlignVal = *AlignValFromAllocate;
6530 Linkage == llvm::GlobalValue::ExternalLinkage &&
6531 Context.getTargetInfo().getTriple().isOSDarwin() &&
6533 Linkage = llvm::GlobalValue::InternalLinkage;
6538 if (LangOpts.HLSL &&
6540 Linkage = llvm::GlobalValue::ExternalLinkage;
6543 if (D->
hasAttr<DLLImportAttr>())
6544 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
6545 else if (D->
hasAttr<DLLExportAttr>())
6546 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
6548 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6550 if (
Linkage == llvm::GlobalVariable::CommonLinkage) {
6552 GV->setConstant(
false);
6557 if (!GV->getInitializer()->isNullValue())
6558 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
6561 setNonAliasAttributes(D, GV);
6563 if (D->
getTLSKind() && !GV->isThreadLocal()) {
6565 CXXThreadLocals.push_back(D);
6572 if (NeedsGlobalCtor || NeedsGlobalDtor)
6573 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
6575 SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
6580 DI->EmitGlobalVariable(GV, D);
6588 if ((NoCommon || D->
hasAttr<NoCommonAttr>()) && !D->
hasAttr<CommonAttr>())
6599 if (D->
hasAttr<SectionAttr>())
6605 if (D->
hasAttr<PragmaClangBSSSectionAttr>() ||
6606 D->
hasAttr<PragmaClangDataSectionAttr>() ||
6607 D->
hasAttr<PragmaClangRelroSectionAttr>() ||
6608 D->
hasAttr<PragmaClangRodataSectionAttr>())
6616 if (D->
hasAttr<WeakImportAttr>())
6625 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6626 if (D->
hasAttr<AlignedAttr>())
6629 if (Context.isAlignmentRequired(VarType))
6633 for (
const FieldDecl *FD : RD->fields()) {
6634 if (FD->isBitField())
6636 if (FD->
hasAttr<AlignedAttr>())
6638 if (Context.isAlignmentRequired(FD->
getType()))
6650 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
6651 Context.getTypeAlignIfKnown(D->
getType()) >
6658llvm::GlobalValue::LinkageTypes
6662 return llvm::Function::InternalLinkage;
6665 return llvm::GlobalVariable::WeakAnyLinkage;
6669 return llvm::GlobalVariable::LinkOnceAnyLinkage;
6674 return llvm::GlobalValue::AvailableExternallyLinkage;
6688 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
6689 : llvm::Function::InternalLinkage;
6703 return llvm::Function::ExternalLinkage;
6706 return D->
hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
6707 : llvm::Function::InternalLinkage;
6708 return llvm::Function::WeakODRLinkage;
6715 CodeGenOpts.NoCommon))
6716 return llvm::GlobalVariable::CommonLinkage;
6722 if (D->
hasAttr<SelectAnyAttr>())
6723 return llvm::GlobalVariable::WeakODRLinkage;
6727 return llvm::GlobalVariable::ExternalLinkage;
6730llvm::GlobalValue::LinkageTypes
6739 llvm::Function *newFn) {
6741 if (old->use_empty())
6744 llvm::Type *newRetTy = newFn->getReturnType();
6749 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
6751 llvm::User *user = ui->getUser();
6755 if (
auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
6756 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
6762 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
6765 if (!callSite->isCallee(&*ui))
6770 if (callSite->getType() != newRetTy && !callSite->use_empty())
6775 llvm::AttributeList oldAttrs = callSite->getAttributes();
6778 unsigned newNumArgs = newFn->arg_size();
6779 if (callSite->arg_size() < newNumArgs)
6785 bool dontTransform =
false;
6786 for (llvm::Argument &A : newFn->args()) {
6787 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
6788 dontTransform =
true;
6793 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
6801 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
6805 callSite->getOperandBundlesAsDefs(newBundles);
6807 llvm::CallBase *newCall;
6809 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles,
"",
6810 callSite->getIterator());
6813 newCall = llvm::InvokeInst::Create(
6814 newFn, oldInvoke->getNormalDest(), oldInvoke->getUnwindDest(),
6815 newArgs, newBundles,
"", callSite->getIterator());
6819 if (!newCall->getType()->isVoidTy())
6820 newCall->takeName(callSite);
6821 newCall->setAttributes(
6822 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
6823 oldAttrs.getRetAttrs(), newArgAttrs));
6824 newCall->setCallingConv(callSite->getCallingConv());
6827 if (!callSite->use_empty())
6828 callSite->replaceAllUsesWith(newCall);
6831 if (callSite->getDebugLoc())
6832 newCall->setDebugLoc(callSite->getDebugLoc());
6834 callSitesToBeRemovedFromParent.push_back(callSite);
6837 for (
auto *callSite : callSitesToBeRemovedFromParent) {
6838 callSite->eraseFromParent();
6852 llvm::Function *NewFn) {
6862 (LangOpts.CUDA && !shouldEmitCUDAGlobalVar(VD)))
6874void CodeGenModule::EmitGlobalFunctionDefinition(
GlobalDecl GD,
6875 llvm::GlobalValue *GV) {
6883 if (!GV || (GV->getValueType() != Ty))
6889 if (!GV->isDeclaration())
6899 if (
getTriple().isOSAIX() && D->isTargetClonesMultiVersion())
6900 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
6912 setNonAliasAttributes(GD, Fn);
6914 bool ShouldAddOptNone = !CodeGenOpts.DisableO0ImplyOptNone &&
6915 (CodeGenOpts.OptimizationLevel == 0) &&
6918 if (DeviceKernelAttr::isOpenCLSpelling(D->
getAttr<DeviceKernelAttr>())) {
6920 !D->
hasAttr<NoInlineAttr>() &&
6921 !Fn->hasFnAttribute(llvm::Attribute::NoInline) &&
6922 !D->
hasAttr<OptimizeNoneAttr>() &&
6923 !Fn->hasFnAttribute(llvm::Attribute::OptimizeNone) &&
6924 !ShouldAddOptNone) {
6925 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
6931 auto GetPriority = [
this](
const auto *
Attr) ->
int {
6936 return Attr->DefaultPriority;
6939 if (
const ConstructorAttr *CA = D->
getAttr<ConstructorAttr>())
6941 if (
const DestructorAttr *DA = D->
getAttr<DestructorAttr>())
6947void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
6949 const AliasAttr *AA = D->
getAttr<AliasAttr>();
6950 assert(AA &&
"Not an alias?");
6954 if (AA->getAliasee() == MangledName) {
6955 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6962 if (Entry && !Entry->isDeclaration())
6965 Aliases.push_back(GD);
6971 llvm::Constant *Aliasee;
6972 llvm::GlobalValue::LinkageTypes
LT;
6974 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
6980 if (
const auto *VD = dyn_cast<VarDecl>(GD.
getDecl()))
6987 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
6989 llvm::GlobalAlias::create(DeclTy, AS, LT,
"", Aliasee, &
getModule());
6992 if (GA->getAliasee() == Entry) {
6993 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6997 assert(Entry->isDeclaration());
7006 GA->takeName(Entry);
7008 Entry->replaceAllUsesWith(GA);
7009 Entry->eraseFromParent();
7011 GA->setName(MangledName);
7019 GA->setLinkage(llvm::Function::WeakAnyLinkage);
7022 if (
const auto *VD = dyn_cast<VarDecl>(D))
7023 if (VD->getTLSKind())
7034void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
7036 const IFuncAttr *IFA = D->
getAttr<IFuncAttr>();
7037 assert(IFA &&
"Not an ifunc?");
7041 if (IFA->getResolver() == MangledName) {
7042 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
7048 if (Entry && !Entry->isDeclaration()) {
7051 DiagnosedConflictingDefinitions.insert(GD).second) {
7052 Diags.Report(D->
getLocation(), diag::err_duplicate_mangled_name)
7055 diag::note_previous_definition);
7060 Aliases.push_back(GD);
7066 llvm::Constant *Resolver =
7067 GetOrCreateLLVMFunction(IFA->getResolver(),
VoidTy, {},
7071 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
7072 DeclTy, AS, llvm::Function::ExternalLinkage,
"", Resolver, &
getModule());
7074 if (GIF->getResolver() == Entry) {
7075 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
7078 assert(Entry->isDeclaration());
7087 GIF->takeName(Entry);
7089 Entry->replaceAllUsesWith(GIF);
7090 Entry->eraseFromParent();
7092 GIF->setName(MangledName);
7098 return llvm::Intrinsic::getOrInsertDeclaration(&
getModule(),
7099 (llvm::Intrinsic::ID)IID, Tys);
7102static llvm::StringMapEntry<llvm::GlobalVariable *> &
7105 bool &IsUTF16,
unsigned &StringLength) {
7106 StringRef String = Literal->getString();
7107 unsigned NumBytes = String.size();
7110 if (!Literal->containsNonAsciiOrNull()) {
7111 StringLength = NumBytes;
7112 return *Map.insert(std::make_pair(String,
nullptr)).first;
7119 const llvm::UTF8 *FromPtr = (
const llvm::UTF8 *)String.data();
7120 llvm::UTF16 *ToPtr = &ToBuf[0];
7122 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
7123 ToPtr + NumBytes, llvm::strictConversion);
7126 StringLength = ToPtr - &ToBuf[0];
7130 return *Map.insert(std::make_pair(
7131 StringRef(
reinterpret_cast<const char *
>(ToBuf.data()),
7132 (StringLength + 1) * 2),
7138 unsigned StringLength = 0;
7139 bool isUTF16 =
false;
7140 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
7145 if (
auto *
C = Entry.second)
7150 const llvm::Triple &Triple =
getTriple();
7153 const bool IsSwiftABI =
7154 static_cast<unsigned>(CFRuntime) >=
7159 if (!CFConstantStringClassRef) {
7160 const char *CFConstantStringClassName =
"__CFConstantStringClassReference";
7162 Ty = llvm::ArrayType::get(Ty, 0);
7164 switch (CFRuntime) {
7168 CFConstantStringClassName =
7169 Triple.isOSDarwin() ?
"$s15SwiftFoundation19_NSCFConstantStringCN"
7170 :
"$s10Foundation19_NSCFConstantStringCN";
7174 CFConstantStringClassName =
7175 Triple.isOSDarwin() ?
"$S15SwiftFoundation19_NSCFConstantStringCN"
7176 :
"$S10Foundation19_NSCFConstantStringCN";
7180 CFConstantStringClassName =
7181 Triple.isOSDarwin() ?
"__T015SwiftFoundation19_NSCFConstantStringCN"
7182 :
"__T010Foundation19_NSCFConstantStringCN";
7189 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
7190 llvm::GlobalValue *GV =
nullptr;
7192 if ((GV = dyn_cast<llvm::GlobalValue>(
C))) {
7199 if ((VD = dyn_cast<VarDecl>(
Result)))
7202 if (Triple.isOSBinFormatELF()) {
7204 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
7206 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
7207 if (!VD || !VD->
hasAttr<DLLExportAttr>())
7208 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
7210 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
7218 CFConstantStringClassRef =
7219 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(
C, Ty) :
C;
7222 QualType CFTy = Context.getCFConstantStringType();
7227 auto Fields = Builder.beginStruct(STy);
7236 Fields.addInt(
IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
7237 Fields.addInt(
Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
7239 Fields.addInt(
IntTy, isUTF16 ? 0x07d0 : 0x07C8);
7243 llvm::Constant *
C =
nullptr;
7246 reinterpret_cast<uint16_t *
>(
const_cast<char *
>(Entry.first().data())),
7247 Entry.first().size() / 2);
7248 C = llvm::ConstantDataArray::get(VMContext, Arr);
7250 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
7256 new llvm::GlobalVariable(
getModule(),
C->getType(),
true,
7257 llvm::GlobalValue::PrivateLinkage,
C,
".str");
7258 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
7261 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
7262 : Context.getTypeAlignInChars(Context.CharTy);
7268 if (Triple.isOSBinFormatMachO())
7269 GV->setSection(isUTF16 ?
"__TEXT,__ustring"
7270 :
"__TEXT,__cstring,cstring_literals");
7273 else if (Triple.isOSBinFormatELF())
7274 GV->setSection(
".rodata");
7280 llvm::IntegerType *LengthTy =
7290 Fields.addInt(LengthTy, StringLength);
7298 GV = Fields.finishAndCreateGlobal(
"_unnamed_cfstring_", Alignment,
7300 llvm::GlobalVariable::PrivateLinkage);
7301 GV->addAttribute(
"objc_arc_inert");
7302 switch (Triple.getObjectFormat()) {
7303 case llvm::Triple::UnknownObjectFormat:
7304 llvm_unreachable(
"unknown file format");
7305 case llvm::Triple::DXContainer:
7306 case llvm::Triple::GOFF:
7307 case llvm::Triple::SPIRV:
7308 case llvm::Triple::XCOFF:
7309 llvm_unreachable(
"unimplemented");
7310 case llvm::Triple::COFF:
7311 case llvm::Triple::ELF:
7312 case llvm::Triple::Wasm:
7313 GV->setSection(
"cfstring");
7315 case llvm::Triple::MachO:
7316 GV->setSection(
"__DATA,__cfstring");
7325 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
7329 if (ObjCFastEnumerationStateType.isNull()) {
7330 RecordDecl *D = Context.buildImplicitRecord(
"__objcFastEnumerationState");
7334 Context.UnsignedLongTy, Context.getPointerType(Context.getObjCIdType()),
7335 Context.getPointerType(Context.UnsignedLongTy),
7336 Context.getConstantArrayType(Context.UnsignedLongTy, llvm::APInt(32, 5),
7339 for (
size_t i = 0; i < 4; ++i) {
7344 FieldTypes[i],
nullptr,
7353 ObjCFastEnumerationStateType = Context.getCanonicalTagType(D);
7356 return ObjCFastEnumerationStateType;
7370 assert(CAT &&
"String literal not of constant array type!");
7372 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
7376 llvm::Type *ElemTy = AType->getElementType();
7377 unsigned NumElements = AType->getNumElements();
7380 if (ElemTy->getPrimitiveSizeInBits() == 16) {
7382 Elements.reserve(NumElements);
7384 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
7386 Elements.resize(NumElements);
7387 return llvm::ConstantDataArray::get(VMContext, Elements);
7390 assert(ElemTy->getPrimitiveSizeInBits() == 32);
7392 Elements.reserve(NumElements);
7394 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
7396 Elements.resize(NumElements);
7397 return llvm::ConstantDataArray::get(VMContext, Elements);
7400static llvm::GlobalVariable *
7409 auto *GV =
new llvm::GlobalVariable(
7410 M,
C->getType(), !CGM.
getLangOpts().WritableStrings, LT,
C, GlobalName,
7411 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
7413 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
7414 if (GV->isWeakForLinker()) {
7415 assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
7416 GV->setComdat(M.getOrInsertComdat(GV->getName()));
7432 llvm::GlobalVariable **Entry =
nullptr;
7433 if (!LangOpts.WritableStrings) {
7434 Entry = &ConstantStringMap[
C];
7435 if (
auto GV = *Entry) {
7436 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
7439 GV->getValueType(), Alignment);
7444 StringRef GlobalVariableName;
7445 llvm::GlobalValue::LinkageTypes LT;
7450 if (
getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
7451 !LangOpts.WritableStrings) {
7452 llvm::raw_svector_ostream Out(MangledNameBuffer);
7454 LT = llvm::GlobalValue::LinkOnceODRLinkage;
7455 GlobalVariableName = MangledNameBuffer;
7457 LT = llvm::GlobalValue::PrivateLinkage;
7458 GlobalVariableName = Name;
7470 SanitizerMD->reportGlobal(GV, S->
getStrTokenLoc(0),
"<string literal>");
7473 GV->getValueType(), Alignment);
7490 StringRef GlobalName) {
7491 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
7496 llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
7499 llvm::GlobalVariable **Entry =
nullptr;
7500 if (!LangOpts.WritableStrings) {
7501 Entry = &ConstantStringMap[
C];
7502 if (
auto GV = *Entry) {
7503 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
7506 GV->getValueType(), Alignment);
7512 GlobalName, Alignment);
7517 GV->getValueType(), Alignment);
7535 MaterializedType = E->
getType();
7539 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E,
nullptr});
7540 if (!InsertResult.second) {
7543 if (!InsertResult.first->second) {
7548 InsertResult.first->second =
new llvm::GlobalVariable(
7549 getModule(),
Type,
false, llvm::GlobalVariable::InternalLinkage,
7553 llvm::cast<llvm::GlobalVariable>(
7554 InsertResult.first->second->stripPointerCasts())
7563 llvm::raw_svector_ostream Out(Name);
7585 std::optional<ConstantEmitter> emitter;
7586 llvm::Constant *InitialValue =
nullptr;
7591 emitter.emplace(*
this);
7592 InitialValue = emitter->emitForInitializer(*
Value, AddrSpace,
7597 Type = InitialValue->getType();
7606 if (
Linkage == llvm::GlobalVariable::ExternalLinkage) {
7608 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
7612 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
7616 Linkage = llvm::GlobalVariable::InternalLinkage;
7620 auto *GV =
new llvm::GlobalVariable(
7622 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
7623 if (emitter) emitter->finalize(GV);
7625 if (!llvm::GlobalValue::isLocalLinkage(
Linkage)) {
7627 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
7629 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
7633 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
7634 if (VD->getTLSKind())
7636 llvm::Constant *CV = GV;
7639 GV, llvm::PointerType::get(
7645 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
7647 Entry->replaceAllUsesWith(CV);
7648 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
7657void CodeGenModule::EmitObjCPropertyImplementations(
const
7670 if (!Getter || Getter->isSynthesizedAccessorStub())
7673 auto *Setter = PID->getSetterMethodDecl();
7674 if (!PD->
isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
7685 if (ivar->getType().isDestructedType())
7706void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
7719 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod,
false);
7734 getContext().getObjCIdType(),
nullptr, D,
true,
7740 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod,
true);
7745void CodeGenModule::EmitLinkageSpec(
const LinkageSpecDecl *LSD) {
7752 EmitDeclContext(LSD);
7755void CodeGenModule::EmitTopLevelStmt(
const TopLevelStmtDecl *D) {
7757 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7760 std::unique_ptr<CodeGenFunction> &CurCGF =
7761 GlobalTopLevelStmtBlockInFlight.first;
7765 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
7773 std::string Name =
"__stmts__" + llvm::utostr(CXXGlobalInits.size());
7774 FunctionArgList Args;
7776 const CGFunctionInfo &FnInfo =
7779 llvm::Function *
Fn = llvm::Function::Create(
7780 FnTy, llvm::GlobalValue::InternalLinkage, Name, &
getModule());
7782 CurCGF.reset(
new CodeGenFunction(*
this));
7783 GlobalTopLevelStmtBlockInFlight.second = D;
7784 CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
7786 CXXGlobalInits.push_back(Fn);
7789 CurCGF->EmitStmt(D->
getStmt());
7792void CodeGenModule::EmitDeclContext(
const DeclContext *DC) {
7793 for (
auto *I : DC->
decls()) {
7799 if (
auto *OID = dyn_cast<ObjCImplDecl>(I)) {
7800 for (
auto *M : OID->methods())
7819 case Decl::CXXConversion:
7820 case Decl::CXXMethod:
7821 case Decl::Function:
7828 case Decl::CXXDeductionGuide:
7833 case Decl::Decomposition:
7834 case Decl::VarTemplateSpecialization:
7836 if (
auto *DD = dyn_cast<DecompositionDecl>(D))
7837 for (
auto *B : DD->flat_bindings())
7838 if (
auto *HD = B->getHoldingVar())
7845 case Decl::IndirectField:
7849 case Decl::Namespace:
7852 case Decl::ClassTemplateSpecialization: {
7855 if (Spec->getSpecializationKind() ==
7857 Spec->hasDefinition())
7858 DI->completeTemplateDefinition(*Spec);
7860 case Decl::CXXRecord: {
7864 DI->EmitAndRetainType(
7868 DI->completeUnusedClass(*CRD);
7871 for (
auto *I : CRD->
decls())
7877 case Decl::UsingShadow:
7878 case Decl::ClassTemplate:
7879 case Decl::VarTemplate:
7881 case Decl::VarTemplatePartialSpecialization:
7882 case Decl::FunctionTemplate:
7883 case Decl::TypeAliasTemplate:
7892 case Decl::UsingEnum:
7896 case Decl::NamespaceAlias:
7900 case Decl::UsingDirective:
7904 case Decl::CXXConstructor:
7907 case Decl::CXXDestructor:
7911 case Decl::StaticAssert:
7912 case Decl::ExplicitInstantiation:
7919 case Decl::ObjCInterface:
7920 case Decl::ObjCCategory:
7923 case Decl::ObjCProtocol: {
7925 if (Proto->isThisDeclarationADefinition())
7926 ObjCRuntime->GenerateProtocol(Proto);
7930 case Decl::ObjCCategoryImpl:
7936 case Decl::ObjCImplementation: {
7938 EmitObjCPropertyImplementations(OMD);
7939 EmitObjCIvarInitializations(OMD);
7940 ObjCRuntime->GenerateClass(OMD);
7944 DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
7945 OMD->getClassInterface()), OMD->getLocation());
7948 case Decl::ObjCMethod: {
7955 case Decl::ObjCCompatibleAlias:
7959 case Decl::PragmaComment: {
7961 switch (PCD->getCommentKind()) {
7963 llvm_unreachable(
"unexpected pragma comment kind");
7978 case Decl::PragmaDetectMismatch: {
7984 case Decl::LinkageSpec:
7988 case Decl::FileScopeAsm: {
7990 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7993 if (LangOpts.OpenMPIsTargetDevice)
7996 if (LangOpts.SYCLIsDevice)
7999 getModule().appendModuleInlineAsm(AD->getAsmString());
8003 case Decl::TopLevelStmt:
8007 case Decl::Import: {
8011 if (!ImportedModules.insert(Import->getImportedModule()))
8015 if (!Import->getImportedOwningModule()) {
8017 DI->EmitImportDecl(*Import);
8023 if (CXX20ModuleInits && Import->getImportedModule() &&
8024 Import->getImportedModule()->isNamedModule())
8033 Visited.insert(Import->getImportedModule());
8034 Stack.push_back(Import->getImportedModule());
8036 while (!Stack.empty()) {
8038 if (!EmittedModuleInitializers.insert(Mod).second)
8041 for (
auto *D : Context.getModuleInitializers(Mod))
8048 if (Submodule->IsExplicit)
8051 if (Visited.insert(Submodule).second)
8052 Stack.push_back(Submodule);
8062 case Decl::OMPThreadPrivate:
8066 case Decl::OMPAllocate:
8070 case Decl::OMPDeclareReduction:
8074 case Decl::OMPDeclareMapper:
8078 case Decl::OMPRequires:
8083 case Decl::TypeAlias:
8085 DI->EmitAndRetainType(
getContext().getTypedefType(
8093 DI->EmitAndRetainType(
8100 DI->EmitAndRetainType(
8104 case Decl::HLSLRootSignature:
8107 case Decl::HLSLBuffer:
8111 case Decl::OpenACCDeclare:
8114 case Decl::OpenACCRoutine:
8129 if (!CodeGenOpts.CoverageMapping)
8132 case Decl::CXXConversion:
8133 case Decl::CXXMethod:
8134 case Decl::Function:
8135 case Decl::ObjCMethod:
8136 case Decl::CXXConstructor:
8137 case Decl::CXXDestructor: {
8146 DeferredEmptyCoverageMappingDecls.try_emplace(D,
true);
8156 if (!CodeGenOpts.CoverageMapping)
8158 if (
const auto *Fn = dyn_cast<FunctionDecl>(D)) {
8159 if (Fn->isTemplateInstantiation())
8162 DeferredEmptyCoverageMappingDecls.insert_or_assign(D,
false);
8170 for (
const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
8173 const Decl *D = Entry.first;
8175 case Decl::CXXConversion:
8176 case Decl::CXXMethod:
8177 case Decl::Function:
8178 case Decl::ObjCMethod: {
8185 case Decl::CXXConstructor: {
8192 case Decl::CXXDestructor: {
8209 if (llvm::Function *F =
getModule().getFunction(
"main")) {
8210 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
8211 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
8212 auto *GA = llvm::GlobalAlias::create(
"__main_void", F);
8213 GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
8222 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
8223 return llvm::ConstantInt::get(i64, PtrInt);
8227 llvm::NamedMDNode *&GlobalMetadata,
8229 llvm::GlobalValue *
Addr) {
8230 if (!GlobalMetadata)
8232 CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
8235 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(
Addr),
8238 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
8241bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
8242 llvm::GlobalValue *CppFunc) {
8244 llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
8247 llvm::SmallVector<llvm::ConstantExpr *> CEs;
8250 if (Elem == CppFunc)
8256 for (llvm::User *User : Elem->users()) {
8260 if (
auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
8261 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
8264 for (llvm::User *CEUser : ConstExpr->users()) {
8265 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
8266 IFuncs.push_back(IFunc);
8271 CEs.push_back(ConstExpr);
8272 }
else if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
8273 IFuncs.push_back(IFunc);
8285 for (llvm::GlobalIFunc *IFunc : IFuncs)
8286 IFunc->setResolver(
nullptr);
8287 for (llvm::ConstantExpr *ConstExpr : CEs)
8288 ConstExpr->destroyConstant();
8292 Elem->eraseFromParent();
8294 for (llvm::GlobalIFunc *IFunc : IFuncs) {
8299 llvm::FunctionType::get(IFunc->getType(),
false);
8300 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
8301 CppFunc->getName(), ResolverTy, {},
false);
8302 IFunc->setResolver(Resolver);
8312void CodeGenModule::EmitStaticExternCAliases() {
8315 for (
auto &I : StaticExternCValues) {
8316 const IdentifierInfo *Name = I.first;
8317 llvm::GlobalValue *Val = I.second;
8325 llvm::GlobalValue *ExistingElem =
8330 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
8337 auto Res = Manglings.find(MangledName);
8338 if (Res == Manglings.end())
8340 Result = Res->getValue();
8351void CodeGenModule::EmitDeclMetadata() {
8352 llvm::NamedMDNode *GlobalMetadata =
nullptr;
8354 for (
auto &I : MangledDeclNames) {
8355 llvm::GlobalValue *
Addr =
getModule().getNamedValue(I.second);
8365void CodeGenFunction::EmitDeclMetadata() {
8366 if (LocalDeclMap.empty())
return;
8371 unsigned DeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
8373 llvm::NamedMDNode *GlobalMetadata =
nullptr;
8375 for (
auto &I : LocalDeclMap) {
8376 const Decl *D = I.first;
8377 llvm::Value *
Addr = I.second.emitRawPointer(*
this);
8378 if (
auto *Alloca = dyn_cast<llvm::AllocaInst>(
Addr)) {
8380 Alloca->setMetadata(
8381 DeclPtrKind, llvm::MDNode::get(
8382 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
8383 }
else if (
auto *GV = dyn_cast<llvm::GlobalValue>(
Addr)) {
8390void CodeGenModule::EmitVersionIdentMetadata() {
8391 llvm::NamedMDNode *IdentMetadata =
8392 TheModule.getOrInsertNamedMetadata(
"llvm.ident");
8394 llvm::LLVMContext &Ctx = TheModule.getContext();
8396 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
8397 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
8400void CodeGenModule::EmitCommandLineMetadata() {
8401 llvm::NamedMDNode *CommandLineMetadata =
8402 TheModule.getOrInsertNamedMetadata(
"llvm.commandline");
8404 llvm::LLVMContext &Ctx = TheModule.getContext();
8406 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
8407 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
8410void CodeGenModule::EmitCoverageFile() {
8411 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu");
8415 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
8416 llvm::LLVMContext &Ctx = TheModule.getContext();
8417 auto *CoverageDataFile =
8419 auto *CoverageNotesFile =
8421 for (
int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
8422 llvm::MDNode *CU = CUNode->getOperand(i);
8423 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
8424 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
8437 LangOpts.ObjCRuntime.isGNUFamily())
8438 return ObjCRuntime->GetEHType(Ty);
8445 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
8447 for (
auto RefExpr : D->
varlist()) {
8450 VD->getAnyInitializer() &&
8451 !VD->getAnyInitializer()->isConstantInitializer(
getContext());
8457 VD,
Addr, RefExpr->getBeginLoc(), PerformInit))
8458 CXXGlobalInits.push_back(InitFunction);
8463CodeGenModule::CreateMetadataIdentifierImpl(
QualType T, MetadataTypeMap &Map,
8467 FnType->getReturnType(), FnType->getParamTypes(),
8468 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
8470 llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
8475 std::string OutName;
8476 llvm::raw_string_ostream Out(OutName);
8481 Out <<
".normalized";
8504 return CreateMetadataIdentifierImpl(T, MetadataIdMap,
"");
8509 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap,
".virtual");
8513 return CreateMetadataIdentifierImpl(T, GeneralizedMetadataIdMap,
8521 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
8522 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
8523 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
8524 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
8525 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
8526 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
8527 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
8528 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
8536 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8538 if (CodeGenOpts.SanitizeCfiCrossDso)
8540 VTable->addTypeMetadata(Offset.getQuantity(),
8541 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
8544 llvm::Metadata *MD = llvm::MDString::get(
getLLVMContext(),
"all-vtables");
8545 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8551 SanStats = std::make_unique<llvm::SanitizerStatReport>(&
getModule());
8561 auto *FTy = llvm::FunctionType::get(SamplerT, {
C->getType()},
false);
8576 bool forPointeeType) {
8587 if (
auto Align = TT->getDecl()->getMaxAlignment()) {
8594 bool AlignForArray = T->isArrayType();
8600 if (T->isIncompleteType()) {
8617 if (T.getQualifiers().hasUnaligned()) {
8619 }
else if (forPointeeType && !AlignForArray &&
8620 (RD = T->getAsCXXRecordDecl())) {
8631 if (
unsigned MaxAlign =
getLangOpts().MaxTypeAlign) {
8644 if (NumAutoVarInit >= StopAfter) {
8647 if (!NumAutoVarInit) {
8661 const Decl *D)
const {
8665 OS << (isa<VarDecl>(D) ?
".static." :
".intern.");
8667 OS << (isa<VarDecl>(D) ?
"__static__" :
"__intern__");
8673 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
8677 llvm::MD5::MD5Result
Result;
8678 for (
const auto &Arg : PreprocessorOpts.Macros)
8679 Hash.update(Arg.first);
8683 llvm::sys::fs::UniqueID ID;
8687 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
8691 SM.getDiagnostics().Report(diag::err_cannot_open_file)
8692 << PLoc.
getFilename() << Status.getError().message();
8694 ID = Status->getUniqueID();
8696 OS << llvm::format(
"%x", ID.getFile()) << llvm::format(
"%x", ID.getDevice())
8697 <<
"_" << llvm::utohexstr(
Result.low(),
true, 8);
8704 assert(DeferredDeclsToEmit.empty() &&
8705 "Should have emitted all decls deferred to emit.");
8706 assert(NewBuilder->DeferredDecls.empty() &&
8707 "Newly created module should not have deferred decls");
8708 NewBuilder->DeferredDecls = std::move(DeferredDecls);
8709 assert(EmittedDeferredDecls.empty() &&
8710 "Still have (unmerged) EmittedDeferredDecls deferred decls");
8712 assert(NewBuilder->DeferredVTables.empty() &&
8713 "Newly created module should not have deferred vtables");
8714 NewBuilder->DeferredVTables = std::move(DeferredVTables);
8716 assert(NewBuilder->EmittedVTables.empty() &&
8717 "Newly created module should not have defined vtables");
8718 NewBuilder->EmittedVTables = std::move(EmittedVTables);
8720 assert(NewBuilder->MangledDeclNames.empty() &&
8721 "Newly created module should not have mangled decl names");
8722 assert(NewBuilder->Manglings.empty() &&
8723 "Newly created module should not have manglings");
8724 NewBuilder->Manglings = std::move(Manglings);
8726 NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
8728 NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
8732 std::string OutName;
8733 llvm::raw_string_ostream Out(OutName);
8741 if (!Context.getTargetInfo().emitVectorDeletingDtors(Context.getLangOpts()))
8750 return RequireVectorDeletingDtor.count(RD);
8754 if (!Context.getTargetInfo().emitVectorDeletingDtors(Context.getLangOpts()))
8756 RequireVectorDeletingDtor.insert(RD);
8770 if (Entry && !Entry->isDeclaration()) {
8775 auto *NewFn = llvm::Function::Create(
8777 llvm::Function::ExternalLinkage, VDName, &
getModule());
8778 SetFunctionAttributes(VectorDtorGD, NewFn,
false,
8780 NewFn->takeName(VDEntry);
8781 VDEntry->replaceAllUsesWith(NewFn);
8782 VDEntry->eraseFromParent();
8783 Entry->replaceAllUsesWith(NewFn);
8784 Entry->eraseFromParent();
8789 addDeferredDeclToEmit(VectorDtorGD);
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines the Diagnostic-related interfaces.
Defines enum values for all the target-independent builtin functions.
static bool shouldAssumeDSOLocal(const CIRGenModule &cgm, cir::CIRGlobalValueInterface gv)
static bool shouldBeInCOMDAT(CIRGenModule &cgm, const Decl &d)
static bool hasUnwindExceptions(const LangOptions &langOpts)
Determines whether the language options require us to model unwind exceptions.
static void setWindowsItaniumDLLImport(CIRGenModule &cgm, bool isLocal, cir::FuncOp funcOp, StringRef name)
static std::string getMangledNameImpl(CIRGenModule &cgm, GlobalDecl gd, const NamedDecl *nd)
static bool hasImplicitAttr(const ValueDecl *decl)
static std::vector< std::string > getFeatureDeltaFromDefault(const CIRGenModule &cgm, llvm::StringRef targetCPU, llvm::StringMap< bool > &featureMap)
Get the feature delta from the default feature map for the given target CPU.
static CIRGenCXXABI * createCXXABI(CIRGenModule &cgm)
static bool isVarDeclStrongDefinition(const ASTContext &astContext, CIRGenModule &cgm, const VarDecl *vd, bool noCommon)
static void setLinkageForGV(cir::GlobalOp &gv, const NamedDecl *nd)
static void emitUsed(CIRGenModule &cgm, StringRef name, std::vector< cir::CIRGlobalValueInterface > &list)
static bool hasExistingGeneralizedTypeMD(llvm::Function *F)
static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, const CPUSpecificAttr *Attr, unsigned CPUIndex, raw_ostream &Out)
static bool AllTrivialInitializers(CodeGenModule &CGM, ObjCImplementationDecl *D)
static const FunctionDecl * GetRuntimeFunctionDecl(ASTContext &C, StringRef Name)
static GlobalDecl getBaseVariantGlobalDecl(const NamedDecl *D)
static void checkAliasForTocData(llvm::GlobalVariable *GVar, const CodeGenOptions &CodeGenOpts, DiagnosticsEngine &Diags, SourceLocation Location)
static const char PFPDeactivationSymbolPrefix[]
static bool HasNonDllImportDtor(QualType T)
static llvm::Constant * GetPointerConstant(llvm::LLVMContext &Context, const void *Ptr)
Turns the given pointer into a constant.
static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S)
static llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM, GlobalDecl GD)
static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO, llvm::Module &M)
static QualType GeneralizeTransparentUnion(QualType Ty)
static std::string getCPUSpecificMangling(const CodeGenModule &CGM, StringRef Name)
static const char AnnotationSection[]
static bool isUniqueInternalLinkageDecl(GlobalDecl GD, CodeGenModule &CGM)
static bool allowKCFIIdentifier(StringRef Name)
static void replaceUsesOfNonProtoConstant(llvm::Constant *old, llvm::Function *newFn)
Replace the uses of a function that was declared with a non-proto type.
static llvm::Constant * castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, llvm::GlobalVariable *GV)
static void checkDataLayoutConsistency(const TargetInfo &Target, llvm::LLVMContext &Context, const LangOptions &Opts)
static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty, bool GeneralizePointers)
static bool needsDestructMethod(ObjCImplementationDecl *impl)
static bool isStackProtectorOn(const LangOptions &LangOpts, const llvm::Triple &Triple, clang::LangOptions::StackProtectorMode Mode)
static void removeImageAccessQualifier(std::string &TyName)
static llvm::StringMapEntry< llvm::GlobalVariable * > & GetConstantCFStringEntry(llvm::StringMap< llvm::GlobalVariable * > &Map, const StringLiteral *Literal, bool TargetIsLSB, bool &IsUTF16, unsigned &StringLength)
static void setLLVMVisibility(llvm::GlobalValue &GV, std::optional< llvm::GlobalValue::VisibilityTypes > V)
static llvm::GlobalVariable * GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, CodeGenModule &CGM, StringRef GlobalName, CharUnits Alignment)
static llvm::APInt getFMVPriority(const TargetInfo &TI, const CodeGenFunction::FMVResolverOption &RO)
static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, SmallVectorImpl< llvm::MDNode * > &Metadata, llvm::SmallPtrSet< Module *, 16 > &Visited)
Add link options implied by the given module, including modules it depends on, using a postorder walk...
static llvm::cl::opt< bool > LimitedCoverage("limited-coverage-experimental", llvm::cl::Hidden, llvm::cl::desc("Emit limited coverage mapping information (experimental)"))
static CGCXXABI * createCXXABI(CodeGenModule &CGM)
static std::unique_ptr< TargetCodeGenInfo > createTargetCodeGenInfo(CodeGenModule &CGM)
static const llvm::GlobalValue * getAliasedGlobal(const llvm::GlobalValue *GV)
static QualType GeneralizeType(ASTContext &Ctx, QualType Ty, bool GeneralizePointers)
static bool shouldSkipAliasEmission(const CodeGenModule &CGM, const ValueDecl *Global)
static constexpr auto ErrnoTBAAMDName
static unsigned ArgInfoAddressSpace(LangAS AS)
static void replaceDeclarationWith(llvm::GlobalValue *Old, llvm::Constant *New)
static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, llvm::Function *NewFn)
ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we implement a function with...
static std::optional< llvm::GlobalValue::VisibilityTypes > getLLVMVisibility(clang::LangOptions::VisibilityFromDLLStorageClassKinds K)
static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, const CXXMethodDecl *MD)
static bool checkAliasedGlobal(const ASTContext &Context, DiagnosticsEngine &Diags, SourceLocation Location, bool IsIFunc, const llvm::GlobalValue *Alias, const llvm::GlobalValue *&GV, const llvm::MapVector< GlobalDecl, StringRef > &MangledDeclNames, SourceRange AliasRange)
static void EmitGlobalDeclMetadata(CodeGenModule &CGM, llvm::NamedMDNode *&GlobalMetadata, GlobalDecl D, llvm::GlobalValue *Addr)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Result
Implement __builtin_bit_cast and related operations.
llvm::MachO::Target Target
llvm::MachO::Record Record
Defines the clang::Module class, which describes a module in the source code.
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()
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
@ Strong
Strong definition.
@ WeakUnknown
Weak for now, might become strong later in this TU.
const ProfileList & getProfileList() const
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
const XRayFunctionFilter & getXRayFilter() const
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
StringRef getCUIDHash() const
const LangOptions & getLangOpts() const
SelectorTable & Selectors
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
const NoSanitizeList & getNoSanitizeList() const
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const
Return the alignment in characters that should be given to a global variable with type T.
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
DiagnosticsEngine & getDiagnostics() const
const TargetInfo & getTargetInfo() const
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
CanQualType getCanonicalTagType(const TagDecl *TD) const
unsigned getTargetAddressSpace(LangAS AS) const
Module * getCurrentNamedModule() const
Get module under construction, nullptr if this is not a C++20 module.
Attr - This represents one attribute.
Represents a block literal declaration, which is like an unnamed FunctionDecl.
bool isLibFunction(unsigned ID) const
Return true if this is a builtin for a libc/libm function, with a "__builtin_" prefix (e....
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Represents a base class of a C++ class.
CXXTemporary * getTemporary()
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Represents a C++ base or member initializer.
Expr * getInit() const
Get the initializer.
FunctionDecl * getOperatorDelete() const
Represents a C++ destructor within a class.
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Represents a static or instance method of a struct/union/class.
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
FunctionDecl * getOperatorNew() const
Represents a C++ struct/union/class.
unsigned getNumBases() const
Retrieves the number of base classes of this class.
bool hasDefinition() const
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
const CXXDestructorDecl * getDestructor() const
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
CharUnits - This is an opaque type for sizes expressed in character units.
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
static CharUnits One()
One - Construct a CharUnits quantity of one.
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::string MSSecureHotPatchFunctionsFile
The name of a file that contains functions which will be compiled for hotpatching.
std::string RecordCommandLine
The string containing the commandline for the llvm.commandline metadata, if non-empty.
std::string FloatABI
The ABI to use for passing floating point arguments.
llvm::Reloc::Model RelocationModel
The name of the relocation model to use.
std::vector< std::string > TocDataVarsUserSpecified
List of global variables explicitly specified by the user as toc-data.
PointerAuthOptions PointerAuth
Configuration for pointer-signing.
std::vector< std::string > MSSecureHotPatchFunctionsList
A list of functions which will be compiled for hotpatching.
ABIInfo - Target specific hooks for defining how a type should be passed or returned from functions.
virtual void appendAttributeMangling(TargetAttr *Attr, raw_ostream &Out) const
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
virtual void handleVarRegistration(const VarDecl *VD, llvm::GlobalVariable &Var)=0
Check whether a variable is a device variable and register it if true.
virtual llvm::GlobalValue * getKernelHandle(llvm::Function *Stub, GlobalDecl GD)=0
Get kernel handle by stub function.
virtual void internalizeDeviceSideVar(const VarDecl *D, llvm::GlobalValue::LinkageTypes &Linkage)=0
Adjust linkage of shadow variables in host compilation.
Implements C++ ABI-specific code generation functions.
virtual void EmitCXXConstructors(const CXXConstructorDecl *D)=0
Emit constructor variants required by this ABI.
virtual llvm::Constant * getAddrOfRTTIDescriptor(QualType Ty)=0
virtual void EmitCXXDestructors(const CXXDestructorDecl *D)=0
Emit destructor variants required by this ABI.
virtual void setCXXDestructorDLLStorage(llvm::GlobalValue *GV, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
virtual llvm::GlobalValue::LinkageTypes getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
MangleContext & getMangleContext()
Gets the mangle context.
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
void EmitGlobalAlias(const llvm::GlobalValue *GV, const GlobalDecl Decl)
Emit information about global variable alias.
void EmitExternalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl)
Emit information about an external variable.
void EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc, QualType FnType, llvm::Function *Fn=nullptr)
Emit debug info for a function declaration.
void AddStringLiteralDebugInfo(llvm::GlobalVariable *GV, const StringLiteral *S)
DebugInfo isn't attached to string literals by default.
CGFunctionInfo - Class to encapsulate the information about a function definition.
void handleGlobalVarDefinition(const VarDecl *VD, llvm::GlobalVariable *Var)
void addRootSignature(const HLSLRootSignatureDecl *D)
void addBuffer(const HLSLBufferDecl *D)
llvm::Type * getSamplerType(const Type *T)
void emitDeferredTargetDecls() const
Emit deferred declare target variables marked for deferred emission.
virtual void emitDeclareTargetFunction(const FunctionDecl *FD, llvm::GlobalValue *GV)
Emit code for handling declare target functions in the runtime.
virtual ConstantAddress getAddrOfDeclareTargetVar(const VarDecl *VD)
Returns the address of the variable marked as declare target with link clause OR as declare target wi...
bool hasRequiresUnifiedSharedMemory() const
Return whether the unified_shared_memory has been specified.
virtual void emitDeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn)
Marks function Fn with properly mangled versions of vector functions.
virtual void registerTargetGlobalVariable(const VarDecl *VD, llvm::Constant *Addr)
Checks if the provided global decl GD is a declare target variable and registers it when emitting cod...
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
void EmitCfiCheckFail()
Emit a cross-DSO CFI failure handling function.
void GenerateObjCGetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCGetter - Synthesize an Objective-C property getter function.
void EmitCfiCheckStub()
Emit a stub for the cross-DSO CFI check function.
void GenerateObjCMethod(const ObjCMethodDecl *OMD)
Generate an Objective-C method.
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
void GenerateObjCSetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCSetter - Synthesize an Objective-C property setter function for the given property.
llvm::LLVMContext & getLLVMContext()
bool isTrivialInitializer(const Expr *Init)
Determine whether the given initializer is trivial in the sense that it requires no code to be genera...
This class organizes the cross-function state that is used while generating LLVM code.
StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD)
ConstantAddress GetAddrOfMSGuidDecl(const MSGuidDecl *GD)
Get the address of a GUID.
void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const
Set visibility, dllimport/dllexport and dso_local.
void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD)
Create and attach type metadata for the given vtable.
void UpdateCompletedType(const TagDecl *TD)
llvm::MDNode * getTBAAAccessTagInfo(TBAAAccessInfo Info)
getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
llvm::GlobalVariable::ThreadLocalMode GetDefaultLLVMTLSModel() const
Get LLVM TLS mode from CodeGenOptions.
void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F, const CGFunctionInfo &FI)
Set the attributes on the LLVM function for the given decl and function info.
void setDSOLocal(llvm::GlobalValue *GV) const
llvm::MDNode * getTBAAStructInfo(QualType QTy)
CGHLSLRuntime & getHLSLRuntime()
Return a reference to the configured HLSL runtime.
llvm::Constant * EmitAnnotationArgs(const AnnotateAttr *Attr)
Emit additional args of the annotation.
llvm::Module & getModule() const
std::optional< llvm::Attribute::AttrKind > StackProtectorAttribute(const Decl *D) const
llvm::GlobalValue * getPFPDeactivationSymbol(const FieldDecl *FD)
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
llvm::ConstantInt * CreateKCFITypeId(QualType T, StringRef Salt)
Generate a KCFI type identifier for T.
CGDebugInfo * getModuleDebugInfo()
llvm::Constant * performAddrSpaceCast(llvm::Constant *Src, llvm::Type *DestTy)
bool NeedAllVtablesTypeId() const
Returns whether this module needs the "all-vtables" type identifier.
void addCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
CodeGenVTables & getVTables()
llvm::ConstantInt * CreateCrossDsoCfiTypeId(llvm::Metadata *MD)
Generate a cross-DSO type identifier for MD.
CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const
Return the store size, in character units, of the given LLVM type.
void createFunctionTypeMetadataForIcall(const FunctionDecl *FD, llvm::Function *F)
Create and attach type metadata to the given function.
bool getExpressionLocationsEnabled() const
Return true if we should emit location information for expressions.
void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C)
bool classNeedsVectorDestructor(const CXXRecordDecl *RD)
Check that class need vector deleting destructor body.
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
void setGVPropertiesAux(llvm::GlobalValue *GV, const NamedDecl *D) const
const IntrusiveRefCntPtr< llvm::vfs::FileSystem > & getFileSystem() const
const ABIInfo & getABIInfo()
void EmitMainVoidAlias()
Emit an alias for "main" if it has no arguments (needed for wasm).
void DecorateInstructionWithInvariantGroup(llvm::Instruction *I, const CXXRecordDecl *RD)
Adds !invariant.barrier !tag to instruction.
DiagnosticsEngine & getDiags() const
bool isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, SourceLocation Loc) const
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
llvm::Constant * getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the constructor/destructor of the given type.
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
llvm::Constant * EmitAnnotateAttr(llvm::GlobalValue *GV, const AnnotateAttr *AA, SourceLocation L)
Generate the llvm::ConstantStruct which contains the annotation information for a given GlobalValue.
void EmitOpenACCDeclare(const OpenACCDeclareDecl *D, CodeGenFunction *CGF=nullptr)
llvm::GlobalValue::LinkageTypes getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage)
Returns LLVM linkage for a declarator.
TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, TBAAAccessInfo SrcInfo)
mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the purposes of memory transfer call...
const LangOptions & getLangOpts() const
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
llvm::Constant * EmitAnnotationLineNo(SourceLocation L)
Emit the annotation line number.
QualType getObjCFastEnumerationStateType()
Retrieve the record type that describes the state of an Objective-C fast enumeration loop (for....
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
CodeGenTypes & getTypes()
bool shouldMapVisibilityToDLLExport(const NamedDecl *D) const
CGOpenCLRuntime & getOpenCLRuntime()
Return a reference to the configured OpenCL runtime.
const std::string & getModuleNameHash() const
const TargetInfo & getTarget() const
bool shouldEmitRTTI(bool ForEH=false)
void EmitGlobal(GlobalDecl D)
Emit code for a single global function or var decl.
llvm::Metadata * CreateMetadataIdentifierForType(QualType T)
Create a metadata identifier for the given type.
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
void createIndirectFunctionTypeMD(const FunctionDecl *FD, llvm::Function *F)
Create and attach type metadata if the function is a potential indirect call target to support call g...
void AppendLinkerOptions(StringRef Opts)
Appends Opts to the "llvm.linker.options" metadata value.
void createCalleeTypeMetadataForIcall(const QualType &QT, llvm::CallBase *CB)
Create and attach type metadata to the given call.
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
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can't be done.
void requireVectorDestructorDefinition(const CXXRecordDecl *RD)
Record that new[] was called for the class, transform vector deleting destructor definition in a form...
TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType)
getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an access to a virtual table poi...
CGCXXABI & getCXXABI() const
ConstantAddress GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
std::string getPFPFieldName(const FieldDecl *FD)
llvm::Constant * GetFunctionStart(const ValueDecl *Decl)
static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V)
void EmitTentativeDefinition(const VarDecl *D)
void EmitDeferredUnusedCoverageMappings()
Emit all the deferred coverage mappings for the uninstrumented functions.
void addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, StringRef Category=StringRef()) const
Imbue XRay attributes to a function, applying the always/never attribute lists in the process.
SanitizerMetadata * getSanitizerMetadata()
llvm::Metadata * CreateMetadataIdentifierGeneralized(QualType T)
Create a metadata identifier for the generalization of the given type.
void EmitGlobalAnnotations()
Emit all the global annotations.
CharUnits getClassPointerAlignment(const CXXRecordDecl *CD)
Returns the assumed alignment of an opaque pointer to the given class.
const llvm::Triple & getTriple() const
SmallVector< const CXXRecordDecl *, 0 > getMostBaseClasses(const CXXRecordDecl *RD)
Return a vector of most-base classes for RD.
void AddDeferredUnusedCoverageMapping(Decl *D)
Stored a deferred empty coverage mapping for an unused and thus uninstrumented top level declaration.
void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV)
If the declaration has internal linkage but is inside an extern "C" linkage specification,...
void DecorateInstructionWithTBAA(llvm::Instruction *Inst, TBAAAccessInfo TBAAInfo)
DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD)
void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535, bool IsDtorAttrFunc=false)
AddGlobalDtor - Add a function to the list that will be called when the module is unloaded.
llvm::Constant * CreateRuntimeVariable(llvm::Type *Ty, StringRef Name)
Create a new runtime global variable with the specified type and name.
void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info, CGCalleeInfo CalleeInfo, llvm::AttributeList &Attrs, unsigned &CallingConv, bool AttrOnCallSite, bool IsThunk)
Get the LLVM attributes and calling convention to use for a particular function type.
llvm::Constant * GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, LangAS AddrSpace, const VarDecl *D, ForDefinition_t IsForDefinition=NotForDefinition)
GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, create and return an llvm...
const llvm::abi::TargetInfo & getLLVMABITargetInfo(llvm::abi::TypeBuilder &TB)
Lazily build and return the LLVMABI library's TargetInfo for the current target.
TBAAAccessInfo getTBAAAccessInfo(QualType AccessType)
getTBAAAccessInfo - Get TBAA information that describes an access to an object of the given type.
void setFunctionLinkage(GlobalDecl GD, llvm::Function *F)
llvm::Constant * GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition=NotForDefinition)
AtomicOptions getAtomicOpts()
Get the current Atomic options.
ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal)
Return a pointer to a constant CFString object for the given string.
ProfileList::ExclusionType isFunctionBlockedFromProfileInstr(llvm::Function *Fn, SourceLocation Loc) const
void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV)
Add global annotations that are set on D, for the global GV.
void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const
Set the TLS mode for the given LLVM GlobalValue for the thread-local variable declaration D.
bool shouldUseLLVMABILowering() const
True when -fexperimental-abi-lowering is in effect AND the active target has an LLVMABI implementatio...
ConstantAddress GetAddrOfConstantStringFromLiteral(const StringLiteral *S, StringRef Name=".str")
Return a pointer to a constant array for the given string literal.
ASTContext & getContext() const
ConstantAddress GetAddrOfTemplateParamObject(const TemplateParamObjectDecl *TPO)
Get the address of a template parameter object.
void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D)
Emit a code for threadprivate directive.
ConstantAddress GetAddrOfUnnamedGlobalConstantDecl(const UnnamedGlobalConstantDecl *GCD)
Get the address of a UnnamedGlobalConstant.
TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, TBAAAccessInfo TargetInfo)
mergeTBAAInfoForCast - Get merged TBAA information for the purposes of type casts.
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
llvm::SanitizerStatReport & getSanStats()
llvm::Constant * EmitAnnotationString(StringRef Str)
Emit an annotation string.
void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare mapper construct.
bool supportsCOMDAT() const
void RefreshTypeCacheForClass(const CXXRecordDecl *Class)
llvm::MDNode * getTBAATypeInfo(QualType QTy)
getTBAATypeInfo - Get metadata used to describe accesses to objects of the given type.
void EmitOMPRequiresDecl(const OMPRequiresDecl *D)
Emit a code for requires directive.
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD)
Tell the consumer that this variable has been instantiated.
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
llvm::Constant * GetConstantArrayFromStringLiteral(const StringLiteral *E)
Return a constant array for the given string.
void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV)
Set attributes which are common to any form of a global definition (alias, Objective-C method,...
std::optional< CharUnits > getOMPAllocateAlignment(const VarDecl *VD)
Return the alignment specified in an allocate directive, if present.
llvm::GlobalVariable * CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, llvm::Align Alignment)
Will return a global variable of the given type.
CharUnits getNaturalPointeeTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, TBAAAccessInfo InfoB)
mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the purposes of conditional ope...
llvm::LLVMContext & getLLVMContext()
llvm::GlobalValue * GetGlobalValue(StringRef Ref)
void GenKernelArgMetadata(llvm::Function *FN, const FunctionDecl *FD=nullptr, CodeGenFunction *CGF=nullptr)
OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument information in the program executab...
void setKCFIType(const FunctionDecl *FD, llvm::Function *F)
Set type metadata to the given function.
void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO)
void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare reduction construct.
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
void AddDetectMismatch(StringRef Name, StringRef Value)
Appends a detect mismatch command to the linker options.
void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const
llvm::Value * createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF)
ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
LangAS GetGlobalConstantAddressSpace() const
Return the AST address space of constant literal, which is used to emit the constant literal as globa...
LangAS GetGlobalVarAddressSpace(const VarDecl *D)
Return the AST address space of the underlying global variable for D, as determined by its declaratio...
void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info, llvm::Function *F, bool IsThunk)
Set the LLVM function attributes (sext, zext, etc).
void EmitOpenACCRoutine(const OpenACCRoutineDecl *D, CodeGenFunction *CGF=nullptr)
void addReplacement(StringRef Name, llvm::Constant *C)
llvm::Constant * getConstantSignedPointer(llvm::Constant *Pointer, const PointerAuthSchema &Schema, llvm::Constant *StorageAddress, GlobalDecl SchemaDecl, QualType SchemaType)
Sign a constant pointer using the given scheme, producing a constant with the same IR type.
void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535, unsigned LexOrder=~0U, llvm::Constant *AssociatedData=nullptr)
AddGlobalCtor - Add a function to the list that will be called before main() runs.
llvm::Metadata * CreateMetadataIdentifierForFnType(QualType T)
Create a metadata identifier for the given function type.
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
llvm::Metadata * CreateMetadataIdentifierForVirtualMemPtrType(QualType T)
Create a metadata identifier that is intended to be used to check virtual calls via a member function...
ConstantAddress GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *)
Return a pointer to a constant array for the given ObjCEncodeExpr node.
const GlobalDecl getMangledNameDecl(StringRef)
void ClearUnusedCoverageMapping(const Decl *D)
Remove the deferred empty coverage mapping as this declaration is actually instrumented.
void EmitTopLevelDecl(Decl *D)
Emit code for a single top level declaration.
llvm::Constant * EmitAnnotationUnit(SourceLocation Loc)
Emit the annotation's translation unit.
ConstantAddress GetAddrOfConstantCString(const std::string &Str, StringRef GlobalName=".str")
Returns a pointer to a character array containing the literal and a terminating '\0' character.
void printPostfixForExternalizedDecl(llvm::raw_ostream &OS, const Decl *D) const
Print the postfix for externalized static variable or kernels for single source offloading languages ...
void moveLazyEmissionStates(CodeGenModule *NewBuilder)
Move some lazily-emitted states to the NewBuilder.
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
void finalizeKCFITypes()
Emit KCFI type identifier constants and remove unused identifiers.
void setValueProfilingFlag(llvm::Module &M)
void setProfileVersion(llvm::Module &M)
void emitEmptyCounterMapping(const Decl *D, StringRef FuncName, llvm::GlobalValue::LinkageTypes Linkage)
Emit a coverage mapping range with a counter zero for an unused declaration.
CodeGenTBAA - This class organizes the cross-module state that is used while lowering AST types to LL...
This class organizes the cross-module state that is used while lowering AST types to LLVM types.
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
const CGFunctionInfo & arrangeCXXMethodDeclaration(const CXXMethodDecl *MD)
C++ methods have some special rules and also have implicit parameters.
const CGFunctionInfo & arrangeFreeFunctionType(CanQual< FunctionProtoType > Ty)
Arrange the argument and result information for a value of the given freestanding function type.
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
unsigned getTargetAddressSpace(QualType T) const
void RefreshTypeCacheForClass(const CXXRecordDecl *RD)
Remove stale types from the type cache when an inheritance model gets assigned to a class.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
void UpdateCompletedType(const TagDecl *TD)
UpdateCompletedType - When we find the full definition for a TagDecl, replace the 'opaque' type we pr...
const CGFunctionInfo & arrangeGlobalDeclaration(GlobalDecl GD)
void EmitThunks(GlobalDecl GD)
EmitThunks - Emit the associated thunks for the given global decl.
A specialization of Address that requires the address to be an LLVM Constant.
static ConstantAddress invalid()
llvm::Constant * tryEmitForInitializer(const VarDecl &D)
Try to emit the initiaizer of the given declaration as an abstract constant.
void finalize(llvm::GlobalVariable *global)
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded.
The standard implementation of ConstantInitBuilder used in Clang.
Organizes the cross-function state that is used while generating code coverage mapping data.
bool hasDiagnostics()
Whether or not the stats we've gathered indicate any potential problems.
void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile)
Report potential problems we've found to Diags.
TargetCodeGenInfo - This class organizes various target-specific codegeneration issues,...
virtual void getDependentLibraryOption(llvm::StringRef Lib, llvm::SmallString< 24 > &Opt) const
Gets the linker options necessary to link a dependent library on this platform.
const T & getABIInfo() const
virtual LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, const VarDecl *D) const
Get target favored AST address space of a global variable for languages other than OpenCL and CUDA.
virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const
setTargetAttributes - Provides a convenient hook to handle extra target-specific attributes for the g...
virtual void emitTargetMetadata(CodeGen::CodeGenModule &CGM, const llvm::MapVector< GlobalDecl, StringRef > &MangledDeclNames) const
emitTargetMetadata - Provides a convenient hook to handle extra target-specific metadata for the give...
virtual void emitTargetGlobals(CodeGen::CodeGenModule &CGM) const
Provides a convenient hook to handle extra target-specific globals.
virtual void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, llvm::SmallString< 32 > &Opt) const
Gets the linker options necessary to detect object file mismatches on this platform.
Represents the canonical version of C arrays with a specified constant size.
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Stores additional source code information like skipped ranges which is required by the coverage mappi...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
void addDecl(Decl *D)
Add the declaration D into this context.
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Decl - This represents one declaration (or definition), e.g.
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
SourceLocation getEndLoc() const LLVM_READONLY
ASTContext & getASTContext() const LLVM_READONLY
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
SourceLocation getLocation() const
SourceLocation getBeginLoc() const LLVM_READONLY
TranslationUnitDecl * getTranslationUnitDecl()
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Represents a ValueDecl that came out of a declarator.
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
This represents one expression.
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Represents a member of a struct/union/class.
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
StringRef getName() const
The name of this FileEntry.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Represents a function declaration or definition.
bool isTargetClonesMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target-clones functional...
bool isMultiVersion() const
True if this function is considered a multiversioned function.
const ParmVarDecl * getParamDecl(unsigned i) const
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
bool isImmediateFunction() const
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
bool isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
bool isInlineBuiltinDeclaration() const
Determine if this function provides an inline implementation of a builtin.
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
FunctionDecl * getDefinition()
Get the definition for this declaration.
bool isTargetVersionMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target-version functiona...
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
bool doesDeclarationForceExternallyVisibleDefinition() const
For a function declaration in C or C++, determine whether this declaration causes the definition to b...
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
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.
@ None
No signing for any function.
@ Swift5_0
Interoperability with the Swift 5.0 runtime.
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
@ FPE_Ignore
Assume that floating-point exceptions are masked.
VisibilityFromDLLStorageClassKinds
@ Keep
Keep the IR-gen assigned visibility.
@ Protected
Override the IR-gen assigned visibility with protected visibility.
@ Default
Override the IR-gen assigned visibility with default visibility.
@ Hidden
Override the IR-gen assigned visibility with hidden visibility.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
clang::ObjCRuntime ObjCRuntime
CoreFoundationABI CFRuntime
std::string CUID
The user provided compilation unit ID, if non-empty.
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Visibility getVisibility() const
void setLinkage(Linkage L)
Linkage getLinkage() const
bool isVisibilityExplicit() const
LinkageSpecLanguageIDs getLanguage() const
Return the language specified by this linkage specification.
Parts getParts() const
Get the decomposed parts of this declaration.
APValue & getAsAPValue() const
Get the value of this MSGuidDecl as an APValue.
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
void mangleBlock(const DeclContext *DC, const BlockDecl *BD, raw_ostream &Out)
void mangleCtorBlock(const CXXConstructorDecl *CD, CXXCtorType CT, const BlockDecl *BD, raw_ostream &Out)
void mangleGlobalBlock(const BlockDecl *BD, const NamedDecl *ID, raw_ostream &Out)
bool shouldMangleDeclName(const NamedDecl *D)
void mangleName(GlobalDecl GD, raw_ostream &)
virtual void mangleCanonicalTypeName(QualType T, raw_ostream &, bool NormalizeIntegers=false)=0
Generates a unique string for an externally visible type for use with TBAA or type uniquing.
virtual void mangleStringLiteral(const StringLiteral *SL, raw_ostream &)=0
ManglerKind getKind() const
virtual void needsUniqueInternalLinkageNames()
virtual void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber, raw_ostream &)=0
void mangleDtorBlock(const CXXDestructorDecl *CD, CXXDtorType DT, const BlockDecl *BD, raw_ostream &Out)
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
unsigned getManglingNumber() const
Describes a module or submodule.
bool isInterfaceOrPartition() const
bool isNamedModuleUnit() const
Is this a C++20 named module unit.
Module * Parent
The parent of this module.
Module * getPrivateModuleFragment() const
Get the Private Module Fragment (sub-module) for this module, it there is one.
Module * getGlobalModuleFragment() const
Get the Global Module Fragment (sub-module) for this module, it there is one.
llvm::iterator_range< submodule_iterator > submodules()
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used.
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
llvm::SmallVector< ModuleRef, 2 > Imports
The set of modules imported by this module, and on which this module depends.
bool UseExportAsModuleLinkName
Autolinking uses the framework name for linking purposes when this is false and the export_as name ot...
This represents a decl that may have a name.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
LinkageInfo getLinkageAndVisibility() const
Determines the linkage and visibility of this entity.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
bool isExternallyVisible() const
Represent a C++ namespace.
This represents 'pragma omp threadprivate ...' directive.
ObjCEncodeExpr, used for @encode in Objective-C.
QualType getEncodedType() const
propimpl_range property_impls() const
const ObjCInterfaceDecl * getClassInterface() const
void addInstanceMethod(ObjCMethodDecl *method)
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
init_iterator init_end()
init_end() - Retrieve an iterator past the last initializer.
CXXCtorInitializer ** init_iterator
init_iterator - Iterates through the ivar initializer list.
init_iterator init_begin()
init_begin() - Retrieve an iterator to the first initializer.
unsigned getNumIvarInitializers() const
getNumArgs - Number of ivars which must be initialized.
void setHasDestructors(bool val)
void setHasNonZeroConstructors(bool val)
Represents an ObjC class declaration.
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
ObjCIvarDecl - Represents an ObjC instance variable.
ObjCIvarDecl * getNextIvar()
static ObjCMethodDecl * Create(ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc, Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo, DeclContext *contextDecl, bool isInstance=true, bool isVariadic=false, bool isPropertyAccessor=false, bool isSynthesizedAccessorStub=false, bool isImplicitlyDeclared=false, bool isDefined=false, ObjCImplementationControl impControl=ObjCImplementationControl::None, bool HasRelatedResultType=false)
Represents one property declaration in an Objective-C interface.
ObjCMethodDecl * getGetterMethodDecl() const
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
The basic abstraction for the target Objective-C runtime.
bool hasUnwindExceptions() const
Does this runtime use zero-cost exceptions?
@ MacOSX
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
@ FragileMacOSX
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
@ GNUstep
'gnustep' is the modern non-fragile GNUstep runtime.
@ ObjFW
'objfw' is the Objective-C runtime included in ObjFW
@ iOS
'ios' is the Apple-provided NeXT-derived runtime on iOS or the iOS simulator; it is always non-fragil...
@ GCC
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI
@ WatchOS
'watchos' is a variant of iOS for Apple's watchOS.
Represents a parameter to a function.
bool isAddressDiscriminated() const
uint16_t getConstantDiscrimination() const
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
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.
A trivial tuple used to represent a source range.
Stmt - This represents one statement.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
SourceLocation getBeginLoc() const LLVM_READONLY
StringLiteral - This represents a string literal expression, e.g.
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
unsigned getLength() const
uint32_t getCodeUnit(size_t i) const
StringRef getString() const
unsigned getCharByteWidth() const
Represents the declaration of a struct/union/class/enum.
void startDefinition()
Starts the definition of this tag declaration.
Exposes information about the current target.
TargetOptions & getTargetOpts() const
Retrieve the target options.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
bool isReadOnlyFeature(StringRef Feature) const
Determine whether the given target feature is read only.
virtual llvm::APInt getFMVPriority(ArrayRef< StringRef > Features) const
bool supportsIFunc() const
Identify whether this target supports IFuncs.
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
virtual bool initFeatureMap(llvm::StringMap< bool > &Features, DiagnosticsEngine &Diags, StringRef CPU, const std::vector< std::string > &FeatureVec) const
Initialize the map with the default set of target features for the CPU this should include all legal ...
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
std::string TuneCPU
If given, the name of the target CPU to tune code for.
std::string CPU
If given, the name of the target CPU to generate code for.
@ Hostcall
printf lowering scheme involving hostcalls, currently used by HIP programs by default
A template parameter object.
const APValue & getValue() const
A declaration that models statements at global scope.
The top declaration context.
static DeclContext * castToDeclContext(const TranslationUnitDecl *D)
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
bool isPointerType() const
const T * castAs() const
Member-template castAs<specific type>.
bool isReferenceType() const
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
bool isHLSLResourceRecord() const
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
bool isObjCObjectPointerType() const
Linkage getLinkage() const
Determine the linkage of this type.
const T * getAs() const
Member-template getAs<specific type>'.
bool isRecordType() const
bool isHLSLResourceRecordArray() const
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
const APValue & getValue() const
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Represents a variable declaration or definition.
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
TLSKind getTLSKind() const
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
bool hasFlexibleArrayInit(const ASTContext &Ctx) const
Whether this variable has a flexible array member initialized with one or more elements.
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
const Expr * getInit() const
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
@ TLS_Dynamic
TLS with a dynamic initializer.
@ DeclarationOnly
This declaration is only a declaration.
@ Definition
This declaration is definitely a definition.
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
StorageClass getStorageClass() const
Returns the storage class as written in the source.
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Defines the clang::TargetInfo interface.
std::unique_ptr< TargetCodeGenInfo > createARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind Kind)
std::unique_ptr< TargetCodeGenInfo > createM68kTargetCodeGenInfo(CodeGenModule &CGM)
@ AttributedType
The l-value was considered opaque, so the alignment was determined from a type, but that type was an ...
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
std::unique_ptr< TargetCodeGenInfo > createBPFTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createMSP430TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel)
std::unique_ptr< TargetCodeGenInfo > createWebAssemblyTargetCodeGenInfo(CodeGenModule &CGM, WebAssemblyABIKind K)
std::unique_ptr< TargetCodeGenInfo > createPPC64_SVR4_TargetCodeGenInfo(CodeGenModule &CGM, PPC64_SVR4_ABIKind Kind, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createMIPSTargetCodeGenInfo(CodeGenModule &CGM, bool IsOS32)
std::unique_ptr< TargetCodeGenInfo > createHexagonTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createNVPTXTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createSystemZTargetCodeGenInfo(CodeGenModule &CGM, bool HasVector, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createWinX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters)
std::unique_ptr< TargetCodeGenInfo > createAIXTargetCodeGenInfo(CodeGenModule &CGM, bool Is64Bit)
std::unique_ptr< TargetCodeGenInfo > createAMDGPUTargetCodeGenInfo(CodeGenModule &CGM)
CGObjCRuntime * CreateMacObjCRuntime(CodeGenModule &CGM)
X86AVXABILevel
The AVX ABI level for X86 targets.
std::unique_ptr< TargetCodeGenInfo > createTCETargetCodeGenInfo(CodeGenModule &CGM)
CGObjCRuntime * CreateGNUObjCRuntime(CodeGenModule &CGM)
Creates an instance of an Objective-C runtime class.
std::unique_ptr< TargetCodeGenInfo > createWindowsARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind K)
std::unique_ptr< TargetCodeGenInfo > createAVRTargetCodeGenInfo(CodeGenModule &CGM, unsigned NPR, unsigned NRR)
std::unique_ptr< TargetCodeGenInfo > createDirectXTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createARCTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createDefaultTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind Kind)
std::unique_ptr< TargetCodeGenInfo > createSPIRVTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createWindowsMIPSTargetCodeGenInfo(CodeGenModule &CGM, bool IsOS32)
std::unique_ptr< TargetCodeGenInfo > createSparcV8TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createVETargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createCommonSPIRTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createRISCVTargetCodeGenInfo(CodeGenModule &CGM, unsigned XLen, unsigned FLen, bool EABI)
std::unique_ptr< TargetCodeGenInfo > createWindowsAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind K)
std::unique_ptr< TargetCodeGenInfo > createSparcV9TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createLanaiTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createPPC32TargetCodeGenInfo(CodeGenModule &CGM, bool SoftFloatABI)
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,...
constexpr bool isInitializedByPipeline(LangAS AS)
bool LT(InterpState &S, CodePtr OpPC)
llvm::PointerUnion< const Decl *, const Expr * > DeclTy
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
CXXCtorType
C++ constructor types.
@ Ctor_Base
Base object ctor.
@ Ctor_Complete
Complete object ctor.
bool isa(CodeGen::Address addr)
GVALinkage
A more specific kind of linkage than enum Linkage.
@ GVA_AvailableExternally
std::string getClangVendor()
Retrieves the Clang vendor tag.
@ ICIS_NoInit
No in-class initializer.
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
@ Asm
Assembly: we accept this only so that we can preprocess it.
@ SD_Thread
Thread storage duration.
@ SD_Static
Static storage duration.
bool isLambdaCallOperator(const CXXMethodDecl *MD)
@ Result
The result type of a method or function.
StringRef languageToString(Language L)
@ Dtor_VectorDeleting
Vector deleting dtor.
@ Dtor_Base
Base object dtor.
@ Dtor_Complete
Complete object dtor.
@ Dtor_Deleting
Deleting dtor.
LangAS
Defines the address space values used by the address space qualifier of QualType.
@ FirstTargetAddressSpace
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::vfs::FileSystem &VFS, DiagnosticsEngine &Diags)
static const char * getCFBranchLabelSchemeFlagVal(const CFBranchLabelSchemeKind Scheme)
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
U cast(CodeGen::Address addr)
@ None
No keyword precedes the qualified type name.
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
bool isExternallyVisible(Linkage L)
@ EST_None
no exception specification
std::string getClangFullVersion()
Retrieves a string representing the complete clang version, which includes the clang version number,...
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
@ DefaultVisibility
Objects with "default" visibility are seen by the dynamic linker and act like normal objects.
cl::opt< bool > SystemHeadersCoverage
int const char * function
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
std::optional< StringRef > Architecture
llvm::SmallVector< StringRef, 8 > Features
llvm::CallingConv::ID RuntimeCC
llvm::PointerType * VoidPtrTy
llvm::IntegerType * Int64Ty
llvm::PointerType * ConstGlobalsPtrTy
void* in the address space for constant globals
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::IntegerType * CharTy
char
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
unsigned char IntAlignInBytes
llvm::Type * HalfTy
half, bfloat, float, double
unsigned char SizeSizeInBytes
llvm::CallingConv::ID getRuntimeCC() const
llvm::IntegerType * SizeTy
llvm::PointerType * GlobalsInt8PtrTy
llvm::IntegerType * Int32Ty
llvm::IntegerType * IntPtrTy
llvm::IntegerType * IntTy
int
llvm::IntegerType * Int16Ty
llvm::PointerType * ProgramPtrTy
Pointer in program address space.
unsigned char PointerAlignInBytes
llvm::PointerType * Int8PtrTy
CharUnits getPointerAlign() const
llvm::PointerType * AllocaInt8PtrTy
EvalResult is a struct with detailed info about an evaluated expression.
APValue Val
Val - This is the value the expression can be folded to.
bool hasSideEffects() const
Return true if the evaluated expression has side effects.
Extra information about a function prototype.
static const LangStandard & getLangStandardForKind(Kind K)
uint16_t Part2
...-89ab-...
uint32_t Part1
{01234567-...
uint16_t Part3
...-cdef-...
uint8_t Part4And5[8]
...-0123-456789abcdef}
A library or framework to link against when an entity from this module is used.
PointerAuthSchema InitFiniPointers
The ABI for function addresses in .init_array and .fini_array.
Describes how types, statements, expressions, and declarations should be printed.