50#include "llvm/ADT/STLExtras.h"
51#include "llvm/ADT/StringExtras.h"
52#include "llvm/ADT/StringSwitch.h"
53#include "llvm/Analysis/TargetLibraryInfo.h"
54#include "llvm/BinaryFormat/ELF.h"
55#include "llvm/IR/AttributeMask.h"
56#include "llvm/IR/CallingConv.h"
57#include "llvm/IR/DataLayout.h"
58#include "llvm/IR/Intrinsics.h"
59#include "llvm/IR/LLVMContext.h"
60#include "llvm/IR/Module.h"
61#include "llvm/IR/ProfileSummary.h"
62#include "llvm/ProfileData/InstrProfReader.h"
63#include "llvm/ProfileData/SampleProf.h"
64#include "llvm/Support/CRC.h"
65#include "llvm/Support/CodeGen.h"
66#include "llvm/Support/CommandLine.h"
67#include "llvm/Support/ConvertUTF.h"
68#include "llvm/Support/ErrorHandling.h"
69#include "llvm/Support/TimeProfiler.h"
70#include "llvm/Support/xxhash.h"
71#include "llvm/TargetParser/RISCVISAInfo.h"
72#include "llvm/TargetParser/Triple.h"
73#include "llvm/TargetParser/X86TargetParser.h"
74#include "llvm/Transforms/Utils/BuildLibCalls.h"
79using namespace CodeGen;
82 "limited-coverage-experimental", llvm::cl::Hidden,
83 llvm::cl::desc(
"Emit limited coverage mapping information (experimental)"));
89 case TargetCXXABI::AppleARM64:
90 case TargetCXXABI::Fuchsia:
91 case TargetCXXABI::GenericAArch64:
92 case TargetCXXABI::GenericARM:
93 case TargetCXXABI::iOS:
94 case TargetCXXABI::WatchOS:
95 case TargetCXXABI::GenericMIPS:
96 case TargetCXXABI::GenericItanium:
97 case TargetCXXABI::WebAssembly:
98 case TargetCXXABI::XL:
100 case TargetCXXABI::Microsoft:
104 llvm_unreachable(
"invalid C++ ABI kind");
107static std::unique_ptr<TargetCodeGenInfo>
113 switch (Triple.getArch()) {
117 case llvm::Triple::m68k:
119 case llvm::Triple::mips:
120 case llvm::Triple::mipsel:
121 if (Triple.getOS() == llvm::Triple::Win32)
125 case llvm::Triple::mips64:
126 case llvm::Triple::mips64el:
129 case llvm::Triple::avr: {
133 unsigned NPR =
Target.getABI() ==
"avrtiny" ? 6 : 18;
134 unsigned NRR =
Target.getABI() ==
"avrtiny" ? 4 : 8;
138 case llvm::Triple::aarch64:
139 case llvm::Triple::aarch64_32:
140 case llvm::Triple::aarch64_be: {
142 if (
Target.getABI() ==
"darwinpcs")
143 Kind = AArch64ABIKind::DarwinPCS;
144 else if (Triple.isOSWindows())
146 else if (
Target.getABI() ==
"aapcs-soft")
147 Kind = AArch64ABIKind::AAPCSSoft;
148 else if (
Target.getABI() ==
"pauthtest")
149 Kind = AArch64ABIKind::PAuthTest;
154 case llvm::Triple::wasm32:
155 case llvm::Triple::wasm64: {
157 if (
Target.getABI() ==
"experimental-mv")
158 Kind = WebAssemblyABIKind::ExperimentalMV;
162 case llvm::Triple::arm:
163 case llvm::Triple::armeb:
164 case llvm::Triple::thumb:
165 case llvm::Triple::thumbeb: {
166 if (Triple.getOS() == llvm::Triple::Win32)
170 StringRef ABIStr =
Target.getABI();
171 if (ABIStr ==
"apcs-gnu")
172 Kind = ARMABIKind::APCS;
173 else if (ABIStr ==
"aapcs16")
174 Kind = ARMABIKind::AAPCS16_VFP;
175 else if (CodeGenOpts.
FloatABI ==
"hard" ||
176 (CodeGenOpts.
FloatABI !=
"soft" && Triple.isHardFloatABI()))
177 Kind = ARMABIKind::AAPCS_VFP;
182 case llvm::Triple::ppc: {
183 if (Triple.isOSAIX())
190 case llvm::Triple::ppcle: {
191 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
194 case llvm::Triple::ppc64:
195 if (Triple.isOSAIX())
198 if (Triple.isOSBinFormatELF()) {
200 if (
Target.getABI() ==
"elfv2")
201 Kind = PPC64_SVR4_ABIKind::ELFv2;
202 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
207 case llvm::Triple::ppc64le: {
208 assert(Triple.isOSBinFormatELF() &&
"PPC64 LE non-ELF not supported!");
210 if (
Target.getABI() ==
"elfv1")
211 Kind = PPC64_SVR4_ABIKind::ELFv1;
212 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
217 case llvm::Triple::nvptx:
218 case llvm::Triple::nvptx64:
221 case llvm::Triple::msp430:
224 case llvm::Triple::riscv32:
225 case llvm::Triple::riscv64: {
226 StringRef ABIStr =
Target.getABI();
227 unsigned XLen =
Target.getPointerWidth(LangAS::Default);
228 unsigned ABIFLen = 0;
229 if (ABIStr.ends_with(
"f"))
231 else if (ABIStr.ends_with(
"d"))
233 bool EABI = ABIStr.ends_with(
"e");
237 case llvm::Triple::systemz: {
238 bool SoftFloat = CodeGenOpts.
FloatABI ==
"soft";
239 bool HasVector = !SoftFloat &&
Target.getABI() ==
"vector";
243 case llvm::Triple::tce:
244 case llvm::Triple::tcele:
247 case llvm::Triple::x86: {
248 bool IsDarwinVectorABI = Triple.isOSDarwin();
249 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
251 if (Triple.getOS() == llvm::Triple::Win32) {
253 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
254 CodeGenOpts.NumRegisterParameters);
257 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
258 CodeGenOpts.NumRegisterParameters, CodeGenOpts.
FloatABI ==
"soft");
261 case llvm::Triple::x86_64: {
262 StringRef ABI =
Target.getABI();
263 X86AVXABILevel AVXLevel = (ABI ==
"avx512" ? X86AVXABILevel::AVX512
264 : ABI ==
"avx" ? X86AVXABILevel::AVX
265 : X86AVXABILevel::None);
267 switch (Triple.getOS()) {
268 case llvm::Triple::UEFI:
269 case llvm::Triple::Win32:
275 case llvm::Triple::hexagon:
277 case llvm::Triple::lanai:
279 case llvm::Triple::r600:
281 case llvm::Triple::amdgcn:
283 case llvm::Triple::sparc:
285 case llvm::Triple::sparcv9:
287 case llvm::Triple::xcore:
289 case llvm::Triple::arc:
291 case llvm::Triple::spir:
292 case llvm::Triple::spir64:
294 case llvm::Triple::spirv32:
295 case llvm::Triple::spirv64:
296 case llvm::Triple::spirv:
298 case llvm::Triple::dxil:
300 case llvm::Triple::ve:
302 case llvm::Triple::csky: {
303 bool IsSoftFloat = !
Target.hasFeature(
"hard-float-abi");
305 Target.hasFeature(
"fpuv2_df") ||
Target.hasFeature(
"fpuv3_df");
310 case llvm::Triple::bpfeb:
311 case llvm::Triple::bpfel:
313 case llvm::Triple::loongarch32:
314 case llvm::Triple::loongarch64: {
315 StringRef ABIStr =
Target.getABI();
316 unsigned ABIFRLen = 0;
317 if (ABIStr.ends_with(
"f"))
319 else if (ABIStr.ends_with(
"d"))
322 CGM,
Target.getPointerWidth(LangAS::Default), ABIFRLen);
328 if (!TheTargetCodeGenInfo)
330 return *TheTargetCodeGenInfo;
334 llvm::LLVMContext &Context,
338 if (Opts.AlignDouble || Opts.OpenCL || Opts.HLSL)
341 llvm::Triple Triple =
Target.getTriple();
342 llvm::DataLayout DL(
Target.getDataLayoutString());
343 auto Check = [&](
const char *Name, llvm::Type *Ty,
unsigned Alignment) {
344 llvm::Align DLAlign = DL.getABITypeAlign(Ty);
345 llvm::Align ClangAlign(Alignment / 8);
346 if (DLAlign != ClangAlign) {
347 llvm::errs() <<
"For target " << Triple.str() <<
" type " << Name
348 <<
" mapping to " << *Ty <<
" has data layout alignment "
349 << DLAlign.value() <<
" while clang specifies "
350 << ClangAlign.value() <<
"\n";
355 Check(
"bool", llvm::Type::getIntNTy(Context,
Target.BoolWidth),
357 Check(
"short", llvm::Type::getIntNTy(Context,
Target.ShortWidth),
359 Check(
"int", llvm::Type::getIntNTy(Context,
Target.IntWidth),
361 Check(
"long", llvm::Type::getIntNTy(Context,
Target.LongWidth),
364 if (Triple.getArch() != llvm::Triple::m68k)
365 Check(
"long long", llvm::Type::getIntNTy(Context,
Target.LongLongWidth),
368 if (
Target.hasInt128Type() && !
Target.getTargetOpts().ForceEnableInt128 &&
369 !Triple.isAMDGPU() && !Triple.isSPIRV() &&
370 Triple.getArch() != llvm::Triple::ve)
371 Check(
"__int128", llvm::Type::getIntNTy(Context, 128),
Target.Int128Align);
373 if (
Target.hasFloat16Type())
374 Check(
"half", llvm::Type::getFloatingPointTy(Context, *
Target.HalfFormat),
376 if (
Target.hasBFloat16Type())
377 Check(
"bfloat", llvm::Type::getBFloatTy(Context),
Target.BFloat16Align);
378 Check(
"float", llvm::Type::getFloatingPointTy(Context, *
Target.FloatFormat),
381 if (!Triple.isOSAIX()) {
383 llvm::Type::getFloatingPointTy(Context, *
Target.DoubleFormat),
386 llvm::Type::getFloatingPointTy(Context, *
Target.LongDoubleFormat),
389 if (
Target.hasFloat128Type())
390 Check(
"__float128", llvm::Type::getFP128Ty(Context),
Target.Float128Align);
391 if (
Target.hasIbm128Type())
392 Check(
"__ibm128", llvm::Type::getPPC_FP128Ty(Context),
Target.Ibm128Align);
394 Check(
"void*", llvm::PointerType::getUnqual(Context),
Target.PointerAlign);
405 : Context(
C), LangOpts(
C.getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
406 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
408 VMContext(M.getContext()), VTables(*this), StackHandler(diags),
410 AtomicOpts(
Target.getAtomicOpts()) {
414 llvm::LLVMContext &LLVMContext = M.getContext();
415 VoidTy = llvm::Type::getVoidTy(LLVMContext);
416 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
417 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
418 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
419 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
420 HalfTy = llvm::Type::getHalfTy(LLVMContext);
421 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
422 FloatTy = llvm::Type::getFloatTy(LLVMContext);
423 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
429 C.toCharUnitsFromBits(
C.getTargetInfo().getMaxPointerWidth()).getQuantity();
431 C.toCharUnitsFromBits(
C.getTargetInfo().getIntAlign()).getQuantity();
433 llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getCharWidth());
434 IntTy = llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getIntWidth());
435 IntPtrTy = llvm::IntegerType::get(LLVMContext,
436 C.getTargetInfo().getMaxPointerWidth());
437 Int8PtrTy = llvm::PointerType::get(LLVMContext,
439 const llvm::DataLayout &DL = M.getDataLayout();
441 llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
443 llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
460 createOpenCLRuntime();
462 createOpenMPRuntime();
469 if (LangOpts.
Sanitize.
hasOneOf(SanitizerKind::Thread | SanitizerKind::Type) ||
470 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
476 if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
486 Block.GlobalUniqueCount = 0;
488 if (
C.getLangOpts().ObjC)
492 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
499 PGOReader = std::move(ReaderOrErr.get());
504 if (CodeGenOpts.CoverageMapping)
508 if (CodeGenOpts.UniqueInternalLinkageNames &&
509 !
getModule().getSourceFileName().empty()) {
513 if (
Path.rfind(Entry.first, 0) != std::string::npos) {
514 Path = Entry.second +
Path.substr(Entry.first.size());
517 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(
Path);
522 getModule().addModuleFlag(llvm::Module::Error,
"NumRegisterParameters",
523 CodeGenOpts.NumRegisterParameters);
533 const llvm::MemoryBuffer &FileBuffer = **BufOrErr;
534 for (llvm::line_iterator I(FileBuffer.getMemBufferRef(),
true),
E;
536 this->MSHotPatchFunctions.push_back(std::string{*I});
541 "failed to open hotpatch functions file "
542 "(-fms-hotpatch-functions-file): %0 : %1");
544 << BufOrErr.getError().message();
549 this->MSHotPatchFunctions.push_back(FuncName);
551 llvm::sort(this->MSHotPatchFunctions);
560void CodeGenModule::createObjCRuntime() {
577 llvm_unreachable(
"bad runtime kind");
580void CodeGenModule::createOpenCLRuntime() {
584void CodeGenModule::createOpenMPRuntime() {
587 Diags.
Report(diag::err_omp_host_ir_file_not_found)
593 case llvm::Triple::nvptx:
594 case llvm::Triple::nvptx64:
595 case llvm::Triple::amdgcn:
596 case llvm::Triple::spirv64:
599 "OpenMP AMDGPU/NVPTX/SPIRV is only prepared to deal with device code.");
603 if (LangOpts.OpenMPSimd)
611void CodeGenModule::createCUDARuntime() {
615void CodeGenModule::createHLSLRuntime() {
620 Replacements[Name] =
C;
623void CodeGenModule::applyReplacements() {
624 for (
auto &I : Replacements) {
625 StringRef MangledName = I.first;
626 llvm::Constant *Replacement = I.second;
630 auto *OldF = cast<llvm::Function>(Entry);
631 auto *NewF = dyn_cast<llvm::Function>(Replacement);
633 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
634 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
636 auto *CE = cast<llvm::ConstantExpr>(Replacement);
637 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
638 CE->getOpcode() == llvm::Instruction::GetElementPtr);
639 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
644 OldF->replaceAllUsesWith(Replacement);
646 NewF->removeFromParent();
647 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
650 OldF->eraseFromParent();
655 GlobalValReplacements.push_back(std::make_pair(GV,
C));
658void CodeGenModule::applyGlobalValReplacements() {
659 for (
auto &I : GlobalValReplacements) {
660 llvm::GlobalValue *GV = I.first;
661 llvm::Constant *
C = I.second;
663 GV->replaceAllUsesWith(
C);
664 GV->eraseFromParent();
671 const llvm::Constant *
C;
672 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
673 C = GA->getAliasee();
674 else if (
auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
675 C = GI->getResolver();
679 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(
C->stripPointerCasts());
683 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
692 bool IsIFunc,
const llvm::GlobalValue *Alias,
const llvm::GlobalValue *&GV,
693 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
697 Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
701 if (GV->hasCommonLinkage()) {
703 if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
704 Diags.
Report(Location, diag::err_alias_to_common);
709 if (GV->isDeclaration()) {
710 Diags.
Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
711 Diags.
Report(Location, diag::note_alias_requires_mangled_name)
712 << IsIFunc << IsIFunc;
715 for (
const auto &[
Decl, Name] : MangledDeclNames) {
716 if (
const auto *ND = dyn_cast<NamedDecl>(
Decl.getDecl())) {
718 if (II && II->
getName() == GV->getName()) {
719 Diags.
Report(Location, diag::note_alias_mangled_name_alternative)
723 (Twine(IsIFunc ?
"ifunc" :
"alias") +
"(\"" + Name +
"\")")
733 const auto *F = dyn_cast<llvm::Function>(GV);
735 Diags.
Report(Location, diag::err_alias_to_undefined)
736 << IsIFunc << IsIFunc;
740 llvm::FunctionType *FTy = F->getFunctionType();
741 if (!FTy->getReturnType()->isPointerTy()) {
742 Diags.
Report(Location, diag::err_ifunc_resolver_return);
756 if (GVar->hasAttribute(
"toc-data")) {
757 auto GVId = GVar->getName();
760 Diags.
Report(Location, diag::warn_toc_unsupported_type)
761 << GVId <<
"the variable has an alias";
763 llvm::AttributeSet CurrAttributes = GVar->getAttributes();
764 llvm::AttributeSet NewAttributes =
765 CurrAttributes.removeAttribute(GVar->getContext(),
"toc-data");
766 GVar->setAttributes(NewAttributes);
770void CodeGenModule::checkAliases() {
777 const auto *
D = cast<ValueDecl>(GD.getDecl());
780 bool IsIFunc =
D->
hasAttr<IFuncAttr>();
782 Location = A->getLocation();
783 Range = A->getRange();
785 llvm_unreachable(
"Not an alias or ifunc?");
789 const llvm::GlobalValue *GV =
nullptr;
791 MangledDeclNames,
Range)) {
797 if (
const llvm::GlobalVariable *GVar =
798 dyn_cast<const llvm::GlobalVariable>(GV))
802 llvm::Constant *Aliasee =
803 IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver()
804 : cast<llvm::GlobalAlias>(Alias)->getAliasee();
806 llvm::GlobalValue *AliaseeGV;
807 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
808 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
810 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
812 if (
const SectionAttr *SA =
D->
getAttr<SectionAttr>()) {
813 StringRef AliasSection = SA->getName();
814 if (AliasSection != AliaseeGV->getSection())
815 Diags.
Report(SA->getLocation(), diag::warn_alias_with_section)
816 << AliasSection << IsIFunc << IsIFunc;
824 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
825 if (GA->isInterposable()) {
826 Diags.
Report(Location, diag::warn_alias_to_weak_alias)
827 << GV->getName() << GA->getName() << IsIFunc;
828 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
829 GA->getAliasee(), Alias->getType());
832 cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee);
834 cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee);
840 cast<llvm::Function>(Aliasee)->addFnAttr(
841 llvm::Attribute::DisableSanitizerInstrumentation);
849 Alias->replaceAllUsesWith(llvm::PoisonValue::get(Alias->getType()));
850 Alias->eraseFromParent();
855 DeferredDeclsToEmit.clear();
856 EmittedDeferredDecls.clear();
857 DeferredAnnotations.clear();
859 OpenMPRuntime->clear();
863 StringRef MainFile) {
866 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
867 if (MainFile.empty())
868 MainFile =
"<stdin>";
869 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
872 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
875 Diags.
Report(diag::warn_profile_data_missing) << Visited << Missing;
879static std::optional<llvm::GlobalValue::VisibilityTypes>
886 return llvm::GlobalValue::DefaultVisibility;
888 return llvm::GlobalValue::HiddenVisibility;
890 return llvm::GlobalValue::ProtectedVisibility;
892 llvm_unreachable(
"unknown option value!");
897 std::optional<llvm::GlobalValue::VisibilityTypes>
V) {
906 GV.setDSOLocal(
false);
907 GV.setVisibility(*
V);
912 if (!LO.VisibilityFromDLLStorageClass)
915 std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
918 std::optional<llvm::GlobalValue::VisibilityTypes>
919 NoDLLStorageClassVisibility =
922 std::optional<llvm::GlobalValue::VisibilityTypes>
923 ExternDeclDLLImportVisibility =
926 std::optional<llvm::GlobalValue::VisibilityTypes>
927 ExternDeclNoDLLStorageClassVisibility =
930 for (llvm::GlobalValue &GV : M.global_values()) {
931 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
934 if (GV.isDeclarationForLinker())
936 llvm::GlobalValue::DLLImportStorageClass
937 ? ExternDeclDLLImportVisibility
938 : ExternDeclNoDLLStorageClassVisibility);
941 llvm::GlobalValue::DLLExportStorageClass
942 ? DLLExportVisibility
943 : NoDLLStorageClassVisibility);
945 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
950 const llvm::Triple &Triple,
954 return LangOpts.getStackProtector() == Mode;
960 EmitModuleInitializers(Primary);
962 DeferredDecls.insert_range(EmittedDeferredDecls);
963 EmittedDeferredDecls.clear();
964 EmitVTablesOpportunistically();
965 applyGlobalValReplacements();
967 emitMultiVersionFunctions();
970 GlobalTopLevelStmtBlockInFlight.first) {
972 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->
getEndLoc());
973 GlobalTopLevelStmtBlockInFlight = {
nullptr,
nullptr};
979 EmitCXXModuleInitFunc(Primary);
981 EmitCXXGlobalInitFunc();
982 EmitCXXGlobalCleanUpFunc();
983 registerGlobalDtorsWithAtExit();
984 EmitCXXThreadLocalInitFunc();
986 if (llvm::Function *ObjCInitFunction =
ObjCRuntime->ModuleInitFunction())
989 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
993 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
994 OpenMPRuntime->clear();
998 PGOReader->getSummary(
false).getMD(VMContext),
999 llvm::ProfileSummary::PSK_Instr);
1006 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
1007 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
1009 EmitStaticExternCAliases();
1014 if (CoverageMapping)
1015 CoverageMapping->emit();
1016 if (CodeGenOpts.SanitizeCfiCrossDso) {
1022 emitAtAvailableLinkGuard();
1030 if (
getTarget().getTargetOpts().CodeObjectVersion !=
1031 llvm::CodeObjectVersionKind::COV_None) {
1032 getModule().addModuleFlag(llvm::Module::Error,
1033 "amdhsa_code_object_version",
1034 getTarget().getTargetOpts().CodeObjectVersion);
1039 auto *MDStr = llvm::MDString::get(
1044 getModule().addModuleFlag(llvm::Module::Error,
"amdgpu_printf_kind",
1057 if (
auto *FD = dyn_cast<FunctionDecl>(
D))
1061 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1065 llvm::ArrayType *ATy = llvm::ArrayType::get(
Int8PtrTy, UsedArray.size());
1067 auto *GV =
new llvm::GlobalVariable(
1068 getModule(), ATy,
false, llvm::GlobalValue::InternalLinkage,
1069 llvm::ConstantArray::get(ATy, UsedArray),
"__clang_gpu_used_external");
1075 auto *GV =
new llvm::GlobalVariable(
1077 llvm::Constant::getNullValue(
Int8Ty),
1086 if (CodeGenOpts.Autolink &&
1087 (Context.
getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
1088 EmitModuleLinkOptions();
1103 if (!ELFDependentLibraries.empty() && !Context.
getLangOpts().CUDAIsDevice) {
1104 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.dependent-libraries");
1105 for (
auto *MD : ELFDependentLibraries)
1106 NMD->addOperand(MD);
1109 if (CodeGenOpts.DwarfVersion) {
1110 getModule().addModuleFlag(llvm::Module::Max,
"Dwarf Version",
1111 CodeGenOpts.DwarfVersion);
1114 if (CodeGenOpts.Dwarf64)
1115 getModule().addModuleFlag(llvm::Module::Max,
"DWARF64", 1);
1119 getModule().setSemanticInterposition(
true);
1121 if (CodeGenOpts.EmitCodeView) {
1123 getModule().addModuleFlag(llvm::Module::Warning,
"CodeView", 1);
1125 if (CodeGenOpts.CodeViewGHash) {
1126 getModule().addModuleFlag(llvm::Module::Warning,
"CodeViewGHash", 1);
1128 if (CodeGenOpts.ControlFlowGuard) {
1130 getModule().addModuleFlag(llvm::Module::Warning,
"cfguard", 2);
1131 }
else if (CodeGenOpts.ControlFlowGuardNoChecks) {
1133 getModule().addModuleFlag(llvm::Module::Warning,
"cfguard", 1);
1135 if (CodeGenOpts.EHContGuard) {
1137 getModule().addModuleFlag(llvm::Module::Warning,
"ehcontguard", 1);
1141 getModule().addModuleFlag(llvm::Module::Warning,
"ms-kernel", 1);
1143 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
1148 getModule().addModuleFlag(llvm::Module::Error,
"StrictVTablePointers",1);
1150 llvm::Metadata *Ops[2] = {
1151 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
1152 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1153 llvm::Type::getInt32Ty(VMContext), 1))};
1155 getModule().addModuleFlag(llvm::Module::Require,
1156 "StrictVTablePointersRequirement",
1157 llvm::MDNode::get(VMContext, Ops));
1163 getModule().addModuleFlag(llvm::Module::Warning,
"Debug Info Version",
1164 llvm::DEBUG_METADATA_VERSION);
1169 uint64_t WCharWidth =
1171 getModule().addModuleFlag(llvm::Module::Error,
"wchar_size", WCharWidth);
1174 getModule().addModuleFlag(llvm::Module::Warning,
1175 "zos_product_major_version",
1176 uint32_t(CLANG_VERSION_MAJOR));
1177 getModule().addModuleFlag(llvm::Module::Warning,
1178 "zos_product_minor_version",
1179 uint32_t(CLANG_VERSION_MINOR));
1180 getModule().addModuleFlag(llvm::Module::Warning,
"zos_product_patchlevel",
1181 uint32_t(CLANG_VERSION_PATCHLEVEL));
1183 getModule().addModuleFlag(llvm::Module::Error,
"zos_product_id",
1184 llvm::MDString::get(VMContext, ProductId));
1189 getModule().addModuleFlag(llvm::Module::Error,
"zos_cu_language",
1190 llvm::MDString::get(VMContext, lang_str));
1194 : std::time(
nullptr);
1195 getModule().addModuleFlag(llvm::Module::Max,
"zos_translation_time",
1196 static_cast<uint64_t
>(TT));
1199 getModule().addModuleFlag(llvm::Module::Error,
"zos_le_char_mode",
1200 llvm::MDString::get(VMContext,
"ascii"));
1204 if (
T.isARM() ||
T.isThumb()) {
1206 uint64_t EnumWidth = Context.
getLangOpts().ShortEnums ? 1 : 4;
1207 getModule().addModuleFlag(llvm::Module::Error,
"min_enum_size", EnumWidth);
1211 StringRef ABIStr =
Target.getABI();
1212 llvm::LLVMContext &Ctx = TheModule.getContext();
1213 getModule().addModuleFlag(llvm::Module::Error,
"target-abi",
1214 llvm::MDString::get(Ctx, ABIStr));
1219 const std::vector<std::string> &Features =
1222 llvm::RISCVISAInfo::parseFeatures(
T.isRISCV64() ? 64 : 32, Features);
1223 if (!errorToBool(ParseResult.takeError()))
1225 llvm::Module::AppendUnique,
"riscv-isa",
1227 Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString())));
1230 if (CodeGenOpts.SanitizeCfiCrossDso) {
1232 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
1235 if (CodeGenOpts.WholeProgramVTables) {
1239 getModule().addModuleFlag(llvm::Module::Error,
"Virtual Function Elim",
1240 CodeGenOpts.VirtualFunctionElimination);
1243 if (LangOpts.
Sanitize.
has(SanitizerKind::CFIICall)) {
1244 getModule().addModuleFlag(llvm::Module::Override,
1245 "CFI Canonical Jump Tables",
1246 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1249 if (CodeGenOpts.SanitizeCfiICallNormalizeIntegers) {
1250 getModule().addModuleFlag(llvm::Module::Override,
"cfi-normalize-integers",
1256 llvm::Module::Append,
"Unique Source File Identifier",
1258 TheModule.getContext(),
1259 llvm::MDString::get(TheModule.getContext(),
1264 getModule().addModuleFlag(llvm::Module::Override,
"kcfi", 1);
1267 if (CodeGenOpts.PatchableFunctionEntryOffset)
1268 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-offset",
1269 CodeGenOpts.PatchableFunctionEntryOffset);
1270 if (CodeGenOpts.SanitizeKcfiArity)
1271 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-arity", 1);
1274 if (CodeGenOpts.CFProtectionReturn &&
1277 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-return",
1281 if (CodeGenOpts.CFProtectionBranch &&
1284 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-branch",
1287 auto Scheme = CodeGenOpts.getCFBranchLabelScheme();
1288 if (
Target.checkCFBranchLabelSchemeSupported(Scheme,
getDiags())) {
1290 Scheme =
Target.getDefaultCFBranchLabelScheme();
1292 llvm::Module::Error,
"cf-branch-label-scheme",
1298 if (CodeGenOpts.FunctionReturnThunks)
1299 getModule().addModuleFlag(llvm::Module::Override,
"function_return_thunk_extern", 1);
1301 if (CodeGenOpts.IndirectBranchCSPrefix)
1302 getModule().addModuleFlag(llvm::Module::Override,
"indirect_branch_cs_prefix", 1);
1314 LangOpts.getSignReturnAddressScope() !=
1316 getModule().addModuleFlag(llvm::Module::Override,
1317 "sign-return-address-buildattr", 1);
1318 if (LangOpts.
Sanitize.
has(SanitizerKind::MemtagStack))
1319 getModule().addModuleFlag(llvm::Module::Override,
1320 "tag-stack-memory-buildattr", 1);
1322 if (
T.isARM() ||
T.isThumb() ||
T.isAArch64()) {
1323 if (LangOpts.BranchTargetEnforcement)
1324 getModule().addModuleFlag(llvm::Module::Min,
"branch-target-enforcement",
1326 if (LangOpts.BranchProtectionPAuthLR)
1327 getModule().addModuleFlag(llvm::Module::Min,
"branch-protection-pauth-lr",
1329 if (LangOpts.GuardedControlStack)
1330 getModule().addModuleFlag(llvm::Module::Min,
"guarded-control-stack", 1);
1332 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address", 1);
1334 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address-all",
1337 getModule().addModuleFlag(llvm::Module::Min,
1338 "sign-return-address-with-bkey", 1);
1340 if (LangOpts.PointerAuthELFGOT)
1341 getModule().addModuleFlag(llvm::Module::Min,
"ptrauth-elf-got", 1);
1344 if (LangOpts.PointerAuthCalls)
1345 getModule().addModuleFlag(llvm::Module::Min,
"ptrauth-sign-personality",
1348 using namespace llvm::ELF;
1349 uint64_t PAuthABIVersion =
1350 (LangOpts.PointerAuthIntrinsics
1351 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS) |
1352 (LangOpts.PointerAuthCalls
1353 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS) |
1354 (LangOpts.PointerAuthReturns
1355 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS) |
1356 (LangOpts.PointerAuthAuthTraps
1357 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS) |
1358 (LangOpts.PointerAuthVTPtrAddressDiscrimination
1359 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR) |
1360 (LangOpts.PointerAuthVTPtrTypeDiscrimination
1361 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR) |
1362 (LangOpts.PointerAuthInitFini
1363 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI) |
1364 (LangOpts.PointerAuthInitFiniAddressDiscrimination
1365 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC) |
1366 (LangOpts.PointerAuthELFGOT
1367 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT) |
1368 (LangOpts.PointerAuthIndirectGotos
1369 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS) |
1370 (LangOpts.PointerAuthTypeInfoVTPtrDiscrimination
1371 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR) |
1372 (LangOpts.PointerAuthFunctionTypeDiscrimination
1373 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR);
1374 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR ==
1375 AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
1376 "Update when new enum items are defined");
1377 if (PAuthABIVersion != 0) {
1378 getModule().addModuleFlag(llvm::Module::Error,
1379 "aarch64-elf-pauthabi-platform",
1380 AARCH64_PAUTH_PLATFORM_LLVM_LINUX);
1381 getModule().addModuleFlag(llvm::Module::Error,
1382 "aarch64-elf-pauthabi-version",
1388 if (CodeGenOpts.StackClashProtector)
1390 llvm::Module::Override,
"probe-stack",
1391 llvm::MDString::get(TheModule.getContext(),
"inline-asm"));
1393 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
1394 getModule().addModuleFlag(llvm::Module::Min,
"stack-probe-size",
1395 CodeGenOpts.StackProbeSize);
1398 llvm::LLVMContext &Ctx = TheModule.getContext();
1400 llvm::Module::Error,
"MemProfProfileFilename",
1404 if (LangOpts.CUDAIsDevice &&
getTriple().isNVPTX()) {
1408 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
1410 llvm::DenormalMode::IEEE);
1413 if (LangOpts.EHAsynch)
1414 getModule().addModuleFlag(llvm::Module::Warning,
"eh-asynch", 1);
1417 if (CodeGenOpts.ImportCallOptimization)
1418 getModule().addModuleFlag(llvm::Module::Warning,
"import-call-optimization",
1422 if (CodeGenOpts.getWinX64EHUnwindV2() != llvm::WinX64EHUnwindV2Mode::Disabled)
1424 llvm::Module::Warning,
"winx64-eh-unwindv2",
1425 static_cast<unsigned>(CodeGenOpts.getWinX64EHUnwindV2()));
1429 getModule().addModuleFlag(llvm::Module::Max,
"openmp", LangOpts.OpenMP);
1431 getModule().addModuleFlag(llvm::Module::Max,
"openmp-device",
1435 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())) {
1436 EmitOpenCLMetadata();
1444 llvm::Metadata *SPIRVerElts[] = {
1445 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1447 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1448 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
1449 llvm::NamedMDNode *SPIRVerMD =
1450 TheModule.getOrInsertNamedMetadata(
"opencl.spir.version");
1451 llvm::LLVMContext &Ctx = TheModule.getContext();
1452 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
1460 if (uint32_t PLevel = Context.
getLangOpts().PICLevel) {
1461 assert(PLevel < 3 &&
"Invalid PIC Level");
1462 getModule().setPICLevel(
static_cast<llvm::PICLevel::Level
>(PLevel));
1464 getModule().setPIELevel(
static_cast<llvm::PIELevel::Level
>(PLevel));
1468 unsigned CM = llvm::StringSwitch<unsigned>(
getCodeGenOpts().CodeModel)
1469 .Case(
"tiny", llvm::CodeModel::Tiny)
1470 .Case(
"small", llvm::CodeModel::Small)
1471 .Case(
"kernel", llvm::CodeModel::Kernel)
1472 .Case(
"medium", llvm::CodeModel::Medium)
1473 .Case(
"large", llvm::CodeModel::Large)
1476 llvm::CodeModel::Model codeModel =
static_cast<llvm::CodeModel::Model
>(CM);
1479 if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
1481 llvm::Triple::x86_64) {
1487 if (CodeGenOpts.NoPLT)
1490 CodeGenOpts.DirectAccessExternalData !=
1491 getModule().getDirectAccessExternalData()) {
1492 getModule().setDirectAccessExternalData(
1493 CodeGenOpts.DirectAccessExternalData);
1495 if (CodeGenOpts.UnwindTables)
1496 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1498 switch (CodeGenOpts.getFramePointer()) {
1503 getModule().setFramePointer(llvm::FramePointerKind::Reserved);
1506 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1509 getModule().setFramePointer(llvm::FramePointerKind::All);
1513 SimplifyPersonality();
1526 EmitVersionIdentMetadata();
1529 EmitCommandLineMetadata();
1537 getModule().setStackProtectorGuardSymbol(
1540 getModule().setStackProtectorGuardOffset(
1545 getModule().addModuleFlag(llvm::Module::Override,
"SkipRaxSetup", 1);
1547 getModule().addModuleFlag(llvm::Module::Override,
"RegCallv4", 1);
1549 if (
getContext().getTargetInfo().getMaxTLSAlign())
1550 getModule().addModuleFlag(llvm::Module::Error,
"MaxTLSAlign",
1551 getContext().getTargetInfo().getMaxTLSAlign());
1569 if (
getTriple().isPPC() && !MustTailCallUndefinedGlobals.empty()) {
1570 for (
auto &I : MustTailCallUndefinedGlobals) {
1571 if (!I.first->isDefined())
1572 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1576 if (!Entry || Entry->isWeakForLinker() ||
1577 Entry->isDeclarationForLinker())
1578 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1584void CodeGenModule::EmitOpenCLMetadata() {
1590 auto EmitVersion = [
this](StringRef MDName,
int Version) {
1591 llvm::Metadata *OCLVerElts[] = {
1592 llvm::ConstantAsMetadata::get(
1593 llvm::ConstantInt::get(
Int32Ty, Version / 100)),
1594 llvm::ConstantAsMetadata::get(
1595 llvm::ConstantInt::get(
Int32Ty, (Version % 100) / 10))};
1596 llvm::NamedMDNode *OCLVerMD = TheModule.getOrInsertNamedMetadata(MDName);
1597 llvm::LLVMContext &Ctx = TheModule.getContext();
1598 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
1601 EmitVersion(
"opencl.ocl.version", CLVersion);
1602 if (LangOpts.OpenCLCPlusPlus) {
1604 EmitVersion(
"opencl.cxx.version", LangOpts.OpenCLCPlusPlusVersion);
1608void CodeGenModule::EmitBackendOptionsMetadata(
1611 getModule().addModuleFlag(llvm::Module::Min,
"SmallDataLimit",
1612 CodeGenOpts.SmallDataLimit);
1629 return TBAA->getTypeInfo(QTy);
1648 return TBAA->getAccessInfo(AccessType);
1655 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
1661 return TBAA->getTBAAStructInfo(QTy);
1667 return TBAA->getBaseTypeInfo(QTy);
1673 return TBAA->getAccessTagInfo(Info);
1680 return TBAA->mergeTBAAInfoForCast(SourceInfo,
TargetInfo);
1688 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
1696 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
1702 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
1707 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
1720 "cannot compile this %0 yet");
1721 std::string Msg =
Type;
1723 << Msg << S->getSourceRange();
1730 "cannot compile this %0 yet");
1731 std::string Msg =
Type;
1736 llvm::function_ref<
void()> Fn) {
1747 if (GV->hasLocalLinkage()) {
1748 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1762 Context.
getLangOpts().OpenMPIsTargetDevice && isa<VarDecl>(
D) &&
1763 D->
hasAttr<OMPDeclareTargetDeclAttr>() &&
1764 D->
getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
1765 OMPDeclareTargetDeclAttr::DT_NoHost &&
1767 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1772 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1776 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
1780 if (GV->hasDLLExportStorageClass()) {
1783 diag::err_hidden_visibility_dllexport);
1786 diag::err_non_default_visibility_dllimport);
1792 !GV->isDeclarationForLinker())
1797 llvm::GlobalValue *GV) {
1798 if (GV->hasLocalLinkage())
1801 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
1805 if (GV->hasDLLImportStorageClass())
1808 const llvm::Triple &TT = CGM.
getTriple();
1810 if (TT.isOSCygMing()) {
1819 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
1828 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
1836 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
1840 if (!TT.isOSBinFormatELF())
1846 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1852 if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias()))
1854 return !(CGM.
getLangOpts().SemanticInterposition ||
1859 if (!GV->isDeclarationForLinker())
1865 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
1872 if (CGOpts.DirectAccessExternalData) {
1878 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1879 if (!Var->isThreadLocal())
1888 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
1904 const auto *
D = dyn_cast<NamedDecl>(GD.
getDecl());
1906 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(
D)) {
1915 if (
D &&
D->isExternallyVisible()) {
1917 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1918 else if ((
D->
hasAttr<DLLExportAttr>() ||
1920 !GV->isDeclarationForLinker())
1921 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
1945 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
1946 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
1947 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
1948 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
1949 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
1952llvm::GlobalVariable::ThreadLocalMode
1954 switch (CodeGenOpts.getDefaultTLSModel()) {
1956 return llvm::GlobalVariable::GeneralDynamicTLSModel;
1958 return llvm::GlobalVariable::LocalDynamicTLSModel;
1960 return llvm::GlobalVariable::InitialExecTLSModel;
1962 return llvm::GlobalVariable::LocalExecTLSModel;
1964 llvm_unreachable(
"Invalid TLS model!");
1968 assert(
D.getTLSKind() &&
"setting TLS mode on non-TLS var!");
1970 llvm::GlobalValue::ThreadLocalMode TLM;
1974 if (
const TLSModelAttr *
Attr =
D.
getAttr<TLSModelAttr>()) {
1978 GV->setThreadLocalMode(TLM);
1984 return (Twine(
'.') + Twine(
Target.CPUSpecificManglingCharacter(Name))).str();
1988 const CPUSpecificAttr *
Attr,
2010 bool OmitMultiVersionMangling =
false) {
2012 llvm::raw_svector_ostream Out(Buffer);
2021 assert(II &&
"Attempt to mangle unnamed decl.");
2022 const auto *FD = dyn_cast<FunctionDecl>(ND);
2027 Out <<
"__regcall4__" << II->
getName();
2029 Out <<
"__regcall3__" << II->
getName();
2030 }
else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
2032 Out <<
"__device_stub__" << II->
getName();
2034 DeviceKernelAttr::isOpenCLSpelling(
2035 FD->getAttr<DeviceKernelAttr>()) &&
2037 Out <<
"__clang_ocl_kern_imp_" << II->
getName();
2053 "Hash computed when not explicitly requested");
2057 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
2058 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
2059 switch (FD->getMultiVersionKind()) {
2063 FD->getAttr<CPUSpecificAttr>(),
2067 auto *
Attr = FD->getAttr<TargetAttr>();
2068 assert(
Attr &&
"Expected TargetAttr to be present "
2069 "for attribute mangling");
2075 auto *
Attr = FD->getAttr<TargetVersionAttr>();
2076 assert(
Attr &&
"Expected TargetVersionAttr to be present "
2077 "for attribute mangling");
2083 auto *
Attr = FD->getAttr<TargetClonesAttr>();
2084 assert(
Attr &&
"Expected TargetClonesAttr to be present "
2085 "for attribute mangling");
2092 llvm_unreachable(
"None multiversion type isn't valid here");
2102 return std::string(Out.str());
2105void CodeGenModule::UpdateMultiVersionNames(
GlobalDecl GD,
2107 StringRef &CurName) {
2114 std::string NonTargetName =
2122 "Other GD should now be a multiversioned function");
2132 if (OtherName != NonTargetName) {
2135 const auto ExistingRecord = Manglings.find(NonTargetName);
2136 if (ExistingRecord != std::end(Manglings))
2137 Manglings.remove(&(*ExistingRecord));
2138 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
2143 CurName = OtherNameRef;
2145 Entry->setName(OtherName);
2155 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
2169 auto FoundName = MangledDeclNames.find(CanonicalGD);
2170 if (FoundName != MangledDeclNames.end())
2171 return FoundName->second;
2175 const auto *ND = cast<NamedDecl>(GD.
getDecl());
2187 assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
2208 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
2209 return MangledDeclNames[CanonicalGD] =
Result.first->first();
2218 llvm::raw_svector_ostream Out(Buffer);
2221 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.
getDecl()), Out);
2222 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(
D))
2224 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(
D))
2229 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
2230 return Result.first->first();
2234 auto it = MangledDeclNames.begin();
2235 while (it != MangledDeclNames.end()) {
2236 if (it->second == Name)
2251 llvm::Constant *AssociatedData) {
2259 bool IsDtorAttrFunc) {
2260 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2262 DtorsUsingAtExit[
Priority].push_back(Dtor);
2270void CodeGenModule::EmitCtorList(CtorList &Fns,
const char *GlobalName) {
2271 if (Fns.empty())
return;
2277 llvm::PointerType *PtrTy = llvm::PointerType::get(
2278 getLLVMContext(), TheModule.getDataLayout().getProgramAddressSpace());
2281 llvm::StructType *CtorStructTy = llvm::StructType::get(
Int32Ty, PtrTy, PtrTy);
2285 auto Ctors = Builder.beginArray(CtorStructTy);
2286 for (
const auto &I : Fns) {
2287 auto Ctor = Ctors.beginStruct(CtorStructTy);
2288 Ctor.addInt(
Int32Ty, I.Priority);
2289 if (InitFiniAuthSchema) {
2290 llvm::Constant *StorageAddress =
2292 ? llvm::ConstantExpr::getIntToPtr(
2293 llvm::ConstantInt::get(
2295 llvm::ConstantPtrAuth::AddrDiscriminator_CtorsDtors),
2299 I.Initializer, InitFiniAuthSchema.
getKey(), StorageAddress,
2300 llvm::ConstantInt::get(
2302 Ctor.add(SignedCtorPtr);
2304 Ctor.add(I.Initializer);
2306 if (I.AssociatedData)
2307 Ctor.add(I.AssociatedData);
2309 Ctor.addNullPointer(PtrTy);
2310 Ctor.finishAndAddTo(Ctors);
2313 auto List = Ctors.finishAndCreateGlobal(GlobalName,
getPointerAlign(),
2315 llvm::GlobalValue::AppendingLinkage);
2319 List->setAlignment(std::nullopt);
2324llvm::GlobalValue::LinkageTypes
2326 const auto *
D = cast<FunctionDecl>(GD.
getDecl());
2330 if (
const auto *Dtor = dyn_cast<CXXDestructorDecl>(
D))
2337 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2338 if (!MDS)
return nullptr;
2340 return llvm::ConstantInt::get(
Int64Ty, llvm::MD5Hash(MDS->getString()));
2360 for (
auto &Param : FnType->param_types())
2364 GeneralizedParams, FnType->getExtProtoInfo());
2371 llvm_unreachable(
"Encountered unknown FunctionType");
2379 FnType->getReturnType(), FnType->getParamTypes(),
2380 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
2382 std::string OutName;
2383 llvm::raw_string_ostream Out(OutName);
2391 Out <<
".normalized";
2393 Out <<
".generalized";
2395 return llvm::ConstantInt::get(
Int32Ty,
2396 static_cast<uint32_t
>(llvm::xxHash64(OutName)));
2401 llvm::Function *F,
bool IsThunk) {
2403 llvm::AttributeList PAL;
2406 if (
CallingConv == llvm::CallingConv::X86_VectorCall &&
2412 Error(
Loc,
"__vectorcall calling convention is not currently supported");
2414 F->setAttributes(PAL);
2415 F->setCallingConv(
static_cast<llvm::CallingConv::ID
>(
CallingConv));
2419 std::string ReadOnlyQual(
"__read_only");
2420 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2421 if (ReadOnlyPos != std::string::npos)
2423 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2425 std::string WriteOnlyQual(
"__write_only");
2426 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2427 if (WriteOnlyPos != std::string::npos)
2428 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2430 std::string ReadWriteQual(
"__read_write");
2431 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2432 if (ReadWritePos != std::string::npos)
2433 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2466 assert(((FD && CGF) || (!FD && !CGF)) &&
2467 "Incorrect use - FD and CGF should either be both null or not!");
2493 for (
unsigned i = 0, e = FD->
getNumParams(); i != e; ++i) {
2496 argNames.push_back(llvm::MDString::get(VMContext, parm->
getName()));
2501 std::string typeQuals;
2505 const Decl *PDecl = parm;
2507 PDecl = TD->getDecl();
2508 const OpenCLAccessAttr *A = PDecl->
getAttr<OpenCLAccessAttr>();
2509 if (A && A->isWriteOnly())
2510 accessQuals.push_back(llvm::MDString::get(VMContext,
"write_only"));
2511 else if (A && A->isReadWrite())
2512 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_write"));
2514 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_only"));
2516 accessQuals.push_back(llvm::MDString::get(VMContext,
"none"));
2518 auto getTypeSpelling = [&](
QualType Ty) {
2519 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2521 if (Ty.isCanonical()) {
2522 StringRef typeNameRef = typeName;
2524 if (typeNameRef.consume_front(
"unsigned "))
2525 return std::string(
"u") + typeNameRef.str();
2526 if (typeNameRef.consume_front(
"signed "))
2527 return typeNameRef.str();
2537 addressQuals.push_back(
2538 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(
2542 std::string typeName = getTypeSpelling(pointeeTy) +
"*";
2543 std::string baseTypeName =
2545 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2546 argBaseTypeNames.push_back(
2547 llvm::MDString::get(VMContext, baseTypeName));
2551 typeQuals =
"restrict";
2554 typeQuals += typeQuals.empty() ?
"const" :
" const";
2556 typeQuals += typeQuals.empty() ?
"volatile" :
" volatile";
2558 uint32_t AddrSpc = 0;
2563 addressQuals.push_back(
2564 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(AddrSpc)));
2568 std::string typeName = getTypeSpelling(ty);
2580 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2581 argBaseTypeNames.push_back(
2582 llvm::MDString::get(VMContext, baseTypeName));
2587 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
2591 Fn->setMetadata(
"kernel_arg_addr_space",
2592 llvm::MDNode::get(VMContext, addressQuals));
2593 Fn->setMetadata(
"kernel_arg_access_qual",
2594 llvm::MDNode::get(VMContext, accessQuals));
2595 Fn->setMetadata(
"kernel_arg_type",
2596 llvm::MDNode::get(VMContext, argTypeNames));
2597 Fn->setMetadata(
"kernel_arg_base_type",
2598 llvm::MDNode::get(VMContext, argBaseTypeNames));
2599 Fn->setMetadata(
"kernel_arg_type_qual",
2600 llvm::MDNode::get(VMContext, argTypeQuals));
2604 Fn->setMetadata(
"kernel_arg_name",
2605 llvm::MDNode::get(VMContext, argNames));
2615 if (!LangOpts.Exceptions)
return false;
2618 if (LangOpts.CXXExceptions)
return true;
2621 if (LangOpts.ObjCExceptions) {
2638 !isa<CXXConstructorDecl, CXXDestructorDecl>(MD);
2643 llvm::SetVector<const CXXRecordDecl *> MostBases;
2648 MostBases.insert(RD);
2650 CollectMostBases(B.getType()->getAsCXXRecordDecl());
2652 CollectMostBases(RD);
2653 return MostBases.takeVector();
2657 llvm::Function *F) {
2658 llvm::AttrBuilder B(F->getContext());
2660 if ((!
D || !
D->
hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2661 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2663 if (CodeGenOpts.StackClashProtector)
2664 B.addAttribute(
"probe-stack",
"inline-asm");
2666 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
2667 B.addAttribute(
"stack-probe-size",
2668 std::to_string(CodeGenOpts.StackProbeSize));
2671 B.addAttribute(llvm::Attribute::NoUnwind);
2673 if (
D &&
D->
hasAttr<NoStackProtectorAttr>())
2675 else if (
D &&
D->
hasAttr<StrictGuardStackCheckAttr>() &&
2677 B.addAttribute(llvm::Attribute::StackProtectStrong);
2679 B.addAttribute(llvm::Attribute::StackProtect);
2681 B.addAttribute(llvm::Attribute::StackProtectStrong);
2683 B.addAttribute(llvm::Attribute::StackProtectReq);
2687 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline))
2688 B.addAttribute(llvm::Attribute::AlwaysInline);
2692 else if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2694 B.addAttribute(llvm::Attribute::NoInline);
2702 if (
D->
hasAttr<ArmLocallyStreamingAttr>())
2703 B.addAttribute(
"aarch64_pstate_sm_body");
2706 if (
Attr->isNewZA())
2707 B.addAttribute(
"aarch64_new_za");
2708 if (
Attr->isNewZT0())
2709 B.addAttribute(
"aarch64_new_zt0");
2714 bool ShouldAddOptNone =
2715 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
2717 ShouldAddOptNone &= !
D->
hasAttr<MinSizeAttr>();
2718 ShouldAddOptNone &= !
D->
hasAttr<AlwaysInlineAttr>();
2721 if (
getLangOpts().HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline) &&
2723 B.addAttribute(llvm::Attribute::AlwaysInline);
2724 }
else if ((ShouldAddOptNone ||
D->
hasAttr<OptimizeNoneAttr>()) &&
2725 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2727 B.addAttribute(llvm::Attribute::OptimizeNone);
2730 B.addAttribute(llvm::Attribute::NoInline);
2735 B.addAttribute(llvm::Attribute::Naked);
2738 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
2739 F->removeFnAttr(llvm::Attribute::MinSize);
2740 }
else if (
D->
hasAttr<NakedAttr>()) {
2742 B.addAttribute(llvm::Attribute::Naked);
2743 B.addAttribute(llvm::Attribute::NoInline);
2744 }
else if (
D->
hasAttr<NoDuplicateAttr>()) {
2745 B.addAttribute(llvm::Attribute::NoDuplicate);
2746 }
else if (
D->
hasAttr<NoInlineAttr>() &&
2747 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2749 B.addAttribute(llvm::Attribute::NoInline);
2750 }
else if (
D->
hasAttr<AlwaysInlineAttr>() &&
2751 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
2753 B.addAttribute(llvm::Attribute::AlwaysInline);
2757 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
2758 B.addAttribute(llvm::Attribute::NoInline);
2762 if (
auto *FD = dyn_cast<FunctionDecl>(
D)) {
2765 auto CheckRedeclForInline = [](
const FunctionDecl *Redecl) {
2766 return Redecl->isInlineSpecified();
2768 if (any_of(FD->
redecls(), CheckRedeclForInline))
2773 return any_of(Pattern->
redecls(), CheckRedeclForInline);
2775 if (CheckForInline(FD)) {
2776 B.addAttribute(llvm::Attribute::InlineHint);
2777 }
else if (CodeGenOpts.getInlining() ==
2780 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2781 B.addAttribute(llvm::Attribute::NoInline);
2788 if (!
D->
hasAttr<OptimizeNoneAttr>()) {
2790 if (!ShouldAddOptNone)
2791 B.addAttribute(llvm::Attribute::OptimizeForSize);
2792 B.addAttribute(llvm::Attribute::Cold);
2795 B.addAttribute(llvm::Attribute::Hot);
2797 B.addAttribute(llvm::Attribute::MinSize);
2804 F->setAlignment(llvm::Align(alignment));
2807 if (LangOpts.FunctionAlignment)
2808 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
2815 if (isa<CXXMethodDecl>(
D) && F->getPointerAlignment(
getDataLayout()) < 2)
2816 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
2821 if (CodeGenOpts.SanitizeCfiCrossDso &&
2822 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2823 if (
auto *FD = dyn_cast<FunctionDecl>(
D)) {
2834 auto *MD = dyn_cast<CXXMethodDecl>(
D);
2837 llvm::Metadata *
Id =
2839 MD->getType(), std::nullopt,
Base));
2840 F->addTypeMetadata(0,
Id);
2847 if (isa_and_nonnull<NamedDecl>(
D))
2850 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2855 if (
const auto *VD = dyn_cast_if_present<VarDecl>(
D);
2857 ((CodeGenOpts.KeepPersistentStorageVariables &&
2858 (VD->getStorageDuration() ==
SD_Static ||
2859 VD->getStorageDuration() ==
SD_Thread)) ||
2860 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
2861 VD->getType().isConstQualified())))
2865bool CodeGenModule::GetCPUAndFeaturesAttributes(
GlobalDecl GD,
2866 llvm::AttrBuilder &Attrs,
2867 bool SetTargetFeatures) {
2873 std::vector<std::string> Features;
2874 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.
getDecl());
2876 const auto *TD = FD ? FD->
getAttr<TargetAttr>() :
nullptr;
2877 const auto *TV = FD ? FD->
getAttr<TargetVersionAttr>() :
nullptr;
2878 assert((!TD || !TV) &&
"both target_version and target specified");
2879 const auto *SD = FD ? FD->
getAttr<CPUSpecificAttr>() :
nullptr;
2880 const auto *TC = FD ? FD->
getAttr<TargetClonesAttr>() :
nullptr;
2881 bool AddedAttr =
false;
2882 if (TD || TV || SD || TC) {
2883 llvm::StringMap<bool> FeatureMap;
2887 for (
const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
2888 Features.push_back((Entry.getValue() ?
"+" :
"-") + Entry.getKey().str());
2896 Target.parseTargetAttr(TD->getFeaturesStr());
2918 if (!TargetCPU.empty()) {
2919 Attrs.addAttribute(
"target-cpu", TargetCPU);
2922 if (!TuneCPU.empty()) {
2923 Attrs.addAttribute(
"tune-cpu", TuneCPU);
2926 if (!Features.empty() && SetTargetFeatures) {
2927 llvm::erase_if(Features, [&](
const std::string& F) {
2930 llvm::sort(Features);
2931 Attrs.addAttribute(
"target-features", llvm::join(Features,
","));
2937 bool IsDefault =
false;
2939 IsDefault = TV->isDefaultVersion();
2940 TV->getFeatures(Feats);
2946 Attrs.addAttribute(
"fmv-features");
2948 }
else if (!Feats.empty()) {
2950 std::set<StringRef> OrderedFeats(Feats.begin(), Feats.end());
2951 std::string FMVFeatures;
2952 for (StringRef F : OrderedFeats)
2953 FMVFeatures.append(
"," + F.str());
2954 Attrs.addAttribute(
"fmv-features", FMVFeatures.substr(1));
2961void CodeGenModule::setNonAliasAttributes(
GlobalDecl GD,
2962 llvm::GlobalObject *GO) {
2967 if (
auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
2970 if (
auto *SA =
D->
getAttr<PragmaClangBSSSectionAttr>())
2971 GV->addAttribute(
"bss-section", SA->getName());
2972 if (
auto *SA =
D->
getAttr<PragmaClangDataSectionAttr>())
2973 GV->addAttribute(
"data-section", SA->getName());
2974 if (
auto *SA =
D->
getAttr<PragmaClangRodataSectionAttr>())
2975 GV->addAttribute(
"rodata-section", SA->getName());
2976 if (
auto *SA =
D->
getAttr<PragmaClangRelroSectionAttr>())
2977 GV->addAttribute(
"relro-section", SA->getName());
2980 if (
auto *F = dyn_cast<llvm::Function>(GO)) {
2983 if (
auto *SA =
D->
getAttr<PragmaClangTextSectionAttr>())
2985 F->setSection(SA->getName());
2987 llvm::AttrBuilder Attrs(F->getContext());
2988 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
2992 llvm::AttributeMask RemoveAttrs;
2993 RemoveAttrs.addAttribute(
"target-cpu");
2994 RemoveAttrs.addAttribute(
"target-features");
2995 RemoveAttrs.addAttribute(
"fmv-features");
2996 RemoveAttrs.addAttribute(
"tune-cpu");
2997 F->removeFnAttrs(RemoveAttrs);
2998 F->addFnAttrs(Attrs);
3002 if (
const auto *CSA =
D->
getAttr<CodeSegAttr>())
3003 GO->setSection(CSA->getName());
3004 else if (
const auto *SA =
D->
getAttr<SectionAttr>())
3005 GO->setSection(SA->getName());
3018 F->setLinkage(llvm::Function::InternalLinkage);
3020 setNonAliasAttributes(GD, F);
3031 GV->
setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
3035 llvm::Function *F) {
3037 if (!LangOpts.
Sanitize.
has(SanitizerKind::CFIICall))
3042 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
3046 F->addTypeMetadata(0, MD);
3050 if (CodeGenOpts.SanitizeCfiCrossDso)
3052 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
3056 llvm::LLVMContext &Ctx = F->getContext();
3057 llvm::MDBuilder MDB(Ctx);
3058 llvm::StringRef Salt;
3061 if (
const auto &Info = FP->getExtraAttributeInfo())
3062 Salt = Info.CFISalt;
3064 F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
3073 return llvm::all_of(Name, [](
const char &
C) {
3074 return llvm::isAlnum(
C) ||
C ==
'_' ||
C ==
'.';
3080 for (
auto &F : M.functions()) {
3082 bool AddressTaken = F.hasAddressTaken();
3083 if (!AddressTaken && F.hasLocalLinkage())
3084 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
3089 if (!AddressTaken || !F.isDeclaration())
3092 const llvm::ConstantInt *
Type;
3093 if (
const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
3094 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
3098 StringRef Name = F.getName();
3102 std::string
Asm = (
".weak __kcfi_typeid_" + Name +
"\n.set __kcfi_typeid_" +
3103 Name +
", " + Twine(
Type->getZExtValue()) +
"\n")
3105 M.appendModuleInlineAsm(
Asm);
3109void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
3110 bool IsIncompleteFunction,
3113 if (F->getIntrinsicID() != llvm::Intrinsic::not_intrinsic) {
3119 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
3121 if (!IsIncompleteFunction)
3128 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
3130 assert(!F->arg_empty() &&
3131 F->arg_begin()->getType()
3132 ->canLosslesslyBitCastTo(F->getReturnType()) &&
3133 "unexpected this return");
3134 F->addParamAttr(0, llvm::Attribute::Returned);
3144 if (!IsIncompleteFunction && F->isDeclaration())
3147 if (
const auto *CSA = FD->
getAttr<CodeSegAttr>())
3148 F->setSection(CSA->getName());
3149 else if (
const auto *SA = FD->
getAttr<SectionAttr>())
3150 F->setSection(SA->getName());
3152 if (
const auto *EA = FD->
getAttr<ErrorAttr>()) {
3154 F->addFnAttr(
"dontcall-error", EA->getUserDiagnostic());
3155 else if (EA->isWarning())
3156 F->addFnAttr(
"dontcall-warn", EA->getUserDiagnostic());
3162 bool HasBody = FD->
hasBody(FDBody);
3164 assert(HasBody &&
"Inline builtin declarations should always have an "
3166 if (shouldEmitFunction(FDBody))
3167 F->addFnAttr(llvm::Attribute::NoBuiltin);
3173 F->addFnAttr(llvm::Attribute::NoBuiltin);
3176 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
3177 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3178 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
3179 if (MD->isVirtual())
3180 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3186 if (!CodeGenOpts.SanitizeCfiCrossDso ||
3187 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
3196 if (CodeGenOpts.InlineMaxStackSize !=
UINT_MAX)
3197 F->addFnAttr(
"inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
3199 if (
const auto *CB = FD->
getAttr<CallbackAttr>()) {
3203 llvm::LLVMContext &Ctx = F->getContext();
3204 llvm::MDBuilder MDB(Ctx);
3208 int CalleeIdx = *CB->encoding_begin();
3209 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
3210 F->addMetadata(llvm::LLVMContext::MD_callback,
3211 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
3212 CalleeIdx, PayloadIndices,
3218 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
3219 "Only globals with definition can force usage.");
3220 LLVMUsed.emplace_back(GV);
3224 assert(!GV->isDeclaration() &&
3225 "Only globals with definition can force usage.");
3226 LLVMCompilerUsed.emplace_back(GV);
3230 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
3231 "Only globals with definition can force usage.");
3233 LLVMCompilerUsed.emplace_back(GV);
3235 LLVMUsed.emplace_back(GV);
3239 std::vector<llvm::WeakTrackingVH> &List) {
3246 UsedArray.resize(List.size());
3247 for (
unsigned i = 0, e = List.size(); i != e; ++i) {
3249 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3250 cast<llvm::Constant>(&*List[i]), CGM.
Int8PtrTy);
3253 if (UsedArray.empty())
3255 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
3257 auto *GV =
new llvm::GlobalVariable(
3258 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
3259 llvm::ConstantArray::get(ATy, UsedArray), Name);
3261 GV->setSection(
"llvm.metadata");
3264void CodeGenModule::emitLLVMUsed() {
3265 emitUsed(*
this,
"llvm.used", LLVMUsed);
3266 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
3271 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3280 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3286 ELFDependentLibraries.push_back(
3287 llvm::MDNode::get(
C, llvm::MDString::get(
C, Lib)));
3294 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
C, MDOpts));
3309 if (
Visited.insert(Import).second)
3326 if (LL.IsFramework) {
3327 llvm::Metadata *Args[2] = {llvm::MDString::get(Context,
"-framework"),
3328 llvm::MDString::get(Context, LL.Library)};
3330 Metadata.push_back(llvm::MDNode::get(Context, Args));
3336 llvm::Metadata *Args[2] = {
3337 llvm::MDString::get(Context,
"lib"),
3338 llvm::MDString::get(Context, LL.Library),
3340 Metadata.push_back(llvm::MDNode::get(Context, Args));
3344 auto *OptString = llvm::MDString::get(Context, Opt);
3345 Metadata.push_back(llvm::MDNode::get(Context, OptString));
3350void CodeGenModule::EmitModuleInitializers(
clang::Module *Primary) {
3352 "We should only emit module initializers for named modules.");
3358 if (isa<ImportDecl>(
D))
3360 assert(isa<VarDecl>(
D) &&
"GMF initializer decl is not a var?");
3367 if (isa<ImportDecl>(
D))
3375 if (isa<ImportDecl>(
D))
3377 assert(isa<VarDecl>(
D) &&
"PMF initializer decl is not a var?");
3383void CodeGenModule::EmitModuleLinkOptions() {
3387 llvm::SetVector<clang::Module *> LinkModules;
3392 for (
Module *M : ImportedModules) {
3395 if (M->getTopLevelModuleName() ==
getLangOpts().CurrentModule &&
3404 while (!Stack.empty()) {
3407 bool AnyChildren =
false;
3417 Stack.push_back(
SM);
3425 LinkModules.insert(Mod);
3434 for (
Module *M : LinkModules)
3437 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
3438 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
3441 if (!LinkerOptionsMetadata.empty()) {
3442 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.linker.options");
3443 for (
auto *MD : LinkerOptionsMetadata)
3444 NMD->addOperand(MD);
3448void CodeGenModule::EmitDeferred() {
3457 if (!DeferredVTables.empty()) {
3458 EmitDeferredVTables();
3463 assert(DeferredVTables.empty());
3470 llvm::append_range(DeferredDeclsToEmit,
3474 if (DeferredDeclsToEmit.empty())
3479 std::vector<GlobalDecl> CurDeclsToEmit;
3480 CurDeclsToEmit.swap(DeferredDeclsToEmit);
3488 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>() &&
3492 if (!FD->
getAttr<SYCLKernelEntryPointAttr>()->isInvalidAttr()) {
3508 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
3526 if (!GV->isDeclaration())
3530 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(
D))
3534 EmitGlobalDefinition(
D, GV);
3539 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
3541 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
3546void CodeGenModule::EmitVTablesOpportunistically() {
3552 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
3553 &&
"Only emit opportunistic vtables with optimizations");
3557 "This queue should only contain external vtables");
3558 if (
getCXXABI().canSpeculativelyEmitVTable(RD))
3561 OpportunisticVTables.clear();
3565 for (
const auto& [MangledName, VD] : DeferredAnnotations) {
3570 DeferredAnnotations.clear();
3572 if (Annotations.empty())
3576 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
3577 Annotations[0]->getType(), Annotations.size()), Annotations);
3578 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
3579 llvm::GlobalValue::AppendingLinkage,
3580 Array,
"llvm.global.annotations");
3585 llvm::Constant *&AStr = AnnotationStrings[Str];
3590 llvm::Constant *
s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
3591 auto *gv =
new llvm::GlobalVariable(
3592 getModule(),
s->getType(),
true, llvm::GlobalValue::PrivateLinkage,
s,
3593 ".str",
nullptr, llvm::GlobalValue::NotThreadLocal,
3596 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3613 SM.getExpansionLineNumber(L);
3614 return llvm::ConstantInt::get(
Int32Ty, LineNo);
3622 llvm::FoldingSetNodeID ID;
3623 for (
Expr *
E : Exprs) {
3624 ID.Add(cast<clang::ConstantExpr>(
E)->getAPValueResult());
3626 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
3631 LLVMArgs.reserve(Exprs.size());
3633 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](
const Expr *
E) {
3634 const auto *CE = cast<clang::ConstantExpr>(
E);
3635 return ConstEmiter.
emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
3638 auto *
Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
3639 auto *GV =
new llvm::GlobalVariable(
getModule(),
Struct->getType(),
true,
3640 llvm::GlobalValue::PrivateLinkage,
Struct,
3643 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3650 const AnnotateAttr *AA,
3658 llvm::Constant *GVInGlobalsAS = GV;
3659 if (GV->getAddressSpace() !=
3661 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
3663 llvm::PointerType::get(
3664 GV->getContext(),
getDataLayout().getDefaultGlobalsAddressSpace()));
3668 llvm::Constant *Fields[] = {
3669 GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
3671 return llvm::ConstantStruct::getAnon(Fields);
3675 llvm::GlobalValue *GV) {
3676 assert(
D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
3686 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
3691 if (NoSanitizeL.containsMainFile(Kind, MainFile.
getName()))
3696 return NoSanitizeL.containsLocation(Kind,
Loc);
3699 return NoSanitizeL.containsFile(Kind, MainFile.
getName());
3703 llvm::GlobalVariable *GV,
3707 if (NoSanitizeL.containsGlobal(Kind, GV->getName(),
Category))
3710 if (NoSanitizeL.containsMainFile(
3711 Kind,
SM.getFileEntryRefForID(
SM.getMainFileID())->getName(),
3714 if (NoSanitizeL.containsLocation(Kind,
Loc,
Category))
3721 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
3722 Ty = AT->getElementType();
3727 if (NoSanitizeL.containsType(Kind, TypeStr,
Category))
3738 auto Attr = ImbueAttr::NONE;
3741 if (
Attr == ImbueAttr::NONE)
3742 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
3744 case ImbueAttr::NONE:
3746 case ImbueAttr::ALWAYS:
3747 Fn->addFnAttr(
"function-instrument",
"xray-always");
3749 case ImbueAttr::ALWAYS_ARG1:
3750 Fn->addFnAttr(
"function-instrument",
"xray-always");
3751 Fn->addFnAttr(
"xray-log-args",
"1");
3753 case ImbueAttr::NEVER:
3754 Fn->addFnAttr(
"function-instrument",
"xray-never");
3767 llvm::driver::ProfileInstrKind Kind =
getCodeGenOpts().getProfileInstr();
3778 if (
auto MainFile =
SM.getFileEntryRefForID(
SM.getMainFileID()))
3792 if (NumGroups > 1) {
3793 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
3802 if (LangOpts.EmitAllDecls)
3805 const auto *VD = dyn_cast<VarDecl>(
Global);
3807 ((CodeGenOpts.KeepPersistentStorageVariables &&
3808 (VD->getStorageDuration() ==
SD_Static ||
3809 VD->getStorageDuration() ==
SD_Thread)) ||
3810 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
3811 VD->getType().isConstQualified())))
3824 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
3825 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
3826 OMPDeclareTargetDeclAttr::getActiveAttr(
Global);
3827 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (
unsigned)-1)
3831 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
3841 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>())
3844 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
3850 if (CXX20ModuleInits && VD->getOwningModule() &&
3851 !VD->getOwningModule()->isModuleMapModule()) {
3860 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
3863 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
Global))
3876 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
3880 llvm::Constant *
Init;
3883 if (!
V.isAbsent()) {
3894 llvm::Constant *Fields[4] = {
3898 llvm::ConstantDataArray::getRaw(
3899 StringRef(
reinterpret_cast<char *
>(Parts.
Part4And5), 8), 8,
3901 Init = llvm::ConstantStruct::getAnon(Fields);
3904 auto *GV =
new llvm::GlobalVariable(
3906 true, llvm::GlobalValue::LinkOnceODRLinkage,
Init, Name);
3908 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3911 if (!
V.isAbsent()) {
3924 llvm::GlobalVariable **Entry =
nullptr;
3925 Entry = &UnnamedGlobalConstantDeclMap[GCD];
3930 llvm::Constant *
Init;
3934 assert(!
V.isAbsent());
3938 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
3940 llvm::GlobalValue::PrivateLinkage,
Init,
3942 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3956 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
3960 llvm::Constant *
Init =
Emitter.emitForInitializer(
3968 llvm::GlobalValue::LinkageTypes
Linkage =
3970 ? llvm::GlobalValue::LinkOnceODRLinkage
3971 : llvm::GlobalValue::InternalLinkage;
3972 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
3976 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3983 const AliasAttr *AA = VD->
getAttr<AliasAttr>();
3984 assert(AA &&
"No alias?");
3994 llvm::Constant *Aliasee;
3995 if (isa<llvm::FunctionType>(DeclTy))
3996 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
4003 auto *F = cast<llvm::GlobalValue>(Aliasee);
4004 F->setLinkage(llvm::Function::ExternalWeakLinkage);
4005 WeakRefReferences.insert(F);
4014 return A->isImplicit();
4018bool CodeGenModule::shouldEmitCUDAGlobalVar(
const VarDecl *
Global)
const {
4019 assert(LangOpts.CUDA &&
"Should not be called by non-CUDA languages");
4024 return !LangOpts.CUDAIsDevice ||
Global->hasAttr<CUDADeviceAttr>() ||
4025 Global->hasAttr<CUDAConstantAttr>() ||
4026 Global->hasAttr<CUDASharedAttr>() ||
4027 Global->getType()->isCUDADeviceBuiltinSurfaceType() ||
4028 Global->getType()->isCUDADeviceBuiltinTextureType();
4035 if (
Global->hasAttr<WeakRefAttr>())
4040 if (
Global->hasAttr<AliasAttr>())
4041 return EmitAliasDefinition(GD);
4044 if (
Global->hasAttr<IFuncAttr>())
4045 return emitIFuncDefinition(GD);
4048 if (
Global->hasAttr<CPUDispatchAttr>())
4049 return emitCPUDispatchDefinition(GD);
4054 if (LangOpts.CUDA) {
4055 assert((isa<FunctionDecl>(
Global) || isa<VarDecl>(
Global)) &&
4056 "Expected Variable or Function");
4057 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
4058 if (!shouldEmitCUDAGlobalVar(VD))
4060 }
else if (LangOpts.CUDAIsDevice) {
4061 const auto *FD = dyn_cast<FunctionDecl>(
Global);
4062 if ((!
Global->hasAttr<CUDADeviceAttr>() ||
4063 (LangOpts.OffloadImplicitHostDeviceTemplates &&
4064 hasImplicitAttr<CUDAHostAttr>(FD) &&
4065 hasImplicitAttr<CUDADeviceAttr>(FD) && !FD->
isConstexpr() &&
4067 !
getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
4068 !
Global->hasAttr<CUDAGlobalAttr>() &&
4069 !(LangOpts.HIPStdPar && isa<FunctionDecl>(
Global) &&
4070 !
Global->hasAttr<CUDAHostAttr>()))
4073 }
else if (!
Global->hasAttr<CUDAHostAttr>() &&
4074 Global->hasAttr<CUDADeviceAttr>())
4078 if (LangOpts.OpenMP) {
4080 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
4082 if (
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(
Global)) {
4083 if (MustBeEmitted(
Global))
4087 if (
auto *DMD = dyn_cast<OMPDeclareMapperDecl>(
Global)) {
4088 if (MustBeEmitted(
Global))
4095 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
4096 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
4102 if (FD->
hasAttr<AnnotateAttr>()) {
4105 DeferredAnnotations[MangledName] = FD;
4120 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
4125 const auto *VD = cast<VarDecl>(
Global);
4126 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
4129 if (LangOpts.OpenMP) {
4131 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
4132 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
4136 if (VD->hasExternalStorage() &&
4137 Res != OMPDeclareTargetDeclAttr::MT_Link)
4140 bool UnifiedMemoryEnabled =
4142 if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4143 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4144 !UnifiedMemoryEnabled) {
4147 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
4148 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4149 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4150 UnifiedMemoryEnabled)) &&
4151 "Link clause or to clause with unified memory expected.");
4170 if (MustBeEmitted(
Global) && MayBeEmittedEagerly(
Global)) {
4172 EmitGlobalDefinition(GD);
4173 addEmittedDeferredDecl(GD);
4180 cast<VarDecl>(
Global)->hasInit()) {
4181 DelayedCXXInitPosition[
Global] = CXXGlobalInits.size();
4182 CXXGlobalInits.push_back(
nullptr);
4188 addDeferredDeclToEmit(GD);
4189 }
else if (MustBeEmitted(
Global)) {
4191 assert(!MayBeEmittedEagerly(
Global));
4192 addDeferredDeclToEmit(GD);
4197 DeferredDecls[MangledName] = GD;
4203 if (
const auto *RT =
4205 if (
auto *RD = dyn_cast<CXXRecordDecl>(RT->getOriginalDecl())) {
4206 RD = RD->getDefinitionOrSelf();
4207 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
4215 struct FunctionIsDirectlyRecursive
4217 const StringRef Name;
4227 if (
Attr && Name ==
Attr->getLabel())
4232 std::string BuiltinNameStr = BI.
getName(BuiltinID);
4233 StringRef BuiltinName = BuiltinNameStr;
4234 return BuiltinName.consume_front(
"__builtin_") && Name == BuiltinName;
4237 bool VisitStmt(
const Stmt *S) {
4238 for (
const Stmt *Child : S->children())
4239 if (Child && this->Visit(Child))
4246 struct DLLImportFunctionVisitor
4248 bool SafeToInline =
true;
4250 bool shouldVisitImplicitCode()
const {
return true; }
4252 bool VisitVarDecl(
VarDecl *VD) {
4255 SafeToInline =
false;
4256 return SafeToInline;
4263 return SafeToInline;
4267 if (
const auto *
D =
E->getTemporary()->getDestructor())
4268 SafeToInline =
D->
hasAttr<DLLImportAttr>();
4269 return SafeToInline;
4274 if (isa<FunctionDecl>(VD))
4275 SafeToInline = VD->
hasAttr<DLLImportAttr>();
4276 else if (
VarDecl *
V = dyn_cast<VarDecl>(VD))
4277 SafeToInline = !
V->hasGlobalStorage() ||
V->hasAttr<DLLImportAttr>();
4278 return SafeToInline;
4282 SafeToInline =
E->getConstructor()->hasAttr<DLLImportAttr>();
4283 return SafeToInline;
4290 SafeToInline =
true;
4292 SafeToInline = M->
hasAttr<DLLImportAttr>();
4294 return SafeToInline;
4298 SafeToInline =
E->getOperatorDelete()->hasAttr<DLLImportAttr>();
4299 return SafeToInline;
4303 SafeToInline =
E->getOperatorNew()->hasAttr<DLLImportAttr>();
4304 return SafeToInline;
4313CodeGenModule::isTriviallyRecursive(
const FunctionDecl *FD) {
4315 if (
getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
4320 Name =
Attr->getLabel();
4325 FunctionIsDirectlyRecursive Walker(Name, Context.
BuiltinInfo);
4327 return Body ? Walker.Visit(Body) :
false;
4330bool CodeGenModule::shouldEmitFunction(
GlobalDecl GD) {
4334 const auto *F = cast<FunctionDecl>(GD.
getDecl());
4337 if (F->isInlineBuiltinDeclaration())
4340 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
4345 if (
const Module *M = F->getOwningModule();
4346 M && M->getTopLevelModule()->isNamedModule() &&
4347 getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
4357 if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
4362 if (F->hasAttr<NoInlineAttr>())
4365 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
4367 DLLImportFunctionVisitor Visitor;
4368 Visitor.TraverseFunctionDecl(
const_cast<FunctionDecl*
>(F));
4369 if (!Visitor.SafeToInline)
4375 for (
const Decl *
Member : Dtor->getParent()->decls())
4376 if (isa<FieldDecl>(
Member))
4390 return !isTriviallyRecursive(F);
4393bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
4394 return CodeGenOpts.OptimizationLevel > 0;
4397void CodeGenModule::EmitMultiVersionFunctionDefinition(
GlobalDecl GD,
4398 llvm::GlobalValue *GV) {
4399 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4402 auto *Spec = FD->
getAttr<CPUSpecificAttr>();
4403 for (
unsigned I = 0; I < Spec->cpus_size(); ++I)
4405 }
else if (
auto *TC = FD->
getAttr<TargetClonesAttr>()) {
4406 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I)
4407 if (TC->isFirstOfVersion(I))
4410 EmitGlobalFunctionDefinition(GD, GV);
4416 AddDeferredMultiVersionResolverToEmit(GD);
4418 GetOrCreateMultiVersionResolver(GD);
4422void CodeGenModule::EmitGlobalDefinition(
GlobalDecl GD, llvm::GlobalValue *GV) {
4423 const auto *
D = cast<ValueDecl>(GD.
getDecl());
4427 "Generating code for declaration");
4429 if (
const auto *FD = dyn_cast<FunctionDecl>(
D)) {
4432 if (!shouldEmitFunction(GD))
4435 llvm::TimeTraceScope TimeScope(
"CodeGen Function", [&]() {
4437 llvm::raw_string_ostream OS(Name);
4443 if (
const auto *
Method = dyn_cast<CXXMethodDecl>(
D)) {
4446 if (isa<CXXConstructorDecl>(
Method) || isa<CXXDestructorDecl>(
Method))
4447 ABI->emitCXXStructor(GD);
4449 EmitMultiVersionFunctionDefinition(GD, GV);
4451 EmitGlobalFunctionDefinition(GD, GV);
4460 return EmitMultiVersionFunctionDefinition(GD, GV);
4461 return EmitGlobalFunctionDefinition(GD, GV);
4464 if (
const auto *VD = dyn_cast<VarDecl>(
D))
4465 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
4467 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
4471 llvm::Function *NewFn);
4487static llvm::GlobalValue::LinkageTypes
4491 return llvm::GlobalValue::InternalLinkage;
4492 return llvm::GlobalValue::WeakODRLinkage;
4495void CodeGenModule::emitMultiVersionFunctions() {
4496 std::vector<GlobalDecl> MVFuncsToEmit;
4497 MultiVersionFuncs.swap(MVFuncsToEmit);
4499 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4500 assert(FD &&
"Expected a FunctionDecl");
4507 if (
Decl->isDefined()) {
4508 EmitGlobalFunctionDefinition(CurGD,
nullptr);
4516 assert(
Func &&
"This should have just been created");
4518 return cast<llvm::Function>(
Func);
4532 if (
const auto *TA = CurFD->
getAttr<TargetAttr>()) {
4533 assert(getTarget().getTriple().isX86() &&
"Unsupported target");
4534 TA->getX86AddedFeatures(Feats);
4535 llvm::Function *Func = createFunction(CurFD);
4536 Options.emplace_back(Func, Feats, TA->getX86Architecture());
4537 }
else if (
const auto *TVA = CurFD->
getAttr<TargetVersionAttr>()) {
4538 if (TVA->isDefaultVersion() && IsDefined)
4539 ShouldEmitResolver = true;
4540 llvm::Function *Func = createFunction(CurFD);
4541 char Delim = getTarget().getTriple().isAArch64() ?
'+' :
',';
4542 TVA->getFeatures(Feats, Delim);
4543 Options.emplace_back(Func, Feats);
4544 }
else if (
const auto *TC = CurFD->
getAttr<TargetClonesAttr>()) {
4545 for (unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
4546 if (!TC->isFirstOfVersion(I))
4548 if (TC->isDefaultVersion(I) && IsDefined)
4549 ShouldEmitResolver = true;
4550 llvm::Function *Func = createFunction(CurFD, I);
4552 if (getTarget().getTriple().isX86()) {
4553 TC->getX86Feature(Feats, I);
4554 Options.emplace_back(Func, Feats, TC->getX86Architecture(I));
4556 char Delim = getTarget().getTriple().isAArch64() ?
'+' :
',';
4557 TC->getFeatures(Feats, I, Delim);
4558 Options.emplace_back(Func, Feats);
4562 llvm_unreachable(
"unexpected MultiVersionKind");
4565 if (!ShouldEmitResolver)
4568 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
4569 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
4570 ResolverConstant = IFunc->getResolver();
4574 *
this, GD, FD,
true);
4581 auto *Alias = llvm::GlobalAlias::create(
4583 MangledName +
".ifunc", IFunc, &
getModule());
4588 llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant);
4593 ResolverFunc->setComdat(
4594 getModule().getOrInsertComdat(ResolverFunc->getName()));
4603 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4609 if (!MVFuncsToEmit.empty())
4614 if (!MultiVersionFuncs.empty())
4615 emitMultiVersionFunctions();
4619 llvm::Constant *
New) {
4620 assert(cast<llvm::Function>(Old)->isDeclaration() &&
"Not a declaration");
4622 Old->replaceAllUsesWith(
New);
4623 Old->eraseFromParent();
4626void CodeGenModule::emitCPUDispatchDefinition(
GlobalDecl GD) {
4627 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4628 assert(FD &&
"Not a FunctionDecl?");
4630 const auto *DD = FD->
getAttr<CPUDispatchAttr>();
4631 assert(DD &&
"Not a cpu_dispatch Function?");
4637 UpdateMultiVersionNames(GD, FD, ResolverName);
4639 llvm::Type *ResolverType;
4642 ResolverType = llvm::FunctionType::get(
4652 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
4653 ResolverName, ResolverType, ResolverGD,
false));
4656 ResolverFunc->setComdat(
4657 getModule().getOrInsertComdat(ResolverFunc->getName()));
4670 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
4673 EmitGlobalFunctionDefinition(ExistingDecl,
nullptr);
4679 Func = GetOrCreateLLVMFunction(
4680 MangledName, DeclTy, ExistingDecl,
4687 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
4688 llvm::transform(Features, Features.begin(),
4689 [](StringRef Str) { return Str.substr(1); });
4690 llvm::erase_if(Features, [&
Target](StringRef Feat) {
4691 return !
Target.validateCpuSupports(Feat);
4693 Options.emplace_back(cast<llvm::Function>(
Func), Features);
4699 return llvm::X86::getCpuSupportsMask(LHS.
Features) >
4700 llvm::X86::getCpuSupportsMask(RHS.
Features);
4707 while (Options.size() > 1 && llvm::all_of(llvm::X86::getCpuSupportsMask(
4708 (Options.end() - 2)->Features),
4709 [](
auto X) { return X == 0; })) {
4710 StringRef LHSName = (Options.end() - 2)->
Function->getName();
4711 StringRef RHSName = (Options.end() - 1)->
Function->getName();
4712 if (LHSName.compare(RHSName) < 0)
4713 Options.erase(Options.end() - 2);
4715 Options.erase(Options.end() - 1);
4719 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4723 auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD));
4724 unsigned AS = IFunc->getType()->getPointerAddressSpace();
4728 if (!isa<llvm::GlobalIFunc>(IFunc)) {
4729 auto *GI = llvm::GlobalIFunc::create(DeclTy, AS,
Linkage,
"",
4736 *
this, GD, FD,
true);
4739 auto *GA = llvm::GlobalAlias::create(DeclTy, AS,
Linkage, AliasName,
4747void CodeGenModule::AddDeferredMultiVersionResolverToEmit(
GlobalDecl GD) {
4748 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4749 assert(FD &&
"Not a FunctionDecl?");
4752 std::string MangledName =
4754 if (!DeferredResolversToEmit.insert(MangledName).second)
4757 MultiVersionFuncs.push_back(GD);
4763llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
GlobalDecl GD) {
4764 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4765 assert(FD &&
"Not a FunctionDecl?");
4767 std::string MangledName =
4772 std::string ResolverName = MangledName;
4776 llvm_unreachable(
"unexpected MultiVersionKind::None for resolver");
4780 ResolverName +=
".ifunc";
4787 ResolverName +=
".resolver";
4790 bool ShouldReturnIFunc =
4800 if (ResolverGV && (isa<llvm::GlobalIFunc>(ResolverGV) || !ShouldReturnIFunc))
4809 AddDeferredMultiVersionResolverToEmit(GD);
4813 if (ShouldReturnIFunc) {
4815 llvm::Type *ResolverType = llvm::FunctionType::get(
4817 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4818 MangledName +
".resolver", ResolverType,
GlobalDecl{},
4820 llvm::GlobalIFunc *GIF =
4823 GIF->setName(ResolverName);
4830 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4832 assert(isa<llvm::GlobalValue>(Resolver) && !ResolverGV &&
4833 "Resolver should be created for the first time");
4838bool CodeGenModule::shouldDropDLLAttribute(
const Decl *
D,
4839 const llvm::GlobalValue *GV)
const {
4840 auto SC = GV->getDLLStorageClass();
4841 if (SC == llvm::GlobalValue::DefaultStorageClass)
4844 return (((SC == llvm::GlobalValue::DLLImportStorageClass &&
4845 !MRD->
hasAttr<DLLImportAttr>()) ||
4846 (SC == llvm::GlobalValue::DLLExportStorageClass &&
4847 !MRD->
hasAttr<DLLExportAttr>())) &&
4858llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
4859 StringRef MangledName, llvm::Type *Ty,
GlobalDecl GD,
bool ForVTable,
4860 bool DontDefer,
bool IsThunk, llvm::AttributeList ExtraAttrs,
4864 std::string NameWithoutMultiVersionMangling;
4865 if (
const FunctionDecl *FD = cast_or_null<FunctionDecl>(
D)) {
4867 if (
getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
4868 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->
isDefined() &&
4869 !DontDefer && !IsForDefinition) {
4872 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
4874 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
4885 UpdateMultiVersionNames(GD, FD, MangledName);
4886 if (!IsForDefinition) {
4892 AddDeferredMultiVersionResolverToEmit(GD);
4894 *
this, GD, FD,
true);
4896 return GetOrCreateMultiVersionResolver(GD);
4901 if (!NameWithoutMultiVersionMangling.empty())
4902 MangledName = NameWithoutMultiVersionMangling;
4907 if (WeakRefReferences.erase(Entry)) {
4909 if (FD && !FD->
hasAttr<WeakAttr>())
4910 Entry->setLinkage(llvm::Function::ExternalLinkage);
4914 if (
D && shouldDropDLLAttribute(
D, Entry)) {
4915 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4921 if (IsForDefinition && !Entry->isDeclaration()) {
4928 DiagnosedConflictingDefinitions.insert(GD).second) {
4932 diag::note_previous_definition);
4936 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
4937 (Entry->getValueType() == Ty)) {
4944 if (!IsForDefinition)
4951 bool IsIncompleteFunction =
false;
4953 llvm::FunctionType *FTy;
4954 if (isa<llvm::FunctionType>(Ty)) {
4955 FTy = cast<llvm::FunctionType>(Ty);
4957 FTy = llvm::FunctionType::get(
VoidTy,
false);
4958 IsIncompleteFunction =
true;
4962 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
4963 Entry ? StringRef() : MangledName, &
getModule());
4968 DeferredAnnotations[MangledName] = cast<ValueDecl>(
D);
4985 if (!Entry->use_empty()) {
4987 Entry->removeDeadConstantUsers();
4993 assert(F->getName() == MangledName &&
"name was uniqued!");
4995 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
4996 if (ExtraAttrs.hasFnAttrs()) {
4997 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
5005 if (isa_and_nonnull<CXXDestructorDecl>(
D) &&
5006 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(
D),
5008 addDeferredDeclToEmit(GD);
5013 auto DDI = DeferredDecls.find(MangledName);
5014 if (DDI != DeferredDecls.end()) {
5018 addDeferredDeclToEmit(DDI->second);
5019 DeferredDecls.erase(DDI);
5034 for (
const auto *FD = cast<FunctionDecl>(
D)->getMostRecentDecl(); FD;
5047 if (!IsIncompleteFunction) {
5048 assert(F->getFunctionType() == Ty);
5064 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
5066 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
5076 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(GD.
getDecl())) {
5079 DD->getParent()->getNumVBases() == 0)
5084 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
5085 false, llvm::AttributeList(),
5088 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
5089 cast<FunctionDecl>(GD.
getDecl())->hasAttr<CUDAGlobalAttr>()) {
5091 cast<llvm::Function>(F->stripPointerCasts()), GD);
5092 if (IsForDefinition)
5100 llvm::GlobalValue *F =
5103 return llvm::NoCFIValue::get(F);
5113 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
5116 if (!
C.getLangOpts().CPlusPlus)
5121 (Name ==
"_ZSt9terminatev" || Name ==
"?terminate@@YAXXZ")
5122 ?
C.Idents.get(
"terminate")
5123 :
C.Idents.get(Name);
5125 for (
const auto &N : {
"__cxxabiv1",
"std"}) {
5129 if (
auto *LSD = dyn_cast<LinkageSpecDecl>(
Result))
5130 for (
const auto *
Result : LSD->lookup(&NS))
5131 if ((ND = dyn_cast<NamespaceDecl>(
Result)))
5136 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
5145 llvm::Function *F, StringRef Name) {
5151 if (!Local && CGM.
getTriple().isWindowsItaniumEnvironment() &&
5154 if (!FD || FD->
hasAttr<DLLImportAttr>()) {
5155 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
5156 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
5163 llvm::AttributeList ExtraAttrs,
bool Local,
bool AssumeConvergent) {
5164 if (AssumeConvergent) {
5166 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5174 llvm::Constant *
C = GetOrCreateLLVMFunction(
5176 false,
false, ExtraAttrs);
5178 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
5194 llvm::AttributeList ExtraAttrs,
bool Local,
5195 bool AssumeConvergent) {
5196 if (AssumeConvergent) {
5198 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5202 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
5206 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
5215 markRegisterParameterAttributes(F);
5241 if (WeakRefReferences.erase(Entry)) {
5243 Entry->setLinkage(llvm::Function::ExternalLinkage);
5247 if (
D && shouldDropDLLAttribute(
D, Entry))
5248 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5250 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd &&
D)
5253 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
5258 if (IsForDefinition && !Entry->isDeclaration()) {
5266 (OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
5268 DiagnosedConflictingDefinitions.insert(
D).second) {
5272 diag::note_previous_definition);
5277 if (Entry->getType()->getAddressSpace() != TargetAS)
5278 return llvm::ConstantExpr::getAddrSpaceCast(
5279 Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
5283 if (!IsForDefinition)
5289 auto *GV =
new llvm::GlobalVariable(
5290 getModule(), Ty,
false, llvm::GlobalValue::ExternalLinkage,
nullptr,
5291 MangledName,
nullptr, llvm::GlobalVariable::NotThreadLocal,
5292 getContext().getTargetAddressSpace(DAddrSpace));
5297 GV->takeName(Entry);
5299 if (!Entry->use_empty()) {
5300 Entry->replaceAllUsesWith(GV);
5303 Entry->eraseFromParent();
5309 auto DDI = DeferredDecls.find(MangledName);
5310 if (DDI != DeferredDecls.end()) {
5313 addDeferredDeclToEmit(DDI->second);
5314 DeferredDecls.erase(DDI);
5319 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
5324 GV->setConstant(
D->getType().isConstantStorage(
getContext(),
false,
false));
5326 GV->setAlignment(
getContext().getDeclAlign(
D).getAsAlign());
5330 if (
D->getTLSKind()) {
5332 CXXThreadLocals.push_back(
D);
5340 if (
getContext().isMSStaticDataMemberInlineDefinition(
D)) {
5341 EmitGlobalVarDefinition(
D);
5345 if (
D->hasExternalStorage()) {
5346 if (
const SectionAttr *SA =
D->
getAttr<SectionAttr>())
5347 GV->setSection(SA->getName());
5351 if (
getTriple().getArch() == llvm::Triple::xcore &&
5353 D->getType().isConstant(Context) &&
5355 GV->setSection(
".cp.rodata");
5358 if (
const auto *CMA =
D->
getAttr<CodeModelAttr>())
5359 GV->setCodeModel(CMA->getModel());
5364 if (Context.
getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
5365 D->getType().isConstQualified() && !GV->hasInitializer() &&
5366 !
D->hasDefinition() &&
D->hasInit() && !
D->
hasAttr<DLLImportAttr>()) {
5370 if (!HasMutableFields) {
5372 const Expr *InitExpr =
D->getAnyInitializer(InitDecl);
5377 auto *InitType =
Init->getType();
5378 if (GV->getValueType() != InitType) {
5383 GV->setName(StringRef());
5386 auto *NewGV = cast<llvm::GlobalVariable>(
5388 ->stripPointerCasts());
5391 GV->eraseFromParent();
5394 GV->setInitializer(
Init);
5395 GV->setConstant(
true);
5396 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
5411 D->hasExternalStorage())
5416 SanitizerMD->reportGlobal(GV, *
D);
5419 D ?
D->getType().getAddressSpace()
5421 assert(
getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
5422 if (DAddrSpace != ExpectedAS) {
5424 *
this, GV, DAddrSpace,
5435 if (isa<CXXConstructorDecl>(
D) || isa<CXXDestructorDecl>(
D))
5437 false, IsForDefinition);
5439 if (isa<CXXMethodDecl>(
D)) {
5447 if (isa<FunctionDecl>(
D)) {
5458 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes
Linkage,
5459 llvm::Align Alignment) {
5460 llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
5461 llvm::GlobalVariable *OldGV =
nullptr;
5465 if (GV->getValueType() == Ty)
5470 assert(GV->isDeclaration() &&
"Declaration has wrong type!");
5475 GV =
new llvm::GlobalVariable(
getModule(), Ty,
true,
5480 GV->takeName(OldGV);
5482 if (!OldGV->use_empty()) {
5483 OldGV->replaceAllUsesWith(GV);
5486 OldGV->eraseFromParent();
5490 !GV->hasAvailableExternallyLinkage())
5491 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5493 GV->setAlignment(Alignment);
5507 assert(
D->hasGlobalStorage() &&
"Not a global variable");
5525 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
5530 assert(!
D->getInit() &&
"Cannot emit definite definitions here!");
5538 if (GV && !GV->isDeclaration())
5543 if (!MustBeEmitted(
D) && !GV) {
5544 DeferredDecls[MangledName] =
D;
5549 EmitGlobalVarDefinition(
D);
5554 if (
auto const *CD = dyn_cast<const CXXConstructorDecl>(
D))
5556 else if (
auto const *DD = dyn_cast<const CXXDestructorDecl>(
D))
5571 if (
const auto *VD = dyn_cast<VarDecl>(
D)) {
5573 cast<llvm::GlobalVariable>(
Addr->stripPointerCasts()), VD);
5574 }
else if (
const auto *FD = dyn_cast<FunctionDecl>(
D)) {
5575 llvm::Function *Fn = cast<llvm::Function>(
Addr);
5576 if (!Fn->getSubprogram())
5587 if (LangOpts.OpenCL) {
5598 if (LangOpts.SYCLIsDevice &&
5602 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
5604 if (
D->
hasAttr<CUDAConstantAttr>())
5610 if (
D->getType().isConstQualified())
5616 if (LangOpts.OpenMP) {
5618 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(
D, AS))
5626 if (LangOpts.OpenCL)
5628 if (LangOpts.SYCLIsDevice)
5630 if (LangOpts.HIP && LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())
5638 if (
auto AS =
getTarget().getConstantAddressSpace())
5651static llvm::Constant *
5653 llvm::GlobalVariable *GV) {
5654 llvm::Constant *Cast = GV;
5660 llvm::PointerType::get(
5667template<
typename SomeDecl>
5669 llvm::GlobalValue *GV) {
5675 if (!
D->template hasAttr<UsedAttr>())
5684 const SomeDecl *
First =
D->getFirstDecl();
5685 if (
First->getDeclContext()->isRecord() || !
First->isInExternCContext())
5691 std::pair<StaticExternCMap::iterator, bool> R =
5692 StaticExternCValues.insert(std::make_pair(
D->getIdentifier(), GV));
5697 R.first->second =
nullptr;
5708 if (
auto *VD = dyn_cast<VarDecl>(&
D))
5722 llvm_unreachable(
"No such linkage");
5730 llvm::GlobalObject &GO) {
5733 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
5741void CodeGenModule::EmitGlobalVarDefinition(
const VarDecl *
D,
5756 if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
5757 OpenMPRuntime->emitTargetGlobalVariable(
D))
5760 llvm::TrackingVH<llvm::Constant>
Init;
5761 bool NeedsGlobalCtor =
false;
5765 bool IsDefinitionAvailableExternally =
5767 bool NeedsGlobalDtor =
5768 !IsDefinitionAvailableExternally &&
5775 if (IsDefinitionAvailableExternally &&
5776 (!
D->hasConstantInitialization() ||
5780 !
D->getType().isConstantStorage(
getContext(),
true,
true)))
5784 const Expr *InitExpr =
D->getAnyInitializer(InitDecl);
5786 std::optional<ConstantEmitter> emitter;
5791 bool IsCUDASharedVar =
5796 bool IsCUDAShadowVar =
5800 bool IsCUDADeviceShadowVar =
5802 (
D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5803 D->getType()->isCUDADeviceBuiltinTextureType());
5805 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) {
5806 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
5808 (
D->getType()->isHLSLResourceRecord() ||
5809 D->getType()->isHLSLResourceRecordArray())) {
5810 Init = llvm::PoisonValue::get(
getTypes().ConvertType(ASTTy));
5811 NeedsGlobalCtor =
D->getType()->isHLSLResourceRecord();
5812 }
else if (
D->
hasAttr<LoaderUninitializedAttr>()) {
5813 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
5814 }
else if (!InitExpr) {
5828 emitter.emplace(*
this);
5829 llvm::Constant *
Initializer = emitter->tryEmitForInitializer(*InitDecl);
5832 if (
D->getType()->isReferenceType())
5837 if (!IsDefinitionAvailableExternally)
5838 NeedsGlobalCtor =
true;
5842 NeedsGlobalCtor =
false;
5854 DelayedCXXInitPosition.erase(
D);
5861 assert(VarSize == CstSize &&
"Emitted constant has unexpected size");
5866 llvm::Type* InitType =
Init->getType();
5867 llvm::Constant *Entry =
5871 Entry = Entry->stripPointerCasts();
5874 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
5885 if (!GV || GV->getValueType() != InitType ||
5886 GV->getType()->getAddressSpace() !=
5890 Entry->setName(StringRef());
5893 GV = cast<llvm::GlobalVariable>(
5895 ->stripPointerCasts());
5898 llvm::Constant *NewPtrForOldDecl =
5899 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5901 Entry->replaceAllUsesWith(NewPtrForOldDecl);
5904 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
5922 if (LangOpts.CUDA) {
5923 if (LangOpts.CUDAIsDevice) {
5924 if (
Linkage != llvm::GlobalValue::InternalLinkage &&
5926 D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5927 D->getType()->isCUDADeviceBuiltinTextureType()))
5928 GV->setExternallyInitialized(
true);
5938 GV->setExternallyInitialized(
true);
5940 GV->setInitializer(
Init);
5947 emitter->finalize(GV);
5950 GV->setConstant((
D->
hasAttr<CUDAConstantAttr>() && LangOpts.CUDAIsDevice) ||
5951 (!NeedsGlobalCtor && !NeedsGlobalDtor &&
5952 D->getType().isConstantStorage(
getContext(),
true,
true)));
5955 if (
const SectionAttr *SA =
D->
getAttr<SectionAttr>()) {
5958 GV->setConstant(
true);
5963 if (std::optional<CharUnits> AlignValFromAllocate =
5965 AlignVal = *AlignValFromAllocate;
5983 Linkage == llvm::GlobalValue::ExternalLinkage &&
5986 Linkage = llvm::GlobalValue::InternalLinkage;
5992 Linkage = llvm::GlobalValue::ExternalLinkage;
5996 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
5997 else if (
D->
hasAttr<DLLExportAttr>())
5998 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
6000 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6002 if (
Linkage == llvm::GlobalVariable::CommonLinkage) {
6004 GV->setConstant(
false);
6009 if (!GV->getInitializer()->isNullValue())
6010 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
6013 setNonAliasAttributes(
D, GV);
6015 if (
D->getTLSKind() && !GV->isThreadLocal()) {
6017 CXXThreadLocals.push_back(
D);
6024 if (NeedsGlobalCtor || NeedsGlobalDtor)
6025 EmitCXXGlobalVarDeclInitFunc(
D, GV, NeedsGlobalCtor);
6027 SanitizerMD->reportGlobal(GV, *
D, NeedsGlobalCtor);
6032 DI->EmitGlobalVariable(GV,
D);
6047 if (
D->getInit() ||
D->hasExternalStorage())
6057 if (
D->
hasAttr<PragmaClangBSSSectionAttr>() ||
6058 D->
hasAttr<PragmaClangDataSectionAttr>() ||
6059 D->
hasAttr<PragmaClangRelroSectionAttr>() ||
6060 D->
hasAttr<PragmaClangRodataSectionAttr>())
6064 if (
D->getTLSKind())
6085 for (
const FieldDecl *FD : RD->fields()) {
6086 if (FD->isBitField())
6088 if (FD->
hasAttr<AlignedAttr>())
6110llvm::GlobalValue::LinkageTypes
6114 return llvm::Function::InternalLinkage;
6117 return llvm::GlobalVariable::WeakAnyLinkage;
6121 return llvm::GlobalVariable::LinkOnceAnyLinkage;
6126 return llvm::GlobalValue::AvailableExternallyLinkage;
6140 return !Context.
getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
6141 : llvm::Function::InternalLinkage;
6155 return llvm::Function::ExternalLinkage;
6158 return D->
hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
6159 : llvm::Function::InternalLinkage;
6160 return llvm::Function::WeakODRLinkage;
6167 CodeGenOpts.NoCommon))
6168 return llvm::GlobalVariable::CommonLinkage;
6175 return llvm::GlobalVariable::WeakODRLinkage;
6179 return llvm::GlobalVariable::ExternalLinkage;
6182llvm::GlobalValue::LinkageTypes
6191 llvm::Function *newFn) {
6193 if (old->use_empty())
6196 llvm::Type *newRetTy = newFn->getReturnType();
6201 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
6203 llvm::User *user = ui->getUser();
6207 if (
auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
6208 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
6214 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
6217 if (!callSite->isCallee(&*ui))
6222 if (callSite->getType() != newRetTy && !callSite->use_empty())
6227 llvm::AttributeList oldAttrs = callSite->getAttributes();
6230 unsigned newNumArgs = newFn->arg_size();
6231 if (callSite->arg_size() < newNumArgs)
6237 bool dontTransform =
false;
6238 for (llvm::Argument &A : newFn->args()) {
6239 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
6240 dontTransform =
true;
6245 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
6253 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
6257 callSite->getOperandBundlesAsDefs(newBundles);
6259 llvm::CallBase *newCall;
6260 if (isa<llvm::CallInst>(callSite)) {
6261 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles,
"",
6262 callSite->getIterator());
6264 auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
6265 newCall = llvm::InvokeInst::Create(
6266 newFn, oldInvoke->getNormalDest(), oldInvoke->getUnwindDest(),
6267 newArgs, newBundles,
"", callSite->getIterator());
6271 if (!newCall->getType()->isVoidTy())
6272 newCall->takeName(callSite);
6273 newCall->setAttributes(
6274 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
6275 oldAttrs.getRetAttrs(), newArgAttrs));
6276 newCall->setCallingConv(callSite->getCallingConv());
6279 if (!callSite->use_empty())
6280 callSite->replaceAllUsesWith(newCall);
6283 if (callSite->getDebugLoc())
6284 newCall->setDebugLoc(callSite->getDebugLoc());
6286 callSitesToBeRemovedFromParent.push_back(callSite);
6289 for (
auto *callSite : callSitesToBeRemovedFromParent) {
6290 callSite->eraseFromParent();
6304 llvm::Function *NewFn) {
6306 if (!isa<llvm::Function>(Old))
return;
6314 (LangOpts.CUDA && !shouldEmitCUDAGlobalVar(VD)))
6326void CodeGenModule::EmitGlobalFunctionDefinition(
GlobalDecl GD,
6327 llvm::GlobalValue *GV) {
6328 const auto *
D = cast<FunctionDecl>(GD.
getDecl());
6335 if (!GV || (GV->getValueType() != Ty))
6341 if (!GV->isDeclaration())
6348 auto *Fn = cast<llvm::Function>(GV);
6360 setNonAliasAttributes(GD, Fn);
6362 bool ShouldAddOptNone = !CodeGenOpts.DisableO0ImplyOptNone &&
6363 (CodeGenOpts.OptimizationLevel == 0) &&
6366 if (DeviceKernelAttr::isOpenCLSpelling(
D->
getAttr<DeviceKernelAttr>())) {
6369 !Fn->hasFnAttribute(llvm::Attribute::NoInline) &&
6371 !Fn->hasFnAttribute(llvm::Attribute::OptimizeNone) &&
6372 !ShouldAddOptNone) {
6373 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
6379 if (
const ConstructorAttr *CA =
D->
getAttr<ConstructorAttr>())
6381 if (
const DestructorAttr *DA =
D->
getAttr<DestructorAttr>())
6387void CodeGenModule::EmitAliasDefinition(
GlobalDecl GD) {
6388 const auto *
D = cast<ValueDecl>(GD.
getDecl());
6389 const AliasAttr *AA =
D->
getAttr<AliasAttr>();
6390 assert(AA &&
"Not an alias?");
6394 if (AA->getAliasee() == MangledName) {
6395 Diags.
Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6402 if (Entry && !Entry->isDeclaration())
6405 Aliases.push_back(GD);
6411 llvm::Constant *Aliasee;
6412 llvm::GlobalValue::LinkageTypes
LT;
6413 if (isa<llvm::FunctionType>(DeclTy)) {
6414 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
6420 if (
const auto *VD = dyn_cast<VarDecl>(GD.
getDecl()))
6427 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
6429 llvm::GlobalAlias::create(DeclTy, AS,
LT,
"", Aliasee, &
getModule());
6432 if (GA->getAliasee() == Entry) {
6433 Diags.
Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6437 assert(Entry->isDeclaration());
6446 GA->takeName(Entry);
6448 Entry->replaceAllUsesWith(GA);
6449 Entry->eraseFromParent();
6451 GA->setName(MangledName);
6459 GA->setLinkage(llvm::Function::WeakAnyLinkage);
6462 if (
const auto *VD = dyn_cast<VarDecl>(
D))
6463 if (VD->getTLSKind())
6469 if (isa<VarDecl>(
D))
6471 DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD);
6474void CodeGenModule::emitIFuncDefinition(
GlobalDecl GD) {
6475 const auto *
D = cast<ValueDecl>(GD.
getDecl());
6476 const IFuncAttr *IFA =
D->
getAttr<IFuncAttr>();
6477 assert(IFA &&
"Not an ifunc?");
6481 if (IFA->getResolver() == MangledName) {
6482 Diags.
Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6488 if (Entry && !Entry->isDeclaration()) {
6491 DiagnosedConflictingDefinitions.insert(GD).second) {
6495 diag::note_previous_definition);
6500 Aliases.push_back(GD);
6506 llvm::Constant *Resolver =
6507 GetOrCreateLLVMFunction(IFA->getResolver(),
VoidTy, {},
6511 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
6512 DeclTy, AS, llvm::Function::ExternalLinkage,
"", Resolver, &
getModule());
6514 if (GIF->getResolver() == Entry) {
6515 Diags.
Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6518 assert(Entry->isDeclaration());
6527 GIF->takeName(Entry);
6529 Entry->replaceAllUsesWith(GIF);
6530 Entry->eraseFromParent();
6532 GIF->setName(MangledName);
6538 return llvm::Intrinsic::getOrInsertDeclaration(&
getModule(),
6539 (llvm::Intrinsic::ID)IID, Tys);
6542static llvm::StringMapEntry<llvm::GlobalVariable *> &
6545 bool &IsUTF16,
unsigned &StringLength) {
6546 StringRef String = Literal->getString();
6547 unsigned NumBytes = String.size();
6550 if (!Literal->containsNonAsciiOrNull()) {
6551 StringLength = NumBytes;
6552 return *Map.insert(std::make_pair(String,
nullptr)).first;
6559 const llvm::UTF8 *FromPtr = (
const llvm::UTF8 *)String.data();
6560 llvm::UTF16 *ToPtr = &ToBuf[0];
6562 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6563 ToPtr + NumBytes, llvm::strictConversion);
6566 StringLength = ToPtr - &ToBuf[0];
6570 return *Map.insert(std::make_pair(
6571 StringRef(
reinterpret_cast<const char *
>(ToBuf.data()),
6572 (StringLength + 1) * 2),
6578 unsigned StringLength = 0;
6579 bool isUTF16 =
false;
6580 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
6585 if (
auto *
C = Entry.second)
6590 const llvm::Triple &Triple =
getTriple();
6593 const bool IsSwiftABI =
6594 static_cast<unsigned>(CFRuntime) >=
6599 if (!CFConstantStringClassRef) {
6600 const char *CFConstantStringClassName =
"__CFConstantStringClassReference";
6602 Ty = llvm::ArrayType::get(Ty, 0);
6604 switch (CFRuntime) {
6608 CFConstantStringClassName =
6609 Triple.isOSDarwin() ?
"$s15SwiftFoundation19_NSCFConstantStringCN"
6610 :
"$s10Foundation19_NSCFConstantStringCN";
6614 CFConstantStringClassName =
6615 Triple.isOSDarwin() ?
"$S15SwiftFoundation19_NSCFConstantStringCN"
6616 :
"$S10Foundation19_NSCFConstantStringCN";
6620 CFConstantStringClassName =
6621 Triple.isOSDarwin() ?
"__T015SwiftFoundation19_NSCFConstantStringCN"
6622 :
"__T010Foundation19_NSCFConstantStringCN";
6629 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
6630 llvm::GlobalValue *GV =
nullptr;
6632 if ((GV = dyn_cast<llvm::GlobalValue>(
C))) {
6639 if ((VD = dyn_cast<VarDecl>(
Result)))
6642 if (Triple.isOSBinFormatELF()) {
6644 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6646 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6647 if (!VD || !VD->
hasAttr<DLLExportAttr>())
6648 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
6650 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
6658 CFConstantStringClassRef =
6659 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(
C, Ty) :
C;
6664 auto *STy = cast<llvm::StructType>(
getTypes().ConvertType(CFTy));
6667 auto Fields = Builder.beginStruct(STy);
6670 Fields.addSignedPointer(cast<llvm::Constant>(CFConstantStringClassRef),
6676 Fields.addInt(
IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
6677 Fields.addInt(
Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
6679 Fields.addInt(
IntTy, isUTF16 ? 0x07d0 : 0x07C8);
6683 llvm::Constant *
C =
nullptr;
6686 reinterpret_cast<uint16_t *
>(
const_cast<char *
>(Entry.first().data())),
6687 Entry.first().size() / 2);
6688 C = llvm::ConstantDataArray::get(VMContext, Arr);
6690 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
6696 new llvm::GlobalVariable(
getModule(),
C->getType(),
true,
6697 llvm::GlobalValue::PrivateLinkage,
C,
".str");
6698 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6708 if (Triple.isOSBinFormatMachO())
6709 GV->setSection(isUTF16 ?
"__TEXT,__ustring"
6710 :
"__TEXT,__cstring,cstring_literals");
6713 else if (Triple.isOSBinFormatELF())
6714 GV->setSection(
".rodata");
6720 llvm::IntegerType *LengthTy =
6730 Fields.addInt(LengthTy, StringLength);
6738 GV = Fields.finishAndCreateGlobal(
"_unnamed_cfstring_", Alignment,
6740 llvm::GlobalVariable::PrivateLinkage);
6741 GV->addAttribute(
"objc_arc_inert");
6742 switch (Triple.getObjectFormat()) {
6743 case llvm::Triple::UnknownObjectFormat:
6744 llvm_unreachable(
"unknown file format");
6745 case llvm::Triple::DXContainer:
6746 case llvm::Triple::GOFF:
6747 case llvm::Triple::SPIRV:
6748 case llvm::Triple::XCOFF:
6749 llvm_unreachable(
"unimplemented");
6750 case llvm::Triple::COFF:
6751 case llvm::Triple::ELF:
6752 case llvm::Triple::Wasm:
6753 GV->setSection(
"cfstring");
6755 case llvm::Triple::MachO:
6756 GV->setSection(
"__DATA,__cfstring");
6765 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
6769 if (ObjCFastEnumerationStateType.
isNull()) {
6771 D->startDefinition();
6779 for (
size_t i = 0; i < 4; ++i) {
6784 FieldTypes[i],
nullptr,
6792 D->completeDefinition();
6796 return ObjCFastEnumerationStateType;
6805 if (
E->getCharByteWidth() == 1) {
6810 assert(CAT &&
"String literal not of constant array type!");
6812 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
6816 llvm::Type *ElemTy = AType->getElementType();
6817 unsigned NumElements = AType->getNumElements();
6820 if (ElemTy->getPrimitiveSizeInBits() == 16) {
6822 Elements.reserve(NumElements);
6824 for(
unsigned i = 0, e =
E->getLength(); i != e; ++i)
6825 Elements.push_back(
E->getCodeUnit(i));
6826 Elements.resize(NumElements);
6827 return llvm::ConstantDataArray::get(VMContext, Elements);
6830 assert(ElemTy->getPrimitiveSizeInBits() == 32);
6832 Elements.reserve(NumElements);
6834 for(
unsigned i = 0, e =
E->getLength(); i != e; ++i)
6835 Elements.push_back(
E->getCodeUnit(i));
6836 Elements.resize(NumElements);
6837 return llvm::ConstantDataArray::get(VMContext, Elements);
6840static llvm::GlobalVariable *
6849 auto *GV =
new llvm::GlobalVariable(
6850 M,
C->getType(), !CGM.
getLangOpts().WritableStrings,
LT,
C, GlobalName,
6851 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
6853 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6854 if (GV->isWeakForLinker()) {
6855 assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
6856 GV->setComdat(M.getOrInsertComdat(GV->getName()));
6872 llvm::GlobalVariable **Entry =
nullptr;
6873 if (!LangOpts.WritableStrings) {
6874 Entry = &ConstantStringMap[
C];
6875 if (
auto GV = *Entry) {
6876 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
6879 GV->getValueType(), Alignment);
6884 StringRef GlobalVariableName;
6885 llvm::GlobalValue::LinkageTypes
LT;
6890 if (
getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
6891 !LangOpts.WritableStrings) {
6892 llvm::raw_svector_ostream Out(MangledNameBuffer);
6894 LT = llvm::GlobalValue::LinkOnceODRLinkage;
6895 GlobalVariableName = MangledNameBuffer;
6897 LT = llvm::GlobalValue::PrivateLinkage;
6898 GlobalVariableName = Name;
6910 SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0),
"<string literal>");
6913 GV->getValueType(), Alignment);
6930 const std::string &Str,
const char *GlobalName) {
6931 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
6936 llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
6939 llvm::GlobalVariable **Entry =
nullptr;
6940 if (!LangOpts.WritableStrings) {
6941 Entry = &ConstantStringMap[
C];
6942 if (
auto GV = *Entry) {
6943 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
6946 GV->getValueType(), Alignment);
6952 GlobalName =
".str";
6955 GlobalName, Alignment);
6960 GV->getValueType(), Alignment);
6965 assert((
E->getStorageDuration() ==
SD_Static ||
6966 E->getStorageDuration() ==
SD_Thread) &&
"not a global temporary");
6967 const auto *VD = cast<VarDecl>(
E->getExtendingDecl());
6972 if (
Init ==
E->getSubExpr())
6977 auto InsertResult = MaterializedGlobalTemporaryMap.insert({
E,
nullptr});
6978 if (!InsertResult.second) {
6981 if (!InsertResult.first->second) {
6986 InsertResult.first->second =
new llvm::GlobalVariable(
6987 getModule(),
Type,
false, llvm::GlobalVariable::InternalLinkage,
6991 llvm::cast<llvm::GlobalVariable>(
6992 InsertResult.first->second->stripPointerCasts())
7001 llvm::raw_svector_ostream Out(Name);
7003 VD,
E->getManglingNumber(), Out);
7006 if (
E->getStorageDuration() ==
SD_Static && VD->evaluateValue()) {
7012 Value =
E->getOrCreateValue(
false);
7023 std::optional<ConstantEmitter> emitter;
7024 llvm::Constant *InitialValue =
nullptr;
7025 bool Constant =
false;
7029 emitter.emplace(*
this);
7030 InitialValue = emitter->emitForInitializer(*
Value, AddrSpace,
7035 Type = InitialValue->getType();
7044 if (
Linkage == llvm::GlobalVariable::ExternalLinkage) {
7046 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
7050 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
7054 Linkage = llvm::GlobalVariable::InternalLinkage;
7058 auto *GV =
new llvm::GlobalVariable(
7060 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
7061 if (emitter) emitter->finalize(GV);
7063 if (!llvm::GlobalValue::isLocalLinkage(
Linkage)) {
7065 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
7067 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
7071 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
7072 if (VD->getTLSKind())
7074 llvm::Constant *CV = GV;
7077 *
this, GV, AddrSpace,
7078 llvm::PointerType::get(
7084 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[
E];
7086 Entry->replaceAllUsesWith(CV);
7087 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
7096void CodeGenModule::EmitObjCPropertyImplementations(
const
7098 for (
const auto *PID :
D->property_impls()) {
7109 if (!Getter || Getter->isSynthesizedAccessorStub())
7112 auto *Setter = PID->getSetterMethodDecl();
7113 if (!PD->
isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
7124 if (ivar->getType().isDestructedType())
7134 E =
D->init_end(); B !=
E; ++B) {
7157 D->addInstanceMethod(DTORMethod);
7159 D->setHasDestructors(
true);
7164 if (
D->getNumIvarInitializers() == 0 ||
7178 D->addInstanceMethod(CTORMethod);
7180 D->setHasNonZeroConstructors(
true);
7191 EmitDeclContext(LSD);
7196 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7199 std::unique_ptr<CodeGenFunction> &CurCGF =
7200 GlobalTopLevelStmtBlockInFlight.first;
7204 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
7212 std::string Name =
"__stmts__" + llvm::utostr(CXXGlobalInits.size());
7218 llvm::Function *
Fn = llvm::Function::Create(
7219 FnTy, llvm::GlobalValue::InternalLinkage, Name, &
getModule());
7222 GlobalTopLevelStmtBlockInFlight.second =
D;
7223 CurCGF->StartFunction(
GlobalDecl(), RetTy, Fn, FnInfo, Args,
7225 CXXGlobalInits.push_back(Fn);
7228 CurCGF->EmitStmt(
D->getStmt());
7231void CodeGenModule::EmitDeclContext(
const DeclContext *DC) {
7232 for (
auto *I : DC->
decls()) {
7238 if (
auto *OID = dyn_cast<ObjCImplDecl>(I)) {
7239 for (
auto *M : OID->methods())
7258 case Decl::CXXConversion:
7259 case Decl::CXXMethod:
7260 case Decl::Function:
7267 case Decl::CXXDeductionGuide:
7272 case Decl::Decomposition:
7273 case Decl::VarTemplateSpecialization:
7275 if (
auto *DD = dyn_cast<DecompositionDecl>(
D))
7276 for (
auto *B : DD->flat_bindings())
7277 if (
auto *HD = B->getHoldingVar())
7284 case Decl::IndirectField:
7288 case Decl::Namespace:
7289 EmitDeclContext(cast<NamespaceDecl>(
D));
7291 case Decl::ClassTemplateSpecialization: {
7292 const auto *Spec = cast<ClassTemplateSpecializationDecl>(
D);
7294 if (Spec->getSpecializationKind() ==
7296 Spec->hasDefinition())
7297 DI->completeTemplateDefinition(*Spec);
7299 case Decl::CXXRecord: {
7303 DI->EmitAndRetainType(
7304 getContext().getCanonicalTagType(cast<RecordDecl>(
D)));
7307 DI->completeUnusedClass(*CRD);
7310 for (
auto *I : CRD->
decls())
7311 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I) || isa<EnumDecl>(I))
7316 case Decl::UsingShadow:
7317 case Decl::ClassTemplate:
7318 case Decl::VarTemplate:
7320 case Decl::VarTemplatePartialSpecialization:
7321 case Decl::FunctionTemplate:
7322 case Decl::TypeAliasTemplate:
7329 DI->EmitUsingDecl(cast<UsingDecl>(*
D));
7331 case Decl::UsingEnum:
7333 DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*
D));
7335 case Decl::NamespaceAlias:
7337 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*
D));
7339 case Decl::UsingDirective:
7341 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*
D));
7343 case Decl::CXXConstructor:
7346 case Decl::CXXDestructor:
7350 case Decl::StaticAssert:
7357 case Decl::ObjCInterface:
7358 case Decl::ObjCCategory:
7361 case Decl::ObjCProtocol: {
7362 auto *Proto = cast<ObjCProtocolDecl>(
D);
7363 if (Proto->isThisDeclarationADefinition())
7368 case Decl::ObjCCategoryImpl:
7371 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(
D));
7374 case Decl::ObjCImplementation: {
7375 auto *OMD = cast<ObjCImplementationDecl>(
D);
7376 EmitObjCPropertyImplementations(OMD);
7377 EmitObjCIvarInitializations(OMD);
7382 DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
7383 OMD->getClassInterface()), OMD->getLocation());
7386 case Decl::ObjCMethod: {
7387 auto *OMD = cast<ObjCMethodDecl>(
D);
7393 case Decl::ObjCCompatibleAlias:
7394 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(
D));
7397 case Decl::PragmaComment: {
7398 const auto *PCD = cast<PragmaCommentDecl>(
D);
7399 switch (PCD->getCommentKind()) {
7401 llvm_unreachable(
"unexpected pragma comment kind");
7416 case Decl::PragmaDetectMismatch: {
7417 const auto *PDMD = cast<PragmaDetectMismatchDecl>(
D);
7422 case Decl::LinkageSpec:
7423 EmitLinkageSpec(cast<LinkageSpecDecl>(
D));
7426 case Decl::FileScopeAsm: {
7428 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7431 if (LangOpts.OpenMPIsTargetDevice)
7434 if (LangOpts.SYCLIsDevice)
7436 auto *AD = cast<FileScopeAsmDecl>(
D);
7437 getModule().appendModuleInlineAsm(AD->getAsmString());
7441 case Decl::TopLevelStmt:
7442 EmitTopLevelStmt(cast<TopLevelStmtDecl>(
D));
7445 case Decl::Import: {
7446 auto *Import = cast<ImportDecl>(
D);
7449 if (!ImportedModules.insert(Import->getImportedModule()))
7453 if (!Import->getImportedOwningModule()) {
7455 DI->EmitImportDecl(*Import);
7461 if (CXX20ModuleInits && Import->getImportedModule() &&
7462 Import->getImportedModule()->isNamedModule())
7471 Visited.insert(Import->getImportedModule());
7472 Stack.push_back(Import->getImportedModule());
7474 while (!Stack.empty()) {
7476 if (!EmittedModuleInitializers.insert(Mod).second)
7486 if (Submodule->IsExplicit)
7489 if (
Visited.insert(Submodule).second)
7490 Stack.push_back(Submodule);
7497 EmitDeclContext(cast<ExportDecl>(
D));
7500 case Decl::OMPThreadPrivate:
7504 case Decl::OMPAllocate:
7508 case Decl::OMPDeclareReduction:
7512 case Decl::OMPDeclareMapper:
7516 case Decl::OMPRequires:
7521 case Decl::TypeAlias:
7523 DI->EmitAndRetainType(
getContext().getTypedefType(
7525 cast<TypedefNameDecl>(
D)));
7531 DI->EmitAndRetainType(
7532 getContext().getCanonicalTagType(cast<RecordDecl>(
D)));
7538 DI->EmitAndRetainType(
7539 getContext().getCanonicalTagType(cast<EnumDecl>(
D)));
7542 case Decl::HLSLRootSignature:
7545 case Decl::HLSLBuffer:
7549 case Decl::OpenACCDeclare:
7552 case Decl::OpenACCRoutine:
7560 assert(isa<TypeDecl>(
D) &&
"Unsupported decl kind");
7567 if (!CodeGenOpts.CoverageMapping)
7570 case Decl::CXXConversion:
7571 case Decl::CXXMethod:
7572 case Decl::Function:
7573 case Decl::ObjCMethod:
7574 case Decl::CXXConstructor:
7575 case Decl::CXXDestructor: {
7576 if (!cast<FunctionDecl>(
D)->doesThisDeclarationHaveABody())
7584 DeferredEmptyCoverageMappingDecls.try_emplace(
D,
true);
7594 if (!CodeGenOpts.CoverageMapping)
7596 if (
const auto *Fn = dyn_cast<FunctionDecl>(
D)) {
7597 if (Fn->isTemplateInstantiation())
7600 DeferredEmptyCoverageMappingDecls.insert_or_assign(
D,
false);
7608 for (
const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
7611 const Decl *
D = Entry.first;
7613 case Decl::CXXConversion:
7614 case Decl::CXXMethod:
7615 case Decl::Function:
7616 case Decl::ObjCMethod: {
7623 case Decl::CXXConstructor: {
7630 case Decl::CXXDestructor: {
7647 if (llvm::Function *F =
getModule().getFunction(
"main")) {
7648 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
7650 auto *GA = llvm::GlobalAlias::create(
"__main_void", F);
7651 GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
7660 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
7661 return llvm::ConstantInt::get(i64, PtrInt);
7665 llvm::NamedMDNode *&GlobalMetadata,
7667 llvm::GlobalValue *
Addr) {
7668 if (!GlobalMetadata)
7670 CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
7673 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(
Addr),
7676 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
7679bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
7680 llvm::GlobalValue *CppFunc) {
7688 if (Elem == CppFunc)
7694 for (llvm::User *User : Elem->users()) {
7698 if (
auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
7699 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
7702 for (llvm::User *CEUser : ConstExpr->users()) {
7703 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
7704 IFuncs.push_back(IFunc);
7709 CEs.push_back(ConstExpr);
7710 }
else if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
7711 IFuncs.push_back(IFunc);
7723 for (llvm::GlobalIFunc *IFunc : IFuncs)
7724 IFunc->setResolver(
nullptr);
7725 for (llvm::ConstantExpr *ConstExpr : CEs)
7726 ConstExpr->destroyConstant();
7730 Elem->eraseFromParent();
7732 for (llvm::GlobalIFunc *IFunc : IFuncs) {
7737 llvm::FunctionType::get(IFunc->getType(),
false);
7738 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
7739 CppFunc->getName(), ResolverTy, {},
false);
7740 IFunc->setResolver(Resolver);
7750void CodeGenModule::EmitStaticExternCAliases() {
7753 for (
auto &I : StaticExternCValues) {
7755 llvm::GlobalValue *Val = I.second;
7763 llvm::GlobalValue *ExistingElem =
7764 getModule().getNamedValue(Name->getName());
7768 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
7775 auto Res = Manglings.find(MangledName);
7776 if (Res == Manglings.end())
7778 Result = Res->getValue();
7789void CodeGenModule::EmitDeclMetadata() {
7790 llvm::NamedMDNode *GlobalMetadata =
nullptr;
7792 for (
auto &I : MangledDeclNames) {
7793 llvm::GlobalValue *
Addr =
getModule().getNamedValue(I.second);
7803void CodeGenFunction::EmitDeclMetadata() {
7804 if (LocalDeclMap.empty())
return;
7809 unsigned DeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
7811 llvm::NamedMDNode *GlobalMetadata =
nullptr;
7813 for (
auto &I : LocalDeclMap) {
7814 const Decl *
D = I.first;
7815 llvm::Value *
Addr = I.second.emitRawPointer(*
this);
7816 if (
auto *Alloca = dyn_cast<llvm::AllocaInst>(
Addr)) {
7818 Alloca->setMetadata(
7819 DeclPtrKind, llvm::MDNode::get(
7820 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
7821 }
else if (
auto *GV = dyn_cast<llvm::GlobalValue>(
Addr)) {
7828void CodeGenModule::EmitVersionIdentMetadata() {
7829 llvm::NamedMDNode *IdentMetadata =
7830 TheModule.getOrInsertNamedMetadata(
"llvm.ident");
7832 llvm::LLVMContext &Ctx = TheModule.getContext();
7834 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
7835 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
7838void CodeGenModule::EmitCommandLineMetadata() {
7839 llvm::NamedMDNode *CommandLineMetadata =
7840 TheModule.getOrInsertNamedMetadata(
"llvm.commandline");
7842 llvm::LLVMContext &Ctx = TheModule.getContext();
7844 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
7845 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
7848void CodeGenModule::EmitCoverageFile() {
7849 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu");
7853 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
7854 llvm::LLVMContext &Ctx = TheModule.getContext();
7855 auto *CoverageDataFile =
7857 auto *CoverageNotesFile =
7859 for (
int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
7860 llvm::MDNode *CU = CUNode->getOperand(i);
7861 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
7862 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
7883 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
7885 for (
auto RefExpr :
D->varlist()) {
7886 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
7888 VD->getAnyInitializer() &&
7889 !VD->getAnyInitializer()->isConstantInitializer(
getContext(),
7896 VD,
Addr, RefExpr->getBeginLoc(), PerformInit))
7897 CXXGlobalInits.push_back(InitFunction);
7902CodeGenModule::CreateMetadataIdentifierImpl(
QualType T, MetadataTypeMap &Map,
7906 FnType->getReturnType(), FnType->getParamTypes(),
7907 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
7909 llvm::Metadata *&InternalId = Map[
T.getCanonicalType()];
7914 std::string OutName;
7915 llvm::raw_string_ostream Out(OutName);
7920 Out <<
".normalized";
7934 return CreateMetadataIdentifierImpl(
T, MetadataIdMap,
"");
7939 return CreateMetadataIdentifierImpl(
T, VirtualMetadataIdMap,
".virtual");
7944 GeneralizedMetadataIdMap,
".generalized");
7951 return ((LangOpts.
Sanitize.
has(SanitizerKind::CFIVCall) &&
7953 (LangOpts.
Sanitize.
has(SanitizerKind::CFINVCall) &&
7955 (LangOpts.
Sanitize.
has(SanitizerKind::CFIDerivedCast) &&
7957 (LangOpts.
Sanitize.
has(SanitizerKind::CFIUnrelatedCast) &&
7966 VTable->addTypeMetadata(Offset.getQuantity(), MD);
7968 if (CodeGenOpts.SanitizeCfiCrossDso)
7970 VTable->addTypeMetadata(Offset.getQuantity(),
7971 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
7974 llvm::Metadata *MD = llvm::MDString::get(
getLLVMContext(),
"all-vtables");
7975 VTable->addTypeMetadata(Offset.getQuantity(), MD);
7981 SanStats = std::make_unique<llvm::SanitizerStatReport>(&
getModule());
7991 auto *FTy = llvm::FunctionType::get(SamplerT, {
C->getType()},
false);
8006 bool forPointeeType) {
8017 if (
auto Align = TT->getDecl()->getMaxAlignment()) {
8047 if (
T.getQualifiers().hasUnaligned()) {
8049 }
else if (forPointeeType && !AlignForArray &&
8061 if (
unsigned MaxAlign =
getLangOpts().MaxTypeAlign) {
8074 if (NumAutoVarInit >= StopAfter) {
8077 if (!NumAutoVarInit) {
8080 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
8081 "number of times ftrivial-auto-var-init=%1 gets applied.");
8095 const Decl *
D)
const {
8099 OS << (isa<VarDecl>(
D) ?
".static." :
".intern.");
8101 OS << (isa<VarDecl>(
D) ?
"__static__" :
"__intern__");
8107 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
8111 llvm::MD5::MD5Result
Result;
8112 for (
const auto &Arg : PreprocessorOpts.
Macros)
8113 Hash.update(Arg.first);
8117 llvm::sys::fs::UniqueID ID;
8118 if (llvm::sys::fs::getUniqueID(PLoc.
getFilename(), ID)) {
8120 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
8121 if (
auto EC = llvm::sys::fs::getUniqueID(PLoc.
getFilename(), ID))
8122 SM.getDiagnostics().Report(diag::err_cannot_open_file)
8125 OS << llvm::format(
"%x", ID.getFile()) << llvm::format(
"%x", ID.getDevice())
8126 <<
"_" << llvm::utohexstr(
Result.low(),
true, 8);
8133 assert(DeferredDeclsToEmit.empty() &&
8134 "Should have emitted all decls deferred to emit.");
8135 assert(NewBuilder->DeferredDecls.empty() &&
8136 "Newly created module should not have deferred decls");
8137 NewBuilder->DeferredDecls = std::move(DeferredDecls);
8138 assert(EmittedDeferredDecls.empty() &&
8139 "Still have (unmerged) EmittedDeferredDecls deferred decls");
8141 assert(NewBuilder->DeferredVTables.empty() &&
8142 "Newly created module should not have deferred vtables");
8143 NewBuilder->DeferredVTables = std::move(DeferredVTables);
8145 assert(NewBuilder->MangledDeclNames.empty() &&
8146 "Newly created module should not have mangled decl names");
8147 assert(NewBuilder->Manglings.empty() &&
8148 "Newly created module should not have manglings");
8149 NewBuilder->Manglings = std::move(Manglings);
8151 NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
8153 NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
Defines the clang::ASTContext interface.
ASTImporterLookupTable & LT
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines the Diagnostic-related interfaces.
Defines enum values for all the target-independent builtin functions.
static bool shouldAssumeDSOLocal(const CIRGenModule &cgm, cir::CIRGlobalValueInterface gv)
static bool shouldBeInCOMDAT(CIRGenModule &cgm, const Decl &d)
static std::string getMangledNameImpl(CIRGenModule &cgm, GlobalDecl gd, const NamedDecl *nd)
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 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 bool hasImplicitAttr(const ValueDecl *D)
static void emitUsed(CodeGenModule &CGM, StringRef Name, std::vector< llvm::WeakTrackingVH > &List)
static bool HasNonDllImportDtor(QualType T)
static llvm::Constant * GetPointerConstant(llvm::LLVMContext &Context, const void *Ptr)
Turns the given pointer into a constant.
static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S)
static llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM, GlobalDecl GD)
static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO, llvm::Module &M)
static std::string getCPUSpecificMangling(const CodeGenModule &CGM, StringRef Name)
static void setWindowsItaniumDLLImport(CodeGenModule &CGM, bool Local, llvm::Function *F, StringRef Name)
static const char AnnotationSection[]
static bool isUniqueInternalLinkageDecl(GlobalDecl GD, CodeGenModule &CGM)
static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty)
static bool allowKCFIIdentifier(StringRef Name)
static 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 bool needsDestructMethod(ObjCImplementationDecl *impl)
static bool isStackProtectorOn(const LangOptions &LangOpts, const llvm::Triple &Triple, clang::LangOptions::StackProtectorMode Mode)
static void removeImageAccessQualifier(std::string &TyName)
static llvm::StringMapEntry< llvm::GlobalVariable * > & GetConstantCFStringEntry(llvm::StringMap< llvm::GlobalVariable * > &Map, const StringLiteral *Literal, bool TargetIsLSB, bool &IsUTF16, unsigned &StringLength)
static void setLLVMVisibility(llvm::GlobalValue &GV, std::optional< llvm::GlobalValue::VisibilityTypes > V)
static llvm::GlobalVariable * GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, CodeGenModule &CGM, StringRef GlobalName, CharUnits Alignment)
static bool hasUnwindExceptions(const LangOptions &LangOpts)
Determines whether the language options require us to model unwind exceptions.
static 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 unsigned ArgInfoAddressSpace(LangAS AS)
static void replaceDeclarationWith(llvm::GlobalValue *Old, llvm::Constant *New)
static QualType GeneralizeType(ASTContext &Ctx, QualType Ty)
static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, llvm::Function *NewFn)
ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we implement a function with...
static std::optional< llvm::GlobalValue::VisibilityTypes > getLLVMVisibility(clang::LangOptions::VisibilityFromDLLStorageClassKinds K)
static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, const CXXMethodDecl *MD)
static bool checkAliasedGlobal(const ASTContext &Context, DiagnosticsEngine &Diags, SourceLocation Location, bool IsIFunc, const llvm::GlobalValue *Alias, const llvm::GlobalValue *&GV, const llvm::MapVector< GlobalDecl, StringRef > &MangledDeclNames, SourceRange AliasRange)
static void EmitGlobalDeclMetadata(CodeGenModule &CGM, llvm::NamedMDNode *&GlobalMetadata, GlobalDecl D, llvm::GlobalValue *Addr)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
llvm::DenseSet< const void * > Visited
llvm::MachO::Target Target
llvm::MachO::Record Record
Defines the clang::Module class, which describes a module in the source code.
static const NamedDecl * getDefinition(const Decl *D)
Defines the SourceManager interface.
static CharUnits getTypeAllocSize(CodeGenModule &CGM, llvm::Type *type)
Defines version macros and version-related utility functions for Clang.
__device__ __2f16 float __ockl_bool s
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
SourceManager & getSourceManager()
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
@ Strong
Strong definition.
@ WeakUnknown
Weak for now, might become strong later in this TU.
const ProfileList & getProfileList() const
llvm::StringMap< SectionInfo > SectionInfos
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
FullSourceLoc getFullLoc(SourceLocation Loc) const
const XRayFunctionFilter & getXRayFilter() const
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=RecordDecl::TagKind::Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
StringRef getCUIDHash() const
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
Builtin::Context & BuiltinInfo
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
SelectorTable & Selectors
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
llvm::SetVector< const ValueDecl * > CUDAExternalDeviceDeclODRUsedByHost
Keep track of CUDA/HIP external kernels or device variables ODR-used by host code.
QualType getCFConstantStringType() const
Return the C structure type used to represent constant CFStrings.
const NoSanitizeList & getNoSanitizeList() const
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
const TargetInfo * getAuxTargetInfo() const
CanQualType UnsignedLongTy
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
const clang::PrintingPolicy & getPrintingPolicy() const
CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const
Return the alignment in characters that should be given to a global variable with type T.
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
QualType getObjCIdType() const
Represents the Objective-CC id type.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
unsigned getTypeAlignIfKnown(QualType T, bool NeedsPreferredAlignment=false) const
Return the alignment of a type, in bits, or 0 if the type is incomplete and we cannot determine the a...
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
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
QualType getWideCharType() const
Return the type of wide characters.
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
Module * getCurrentNamedModule() const
Get module under construction, nullptr if this is not a C++20 module.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Attr - This represents one attribute.
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
bool isLibFunction(unsigned ID) const
Return true if this is a builtin for a libc/libm function, with a "__builtin_" prefix (e....
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Represents a base class of a C++ class.
Represents binding an expression to a temporary.
Represents a call to a C++ constructor.
Represents a C++ base or member initializer.
Expr * getInit() const
Get the initializer.
Represents a delete expression for memory deallocation and destructor calls, e.g.
Represents a C++ destructor within a class.
Represents a call to a member function that may be written either with member call syntax (e....
Represents a static or instance method of a struct/union/class.
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Represents a C++ struct/union/class.
bool hasMutableFields() const
Determine whether this class, or any of its class subobjects, contains a mutable field.
unsigned getNumBases() const
Retrieves the number of base classes of this class.
bool hasDefinition() const
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
CanProxy< U > castAs() const
CharUnits - This is an opaque type for sizes expressed in character units.
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
static CharUnits One()
One - Construct a CharUnits quantity of one.
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::string UniqueSourceFileIdentifier
If non-empty, allow the compiler to assume that the given source file identifier is unique at link ti...
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::string CoverageNotesFile
The filename with path we use for coverage notes files.
std::string ProfileInstrumentUsePath
Name of the profile file to use as input for -fprofile-instr-use.
std::string MemoryProfileOutput
Name of the profile file to use as output for with -fmemory-profile.
std::vector< std::string > TocDataVarsUserSpecified
List of global variables explicitly specified by the user as toc-data.
std::string CoverageDataFile
The filename with path we use for coverage data files.
PointerAuthOptions PointerAuth
Configuration for pointer-signing.
llvm::DenormalMode FP32DenormalMode
The floating-point denormal mode to use, for float.
SanitizerSet SanitizeTrap
Set of sanitizer checks that trap rather than diagnose.
std::string ProfileRemappingFile
Name of the profile remapping file to apply to the profile data supplied by -fprofile-sample-use or -...
std::vector< std::string > MSSecureHotPatchFunctionsList
A list of functions which will be compiled for hotpatching.
bool hasProfileClangUse() const
Check if Clang profile use is on.
std::string SymbolPartition
The name of the partition that symbols are assigned to, specified with -fsymbol-partition (see https:...
ABIInfo - Target specific hooks for defining how a type should be passed or returned from functions.
virtual void appendAttributeMangling(TargetAttr *Attr, raw_ostream &Out) const
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
virtual void handleVarRegistration(const VarDecl *VD, llvm::GlobalVariable &Var)=0
Check whether a variable is a device variable and register it if true.
virtual llvm::GlobalValue * getKernelHandle(llvm::Function *Stub, GlobalDecl GD)=0
Get kernel handle by stub function.
virtual void internalizeDeviceSideVar(const VarDecl *D, llvm::GlobalValue::LinkageTypes &Linkage)=0
Adjust linkage of shadow variables in host compilation.
Implements C++ ABI-specific code generation functions.
virtual void EmitCXXConstructors(const CXXConstructorDecl *D)=0
Emit constructor variants required by this ABI.
virtual llvm::Constant * getAddrOfRTTIDescriptor(QualType Ty)=0
virtual void EmitCXXDestructors(const CXXDestructorDecl *D)=0
Emit destructor variants required by this ABI.
virtual void setCXXDestructorDLLStorage(llvm::GlobalValue *GV, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
virtual llvm::GlobalValue::LinkageTypes getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
MangleContext & getMangleContext()
Gets the mangle context.
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
void 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 addBuffer(const HLSLBufferDecl *D)
llvm::Type * getSamplerType(const Type *T)
void emitDeferredTargetDecls() const
Emit deferred declare target variables marked for deferred emission.
virtual void emitDeclareTargetFunction(const FunctionDecl *FD, llvm::GlobalValue *GV)
Emit code for handling declare target functions in the runtime.
virtual ConstantAddress getAddrOfDeclareTargetVar(const VarDecl *VD)
Returns the address of the variable marked as declare target with link clause OR as declare target wi...
bool hasRequiresUnifiedSharedMemory() const
Return whether the unified_shared_memory has been specified.
virtual void emitDeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn)
Marks function Fn with properly mangled versions of vector functions.
virtual void registerTargetGlobalVariable(const VarDecl *VD, llvm::Constant *Addr)
Checks if the provided global decl GD is a declare target variable and registers it when emitting cod...
Class supports emissionof SIMD-only code.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
void EmitCfiCheckFail()
Emit a cross-DSO CFI failure handling function.
void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, ObjCMethodDecl *MD, bool ctor)
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
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()
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)
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
void setGVPropertiesAux(llvm::GlobalValue *GV, const NamedDecl *D) const
const ABIInfo & getABIInfo()
void EmitMainVoidAlias()
Emit an alias for "main" if it has no arguments (needed for wasm).
void DecorateInstructionWithInvariantGroup(llvm::Instruction *I, const CXXRecordDecl *RD)
Adds !invariant.barrier !tag to instruction.
DiagnosticsEngine & getDiags() const
bool isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, SourceLocation Loc) const
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
llvm::Constant * getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the constructor/destructor of the given type.
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
llvm::Constant * EmitAnnotateAttr(llvm::GlobalValue *GV, const AnnotateAttr *AA, SourceLocation L)
Generate the llvm::ConstantStruct which contains the annotation information for a given GlobalValue.
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 AppendLinkerOptions(StringRef Opts)
Appends Opts to the "llvm.linker.options" metadata value.
void EmitExternalDeclaration(const DeclaratorDecl *D)
void AddDependentLib(StringRef Lib)
Appends a dependent lib to the appropriate metadata value.
void Release()
Finalize LLVM code generation.
ProfileList::ExclusionType isFunctionBlockedByProfileList(llvm::Function *Fn, SourceLocation Loc) const
llvm::MDNode * getTBAABaseTypeInfo(QualType QTy)
getTBAABaseTypeInfo - Get metadata that describes the given base access type.
bool lookupRepresentativeDecl(StringRef MangledName, GlobalDecl &Result) const
void EmitOMPAllocateDecl(const OMPAllocateDecl *D)
Emit a code for the allocate directive.
void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const
Set the visibility for the given LLVM GlobalValue.
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD)
Returns LLVM linkage for a declarator.
bool HasHiddenLTOVisibility(const CXXRecordDecl *RD)
Returns whether the given record has hidden LTO visibility and therefore may participate in (single-m...
const llvm::DataLayout & getDataLayout() const
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can't be done.
TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType)
getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an access to a virtual table poi...
CGCXXABI & getCXXABI() const
ConstantAddress GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
llvm::Constant * GetFunctionStart(const ValueDecl *Decl)
static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V)
void EmitTentativeDefinition(const VarDecl *D)
void EmitDeferredUnusedCoverageMappings()
Emit all the deferred coverage mappings for the uninstrumented functions.
void addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, StringRef Category=StringRef()) const
Imbue XRay attributes to a function, applying the always/never attribute lists in the process.
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...
TBAAAccessInfo getTBAAAccessInfo(QualType AccessType)
getTBAAAccessInfo - Get TBAA information that describes an access to an object of the given type.
void setFunctionLinkage(GlobalDecl GD, llvm::Function *F)
llvm::Constant * GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition=NotForDefinition)
ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal)
Return a pointer to a constant CFString object for the given string.
ProfileList::ExclusionType isFunctionBlockedFromProfileInstr(llvm::Function *Fn, SourceLocation Loc) const
void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV)
Add global annotations that are set on D, for the global GV.
void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const
Set the TLS mode for the given LLVM GlobalValue for the thread-local variable declaration D.
ConstantAddress GetAddrOfConstantStringFromLiteral(const StringLiteral *S, StringRef Name=".str")
Return a pointer to a constant array for the given string literal.
ASTContext & getContext() const
ConstantAddress GetAddrOfTemplateParamObject(const TemplateParamObjectDecl *TPO)
Get the address of a template parameter object.
void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D)
Emit a code for threadprivate directive.
ConstantAddress GetAddrOfUnnamedGlobalConstantDecl(const UnnamedGlobalConstantDecl *GCD)
Get the address of a UnnamedGlobalConstant.
TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, TBAAAccessInfo TargetInfo)
mergeTBAAInfoForCast - Get merged TBAA information for the purposes of type casts.
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
llvm::SanitizerStatReport & getSanStats()
llvm::Constant * EmitAnnotationString(StringRef Str)
Emit an annotation string.
void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare mapper construct.
bool supportsCOMDAT() const
void RefreshTypeCacheForClass(const CXXRecordDecl *Class)
llvm::MDNode * getTBAATypeInfo(QualType QTy)
getTBAATypeInfo - Get metadata used to describe accesses to objects of the given type.
void EmitOMPRequiresDecl(const OMPRequiresDecl *D)
Emit a code for requires directive.
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD)
Tell the consumer that this variable has been instantiated.
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
llvm::Constant * GetConstantArrayFromStringLiteral(const StringLiteral *E)
Return a constant array for the given string.
void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV)
Set attributes which are common to any form of a global definition (alias, Objective-C method,...
std::optional< CharUnits > getOMPAllocateAlignment(const VarDecl *VD)
Return the alignment specified in an allocate directive, if present.
llvm::GlobalVariable * CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, llvm::Align Alignment)
Will return a global variable of the given type.
CharUnits getNaturalPointeeTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, TBAAAccessInfo InfoB)
mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the purposes of conditional ope...
llvm::LLVMContext & getLLVMContext()
llvm::GlobalValue * GetGlobalValue(StringRef Ref)
void GenKernelArgMetadata(llvm::Function *FN, const FunctionDecl *FD=nullptr, CodeGenFunction *CGF=nullptr)
OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument information in the program executab...
void 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.
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
llvm::Metadata * CreateMetadataIdentifierForVirtualMemPtrType(QualType T)
Create a metadata identifier that is intended to be used to check virtual calls via a member function...
ConstantAddress GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *)
Return a pointer to a constant array for the given ObjCEncodeExpr node.
const GlobalDecl getMangledNameDecl(StringRef)
void ClearUnusedCoverageMapping(const Decl *D)
Remove the deferred empty coverage mapping as this declaration is actually instrumented.
void EmitTopLevelDecl(Decl *D)
Emit code for a single top level declaration.
llvm::Constant * EmitAnnotationUnit(SourceLocation Loc)
Emit the annotation's translation unit.
ConstantAddress GetAddrOfConstantCString(const std::string &Str, const char *GlobalName=nullptr)
Returns a pointer to a character array containing the literal and a terminating '\0' character.
void printPostfixForExternalizedDecl(llvm::raw_ostream &OS, const Decl *D) const
Print the postfix for externalized static variable or kernels for single source offloading languages ...
void moveLazyEmissionStates(CodeGenModule *NewBuilder)
Move some lazily-emitted states to the NewBuilder.
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
void finalizeKCFITypes()
Emit KCFI type identifier constants and remove unused identifiers.
void setValueProfilingFlag(llvm::Module &M)
void setProfileVersion(llvm::Module &M)
void emitEmptyCounterMapping(const Decl *D, StringRef FuncName, llvm::GlobalValue::LinkageTypes Linkage)
Emit a coverage mapping range with a counter zero for an unused declaration.
CodeGenTBAA - This class organizes the cross-module state that is used while lowering AST types to LL...
This class organizes the cross-module state that is used while lowering AST types to LLVM types.
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
const CGFunctionInfo & arrangeCXXMethodDeclaration(const CXXMethodDecl *MD)
C++ methods have some special rules and also have implicit parameters.
const CGFunctionInfo & arrangeFreeFunctionType(CanQual< FunctionProtoType > Ty)
Arrange the argument and result information for a value of the given freestanding function type.
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
unsigned getTargetAddressSpace(QualType T) const
void RefreshTypeCacheForClass(const CXXRecordDecl *RD)
Remove stale types from the type cache when an inheritance model gets assigned to a class.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
void UpdateCompletedType(const TagDecl *TD)
UpdateCompletedType - When we find the full definition for a TagDecl, replace the 'opaque' type we pr...
const CGFunctionInfo & arrangeGlobalDeclaration(GlobalDecl GD)
void GenerateClassData(const CXXRecordDecl *RD)
GenerateClassData - Generate all the class data required to be generated upon definition of a KeyFunc...
void EmitThunks(GlobalDecl GD)
EmitThunks - Emit the associated thunks for the given global decl.
A specialization of Address that requires the address to be an LLVM Constant.
static ConstantAddress invalid()
llvm::Constant * tryEmitForInitializer(const VarDecl &D)
Try to emit the initiaizer of the given declaration as an abstract constant.
void finalize(llvm::GlobalVariable *global)
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded.
The standard implementation of ConstantInitBuilder used in Clang.
Organizes the cross-function state that is used while generating code coverage mapping data.
FunctionArgList - Type for representing both the decl and type of parameters to a function.
bool hasDiagnostics()
Whether or not the stats we've gathered indicate any potential problems.
void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile)
Report potential problems we've found to Diags.
TargetCodeGenInfo - This class organizes various target-specific codegeneration issues,...
virtual void getDependentLibraryOption(llvm::StringRef Lib, llvm::SmallString< 24 > &Opt) const
Gets the linker options necessary to link a dependent library on this platform.
Address performAddrSpaceCast(CodeGen::CodeGenFunction &CGF, Address Addr, LangAS SrcAddr, llvm::Type *DestTy, bool IsNonNull=false) const
const T & getABIInfo() const
virtual LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, const VarDecl *D) const
Get target favored AST address space of a global variable for languages other than OpenCL and CUDA.
virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const
setTargetAttributes - Provides a convenient hook to handle extra target-specific attributes for the g...
virtual LangAS getASTAllocaAddressSpace() const
Get the AST address space for alloca.
virtual void emitTargetMetadata(CodeGen::CodeGenModule &CGM, const llvm::MapVector< GlobalDecl, StringRef > &MangledDeclNames) const
emitTargetMetadata - Provides a convenient hook to handle extra target-specific metadata for the give...
virtual void emitTargetGlobals(CodeGen::CodeGenModule &CGM) const
Provides a convenient hook to handle extra target-specific globals.
virtual void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, llvm::SmallString< 32 > &Opt) const
Gets the linker options necessary to detect object file mismatches on this platform.
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Represents the canonical version of C arrays with a specified constant size.
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Stores additional source code information like skipped ranges which is required by the coverage mappi...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
A reference to a declared variable, function, enum, etc.
Decl - This represents one declaration (or definition), e.g.
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
SourceLocation getEndLoc() const LLVM_READONLY
ASTContext & getASTContext() const LLVM_READONLY
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
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.
const Attr * getDefiningAttr() const
Return this declaration's defining attribute if it has one.
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
SourceLocation getLocation() const
SourceLocation getBeginLoc() const LLVM_READONLY
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Represents a ValueDecl that came out of a declarator.
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
This represents one expression.
Represents a member of a struct/union/class.
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
StringRef getName() const
The name of this FileEntry.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Represents a function declaration or definition.
bool isTargetClonesMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target-clones functional...
bool isMultiVersion() const
True if this function is considered a multiversioned function.
const ParmVarDecl * getParamDecl(unsigned i) const
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
bool isImmediateFunction() const
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
bool 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 * getDefinition()
Get the definition for this declaration.
bool isTargetVersionMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target-version functiona...
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
bool doesDeclarationForceExternallyVisibleDefinition() const
For a function declaration in C or C++, determine whether this declaration causes the definition to b...
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const override
Appends a human-readable name for this declaration into the given stream.
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Represents a prototype with parameter type info, e.g.
FunctionType - C99 6.7.5.3 - Function Declarators.
CallingConv getCallConv() const
GlobalDecl - represents a global declaration.
GlobalDecl getWithMultiVersionIndex(unsigned Index)
CXXCtorType getCtorType() const
GlobalDecl getWithKernelReferenceKind(KernelReferenceKind Kind)
GlobalDecl getCanonicalDecl() const
KernelReferenceKind getKernelReferenceKind() const
GlobalDecl getWithDecl(const Decl *D)
unsigned getMultiVersionIndex() const
CXXDtorType getDtorType() const
const Decl * getDecl() const
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
@ None
No signing for any function.
@ Swift5_0
Interoperability with the Swift 5.0 runtime.
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
VisibilityFromDLLStorageClassKinds
@ Keep
Keep the IR-gen assigned visibility.
@ Protected
Override the IR-gen assigned visibility with protected visibility.
@ Default
Override the IR-gen assigned visibility with default visibility.
@ Hidden
Override the IR-gen assigned visibility with hidden visibility.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
bool isSignReturnAddressWithAKey() const
Check if return address signing uses AKey.
clang::ObjCRuntime ObjCRuntime
CoreFoundationABI CFRuntime
SanitizerSet Sanitize
Set of enabled sanitizers.
bool hasSignReturnAddress() const
Check if return address signing is enabled.
std::string OMPHostIRFile
Name of the IR file that contains the result of the OpenMP target host code generation.
std::map< std::string, std::string, std::greater< std::string > > MacroPrefixMap
A prefix map for FILE, BASE_FILE and __builtin_FILE().
LangStandard::Kind LangStd
The used language standard.
bool isSignReturnAddressScopeAll() const
Check if leaf functions are also signed.
std::string CUID
The user provided compilation unit ID, if non-empty.
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Visibility getVisibility() const
void setLinkage(Linkage L)
Linkage getLinkage() const
bool isVisibilityExplicit() const
Represents a linkage specification.
LinkageSpecLanguageIDs getLanguage() const
Return the language specified by this linkage specification.
Parts getParts() const
Get the decomposed parts of this declaration.
APValue & getAsAPValue() const
Get the value of this MSGuidDecl as an APValue.
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
void mangleBlock(const DeclContext *DC, const BlockDecl *BD, raw_ostream &Out)
void mangleCtorBlock(const CXXConstructorDecl *CD, CXXCtorType CT, const BlockDecl *BD, raw_ostream &Out)
void mangleGlobalBlock(const BlockDecl *BD, const NamedDecl *ID, raw_ostream &Out)
bool shouldMangleDeclName(const NamedDecl *D)
void mangleName(GlobalDecl GD, raw_ostream &)
virtual void mangleCanonicalTypeName(QualType T, raw_ostream &, bool NormalizeIntegers=false)=0
Generates a unique string for an externally visible type for use with TBAA or type uniquing.
virtual void mangleStringLiteral(const StringLiteral *SL, raw_ostream &)=0
ManglerKind getKind() const
virtual void needsUniqueInternalLinkageNames()
virtual void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber, raw_ostream &)=0
void mangleDtorBlock(const CXXDestructorDecl *CD, CXXDtorType DT, const BlockDecl *BD, raw_ostream &Out)
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Describes a module or submodule.
bool isInterfaceOrPartition() const
bool isNamedModuleUnit() const
Is this a C++20 named module unit.
Module * Parent
The parent of this module.
Module * getPrivateModuleFragment() const
Get the Private Module Fragment (sub-module) for this module, it there is one.
llvm::SmallSetVector< Module *, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Module * getGlobalModuleFragment() const
Get the Global Module Fragment (sub-module) for this module, it there is one.
llvm::iterator_range< submodule_iterator > submodules()
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used.
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
bool UseExportAsModuleLinkName
Autolinking uses the framework name for linking purposes when this is false and the export_as name ot...
This represents a decl that may have a name.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
LinkageInfo getLinkageAndVisibility() const
Determines the linkage and visibility of this entity.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Represent a C++ namespace.
This represents '#pragma omp threadprivate ...' directive.
ObjCEncodeExpr, used for @encode in Objective-C.
const ObjCInterfaceDecl * getClassInterface() const
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Represents an ObjC class declaration.
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
ObjCIvarDecl - Represents an ObjC instance variable.
ObjCIvarDecl * getNextIvar()
ObjCMethodDecl - Represents an instance or class method declaration.
static ObjCMethodDecl * Create(ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc, Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo, DeclContext *contextDecl, bool isInstance=true, bool isVariadic=false, bool isPropertyAccessor=false, bool isSynthesizedAccessorStub=false, bool isImplicitlyDeclared=false, bool isDefined=false, ObjCImplementationControl impControl=ObjCImplementationControl::None, bool HasRelatedResultType=false)
Represents one property declaration in an Objective-C interface.
ObjCMethodDecl * getGetterMethodDecl() const
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
The basic abstraction for the target Objective-C runtime.
bool hasUnwindExceptions() const
Does this runtime use zero-cost exceptions?
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
@ MacOSX
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
@ FragileMacOSX
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
@ GNUstep
'gnustep' is the modern non-fragile GNUstep runtime.
@ ObjFW
'objfw' is the Objective-C runtime included in ObjFW
@ iOS
'ios' is the Apple-provided NeXT-derived runtime on iOS or the iOS simulator; it is always non-fragil...
@ GCC
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI
@ WatchOS
'watchos' is a variant of iOS for Apple's watchOS.
Represents a parameter to a function.
ParsedAttr - Represents a syntactic attribute.
bool isAddressDiscriminated() const
uint16_t getConstantDiscrimination() const
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::optional< uint64_t > SourceDateEpoch
If set, the UNIX timestamp specified by SOURCE_DATE_EPOCH.
std::vector< std::pair< std::string, bool > > Macros
Represents an unpacked "presumed" location which can be presented to the user.
const char * getFilename() const
Return the presumed filename of this location.
unsigned getLine() const
Return the presumed line number of this location.
PrettyStackTraceDecl - If a crash occurs, indicate that it happened when doing something to a specifi...
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.
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.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Selector getSelector(unsigned NumArgs, const IdentifierInfo **IIV)
Can create any sort of selector.
Smart pointer class that efficiently represents Objective-C method names.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Stmt - This represents one statement.
StringLiteral - This represents a string literal expression, e.g.
Represents the declaration of a struct/union/class/enum.
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Exposes information about the current target.
TargetOptions & getTargetOpts() const
Retrieve the target options.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
bool isReadOnlyFeature(StringRef Feature) const
Determine whether the given target feature is read only.
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
virtual llvm::APInt getFMVPriority(ArrayRef< StringRef > Features) const
bool supportsIFunc() const
Identify whether this target supports IFuncs.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
std::string TuneCPU
If given, the name of the target CPU to tune code for.
std::string CPU
If given, the name of the target CPU to generate code for.
@ Hostcall
printf lowering scheme involving hostcalls, currently used by HIP programs by default
A template parameter object.
const APValue & getValue() const
A declaration that models statements at global scope.
The top declaration context.
static DeclContext * castToDeclContext(const TranslationUnitDecl *D)
The base class of the type hierarchy.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
bool isPointerType() const
const T * castAs() const
Member-template castAs<specific type>.
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
bool isObjCObjectPointerType() const
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Linkage getLinkage() const
Determine the linkage of this type.
const T * getAs() const
Member-template getAs<specific type>'.
bool isRecordType() const
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
const APValue & getValue() const
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Represents a variable declaration or definition.
TLSKind getTLSKind() const
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
bool hasFlexibleArrayInit(const ASTContext &Ctx) const
Whether this variable has a flexible array member initialized with one or more elements.
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
@ TLS_Dynamic
TLS with a dynamic initializer.
@ DeclarationOnly
This declaration is only a declaration.
@ Definition
This declaration is definitely a definition.
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Defines the clang::TargetInfo interface.
std::unique_ptr< TargetCodeGenInfo > createARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind Kind)
std::unique_ptr< TargetCodeGenInfo > createM68kTargetCodeGenInfo(CodeGenModule &CGM)
@ AttributedType
The l-value was considered opaque, so the alignment was determined from a type, but that type was an ...
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
std::unique_ptr< TargetCodeGenInfo > createBPFTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createMSP430TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel)
std::unique_ptr< TargetCodeGenInfo > createWebAssemblyTargetCodeGenInfo(CodeGenModule &CGM, WebAssemblyABIKind K)
std::unique_ptr< TargetCodeGenInfo > createPPC64_SVR4_TargetCodeGenInfo(CodeGenModule &CGM, PPC64_SVR4_ABIKind Kind, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createMIPSTargetCodeGenInfo(CodeGenModule &CGM, bool IsOS32)
std::unique_ptr< TargetCodeGenInfo > createHexagonTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createNVPTXTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createSystemZTargetCodeGenInfo(CodeGenModule &CGM, bool HasVector, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createWinX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters)
std::unique_ptr< TargetCodeGenInfo > createAIXTargetCodeGenInfo(CodeGenModule &CGM, bool Is64Bit)
std::unique_ptr< TargetCodeGenInfo > createAMDGPUTargetCodeGenInfo(CodeGenModule &CGM)
CGObjCRuntime * CreateMacObjCRuntime(CodeGenModule &CGM)
X86AVXABILevel
The AVX ABI level for X86 targets.
std::unique_ptr< TargetCodeGenInfo > createTCETargetCodeGenInfo(CodeGenModule &CGM)
CGObjCRuntime * CreateGNUObjCRuntime(CodeGenModule &CGM)
Creates an instance of an Objective-C runtime class.
std::unique_ptr< TargetCodeGenInfo > createWindowsARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind K)
std::unique_ptr< TargetCodeGenInfo > createAVRTargetCodeGenInfo(CodeGenModule &CGM, unsigned NPR, unsigned NRR)
std::unique_ptr< TargetCodeGenInfo > createDirectXTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createARCTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createDefaultTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind Kind)
std::unique_ptr< TargetCodeGenInfo > createSPIRVTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createWindowsMIPSTargetCodeGenInfo(CodeGenModule &CGM, bool IsOS32)
std::unique_ptr< TargetCodeGenInfo > createSparcV8TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createVETargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createCommonSPIRTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createRISCVTargetCodeGenInfo(CodeGenModule &CGM, unsigned XLen, unsigned FLen, bool EABI)
std::unique_ptr< TargetCodeGenInfo > createWindowsAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind K)
std::unique_ptr< TargetCodeGenInfo > createSparcV9TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createLanaiTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createPPC32TargetCodeGenInfo(CodeGenModule &CGM, bool SoftFloatABI)
CGCUDARuntime * CreateNVCUDARuntime(CodeGenModule &CGM)
Creates an instance of a CUDA runtime class.
std::unique_ptr< TargetCodeGenInfo > createLoongArchTargetCodeGenInfo(CodeGenModule &CGM, unsigned GRLen, unsigned FLen)
std::unique_ptr< TargetCodeGenInfo > createPPC64TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createWinX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel)
std::unique_ptr< TargetCodeGenInfo > createXCoreTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createCSKYTargetCodeGenInfo(CodeGenModule &CGM, unsigned FLen)
llvm::PointerUnion< const Decl *, const Expr * > DeclTy
The JSON file list parser is used to communicate input to InstallAPI.
CXXCtorType
C++ constructor types.
@ Ctor_Base
Base object ctor.
@ Ctor_Complete
Complete object ctor.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, DiagnosticsEngine &Diags)
GVALinkage
A more specific kind of linkage than enum Linkage.
@ GVA_AvailableExternally
std::string getClangVendor()
Retrieves the Clang vendor tag.
@ ICIS_NoInit
No in-class initializer.
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ Asm
Assembly: we accept this only so that we can preprocess it.
@ SD_Thread
Thread storage duration.
@ SD_Static
Static storage duration.
bool isLambdaCallOperator(const CXXMethodDecl *MD)
@ Result
The result type of a method or function.
StringRef languageToString(Language L)
@ Dtor_Base
Base object dtor.
@ Dtor_Complete
Complete object dtor.
LangAS
Defines the address space values used by the address space qualifier of QualType.
@ FirstTargetAddressSpace
static const char * getCFBranchLabelSchemeFlagVal(const CFBranchLabelSchemeKind Scheme)
const FunctionProtoType * T
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
@ 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::IntegerType * Int64Ty
llvm::PointerType * ConstGlobalsPtrTy
void* in the address space for constant globals
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::IntegerType * CharTy
char
LangAS ASTAllocaAddressSpace
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
unsigned char IntAlignInBytes
llvm::Type * HalfTy
half, bfloat, float, double
unsigned char SizeSizeInBytes
llvm::CallingConv::ID getRuntimeCC() const
llvm::IntegerType * SizeTy
llvm::PointerType * GlobalsInt8PtrTy
llvm::IntegerType * Int32Ty
llvm::IntegerType * IntPtrTy
llvm::IntegerType * IntTy
int
llvm::IntegerType * Int16Ty
unsigned char PointerAlignInBytes
llvm::PointerType * Int8PtrTy
CharUnits getPointerAlign() const
llvm::PointerType * AllocaInt8PtrTy
EvalResult is a struct with detailed info about an evaluated expression.
APValue Val
Val - This is the value the expression can be folded to.
bool hasSideEffects() const
Extra information about a function prototype.
static const LangStandard & getLangStandardForKind(Kind K)
Parts of a decomposed MSGuidDecl.
uint16_t Part2
...-89ab-...
uint32_t Part1
{01234567-...
uint16_t Part3
...-cdef-...
uint8_t Part4And5[8]
...-0123-456789abcdef}
A library or framework to link against when an entity from this module is used.
Contains information gathered from parsing the contents of TargetAttr.
PointerAuthSchema InitFiniPointers
The ABI for function addresses in .init_array and .fini_array.
Describes how types, statements, expressions, and declarations should be printed.
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
bool hasOneOf(SanitizerMask K) const
Check if one or more sanitizers are enabled.