52#include "llvm/ABI/IRTypeMapper.h"
53#include "llvm/ABI/TargetInfo.h"
54#include "llvm/ADT/STLExtras.h"
55#include "llvm/ADT/StringExtras.h"
56#include "llvm/ADT/StringSwitch.h"
57#include "llvm/Analysis/TargetLibraryInfo.h"
58#include "llvm/BinaryFormat/ELF.h"
59#include "llvm/IR/AttributeMask.h"
60#include "llvm/IR/CallingConv.h"
61#include "llvm/IR/DataLayout.h"
62#include "llvm/IR/Intrinsics.h"
63#include "llvm/IR/LLVMContext.h"
64#include "llvm/IR/Module.h"
65#include "llvm/IR/ProfileSummary.h"
66#include "llvm/ProfileData/InstrProfReader.h"
67#include "llvm/ProfileData/SampleProf.h"
68#include "llvm/Support/ARMBuildAttributes.h"
69#include "llvm/Support/CRC.h"
70#include "llvm/Support/CodeGen.h"
71#include "llvm/Support/CommandLine.h"
72#include "llvm/Support/ConvertUTF.h"
73#include "llvm/Support/ErrorHandling.h"
74#include "llvm/Support/TimeProfiler.h"
75#include "llvm/TargetParser/AArch64TargetParser.h"
76#include "llvm/TargetParser/RISCVISAInfo.h"
77#include "llvm/TargetParser/Triple.h"
78#include "llvm/TargetParser/X86TargetParser.h"
79#include "llvm/Transforms/Instrumentation/KCFI.h"
80#include "llvm/Transforms/Utils/BuildLibCalls.h"
81#include "llvm/Transforms/Utils/KCFIHash.h"
82#include "llvm/Transforms/Utils/ModuleUtils.h"
90 "limited-coverage-experimental", llvm::cl::Hidden,
91 llvm::cl::desc(
"Emit limited coverage mapping information (experimental)"));
98 case TargetCXXABI::AppleARM64:
99 case TargetCXXABI::Fuchsia:
100 case TargetCXXABI::GenericAArch64:
101 case TargetCXXABI::GenericARM:
102 case TargetCXXABI::iOS:
103 case TargetCXXABI::WatchOS:
104 case TargetCXXABI::GenericMIPS:
105 case TargetCXXABI::GenericItanium:
106 case TargetCXXABI::WebAssembly:
107 case TargetCXXABI::XL:
109 case TargetCXXABI::Microsoft:
113 llvm_unreachable(
"invalid C++ ABI kind");
116static std::unique_ptr<TargetCodeGenInfo>
119 const llvm::Triple &Triple =
Target.getTriple();
122 switch (Triple.getArch()) {
126 case llvm::Triple::m68k:
128 case llvm::Triple::mips:
129 case llvm::Triple::mipsel:
130 if (Triple.getOS() == llvm::Triple::Win32)
134 case llvm::Triple::mips64:
135 case llvm::Triple::mips64el:
138 case llvm::Triple::avr: {
142 unsigned NPR =
Target.getABI() ==
"avrtiny" ? 6 : 18;
143 unsigned NRR =
Target.getABI() ==
"avrtiny" ? 4 : 8;
147 case llvm::Triple::aarch64:
148 case llvm::Triple::aarch64_32:
149 case llvm::Triple::aarch64_be: {
151 if (
Target.getABI() ==
"darwinpcs")
152 Kind = AArch64ABIKind::DarwinPCS;
153 else if (Triple.isOSWindows())
155 else if (
Target.getABI() ==
"aapcs-soft")
156 Kind = AArch64ABIKind::AAPCSSoft;
161 case llvm::Triple::wasm32:
162 case llvm::Triple::wasm64: {
164 if (
Target.getABI() ==
"experimental-mv")
165 Kind = WebAssemblyABIKind::ExperimentalMV;
169 case llvm::Triple::arm:
170 case llvm::Triple::armeb:
171 case llvm::Triple::thumb:
172 case llvm::Triple::thumbeb: {
173 if (Triple.getOS() == llvm::Triple::Win32)
177 StringRef ABIStr =
Target.getABI();
178 if (ABIStr ==
"apcs-gnu")
179 Kind = ARMABIKind::APCS;
180 else if (ABIStr ==
"aapcs16")
181 Kind = ARMABIKind::AAPCS16_VFP;
182 else if (CodeGenOpts.
FloatABI ==
"hard" ||
183 (CodeGenOpts.
FloatABI !=
"soft" && Triple.isHardFloatABI()))
184 Kind = ARMABIKind::AAPCS_VFP;
189 case llvm::Triple::ppc: {
190 if (Triple.isOSAIX())
197 case llvm::Triple::ppcle: {
202 case llvm::Triple::ppc64:
203 if (Triple.isOSAIX())
206 if (Triple.isOSBinFormatELF()) {
208 if (
Target.getABI() ==
"elfv2")
209 Kind = PPC64_SVR4_ABIKind::ELFv2;
210 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
215 case llvm::Triple::ppc64le: {
216 assert(Triple.isOSBinFormatELF() &&
"PPC64 LE non-ELF not supported!");
218 if (
Target.getABI() ==
"elfv1")
219 Kind = PPC64_SVR4_ABIKind::ELFv1;
220 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
225 case llvm::Triple::nvptx:
226 case llvm::Triple::nvptx64:
229 case llvm::Triple::msp430:
232 case llvm::Triple::riscv32:
233 case llvm::Triple::riscv64:
234 case llvm::Triple::riscv32be:
235 case llvm::Triple::riscv64be: {
236 StringRef ABIStr =
Target.getABI();
238 unsigned ABIFLen = 0;
239 if (ABIStr.ends_with(
"f"))
241 else if (ABIStr.ends_with(
"d"))
243 bool EABI = ABIStr.ends_with(
"e");
247 case llvm::Triple::systemz: {
248 bool SoftFloat = CodeGenOpts.
FloatABI ==
"soft";
249 bool HasVector = !SoftFloat &&
Target.getABI() ==
"vector";
250 if (Triple.getOS() == llvm::Triple::ZOS)
255 case llvm::Triple::tce:
256 case llvm::Triple::tcele:
257 case llvm::Triple::tcele64:
260 case llvm::Triple::x86: {
261 bool IsDarwinVectorABI = Triple.isOSDarwin();
262 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
264 if (Triple.getOS() == llvm::Triple::Win32) {
266 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
267 CodeGenOpts.NumRegisterParameters);
270 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
271 CodeGenOpts.NumRegisterParameters, CodeGenOpts.
FloatABI ==
"soft");
274 case llvm::Triple::x86_64: {
275 StringRef ABI =
Target.getABI();
276 X86AVXABILevel AVXLevel = (ABI ==
"avx512" ? X86AVXABILevel::AVX512
277 : ABI ==
"avx" ? X86AVXABILevel::AVX
278 : X86AVXABILevel::None);
280 switch (Triple.getOS()) {
281 case llvm::Triple::UEFI:
282 case llvm::Triple::Win32:
288 case llvm::Triple::hexagon:
290 case llvm::Triple::lanai:
292 case llvm::Triple::r600:
294 case llvm::Triple::amdgcn:
296 case llvm::Triple::sparc:
298 case llvm::Triple::sparcv9:
300 case llvm::Triple::xcore:
302 case llvm::Triple::arc:
304 case llvm::Triple::spir:
305 case llvm::Triple::spir64:
307 case llvm::Triple::spirv32:
308 case llvm::Triple::spirv64:
309 case llvm::Triple::spirv:
311 case llvm::Triple::dxil:
313 case llvm::Triple::ve:
315 case llvm::Triple::csky: {
316 bool IsSoftFloat = !
Target.hasFeature(
"hard-float-abi");
318 Target.hasFeature(
"fpuv2_df") ||
Target.hasFeature(
"fpuv3_df");
323 case llvm::Triple::bpfeb:
324 case llvm::Triple::bpfel:
326 case llvm::Triple::loongarch32:
327 case llvm::Triple::loongarch64: {
328 StringRef ABIStr =
Target.getABI();
329 unsigned ABIFRLen = 0;
330 if (ABIStr.ends_with(
"f"))
332 else if (ABIStr.ends_with(
"d"))
341 if (!TheTargetCodeGenInfo)
343 return *TheTargetCodeGenInfo;
347 if (!CodeGenOpts.ExperimentalABILowering)
354const llvm::abi::TargetInfo &
356 if (TheLLVMABITargetInfo)
357 return *TheLLVMABITargetInfo;
360 "LLVMABI lowering requested for an unsupported target");
361 TheLLVMABITargetInfo = llvm::abi::createBPFTargetInfo(TB);
362 return *TheLLVMABITargetInfo;
366 llvm::LLVMContext &Context,
370 if (Opts.AlignDouble || Opts.OpenCL)
373 llvm::Triple Triple =
Target.getTriple();
374 llvm::DataLayout DL(
Target.getDataLayoutString());
375 auto Check = [&](
const char *Name, llvm::Type *Ty,
unsigned Alignment) {
376 llvm::Align DLAlign = DL.getABITypeAlign(Ty);
377 llvm::Align ClangAlign(Alignment / 8);
378 if (DLAlign != ClangAlign) {
379 llvm::errs() <<
"For target " << Triple.str() <<
" type " << Name
380 <<
" mapping to " << *Ty <<
" has data layout alignment "
381 << DLAlign.value() <<
" while clang specifies "
382 << ClangAlign.value() <<
"\n";
387 Check(
"bool", llvm::Type::getIntNTy(Context,
Target.BoolWidth),
389 Check(
"short", llvm::Type::getIntNTy(Context,
Target.ShortWidth),
391 Check(
"int", llvm::Type::getIntNTy(Context,
Target.IntWidth),
393 Check(
"long", llvm::Type::getIntNTy(Context,
Target.LongWidth),
396 if (Triple.getArch() != llvm::Triple::m68k)
397 Check(
"long long", llvm::Type::getIntNTy(Context,
Target.LongLongWidth),
400 if (
Target.hasInt128Type() && !
Target.getTargetOpts().ForceEnableInt128 &&
401 !Triple.isAMDGPU() && !Triple.isSPIRV() &&
402 Triple.getArch() != llvm::Triple::ve)
403 Check(
"__int128", llvm::Type::getIntNTy(Context, 128),
Target.Int128Align);
405 if (
Target.hasFloat16Type())
406 Check(
"half", llvm::Type::getFloatingPointTy(Context, *
Target.HalfFormat),
408 if (
Target.hasBFloat16Type())
409 Check(
"bfloat", llvm::Type::getBFloatTy(Context),
Target.BFloat16Align);
410 Check(
"float", llvm::Type::getFloatingPointTy(Context, *
Target.FloatFormat),
412 Check(
"double", llvm::Type::getFloatingPointTy(Context, *
Target.DoubleFormat),
415 llvm::Type::getFloatingPointTy(Context, *
Target.LongDoubleFormat),
417 if (
Target.hasFloat128Type())
418 Check(
"__float128", llvm::Type::getFP128Ty(Context),
Target.Float128Align);
419 if (
Target.hasIbm128Type())
420 Check(
"__ibm128", llvm::Type::getPPC_FP128Ty(Context),
Target.Ibm128Align);
422 Check(
"void*", llvm::PointerType::getUnqual(Context),
Target.PointerAlign);
424 if (
Target.vectorsAreElementAligned() != DL.vectorsAreElementAligned()) {
425 llvm::errs() <<
"Datalayout for target " << Triple.str()
426 <<
" sets element-aligned vectors to '"
427 <<
Target.vectorsAreElementAligned()
428 <<
"' but clang specifies '" << DL.vectorsAreElementAligned()
442 : Context(
C), LangOpts(
C.
getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
443 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
445 VMContext(M.
getContext()), VTables(*this), StackHandler(diags),
449 AbiMapper = std::make_unique<QualTypeMapper>(
C, M.getDataLayout(), AbiAlloc);
450 AbiReverseMapper = std::make_unique<llvm::abi::IRTypeMapper>(
451 M.getContext(), M.getDataLayout());
455 llvm::LLVMContext &LLVMContext = M.getContext();
456 VoidTy = llvm::Type::getVoidTy(LLVMContext);
457 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
458 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
459 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
460 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
461 HalfTy = llvm::Type::getHalfTy(LLVMContext);
462 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
463 FloatTy = llvm::Type::getFloatTy(LLVMContext);
464 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
470 C.toCharUnitsFromBits(
C.getTargetInfo().getMaxPointerWidth()).getQuantity();
472 C.toCharUnitsFromBits(
C.getTargetInfo().getIntAlign()).getQuantity();
474 llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getCharWidth());
475 IntTy = llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getIntWidth());
476 IntPtrTy = llvm::IntegerType::get(LLVMContext,
477 C.getTargetInfo().getMaxPointerWidth());
478 Int8PtrTy = llvm::PointerType::get(LLVMContext,
480 const llvm::DataLayout &DL = M.getDataLayout();
482 llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
484 llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
486 llvm::PointerType::get(LLVMContext, DL.getProgramAddressSpace());
502 createOpenCLRuntime();
504 createOpenMPRuntime();
511 if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Thread | SanitizerKind::Type) ||
512 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
518 if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
519 CodeGenOpts.CoverageNotesFile.size() ||
520 CodeGenOpts.CoverageDataFile.size())
528 Block.GlobalUniqueCount = 0;
530 if (
C.getLangOpts().ObjC)
533 if (CodeGenOpts.hasProfileClangUse()) {
534 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
535 CodeGenOpts.ProfileInstrumentUsePath, *FS,
536 CodeGenOpts.ProfileRemappingFile);
537 if (
auto E = ReaderOrErr.takeError()) {
538 llvm::handleAllErrors(std::move(E), [&](
const llvm::ErrorInfoBase &EI) {
539 Diags.Report(diag::err_reading_profile)
540 << CodeGenOpts.ProfileInstrumentUsePath << EI.message();
544 PGOReader = std::move(ReaderOrErr.get());
549 if (CodeGenOpts.CoverageMapping)
553 if (CodeGenOpts.UniqueInternalLinkageNames &&
554 !
getModule().getSourceFileName().empty()) {
558 Context.getTargetInfo());
559 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path);
563 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
564 getModule().addModuleFlag(llvm::Module::Error,
"NumRegisterParameters",
565 CodeGenOpts.NumRegisterParameters);
574 const llvm::MemoryBuffer &FileBuffer = **BufOrErr;
575 for (llvm::line_iterator I(FileBuffer.getMemBufferRef(),
true), E;
577 this->MSHotPatchFunctions.push_back(std::string{*I});
579 auto &DE = Context.getDiagnostics();
580 DE.Report(diag::err_open_hotpatch_file_failed)
582 << BufOrErr.getError().message();
587 this->MSHotPatchFunctions.push_back(FuncName);
589 llvm::sort(this->MSHotPatchFunctions);
592 if (!Context.getAuxTargetInfo())
598void CodeGenModule::createObjCRuntime() {
615 llvm_unreachable(
"bad runtime kind");
618void CodeGenModule::createOpenCLRuntime() {
622void CodeGenModule::createOpenMPRuntime() {
623 if (!LangOpts.OMPHostIRFile.empty() && !FS->exists(LangOpts.OMPHostIRFile))
624 Diags.Report(diag::err_omp_host_ir_file_not_found)
625 << LangOpts.OMPHostIRFile;
630 case llvm::Triple::nvptx:
631 case llvm::Triple::nvptx64:
632 case llvm::Triple::amdgcn:
633 case llvm::Triple::spirv64:
636 "OpenMP AMDGPU/NVPTX/SPIRV is only prepared to deal with device code.");
637 OpenMPRuntime.reset(
new CGOpenMPRuntimeGPU(*
this));
640 if (LangOpts.OpenMPSimd)
641 OpenMPRuntime.reset(
new CGOpenMPSIMDRuntime(*
this));
643 OpenMPRuntime.reset(
new CGOpenMPRuntime(*
this));
648void CodeGenModule::createCUDARuntime() {
652void CodeGenModule::createHLSLRuntime() {
653 HLSLRuntime.reset(
new CGHLSLRuntime(*
this));
657 Replacements[Name] =
C;
660void CodeGenModule::applyReplacements() {
661 for (
auto &I : Replacements) {
662 StringRef MangledName = I.first;
663 llvm::Constant *Replacement = I.second;
668 auto *NewF = dyn_cast<llvm::Function>(Replacement);
670 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
671 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
674 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
675 CE->getOpcode() == llvm::Instruction::GetElementPtr);
676 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
681 OldF->replaceAllUsesWith(Replacement);
683 NewF->removeFromParent();
684 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
687 OldF->eraseFromParent();
692 GlobalValReplacements.push_back(std::make_pair(GV,
C));
695void CodeGenModule::applyGlobalValReplacements() {
696 for (
auto &I : GlobalValReplacements) {
697 llvm::GlobalValue *GV = I.first;
698 llvm::Constant *
C = I.second;
700 GV->replaceAllUsesWith(
C);
701 GV->eraseFromParent();
708 const llvm::Constant *
C;
709 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
710 C = GA->getAliasee();
711 else if (
auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
712 C = GI->getResolver();
716 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(
C->stripPointerCasts());
720 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
729 bool IsIFunc,
const llvm::GlobalValue *Alias,
const llvm::GlobalValue *&GV,
730 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
734 Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
738 if (GV->hasCommonLinkage()) {
739 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
740 if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
741 Diags.
Report(Location, diag::err_alias_to_common);
746 if (GV->isDeclaration()) {
747 Diags.
Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
748 Diags.
Report(Location, diag::note_alias_requires_mangled_name)
749 << IsIFunc << IsIFunc;
752 for (
const auto &[
Decl, Name] : MangledDeclNames) {
753 if (
const auto *ND = dyn_cast<NamedDecl>(
Decl.getDecl())) {
755 if (II && II->
getName() == GV->getName()) {
756 Diags.
Report(Location, diag::note_alias_mangled_name_alternative)
760 (Twine(IsIFunc ?
"ifunc" :
"alias") +
"(\"" + Name +
"\")")
770 const auto *F = dyn_cast<llvm::Function>(GV);
772 Diags.
Report(Location, diag::err_alias_to_undefined)
773 << IsIFunc << IsIFunc;
777 llvm::FunctionType *FTy = F->getFunctionType();
778 if (!FTy->getReturnType()->isPointerTy()) {
779 Diags.
Report(Location, diag::err_ifunc_resolver_return);
793 if (GVar->hasAttribute(
"toc-data")) {
794 auto GVId = GVar->getName();
797 Diags.
Report(Location, diag::warn_toc_unsupported_type)
798 << GVId <<
"the variable has an alias";
800 llvm::AttributeSet CurrAttributes = GVar->getAttributes();
801 llvm::AttributeSet NewAttributes =
802 CurrAttributes.removeAttribute(GVar->getContext(),
"toc-data");
803 GVar->setAttributes(NewAttributes);
807void CodeGenModule::checkAliases() {
812 DiagnosticsEngine &Diags =
getDiags();
813 for (
const GlobalDecl &GD : Aliases) {
815 SourceLocation Location;
817 bool IsIFunc = D->hasAttr<IFuncAttr>();
818 if (
const Attr *A = D->getDefiningAttr()) {
819 Location = A->getLocation();
820 Range = A->getRange();
822 llvm_unreachable(
"Not an alias or ifunc?");
826 const llvm::GlobalValue *GV =
nullptr;
828 MangledDeclNames, Range)) {
834 GlobalDecl AliaseeGD;
837 Diags.Report(Location, diag::err_alias_to_undefined)
838 << IsIFunc << IsIFunc;
847 if (AliasIsFuncDecl != AliaseeIsFunc) {
848 Diags.Report(Location, diag::err_alias_between_function_and_variable)
851 diag::note_aliasee_declaration);
858 if (AliasIsFuncDecl && AliaseeIsFunc) {
859 QualType AliasTy = D->getType();
861 auto shouldReportTypeMismatch = [&]() {
862 const auto *AliasFTy =
864 const auto *AliaseeFTy =
866 assert(AliasFTy && AliaseeFTy);
867 if (!Context.typesAreCompatible(AliasFTy->getReturnType(),
870 const auto *AliasFPTy = dyn_cast<FunctionProtoType>(AliasFTy);
871 const auto *AliaseeFPTy = dyn_cast<FunctionProtoType>(AliaseeFTy);
873 if ((AliasFPTy && AliasFPTy->isVariadic() && !AliaseeFPTy) ||
874 (AliaseeFPTy && AliaseeFPTy->isVariadic() && !AliasFPTy))
877 if (!AliasFPTy || !AliaseeFPTy)
881 if (AliasFPTy->getNumParams() != AliaseeFPTy->getNumParams() ||
882 AliasFPTy->isVariadic() != AliaseeFPTy->isVariadic())
884 for (
unsigned i = 0; i < AliasFPTy->getNumParams(); ++i)
885 if (!Context.typesAreCompatible(AliasFPTy->getParamType(i),
886 AliaseeFPTy->getParamType(i)))
890 if (shouldReportTypeMismatch()) {
891 Diags.Report(Location, diag::warn_alias_type_mismatch)
892 << AliasTy << AliaseeTy;
894 diag::note_aliasee_declaration);
900 if (
const llvm::GlobalVariable *GVar =
901 dyn_cast<const llvm::GlobalVariable>(GV))
905 llvm::Constant *Aliasee =
909 llvm::GlobalValue *AliaseeGV;
910 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
915 if (
const SectionAttr *SA = D->getAttr<SectionAttr>()) {
916 StringRef AliasSection = SA->getName();
917 if (AliasSection != AliaseeGV->getSection())
918 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
919 << AliasSection << IsIFunc << IsIFunc;
927 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
928 if (GA->isInterposable()) {
929 Diags.Report(Location, diag::warn_alias_to_weak_alias)
930 << GV->getName() << GA->getName() << IsIFunc;
931 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
932 GA->getAliasee(), Alias->getType());
944 llvm::Attribute::DisableSanitizerInstrumentation);
949 for (
const GlobalDecl &GD : Aliases) {
952 Alias->replaceAllUsesWith(llvm::PoisonValue::get(Alias->getType()));
953 Alias->eraseFromParent();
958 DeferredDeclsToEmit.clear();
959 EmittedDeferredDecls.clear();
960 DeferredAnnotations.clear();
962 OpenMPRuntime->clear();
966 StringRef MainFile) {
969 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
970 if (MainFile.empty())
971 MainFile =
"<stdin>";
972 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
975 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
978 Diags.
Report(diag::warn_profile_data_missing) << Visited << Missing;
982static std::optional<llvm::GlobalValue::VisibilityTypes>
989 return llvm::GlobalValue::DefaultVisibility;
991 return llvm::GlobalValue::HiddenVisibility;
993 return llvm::GlobalValue::ProtectedVisibility;
995 llvm_unreachable(
"unknown option value!");
1000 std::optional<llvm::GlobalValue::VisibilityTypes>
V) {
1009 GV.setDSOLocal(
false);
1010 GV.setVisibility(*
V);
1015 if (!LO.VisibilityFromDLLStorageClass)
1018 std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
1021 std::optional<llvm::GlobalValue::VisibilityTypes>
1022 NoDLLStorageClassVisibility =
1025 std::optional<llvm::GlobalValue::VisibilityTypes>
1026 ExternDeclDLLImportVisibility =
1029 std::optional<llvm::GlobalValue::VisibilityTypes>
1030 ExternDeclNoDLLStorageClassVisibility =
1033 for (llvm::GlobalValue &GV : M.global_values()) {
1034 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
1037 if (GV.isDeclarationForLinker())
1039 llvm::GlobalValue::DLLImportStorageClass
1040 ? ExternDeclDLLImportVisibility
1041 : ExternDeclNoDLLStorageClassVisibility);
1044 llvm::GlobalValue::DLLExportStorageClass
1045 ? DLLExportVisibility
1046 : NoDLLStorageClassVisibility);
1048 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1053 const llvm::Triple &Triple,
1057 return LangOpts.getStackProtector() == Mode;
1060std::optional<llvm::Attribute::AttrKind>
1062 if (D && D->
hasAttr<NoStackProtectorAttr>())
1064 else if (D && D->
hasAttr<StrictGuardStackCheckAttr>() &&
1066 return llvm::Attribute::StackProtectStrong;
1068 return llvm::Attribute::StackProtect;
1070 return llvm::Attribute::StackProtectStrong;
1072 return llvm::Attribute::StackProtectReq;
1073 return std::nullopt;
1079 EmitModuleInitializers(Primary);
1081 DeferredDecls.insert_range(EmittedDeferredDecls);
1082 EmittedDeferredDecls.clear();
1083 EmitVTablesOpportunistically();
1084 applyGlobalValReplacements();
1085 applyReplacements();
1086 emitMultiVersionFunctions();
1087 emitPFPFieldsWithEvaluatedOffset();
1089 if (Context.getLangOpts().IncrementalExtensions &&
1090 GlobalTopLevelStmtBlockInFlight.first) {
1092 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->
getEndLoc());
1093 GlobalTopLevelStmtBlockInFlight = {
nullptr,
nullptr};
1099 EmitCXXModuleInitFunc(Primary);
1101 EmitCXXGlobalInitFunc();
1102 EmitCXXGlobalCleanUpFunc();
1103 registerGlobalDtorsWithAtExit();
1104 EmitCXXThreadLocalInitFunc();
1106 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
1108 if (Context.getLangOpts().CUDA && CUDARuntime) {
1109 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
1112 if (OpenMPRuntime) {
1113 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
1114 OpenMPRuntime->clear();
1118 PGOReader->getSummary(
false).getMD(VMContext),
1119 llvm::ProfileSummary::PSK_Instr);
1120 if (PGOStats.hasDiagnostics())
1126 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
1127 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
1129 EmitStaticExternCAliases();
1134 if (CoverageMapping)
1135 CoverageMapping->emit();
1136 if (CodeGenOpts.SanitizeCfiCrossDso) {
1140 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
1142 emitAtAvailableLinkGuard();
1143 if (Context.getTargetInfo().getTriple().isWasm())
1150 if (
getTarget().getTargetOpts().CodeObjectVersion !=
1151 llvm::CodeObjectVersionKind::COV_None) {
1152 getModule().addModuleFlag(llvm::Module::Error,
1153 "amdhsa_code_object_version",
1154 getTarget().getTargetOpts().CodeObjectVersion);
1159 auto *MDStr = llvm::MDString::get(
1164 getModule().addModuleFlag(llvm::Module::Error,
"amdgpu_printf_kind",
1173 if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) {
1175 for (
auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) {
1177 if (
auto *FD = dyn_cast<FunctionDecl>(D))
1181 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1185 llvm::ArrayType *ATy = llvm::ArrayType::get(
Int8PtrTy, UsedArray.size());
1187 auto *GV =
new llvm::GlobalVariable(
1188 getModule(), ATy,
false, llvm::GlobalValue::InternalLinkage,
1189 llvm::ConstantArray::get(ATy, UsedArray),
"__clang_gpu_used_external");
1195 auto *GV =
new llvm::GlobalVariable(
1197 llvm::Constant::getNullValue(
Int8Ty),
1206 if (CodeGenOpts.Autolink &&
1207 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
1208 EmitModuleLinkOptions();
1223 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
1224 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.dependent-libraries");
1225 for (
auto *MD : ELFDependentLibraries)
1226 NMD->addOperand(MD);
1229 if (CodeGenOpts.DwarfVersion) {
1230 getModule().addModuleFlag(llvm::Module::Max,
"Dwarf Version",
1231 CodeGenOpts.DwarfVersion);
1234 if (CodeGenOpts.Dwarf64)
1235 getModule().addModuleFlag(llvm::Module::Max,
"DWARF64", 1);
1237 if (Context.getLangOpts().SemanticInterposition)
1239 getModule().setSemanticInterposition(
true);
1241 if (CodeGenOpts.EmitCodeView) {
1243 getModule().addModuleFlag(llvm::Module::Warning,
"CodeView", 1);
1245 if (CodeGenOpts.CodeViewGHash) {
1246 getModule().addModuleFlag(llvm::Module::Warning,
"CodeViewGHash", 1);
1248 if (CodeGenOpts.ControlFlowGuard) {
1251 llvm::Module::Warning,
"cfguard",
1252 static_cast<unsigned>(llvm::ControlFlowGuardMode::Enabled));
1253 }
else if (CodeGenOpts.ControlFlowGuardNoChecks) {
1256 llvm::Module::Warning,
"cfguard",
1257 static_cast<unsigned>(llvm::ControlFlowGuardMode::TableOnly));
1259 if (CodeGenOpts.getWinControlFlowGuardMechanism() !=
1260 llvm::ControlFlowGuardMechanism::Automatic) {
1263 llvm::Module::Warning,
"cfguard-mechanism",
1264 static_cast<unsigned>(CodeGenOpts.getWinControlFlowGuardMechanism()));
1266 if (CodeGenOpts.EHContGuard) {
1268 getModule().addModuleFlag(llvm::Module::Warning,
"ehcontguard", 1);
1270 if (Context.getLangOpts().Kernel) {
1272 getModule().addModuleFlag(llvm::Module::Warning,
"ms-kernel", 1);
1274 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
1279 getModule().addModuleFlag(llvm::Module::Error,
"StrictVTablePointers",1);
1281 llvm::Metadata *Ops[2] = {
1282 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
1283 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1284 llvm::Type::getInt32Ty(VMContext), 1))};
1286 getModule().addModuleFlag(llvm::Module::Require,
1287 "StrictVTablePointersRequirement",
1288 llvm::MDNode::get(VMContext, Ops));
1294 getModule().addModuleFlag(llvm::Module::Warning,
"Debug Info Version",
1295 llvm::DEBUG_METADATA_VERSION);
1300 uint64_t WCharWidth =
1301 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
1302 if (WCharWidth !=
getTriple().getDefaultWCharSize())
1303 getModule().addModuleFlag(llvm::Module::Error,
"wchar_size", WCharWidth);
1306 getModule().addModuleFlag(llvm::Module::Warning,
1307 "zos_product_major_version",
1309 getModule().addModuleFlag(llvm::Module::Warning,
1310 "zos_product_minor_version",
1312 getModule().addModuleFlag(llvm::Module::Warning,
"zos_product_patchlevel",
1313 uint32_t(CLANG_VERSION_PATCHLEVEL));
1315 getModule().addModuleFlag(llvm::Module::Error,
"zos_product_id",
1316 llvm::MDString::get(VMContext, ProductId));
1321 getModule().addModuleFlag(llvm::Module::Error,
"zos_cu_language",
1322 llvm::MDString::get(VMContext, lang_str));
1324 time_t TT = PreprocessorOpts.SourceDateEpoch
1325 ? *PreprocessorOpts.SourceDateEpoch
1326 : std::time(
nullptr);
1327 getModule().addModuleFlag(llvm::Module::Max,
"zos_translation_time",
1328 static_cast<uint64_t
>(TT));
1331 getModule().addModuleFlag(llvm::Module::Error,
"zos_le_char_mode",
1332 llvm::MDString::get(VMContext,
"ascii"));
1335 llvm::Triple T = Context.getTargetInfo().getTriple();
1336 if (T.isARM() || T.isThumb()) {
1338 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
1339 getModule().addModuleFlag(llvm::Module::Error,
"min_enum_size", EnumWidth);
1343 StringRef ABIStr = Target.getABI();
1344 llvm::LLVMContext &Ctx = TheModule.getContext();
1345 getModule().addModuleFlag(llvm::Module::Error,
"target-abi",
1346 llvm::MDString::get(Ctx, ABIStr));
1351 const std::vector<std::string> &Features =
1354 llvm::RISCVISAInfo::parseFeatures(T.isRISCV64() ? 64 : 32, Features);
1355 if (!errorToBool(ParseResult.takeError()))
1357 llvm::Module::AppendUnique,
"riscv-isa",
1359 Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString())));
1362 if (CodeGenOpts.SanitizeCfiCrossDso) {
1364 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
1367 if (CodeGenOpts.WholeProgramVTables) {
1371 getModule().addModuleFlag(llvm::Module::Error,
"Virtual Function Elim",
1372 CodeGenOpts.VirtualFunctionElimination);
1375 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
1376 getModule().addModuleFlag(llvm::Module::Override,
1377 "CFI Canonical Jump Tables",
1378 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1381 if (CodeGenOpts.SanitizeCfiICallNormalizeIntegers) {
1382 getModule().addModuleFlag(llvm::Module::Override,
"cfi-normalize-integers",
1386 if (!CodeGenOpts.UniqueSourceFileIdentifier.empty()) {
1388 llvm::Module::Append,
"Unique Source File Identifier",
1390 TheModule.getContext(),
1391 llvm::MDString::get(TheModule.getContext(),
1392 CodeGenOpts.UniqueSourceFileIdentifier)));
1395 if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) {
1396 getModule().addModuleFlag(llvm::Module::Override,
"kcfi", 1);
1399 if (CodeGenOpts.PatchableFunctionEntryOffset)
1400 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-offset",
1401 CodeGenOpts.PatchableFunctionEntryOffset);
1402 if (CodeGenOpts.SanitizeKcfiArity)
1403 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-arity", 1);
1406 llvm::Module::Override,
"kcfi-hash",
1407 llvm::MDString::get(
1409 llvm::stringifyKCFIHashAlgorithm(CodeGenOpts.SanitizeKcfiHash)));
1412 if (CodeGenOpts.CFProtectionReturn &&
1413 Target.checkCFProtectionReturnSupported(
getDiags())) {
1415 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-return",
1419 if (CodeGenOpts.CFProtectionBranch &&
1420 Target.checkCFProtectionBranchSupported(
getDiags())) {
1422 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-branch",
1425 auto Scheme = CodeGenOpts.getCFBranchLabelScheme();
1426 if (Target.checkCFBranchLabelSchemeSupported(Scheme,
getDiags())) {
1428 Scheme = Target.getDefaultCFBranchLabelScheme();
1430 llvm::Module::Error,
"cf-branch-label-scheme",
1436 if (CodeGenOpts.FunctionReturnThunks)
1437 getModule().addModuleFlag(llvm::Module::Override,
"function_return_thunk_extern", 1);
1439 if (CodeGenOpts.IndirectBranchCSPrefix)
1440 getModule().addModuleFlag(llvm::Module::Override,
"indirect_branch_cs_prefix", 1);
1451 if (Context.getTargetInfo().hasFeature(
"ptrauth") &&
1452 LangOpts.getSignReturnAddressScope() !=
1454 getModule().addModuleFlag(llvm::Module::Override,
1455 "sign-return-address-buildattr", 1);
1456 if (LangOpts.Sanitize.has(SanitizerKind::MemtagStack))
1457 getModule().addModuleFlag(llvm::Module::Override,
1458 "tag-stack-memory-buildattr", 1);
1460 if (T.isARM() || T.isThumb() || T.isAArch64()) {
1468 if (LangOpts.BranchTargetEnforcement)
1469 getModule().addModuleFlag(llvm::Module::Min,
"branch-target-enforcement",
1471 if (LangOpts.BranchProtectionPAuthLR)
1472 getModule().addModuleFlag(llvm::Module::Min,
"branch-protection-pauth-lr",
1474 if (LangOpts.GuardedControlStack)
1475 getModule().addModuleFlag(llvm::Module::Min,
"guarded-control-stack", 2);
1476 if (LangOpts.hasSignReturnAddress())
1477 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address", 2);
1478 if (LangOpts.isSignReturnAddressScopeAll())
1479 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address-all",
1481 if (!LangOpts.isSignReturnAddressWithAKey())
1482 getModule().addModuleFlag(llvm::Module::Min,
1483 "sign-return-address-with-bkey", 2);
1485 if (LangOpts.PointerAuthELFGOT)
1486 getModule().addModuleFlag(llvm::Module::Error,
"ptrauth-elf-got", 1);
1489 if (LangOpts.PointerAuthCalls)
1490 getModule().addModuleFlag(llvm::Module::Error,
1491 "ptrauth-sign-personality", 1);
1493 using namespace llvm::ELF;
1494 uint64_t PAuthABIVersion =
1495 (LangOpts.PointerAuthIntrinsics
1496 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS) |
1497 (LangOpts.PointerAuthCalls
1498 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS) |
1499 (LangOpts.PointerAuthReturns
1500 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS) |
1501 (LangOpts.PointerAuthAuthTraps
1502 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS) |
1503 (LangOpts.PointerAuthVTPtrAddressDiscrimination
1504 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR) |
1505 (LangOpts.PointerAuthVTPtrTypeDiscrimination
1506 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR) |
1507 (LangOpts.PointerAuthInitFini
1508 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI) |
1509 (LangOpts.PointerAuthInitFiniAddressDiscrimination
1510 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC) |
1511 (LangOpts.PointerAuthELFGOT
1512 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT) |
1513 (LangOpts.PointerAuthIndirectGotos
1514 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS) |
1515 (LangOpts.PointerAuthTypeInfoVTPtrDiscrimination
1516 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR) |
1517 (LangOpts.PointerAuthFunctionTypeDiscrimination
1518 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR);
1519 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR ==
1520 AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
1521 "Update when new enum items are defined");
1522 if (PAuthABIVersion != 0) {
1523 getModule().addModuleFlag(llvm::Module::Error,
1524 "aarch64-elf-pauthabi-platform",
1525 AARCH64_PAUTH_PLATFORM_LLVM_LINUX);
1526 getModule().addModuleFlag(llvm::Module::Error,
1527 "aarch64-elf-pauthabi-version",
1532 if ((T.isARM() || T.isThumb()) &&
getTriple().isTargetAEABI() &&
1534 uint32_t TagVal = 0;
1535 llvm::Module::ModFlagBehavior DenormalTagBehavior = llvm::Module::Max;
1537 llvm::DenormalMode::getPositiveZero()) {
1538 TagVal = llvm::ARMBuildAttrs::PositiveZero;
1540 llvm::DenormalMode::getIEEE()) {
1541 TagVal = llvm::ARMBuildAttrs::IEEEDenormals;
1542 DenormalTagBehavior = llvm::Module::Override;
1544 llvm::DenormalMode::getPreserveSign()) {
1545 TagVal = llvm::ARMBuildAttrs::PreserveFPSign;
1547 getModule().addModuleFlag(DenormalTagBehavior,
"arm-eabi-fp-denormal",
1552 getModule().addModuleFlag(llvm::Module::Min,
"arm-eabi-fp-exceptions",
1553 llvm::ARMBuildAttrs::Allowed);
1556 TagVal = llvm::ARMBuildAttrs::AllowIEEENormal;
1558 TagVal = llvm::ARMBuildAttrs::AllowIEEE754;
1559 getModule().addModuleFlag(llvm::Module::Min,
"arm-eabi-fp-number-model",
1563 if (CodeGenOpts.StackClashProtector)
1565 llvm::Module::Override,
"probe-stack",
1566 llvm::MDString::get(TheModule.getContext(),
"inline-asm"));
1568 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
1569 getModule().addModuleFlag(llvm::Module::Min,
"stack-probe-size",
1570 CodeGenOpts.StackProbeSize);
1572 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1573 llvm::LLVMContext &Ctx = TheModule.getContext();
1575 llvm::Module::Error,
"MemProfProfileFilename",
1576 llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
1579 if (LangOpts.CUDAIsDevice &&
getTriple().isNVPTX()) {
1583 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
1584 CodeGenOpts.FP32DenormalMode.Output !=
1585 llvm::DenormalMode::IEEE);
1588 if (LangOpts.EHAsynch)
1589 getModule().addModuleFlag(llvm::Module::Warning,
"eh-asynch", 1);
1592 if (CodeGenOpts.ImportCallOptimization)
1593 getModule().addModuleFlag(llvm::Module::Warning,
"import-call-optimization",
1603 auto UnwindMode = CodeGenOpts.getWinX64EHUnwind();
1604 if (UnwindMode == llvm::WinX64EHUnwindMode::Default) {
1605 if (T.isOSWindows() && T.isX86_64() &&
1606 Context.getTargetInfo().hasFeature(
"egpr"))
1607 UnwindMode = llvm::WinX64EHUnwindMode::V3;
1609 UnwindMode = llvm::WinX64EHUnwindMode::V1;
1611 if (UnwindMode != llvm::WinX64EHUnwindMode::V1)
1612 getModule().addModuleFlag(llvm::Module::Warning,
"winx64-eh-unwind",
1613 static_cast<unsigned>(UnwindMode));
1617 getModule().addModuleFlag(llvm::Module::Max,
"openmp", LangOpts.OpenMP);
1619 getModule().addModuleFlag(llvm::Module::Max,
"openmp-device",
1623 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())) {
1624 EmitOpenCLMetadata();
1631 auto Version = LangOpts.getOpenCLCompatibleVersion();
1632 llvm::Metadata *SPIRVerElts[] = {
1633 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1635 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1636 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
1637 llvm::NamedMDNode *SPIRVerMD =
1638 TheModule.getOrInsertNamedMetadata(
"opencl.spir.version");
1639 llvm::LLVMContext &Ctx = TheModule.getContext();
1640 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
1648 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
1649 assert(PLevel < 3 &&
"Invalid PIC Level");
1650 getModule().setPICLevel(
static_cast<llvm::PICLevel::Level
>(PLevel));
1651 if (Context.getLangOpts().PIE)
1652 getModule().setPIELevel(
static_cast<llvm::PIELevel::Level
>(PLevel));
1656 unsigned CM = llvm::StringSwitch<unsigned>(
getCodeGenOpts().CodeModel)
1657 .Case(
"tiny", llvm::CodeModel::Tiny)
1658 .Case(
"small", llvm::CodeModel::Small)
1659 .Case(
"kernel", llvm::CodeModel::Kernel)
1660 .Case(
"medium", llvm::CodeModel::Medium)
1661 .Case(
"large", llvm::CodeModel::Large)
1664 llvm::CodeModel::Model codeModel =
static_cast<llvm::CodeModel::Model
>(CM);
1667 if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
1668 Context.getTargetInfo().getTriple().getArch() ==
1669 llvm::Triple::x86_64) {
1675 if (CodeGenOpts.NoPLT)
1678 CodeGenOpts.DirectAccessExternalData !=
1679 getModule().getDirectAccessExternalData()) {
1680 getModule().setDirectAccessExternalData(
1681 CodeGenOpts.DirectAccessExternalData);
1683 if (CodeGenOpts.UnwindTables)
1684 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1686 switch (CodeGenOpts.getFramePointer()) {
1691 getModule().setFramePointer(llvm::FramePointerKind::Reserved);
1694 getModule().setFramePointer(llvm::FramePointerKind::NonLeafNoReserve);
1697 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1700 getModule().setFramePointer(llvm::FramePointerKind::All);
1704 SimplifyPersonality();
1717 EmitVersionIdentMetadata();
1720 EmitCommandLineMetadata();
1728 getModule().setStackProtectorGuardSymbol(
1731 getModule().setStackProtectorGuardOffset(
1734 getModule().setStackProtectorGuardValueWidth(
1737 if (
getModule().getStackProtectorGuard() !=
"global") {
1738 Diags.Report(diag::err_opt_not_valid_without_opt)
1739 <<
"-mstack-protector-guard-record"
1740 <<
"-mstack-protector-guard=global";
1742 getModule().setStackProtectorGuardRecord(
true);
1747 getModule().addModuleFlag(llvm::Module::Override,
"SkipRaxSetup", 1);
1749 getModule().addModuleFlag(llvm::Module::Override,
"RegCallv4", 1);
1751 if (
getContext().getTargetInfo().getMaxTLSAlign())
1752 getModule().addModuleFlag(llvm::Module::Error,
"MaxTLSAlign",
1753 getContext().getTargetInfo().getMaxTLSAlign());
1771 if (!MustTailCallUndefinedGlobals.empty()) {
1773 for (
auto &I : MustTailCallUndefinedGlobals) {
1774 if (!I.first->isDefined())
1775 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1779 if (!Entry || Entry->isWeakForLinker() ||
1780 Entry->isDeclarationForLinker())
1781 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1785 for (
auto &I : MustTailCallUndefinedGlobals) {
1794 if (Entry->isDeclarationForLinker()) {
1797 Entry->hasHiddenVisibility() || Entry->hasProtectedVisibility();
1799 CalleeIsLocal = Entry->isDSOLocal();
1803 getDiags().
Report(I.second, diag::err_mips_impossible_musttail) << 1;
1816 llvm::MDBuilder MDB(TheModule.getContext());
1817 uint64_t Size = Context.getTypeSizeInChars(Context.IntTy).getQuantity();
1818 llvm::MDNode *StructNode =
1819 CodeGenOpts.NewStructPathTBAA
1820 ? MDB.createTBAATypeNode(TBAA->getChar(), Size,
1821 MDB.createString(
"__libc_errno"),
1822 {{0, Size, IntegerNode}})
1823 : MDB.createTBAAStructTypeNode(
"__libc_errno",
1824 {{IntegerNode, 0}});
1827 auto *ErrnoTBAAMD = TheModule.getOrInsertNamedMetadata(
ErrnoTBAAMDName);
1828 ErrnoTBAAMD->addOperand(StructTagNode);
1833void CodeGenModule::EmitOpenCLMetadata() {
1839 auto EmitVersion = [
this](StringRef MDName,
int Version) {
1840 llvm::Metadata *OCLVerElts[] = {
1841 llvm::ConstantAsMetadata::get(
1842 llvm::ConstantInt::get(
Int32Ty, Version / 100)),
1843 llvm::ConstantAsMetadata::get(
1844 llvm::ConstantInt::get(
Int32Ty, (Version % 100) / 10))};
1845 llvm::NamedMDNode *OCLVerMD = TheModule.getOrInsertNamedMetadata(MDName);
1846 llvm::LLVMContext &Ctx = TheModule.getContext();
1847 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
1850 EmitVersion(
"opencl.ocl.version", CLVersion);
1851 if (LangOpts.OpenCLCPlusPlus) {
1853 EmitVersion(
"opencl.cxx.version", LangOpts.OpenCLCPlusPlusVersion);
1857void CodeGenModule::EmitBackendOptionsMetadata(
1858 const CodeGenOptions &CodeGenOpts) {
1860 getModule().addModuleFlag(llvm::Module::Min,
"SmallDataLimit",
1861 CodeGenOpts.SmallDataLimit);
1865 if (LangOpts.AllocTokenMode) {
1866 StringRef S = llvm::getAllocTokenModeAsString(*LangOpts.AllocTokenMode);
1867 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-mode",
1868 llvm::MDString::get(VMContext, S));
1870 if (LangOpts.AllocTokenMax)
1872 llvm::Module::Error,
"alloc-token-max",
1873 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1874 *LangOpts.AllocTokenMax));
1875 if (CodeGenOpts.SanitizeAllocTokenFastABI)
1876 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-fast-abi", 1);
1877 if (CodeGenOpts.SanitizeAllocTokenExtended)
1878 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-extended", 1);
1894 return TBAA->getTypeInfo(QTy);
1913 return TBAA->getAccessInfo(AccessType);
1920 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
1926 return TBAA->getTBAAStructInfo(QTy);
1932 return TBAA->getBaseTypeInfo(QTy);
1938 return TBAA->getAccessTagInfo(Info);
1945 return TBAA->mergeTBAAInfoForCast(SourceInfo,
TargetInfo);
1953 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
1961 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
1967 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
1972 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
1984 std::string Msg =
Type;
1986 diag::err_codegen_unsupported)
1992 diag::err_codegen_unsupported)
1999 std::string Msg =
Type;
2001 diag::err_codegen_unsupported)
2006 llvm::function_ref<
void()> Fn) {
2007 StackHandler.runWithSufficientStackSpace(Loc, Fn);
2017 if (GV->hasLocalLinkage()) {
2018 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2031 if (Context.getLangOpts().OpenMP &&
2032 Context.getLangOpts().OpenMPIsTargetDevice &&
isa<VarDecl>(D) &&
2033 D->
hasAttr<OMPDeclareTargetDeclAttr>() &&
2034 D->
getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
2035 OMPDeclareTargetDeclAttr::DT_NoHost &&
2037 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
2044 if (Context.getLangOpts().CUDAIsDevice &&
2046 !D->
hasAttr<OMPDeclareTargetDeclAttr>()) {
2047 bool NeedsProtected =
false;
2051 else if (
const auto *VD = dyn_cast<VarDecl>(D))
2052 NeedsProtected = VD->hasAttr<CUDADeviceAttr>() ||
2053 VD->hasAttr<CUDAConstantAttr>() ||
2054 VD->getType()->isCUDADeviceBuiltinSurfaceType() ||
2055 VD->getType()->isCUDADeviceBuiltinTextureType();
2056 if (NeedsProtected) {
2057 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
2063 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
2067 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
2071 if (GV->hasDLLExportStorageClass()) {
2074 diag::err_hidden_visibility_dllexport);
2077 diag::err_non_default_visibility_dllimport);
2083 !GV->isDeclarationForLinker())
2088 llvm::GlobalValue *GV) {
2089 if (GV->hasLocalLinkage())
2092 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
2096 if (GV->hasDLLImportStorageClass())
2099 const llvm::Triple &TT = CGM.
getTriple();
2101 if (TT.isOSCygMing()) {
2119 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
2127 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
2131 if (!TT.isOSBinFormatELF())
2137 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
2145 return !(CGM.
getLangOpts().SemanticInterposition ||
2150 if (!GV->isDeclarationForLinker())
2156 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
2163 if (CGOpts.DirectAccessExternalData) {
2169 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
2170 if (!Var->isThreadLocal())
2195 const auto *D = dyn_cast<NamedDecl>(GD.
getDecl());
2197 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
2207 if (D->
hasAttr<DLLImportAttr>())
2208 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2209 else if ((D->
hasAttr<DLLExportAttr>() ||
2211 !GV->isDeclarationForLinker())
2212 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2232 GV->setPartition(CodeGenOpts.SymbolPartition);
2236 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
2237 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
2238 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
2239 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
2240 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
2243llvm::GlobalVariable::ThreadLocalMode
2245 switch (CodeGenOpts.getDefaultTLSModel()) {
2247 return llvm::GlobalVariable::GeneralDynamicTLSModel;
2249 return llvm::GlobalVariable::LocalDynamicTLSModel;
2251 return llvm::GlobalVariable::InitialExecTLSModel;
2253 return llvm::GlobalVariable::LocalExecTLSModel;
2255 llvm_unreachable(
"Invalid TLS model!");
2259 assert(D.
getTLSKind() &&
"setting TLS mode on non-TLS var!");
2261 llvm::GlobalValue::ThreadLocalMode TLM;
2265 if (
const TLSModelAttr *
Attr = D.
getAttr<TLSModelAttr>()) {
2269 GV->setThreadLocalMode(TLM);
2275 return (Twine(
'.') + Twine(
Target.CPUSpecificManglingCharacter(Name))).str();
2279 const CPUSpecificAttr *
Attr,
2296 !D->
hasAttr<AsmLabelAttr>() &&
2302 bool OmitMultiVersionMangling =
false) {
2304 llvm::raw_svector_ostream Out(Buffer);
2313 assert(II &&
"Attempt to mangle unnamed decl.");
2314 const auto *FD = dyn_cast<FunctionDecl>(ND);
2319 Out <<
"__regcall4__" << II->
getName();
2321 Out <<
"__regcall3__" << II->
getName();
2322 }
else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
2324 Out <<
"__device_stub__" << II->
getName();
2326 DeviceKernelAttr::isOpenCLSpelling(
2327 FD->getAttr<DeviceKernelAttr>()) &&
2329 Out <<
"__clang_ocl_kern_imp_" << II->
getName();
2345 "Hash computed when not explicitly requested");
2349 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
2350 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
2351 switch (FD->getMultiVersionKind()) {
2355 FD->getAttr<CPUSpecificAttr>(),
2359 auto *
Attr = FD->getAttr<TargetAttr>();
2360 assert(
Attr &&
"Expected TargetAttr to be present "
2361 "for attribute mangling");
2367 auto *
Attr = FD->getAttr<TargetVersionAttr>();
2368 assert(
Attr &&
"Expected TargetVersionAttr to be present "
2369 "for attribute mangling");
2375 auto *
Attr = FD->getAttr<TargetClonesAttr>();
2376 assert(
Attr &&
"Expected TargetClonesAttr to be present "
2377 "for attribute mangling");
2384 llvm_unreachable(
"None multiversion type isn't valid here");
2394 return std::string(Out.str());
2397void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
2398 const FunctionDecl *FD,
2399 StringRef &CurName) {
2406 std::string NonTargetName =
2414 "Other GD should now be a multiversioned function");
2424 if (OtherName != NonTargetName) {
2427 const auto ExistingRecord = Manglings.find(NonTargetName);
2428 if (ExistingRecord != std::end(Manglings))
2429 Manglings.remove(&(*ExistingRecord));
2430 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
2435 CurName = OtherNameRef;
2437 Entry->setName(OtherName);
2447 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
2461 auto FoundName = MangledDeclNames.find(CanonicalGD);
2462 if (FoundName != MangledDeclNames.end())
2463 return FoundName->second;
2500 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
2501 return MangledDeclNames[CanonicalGD] =
Result.first->first();
2510 llvm::raw_svector_ostream Out(Buffer);
2513 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
2514 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(D))
2516 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(D))
2521 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
2522 return Result.first->first();
2526 auto it = MangledDeclNames.begin();
2527 while (it != MangledDeclNames.end()) {
2528 if (it->second == Name)
2543 llvm::Constant *AssociatedData) {
2545 GlobalCtors.push_back(
Structor(Priority, LexOrder, Ctor, AssociatedData));
2551 bool IsDtorAttrFunc) {
2552 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2554 DtorsUsingAtExit[Priority].push_back(Dtor);
2559 GlobalDtors.push_back(
Structor(Priority, ~0
U, Dtor,
nullptr));
2562void CodeGenModule::EmitCtorList(CtorList &Fns,
const char *GlobalName) {
2563 if (Fns.empty())
return;
2569 llvm::PointerType *PtrTy = llvm::PointerType::get(
2570 getLLVMContext(), TheModule.getDataLayout().getProgramAddressSpace());
2573 llvm::StructType *CtorStructTy = llvm::StructType::get(
Int32Ty, PtrTy, PtrTy);
2577 auto Ctors = Builder.beginArray(CtorStructTy);
2578 for (
const auto &I : Fns) {
2579 auto Ctor = Ctors.beginStruct(CtorStructTy);
2580 Ctor.addInt(
Int32Ty, I.Priority);
2581 if (InitFiniAuthSchema) {
2582 llvm::Constant *StorageAddress =
2584 ? llvm::ConstantExpr::getIntToPtr(
2585 llvm::ConstantInt::get(
2587 llvm::ConstantPtrAuth::AddrDiscriminator_CtorsDtors),
2591 I.Initializer, InitFiniAuthSchema.
getKey(), StorageAddress,
2592 llvm::ConstantInt::get(
2594 Ctor.add(SignedCtorPtr);
2596 Ctor.add(I.Initializer);
2598 if (I.AssociatedData)
2599 Ctor.add(I.AssociatedData);
2601 Ctor.addNullPointer(PtrTy);
2602 Ctor.finishAndAddTo(Ctors);
2605 auto List = Ctors.finishAndCreateGlobal(GlobalName,
getPointerAlign(),
2607 llvm::GlobalValue::AppendingLinkage);
2611 List->setAlignment(std::nullopt);
2616llvm::GlobalValue::LinkageTypes
2622 if (
const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
2629 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2630 if (!MDS)
return nullptr;
2632 return llvm::ConstantInt::get(
Int64Ty, llvm::MD5Hash(MDS->getString()));
2640 if (!UD->
hasAttr<TransparentUnionAttr>())
2642 if (!UD->
fields().empty())
2643 return UD->
fields().begin()->getType();
2652 bool GeneralizePointers) {
2665 bool GeneralizePointers) {
2668 for (
auto &Param : FnType->param_types())
2669 GeneralizedParams.push_back(
2673 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers),
2674 GeneralizedParams, FnType->getExtProtoInfo());
2679 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers));
2681 llvm_unreachable(
"Encountered unknown FunctionType");
2689 FnType->getReturnType(), FnType->getParamTypes(),
2690 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
2692 std::string OutName;
2693 llvm::raw_string_ostream Out(OutName);
2701 Out <<
".normalized";
2703 Out <<
".generalized";
2705 return llvm::ConstantInt::get(
2711 llvm::Function *F,
bool IsThunk) {
2713 llvm::AttributeList PAL;
2716 if (
CallingConv == llvm::CallingConv::X86_VectorCall &&
2720 Loc = D->getLocation();
2722 Error(Loc,
"__vectorcall calling convention is not currently supported");
2724 F->setAttributes(PAL);
2725 F->setCallingConv(
static_cast<llvm::CallingConv::ID
>(
CallingConv));
2729 std::string ReadOnlyQual(
"__read_only");
2730 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2731 if (ReadOnlyPos != std::string::npos)
2733 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2735 std::string WriteOnlyQual(
"__write_only");
2736 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2737 if (WriteOnlyPos != std::string::npos)
2738 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2740 std::string ReadWriteQual(
"__read_write");
2741 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2742 if (ReadWritePos != std::string::npos)
2743 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2776 assert(((FD && CGF) || (!FD && !CGF)) &&
2777 "Incorrect use - FD and CGF should either be both null or not!");
2803 for (
unsigned i = 0, e = FD->
getNumParams(); i != e; ++i) {
2806 argNames.push_back(llvm::MDString::get(VMContext, parm->
getName()));
2811 std::string typeQuals;
2815 const Decl *PDecl = parm;
2817 PDecl = TD->getDecl();
2818 const OpenCLAccessAttr *A = PDecl->
getAttr<OpenCLAccessAttr>();
2819 if (A && A->isWriteOnly())
2820 accessQuals.push_back(llvm::MDString::get(VMContext,
"write_only"));
2821 else if (A && A->isReadWrite())
2822 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_write"));
2824 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_only"));
2826 accessQuals.push_back(llvm::MDString::get(VMContext,
"none"));
2828 auto getTypeSpelling = [&](
QualType Ty) {
2829 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2831 if (Ty.isCanonical()) {
2832 StringRef typeNameRef = typeName;
2834 if (typeNameRef.consume_front(
"unsigned "))
2835 return std::string(
"u") + typeNameRef.str();
2836 if (typeNameRef.consume_front(
"signed "))
2837 return typeNameRef.str();
2847 addressQuals.push_back(
2848 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(
2852 std::string typeName = getTypeSpelling(pointeeTy) +
"*";
2853 std::string baseTypeName =
2855 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2856 argBaseTypeNames.push_back(
2857 llvm::MDString::get(VMContext, baseTypeName));
2861 typeQuals =
"restrict";
2864 typeQuals += typeQuals.empty() ?
"const" :
" const";
2866 typeQuals += typeQuals.empty() ?
"volatile" :
" volatile";
2868 uint32_t AddrSpc = 0;
2873 addressQuals.push_back(
2874 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(AddrSpc)));
2878 std::string typeName = getTypeSpelling(ty);
2890 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2891 argBaseTypeNames.push_back(
2892 llvm::MDString::get(VMContext, baseTypeName));
2897 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
2901 Fn->setMetadata(
"kernel_arg_addr_space",
2902 llvm::MDNode::get(VMContext, addressQuals));
2903 Fn->setMetadata(
"kernel_arg_access_qual",
2904 llvm::MDNode::get(VMContext, accessQuals));
2905 Fn->setMetadata(
"kernel_arg_type",
2906 llvm::MDNode::get(VMContext, argTypeNames));
2907 Fn->setMetadata(
"kernel_arg_base_type",
2908 llvm::MDNode::get(VMContext, argBaseTypeNames));
2909 Fn->setMetadata(
"kernel_arg_type_qual",
2910 llvm::MDNode::get(VMContext, argTypeQuals));
2914 Fn->setMetadata(
"kernel_arg_name",
2915 llvm::MDNode::get(VMContext, argNames));
2925 if (!LangOpts.Exceptions)
return false;
2928 if (LangOpts.CXXExceptions)
return true;
2931 if (LangOpts.ObjCExceptions) {
2951SmallVector<const CXXRecordDecl *, 0>
2953 llvm::SetVector<const CXXRecordDecl *> MostBases;
2958 MostBases.insert(RD);
2960 CollectMostBases(B.getType()->getAsCXXRecordDecl());
2962 CollectMostBases(RD);
2963 return MostBases.takeVector();
2967 llvm::Function *F) {
2968 llvm::AttrBuilder B(F->getContext());
2970 if ((!D || !D->
hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2971 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2973 if (CodeGenOpts.StackClashProtector)
2974 B.addAttribute(
"probe-stack",
"inline-asm");
2976 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
2977 B.addAttribute(
"stack-probe-size",
2978 std::to_string(CodeGenOpts.StackProbeSize));
2981 B.addAttribute(llvm::Attribute::NoUnwind);
2983 if (std::optional<llvm::Attribute::AttrKind>
Attr =
2985 B.addAttribute(*
Attr);
2990 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline))
2991 B.addAttribute(llvm::Attribute::AlwaysInline);
2995 else if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2997 B.addAttribute(llvm::Attribute::NoInline);
3005 if (D->
hasAttr<ArmLocallyStreamingAttr>())
3006 B.addAttribute(
"aarch64_pstate_sm_body");
3009 if (
Attr->isNewZA())
3010 B.addAttribute(
"aarch64_new_za");
3011 if (
Attr->isNewZT0())
3012 B.addAttribute(
"aarch64_new_zt0");
3017 bool ShouldAddOptNone =
3018 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
3020 ShouldAddOptNone &= !D->
hasAttr<MinSizeAttr>();
3021 ShouldAddOptNone &= !D->
hasAttr<AlwaysInlineAttr>();
3024 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline) &&
3025 !D->
hasAttr<NoInlineAttr>()) {
3026 B.addAttribute(llvm::Attribute::AlwaysInline);
3027 }
else if ((ShouldAddOptNone || D->
hasAttr<OptimizeNoneAttr>()) &&
3028 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
3030 B.addAttribute(llvm::Attribute::OptimizeNone);
3033 B.addAttribute(llvm::Attribute::NoInline);
3038 B.addAttribute(llvm::Attribute::Naked);
3041 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
3042 F->removeFnAttr(llvm::Attribute::MinSize);
3043 }
else if (D->
hasAttr<NakedAttr>()) {
3045 B.addAttribute(llvm::Attribute::Naked);
3046 B.addAttribute(llvm::Attribute::NoInline);
3047 }
else if (D->
hasAttr<NoDuplicateAttr>()) {
3048 B.addAttribute(llvm::Attribute::NoDuplicate);
3049 }
else if (D->
hasAttr<NoInlineAttr>() &&
3050 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
3052 B.addAttribute(llvm::Attribute::NoInline);
3053 }
else if (D->
hasAttr<AlwaysInlineAttr>() &&
3054 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
3056 B.addAttribute(llvm::Attribute::AlwaysInline);
3060 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
3061 B.addAttribute(llvm::Attribute::NoInline);
3065 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
3068 auto CheckRedeclForInline = [](
const FunctionDecl *Redecl) {
3069 return Redecl->isInlineSpecified();
3071 if (any_of(FD->
redecls(), CheckRedeclForInline))
3076 return any_of(Pattern->
redecls(), CheckRedeclForInline);
3078 if (CheckForInline(FD)) {
3079 B.addAttribute(llvm::Attribute::InlineHint);
3080 }
else if (CodeGenOpts.getInlining() ==
3083 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
3084 B.addAttribute(llvm::Attribute::NoInline);
3091 if (!D->
hasAttr<OptimizeNoneAttr>()) {
3093 if (!ShouldAddOptNone)
3094 B.addAttribute(llvm::Attribute::OptimizeForSize);
3095 B.addAttribute(llvm::Attribute::Cold);
3098 B.addAttribute(llvm::Attribute::Hot);
3099 if (D->
hasAttr<MinSizeAttr>())
3100 B.addAttribute(llvm::Attribute::MinSize);
3105 if (CodeGenOpts.DisableOutlining || D->
hasAttr<NoOutlineAttr>())
3106 B.addAttribute(llvm::Attribute::NoOutline);
3110 llvm::MaybeAlign ExplicitAlignment;
3111 if (
unsigned alignment = D->
getMaxAlignment() / Context.getCharWidth())
3112 ExplicitAlignment = llvm::Align(alignment);
3113 else if (LangOpts.FunctionAlignment)
3114 ExplicitAlignment = llvm::Align(1ull << LangOpts.FunctionAlignment);
3116 if (ExplicitAlignment) {
3117 F->setAlignment(ExplicitAlignment);
3118 F->setPreferredAlignment(ExplicitAlignment);
3119 }
else if (LangOpts.PreferredFunctionAlignment) {
3120 F->setPreferredAlignment(llvm::Align(LangOpts.PreferredFunctionAlignment));
3129 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
3134 if (CodeGenOpts.SanitizeCfiCrossDso &&
3135 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
3136 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
3144 if (CodeGenOpts.CallGraphSection) {
3145 if (
auto *FD = dyn_cast<FunctionDecl>(D))
3152 auto *MD = dyn_cast<CXXMethodDecl>(D);
3155 llvm::Metadata *Id =
3157 MD->getType(), std::nullopt,
Base));
3158 F->addTypeMetadata(0, Id);
3165 if (
const auto *FD = dyn_cast<FunctionDecl>(D))
3166 if (FD->
hasAttr<SYCLExternalAttr>())
3167 addSYCLModuleIdAttr(F);
3171void CodeGenModule::addSYCLModuleIdAttr(llvm::Function *Fn) {
3173 Fn->addFnAttr(
"sycl-module-id",
getModule().getModuleIdentifier());
3178 if (isa_and_nonnull<NamedDecl>(D))
3181 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
3183 if (D && D->
hasAttr<UsedAttr>())
3186 if (
const auto *VD = dyn_cast_if_present<VarDecl>(D);
3188 ((CodeGenOpts.KeepPersistentStorageVariables &&
3189 (VD->getStorageDuration() ==
SD_Static ||
3190 VD->getStorageDuration() ==
SD_Thread)) ||
3191 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
3192 VD->getType().isConstQualified())))
3197static std::vector<std::string>
3199 llvm::StringMap<bool> &FeatureMap) {
3200 llvm::StringMap<bool> DefaultFeatureMap;
3204 std::vector<std::string> Delta;
3205 for (
const auto &[K,
V] : FeatureMap) {
3206 auto DefaultIt = DefaultFeatureMap.find(K);
3207 if (DefaultIt == DefaultFeatureMap.end() || DefaultIt->getValue() !=
V)
3208 Delta.push_back((
V ?
"+" :
"-") + K.str());
3214bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
3215 llvm::AttrBuilder &Attrs,
3216 bool SetTargetFeatures) {
3222 std::vector<std::string> Features;
3223 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.
getDecl());
3226 const auto *TV = FD ? FD->
getAttr<TargetVersionAttr>() :
nullptr;
3227 assert((!TD || !TV) &&
"both target_version and target specified");
3230 bool AddedAttr =
false;
3231 if (TD || TV || SD || TC) {
3232 llvm::StringMap<bool> FeatureMap;
3239 StringRef FeatureStr = TD ? TD->getFeaturesStr() : StringRef();
3242 if (!FeatureStr.empty()) {
3243 ParsedTargetAttr ParsedAttr = Target.parseTargetAttr(FeatureStr);
3244 if (!ParsedAttr.
CPU.empty() &&
3246 TargetCPU = ParsedAttr.
CPU;
3249 if (!ParsedAttr.
Tune.empty() &&
3251 TuneCPU = ParsedAttr.
Tune;
3267 for (
const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
3268 Features.push_back((Entry.getValue() ?
"+" :
"-") +
3269 Entry.getKey().str());
3275 llvm::StringMap<bool> FeatureMap;
3289 if (!TargetCPU.empty()) {
3290 Attrs.addAttribute(
"target-cpu", TargetCPU);
3293 if (!TuneCPU.empty()) {
3294 Attrs.addAttribute(
"tune-cpu", TuneCPU);
3297 if (!Features.empty() && SetTargetFeatures) {
3298 llvm::erase_if(Features, [&](
const std::string& F) {
3301 llvm::sort(Features);
3302 Attrs.addAttribute(
"target-features", llvm::join(Features,
","));
3307 llvm::SmallVector<StringRef, 8> Feats;
3308 bool IsDefault =
false;
3310 IsDefault = TV->isDefaultVersion();
3311 TV->getFeatures(Feats);
3317 Attrs.addAttribute(
"fmv-features");
3319 }
else if (!Feats.empty()) {
3321 std::set<StringRef> OrderedFeats(Feats.begin(), Feats.end());
3322 std::string FMVFeatures;
3323 for (StringRef F : OrderedFeats)
3324 FMVFeatures.append(
"," + F.str());
3325 Attrs.addAttribute(
"fmv-features", FMVFeatures.substr(1));
3332void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
3333 llvm::GlobalObject *GO) {
3338 if (
auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
3341 if (
auto *SA = D->
getAttr<PragmaClangBSSSectionAttr>())
3342 GV->addAttribute(
"bss-section", SA->getName());
3343 if (
auto *SA = D->
getAttr<PragmaClangDataSectionAttr>())
3344 GV->addAttribute(
"data-section", SA->getName());
3345 if (
auto *SA = D->
getAttr<PragmaClangRodataSectionAttr>())
3346 GV->addAttribute(
"rodata-section", SA->getName());
3347 if (
auto *SA = D->
getAttr<PragmaClangRelroSectionAttr>())
3348 GV->addAttribute(
"relro-section", SA->getName());
3351 if (
auto *F = dyn_cast<llvm::Function>(GO)) {
3354 if (
auto *SA = D->
getAttr<PragmaClangTextSectionAttr>())
3355 if (!D->
getAttr<SectionAttr>())
3356 F->setSection(SA->getName());
3358 llvm::AttrBuilder Attrs(F->getContext());
3359 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
3363 llvm::AttributeMask RemoveAttrs;
3364 RemoveAttrs.addAttribute(
"target-cpu");
3365 RemoveAttrs.addAttribute(
"target-features");
3366 RemoveAttrs.addAttribute(
"fmv-features");
3367 RemoveAttrs.addAttribute(
"tune-cpu");
3368 F->removeFnAttrs(RemoveAttrs);
3369 F->addFnAttrs(Attrs);
3373 if (
const auto *CSA = D->
getAttr<CodeSegAttr>())
3374 GO->setSection(CSA->getName());
3375 else if (
const auto *SA = D->
getAttr<SectionAttr>())
3376 GO->setSection(SA->getName());
3389 F->setLinkage(llvm::Function::InternalLinkage);
3391 setNonAliasAttributes(GD, F);
3402 GV->
setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
3406 llvm::Function *F) {
3409 if (!F->hasLocalLinkage() ||
3410 F->getFunction().hasAddressTaken(
nullptr,
true,
3413 F->addMetadata(llvm::LLVMContext::MD_callgraph,
3414 *llvm::MDTuple::get(
3421 llvm::Function *F) {
3423 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
3434 F->addTypeMetadata(0, MD);
3441 if (CodeGenOpts.SanitizeCfiCrossDso)
3443 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
3447 llvm::CallBase *CB) {
3452 if (!CodeGenOpts.CallGraphSection || !CB->isIndirectCall() ||
3457 llvm::MDTuple *TypeTuple = llvm::MDTuple::get(
getLLVMContext(), {TypeIdMD});
3458 llvm::MDTuple *MDN = llvm::MDNode::get(
getLLVMContext(), {TypeTuple});
3459 CB->setMetadata(llvm::LLVMContext::MD_callee_type, MDN);
3463 llvm::LLVMContext &Ctx = F->getContext();
3464 llvm::MDBuilder MDB(Ctx);
3465 llvm::StringRef Salt;
3468 if (
const auto &Info = FP->getExtraAttributeInfo())
3469 Salt = Info.CFISalt;
3471 F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
3480 return llvm::all_of(Name, [](
const char &
C) {
3481 return llvm::isAlnum(
C) ||
C ==
'_' ||
C ==
'.';
3487 for (
auto &F : M.functions()) {
3489 bool AddressTaken = F.hasAddressTaken();
3490 if (!AddressTaken && F.hasLocalLinkage())
3491 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
3496 if (!AddressTaken || !F.isDeclaration())
3499 const llvm::ConstantInt *
Type;
3500 if (
const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
3501 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
3505 StringRef Name = F.getName();
3509 std::string
Asm = (
".weak __kcfi_typeid_" + Name +
"\n.set __kcfi_typeid_" +
3510 Name +
", " + Twine(
Type->getZExtValue()) +
" /* " +
3511 Twine(
Type->getSExtValue()) +
" */\n")
3513 M.appendModuleInlineAsm(
Asm);
3517void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
3518 bool IsIncompleteFunction,
3521 if (F->getIntrinsicID() != llvm::Intrinsic::not_intrinsic) {
3529 if (!IsIncompleteFunction)
3536 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
3538 assert(!F->arg_empty() &&
3539 F->arg_begin()->getType()
3540 ->canLosslesslyBitCastTo(F->getReturnType()) &&
3541 "unexpected this return");
3542 F->addParamAttr(0, llvm::Attribute::Returned);
3552 if (!IsIncompleteFunction && F->isDeclaration())
3555 if (
const auto *CSA = FD->
getAttr<CodeSegAttr>())
3556 F->setSection(CSA->getName());
3557 else if (
const auto *SA = FD->
getAttr<SectionAttr>())
3558 F->setSection(SA->getName());
3560 if (
const auto *EA = FD->
getAttr<ErrorAttr>()) {
3562 F->addFnAttr(
"dontcall-error", EA->getUserDiagnostic());
3563 else if (EA->isWarning())
3564 F->addFnAttr(
"dontcall-warn", EA->getUserDiagnostic());
3569 const FunctionDecl *FDBody;
3570 bool HasBody = FD->
hasBody(FDBody);
3572 assert(HasBody &&
"Inline builtin declarations should always have an "
3574 if (shouldEmitFunction(FDBody))
3575 F->addFnAttr(llvm::Attribute::NoBuiltin);
3581 F->addFnAttr(llvm::Attribute::NoBuiltin);
3585 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3586 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
3587 if (MD->isVirtual())
3588 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3594 if (!CodeGenOpts.SanitizeCfiCrossDso ||
3595 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
3598 if (CodeGenOpts.CallGraphSection)
3601 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
3607 if (CodeGenOpts.InlineMaxStackSize !=
UINT_MAX)
3608 F->addFnAttr(
"inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
3610 if (
const auto *CB = FD->
getAttr<CallbackAttr>()) {
3614 llvm::LLVMContext &Ctx = F->getContext();
3615 llvm::MDBuilder MDB(Ctx);
3619 int CalleeIdx = *CB->encoding_begin();
3620 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
3621 F->addMetadata(llvm::LLVMContext::MD_callback,
3622 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
3623 CalleeIdx, PayloadIndices,
3630 "Only globals with definition can force usage.");
3631 LLVMUsed.emplace_back(GV);
3635 assert(!GV->isDeclaration() &&
3636 "Only globals with definition can force usage.");
3637 LLVMCompilerUsed.emplace_back(GV);
3642 "Only globals with definition can force usage.");
3644 LLVMCompilerUsed.emplace_back(GV);
3646 LLVMUsed.emplace_back(GV);
3650 std::vector<llvm::WeakTrackingVH> &List) {
3657 UsedArray.resize(List.size());
3658 for (
unsigned i = 0, e = List.size(); i != e; ++i) {
3660 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3664 if (UsedArray.empty())
3666 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
3668 auto *GV =
new llvm::GlobalVariable(
3669 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
3670 llvm::ConstantArray::get(ATy, UsedArray), Name);
3672 GV->setSection(
"llvm.metadata");
3675void CodeGenModule::emitLLVMUsed() {
3676 emitUsed(*
this,
"llvm.used", LLVMUsed);
3677 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
3682 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3691 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3697 ELFDependentLibraries.push_back(
3698 llvm::MDNode::get(
C, llvm::MDString::get(
C, Lib)));
3705 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
C, MDOpts));
3712void CodeGenModule::ProcessPragmaCommentCopyright(StringRef Comment,
3713 bool isFromASTFile) {
3715 "pragma comment copyright is supported only when targeting AIX");
3728 assert(!LoadTimeCommentGlobal &&
3729 "Only one copyright pragma allowed per translation unit.");
3734 uint64_t Hash = xxh3_64bits(Comment);
3735 std::string GlobalName =
3736 (
"__loadtime_comment_str_" + Twine::utohexstr(Hash)).str();
3739 llvm::Constant *StrInit =
3740 llvm::ConstantDataArray::getString(
C, Comment,
true);
3743 auto *GV =
new llvm::GlobalVariable(
getModule(), StrInit->getType(),
3745 llvm::GlobalValue::WeakODRLinkage,
3746 StrInit, GlobalName);
3748 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
3749 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3750 GV->setAlignment(llvm::Align(1));
3756 GV->setSection(
"__loadtime_comment");
3759 GV->setMetadata(
"loadtime_comment", llvm::MDNode::get(
C, {}));
3762 llvm::appendToCompilerUsed(
getModule(), {GV});
3764 LoadTimeCommentGlobal = GV;
3773 if (Mod->
Parent && Visited.insert(Mod->
Parent).second) {
3779 if (Visited.insert(Import).second)
3796 if (LL.IsFramework) {
3797 llvm::Metadata *Args[2] = {llvm::MDString::get(Context,
"-framework"),
3798 llvm::MDString::get(Context, LL.Library)};
3800 Metadata.push_back(llvm::MDNode::get(Context, Args));
3806 llvm::Metadata *Args[2] = {
3807 llvm::MDString::get(Context,
"lib"),
3808 llvm::MDString::get(Context, LL.Library),
3810 Metadata.push_back(llvm::MDNode::get(Context, Args));
3814 auto *OptString = llvm::MDString::get(Context, Opt);
3815 Metadata.push_back(llvm::MDNode::get(Context, OptString));
3820void CodeGenModule::EmitModuleInitializers(
clang::Module *Primary) {
3822 "We should only emit module initializers for named modules.");
3830 assert(
isa<VarDecl>(D) &&
"GMF initializer decl is not a var?");
3847 assert(
isa<VarDecl>(D) &&
"PMF initializer decl is not a var?");
3853void CodeGenModule::EmitModuleLinkOptions() {
3857 llvm::SetVector<clang::Module *> LinkModules;
3858 llvm::SmallPtrSet<clang::Module *, 16> Visited;
3859 SmallVector<clang::Module *, 16> Stack;
3862 for (
Module *M : ImportedModules) {
3865 if (M->getTopLevelModuleName() ==
getLangOpts().CurrentModule &&
3868 if (Visited.insert(M).second)
3874 while (!Stack.empty()) {
3877 bool AnyChildren =
false;
3886 if (Visited.insert(
SM).second) {
3887 Stack.push_back(
SM);
3895 LinkModules.insert(Mod);
3902 SmallVector<llvm::MDNode *, 16> MetadataArgs;
3904 for (
Module *M : LinkModules)
3905 if (Visited.insert(M).second)
3907 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
3908 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
3911 if (!LinkerOptionsMetadata.empty()) {
3912 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.linker.options");
3913 for (
auto *MD : LinkerOptionsMetadata)
3914 NMD->addOperand(MD);
3918void CodeGenModule::EmitDeferred() {
3927 if (!DeferredVTables.empty()) {
3928 EmitDeferredVTables();
3933 assert(DeferredVTables.empty());
3940 llvm::append_range(DeferredDeclsToEmit,
3944 if (DeferredDeclsToEmit.empty())
3949 std::vector<GlobalDecl> CurDeclsToEmit;
3950 CurDeclsToEmit.swap(DeferredDeclsToEmit);
3952 for (GlobalDecl &D : CurDeclsToEmit) {
3958 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>() &&
3962 if (!FD->
getAttr<SYCLKernelEntryPointAttr>()->isInvalidAttr()) {
3978 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
3996 if (!GV->isDeclaration())
4000 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
4004 EmitGlobalDefinition(D, GV);
4009 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
4011 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
4016void CodeGenModule::EmitVTablesOpportunistically() {
4022 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
4023 &&
"Only emit opportunistic vtables with optimizations");
4025 for (
const CXXRecordDecl *RD : OpportunisticVTables) {
4027 "This queue should only contain external vtables");
4028 if (
getCXXABI().canSpeculativelyEmitVTable(RD))
4029 VTables.GenerateClassData(RD);
4031 OpportunisticVTables.clear();
4035 for (
const auto& [MangledName, VD] : DeferredAnnotations) {
4040 DeferredAnnotations.clear();
4042 if (Annotations.empty())
4046 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
4047 Annotations[0]->
getType(), Annotations.size()), Annotations);
4048 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
4049 llvm::GlobalValue::AppendingLinkage,
4050 Array,
"llvm.global.annotations");
4055 llvm::Constant *&AStr = AnnotationStrings[Str];
4060 llvm::Constant *s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
4061 auto *gv =
new llvm::GlobalVariable(
4062 getModule(), s->getType(),
true, llvm::GlobalValue::PrivateLinkage, s,
4063 ".str",
nullptr, llvm::GlobalValue::NotThreadLocal,
4066 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4083 SM.getExpansionLineNumber(L);
4084 return llvm::ConstantInt::get(
Int32Ty, LineNo);
4092 llvm::FoldingSetNodeID ID;
4093 for (
Expr *E : Exprs) {
4096 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
4101 LLVMArgs.reserve(Exprs.size());
4103 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](
const Expr *E) {
4105 return ConstEmiter.
emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
4108 auto *
Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
4109 auto *GV =
new llvm::GlobalVariable(
getModule(),
Struct->getType(),
true,
4110 llvm::GlobalValue::PrivateLinkage,
Struct,
4113 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4120 const AnnotateAttr *AA,
4128 llvm::Constant *GVInGlobalsAS = GV;
4129 if (GV->getAddressSpace() !=
4131 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
4133 llvm::PointerType::get(
4134 GV->getContext(),
getDataLayout().getDefaultGlobalsAddressSpace()));
4138 llvm::Constant *Fields[] = {
4139 GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
4141 return llvm::ConstantStruct::getAnon(Fields);
4145 llvm::GlobalValue *GV) {
4146 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
4156 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
4159 auto &
SM = Context.getSourceManager();
4161 if (NoSanitizeL.containsMainFile(Kind, MainFile.
getName()))
4166 return NoSanitizeL.containsLocation(Kind, Loc);
4169 return NoSanitizeL.containsFile(Kind, MainFile.
getName());
4173 llvm::GlobalVariable *GV,
4175 StringRef Category)
const {
4177 if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
4179 auto &
SM = Context.getSourceManager();
4180 if (NoSanitizeL.containsMainFile(
4181 Kind,
SM.getFileEntryRefForID(
SM.getMainFileID())->getName(),
4184 if (NoSanitizeL.containsLocation(Kind, Loc, Category))
4191 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
4192 Ty = AT->getElementType();
4197 if (NoSanitizeL.containsType(Kind, TypeStr, Category))
4205 StringRef Category)
const {
4208 auto Attr = ImbueAttr::NONE;
4210 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
4211 if (
Attr == ImbueAttr::NONE)
4212 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
4214 case ImbueAttr::NONE:
4216 case ImbueAttr::ALWAYS:
4217 Fn->addFnAttr(
"function-instrument",
"xray-always");
4219 case ImbueAttr::ALWAYS_ARG1:
4220 Fn->addFnAttr(
"function-instrument",
"xray-always");
4221 Fn->addFnAttr(
"xray-log-args",
"1");
4223 case ImbueAttr::NEVER:
4224 Fn->addFnAttr(
"function-instrument",
"xray-never");
4237 llvm::driver::ProfileInstrKind Kind =
getCodeGenOpts().getProfileInstr();
4247 auto &
SM = Context.getSourceManager();
4248 if (
auto MainFile =
SM.getFileEntryRefForID(
SM.getMainFileID()))
4262 if (NumGroups > 1) {
4263 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
4272 if (LangOpts.EmitAllDecls)
4275 const auto *VD = dyn_cast<VarDecl>(
Global);
4277 ((CodeGenOpts.KeepPersistentStorageVariables &&
4278 (VD->getStorageDuration() ==
SD_Static ||
4279 VD->getStorageDuration() ==
SD_Thread)) ||
4280 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
4281 VD->getType().isConstQualified())))
4294 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
4295 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
4296 OMPDeclareTargetDeclAttr::getActiveAttr(
Global);
4297 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (
unsigned)-1)
4301 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
4311 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>())
4318 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
4319 if (Context.getInlineVariableDefinitionKind(VD) ==
4324 if (CXX20ModuleInits && VD->getOwningModule() &&
4325 !VD->getOwningModule()->isModuleMapModule()) {
4334 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
4337 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
Global))
4350 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
4354 llvm::Constant *
Init;
4357 if (!
V.isAbsent()) {
4368 llvm::Constant *Fields[4] = {
4372 llvm::ConstantDataArray::getRaw(
4373 StringRef(
reinterpret_cast<char *
>(Parts.
Part4And5), 8), 8,
4375 Init = llvm::ConstantStruct::getAnon(Fields);
4378 auto *GV =
new llvm::GlobalVariable(
4380 true, llvm::GlobalValue::LinkOnceODRLinkage,
Init, Name);
4382 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4385 if (!
V.isAbsent()) {
4398 llvm::GlobalVariable **Entry =
nullptr;
4399 Entry = &UnnamedGlobalConstantDeclMap[GCD];
4404 llvm::Constant *
Init;
4408 assert(!
V.isAbsent());
4412 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
4414 llvm::GlobalValue::PrivateLinkage,
Init,
4416 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4431 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
4435 llvm::Constant *
Init =
Emitter.emitForInitializer(
4443 llvm::GlobalValue::LinkageTypes
Linkage =
4445 ? llvm::GlobalValue::LinkOnceODRLinkage
4446 : llvm::GlobalValue::InternalLinkage;
4447 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
4451 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4458 const AliasAttr *AA = VD->
getAttr<AliasAttr>();
4459 assert(AA &&
"No alias?");
4469 llvm::Constant *Aliasee;
4471 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
4479 F->setLinkage(llvm::Function::ExternalWeakLinkage);
4480 WeakRefReferences.insert(F);
4488 if (
auto *A = D->
getAttr<AttrT>())
4489 return A->isImplicit();
4496 if (!LangOpts.OpenMPIsTargetDevice && !LangOpts.CUDA)
4499 const auto *AA =
Global->getAttr<AliasAttr>();
4507 const auto *AliaseeDecl = dyn_cast<ValueDecl>(AliaseeGD.getDecl());
4508 if (LangOpts.OpenMPIsTargetDevice)
4509 return !AliaseeDecl ||
4510 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(AliaseeDecl);
4513 const bool HasDeviceAttr =
Global->hasAttr<CUDADeviceAttr>();
4514 const bool AliaseeHasDeviceAttr =
4515 AliaseeDecl && AliaseeDecl->hasAttr<CUDADeviceAttr>();
4517 if (LangOpts.CUDAIsDevice)
4518 return !HasDeviceAttr || !AliaseeHasDeviceAttr;
4525bool CodeGenModule::shouldEmitCUDAGlobalVar(
const VarDecl *
Global)
const {
4526 assert(LangOpts.CUDA &&
"Should not be called by non-CUDA languages");
4531 return !LangOpts.CUDAIsDevice ||
Global->hasAttr<CUDADeviceAttr>() ||
4532 Global->hasAttr<CUDAConstantAttr>() ||
4533 Global->hasAttr<CUDASharedAttr>() ||
4534 Global->getType()->isCUDADeviceBuiltinSurfaceType() ||
4535 Global->getType()->isCUDADeviceBuiltinTextureType();
4542 if (
Global->hasAttr<WeakRefAttr>())
4547 if (
Global->hasAttr<AliasAttr>()) {
4550 return EmitAliasDefinition(GD);
4554 if (
Global->hasAttr<IFuncAttr>())
4555 return emitIFuncDefinition(GD);
4558 if (
Global->hasAttr<CPUDispatchAttr>())
4559 return emitCPUDispatchDefinition(GD);
4564 if (LangOpts.CUDA) {
4566 "Expected Variable or Function");
4567 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
4568 if (!shouldEmitCUDAGlobalVar(VD))
4570 }
else if (LangOpts.CUDAIsDevice) {
4571 const auto *FD = dyn_cast<FunctionDecl>(
Global);
4572 if ((!
Global->hasAttr<CUDADeviceAttr>() ||
4573 (LangOpts.OffloadImplicitHostDeviceTemplates &&
4577 !
getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
4578 !
Global->hasAttr<CUDAGlobalAttr>() &&
4580 !
Global->hasAttr<CUDAHostAttr>()))
4583 }
else if (!
Global->hasAttr<CUDAHostAttr>() &&
4584 Global->hasAttr<CUDADeviceAttr>())
4588 if (LangOpts.OpenMP) {
4590 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
4592 if (
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(
Global)) {
4593 if (MustBeEmitted(
Global))
4597 if (
auto *DMD = dyn_cast<OMPDeclareMapperDecl>(
Global)) {
4598 if (MustBeEmitted(
Global))
4605 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
4606 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
4612 if (FD->
hasAttr<AnnotateAttr>()) {
4615 DeferredAnnotations[MangledName] = FD;
4630 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
4636 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
4638 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
4639 if (LangOpts.OpenMP) {
4641 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
4642 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
4646 if (VD->hasExternalStorage() &&
4647 Res != OMPDeclareTargetDeclAttr::MT_Link)
4650 bool UnifiedMemoryEnabled =
4652 if (*Res == OMPDeclareTargetDeclAttr::MT_Local ||
4653 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4654 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4655 !UnifiedMemoryEnabled)) {
4658 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
4659 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4660 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4661 UnifiedMemoryEnabled)) &&
4662 "Link clause or to clause with unified memory expected.");
4672 if (LangOpts.HLSL) {
4673 if (VD->getStorageClass() ==
SC_Extern) {
4682 if (Context.getInlineVariableDefinitionKind(VD) ==
4692 if (MustBeEmitted(
Global) && MayBeEmittedEagerly(
Global)) {
4694 EmitGlobalDefinition(GD);
4695 addEmittedDeferredDecl(GD);
4703 DelayedCXXInitPosition[
Global] = CXXGlobalInits.size();
4704 CXXGlobalInits.push_back(
nullptr);
4710 addDeferredDeclToEmit(GD);
4711 }
else if (MustBeEmitted(
Global)) {
4713 assert(!MayBeEmittedEagerly(
Global));
4714 addDeferredDeclToEmit(GD);
4719 DeferredDecls[MangledName] = GD;
4725 if (
const auto *RT =
4726 T->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
4727 if (
auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
4728 RD = RD->getDefinitionOrSelf();
4729 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
4738struct DLLImportFunctionVisitor
4739 :
public RecursiveASTVisitor<DLLImportFunctionVisitor> {
4740 bool SafeToInline =
true;
4742 bool shouldVisitImplicitCode()
const {
return true; }
4744 bool VisitVarDecl(VarDecl *VD) {
4747 SafeToInline =
false;
4748 return SafeToInline;
4755 return SafeToInline;
4758 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
4760 SafeToInline = D->
hasAttr<DLLImportAttr>();
4761 return SafeToInline;
4764 bool VisitDeclRefExpr(DeclRefExpr *E) {
4767 SafeToInline = VD->
hasAttr<DLLImportAttr>();
4768 else if (VarDecl *
V = dyn_cast<VarDecl>(VD))
4769 SafeToInline = !
V->hasGlobalStorage() ||
V->hasAttr<DLLImportAttr>();
4770 return SafeToInline;
4773 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
4775 return SafeToInline;
4778 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4782 SafeToInline =
true;
4784 SafeToInline = M->
hasAttr<DLLImportAttr>();
4786 return SafeToInline;
4789 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
4791 return SafeToInline;
4794 bool VisitCXXNewExpr(CXXNewExpr *E) {
4796 return SafeToInline;
4801bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
4808 if (F->isInlineBuiltinDeclaration())
4811 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
4816 if (
const Module *M = F->getOwningModule();
4817 M && M->getTopLevelModule()->isNamedModule() &&
4818 getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
4828 if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
4833 if (F->hasAttr<NoInlineAttr>())
4836 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
4838 DLLImportFunctionVisitor Visitor;
4839 Visitor.TraverseFunctionDecl(
const_cast<FunctionDecl*
>(F));
4840 if (!Visitor.SafeToInline)
4843 if (
const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
4850 for (
const CXXBaseSpecifier &B :
Dtor->getParent()->bases())
4864bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
4865 return CodeGenOpts.OptimizationLevel > 0;
4868void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
4869 llvm::GlobalValue *GV) {
4873 auto *Spec = FD->
getAttr<CPUSpecificAttr>();
4874 for (
unsigned I = 0; I < Spec->cpus_size(); ++I)
4876 }
else if (
auto *TC = FD->
getAttr<TargetClonesAttr>()) {
4877 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I)
4878 if (TC->isFirstOfVersion(I))
4881 EmitGlobalFunctionDefinition(GD, GV);
4887 AddDeferredMultiVersionResolverToEmit(GD);
4889 GetOrCreateMultiVersionResolver(GD);
4893void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
4896 PrettyStackTraceDecl CrashInfo(
const_cast<ValueDecl *
>(D), D->
getLocation(),
4897 Context.getSourceManager(),
4898 "Generating code for declaration");
4900 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
4903 if (!shouldEmitFunction(GD))
4906 llvm::TimeTraceScope TimeScope(
"CodeGen Function", [&]() {
4908 llvm::raw_string_ostream
OS(Name);
4914 if (
const auto *
Method = dyn_cast<CXXMethodDecl>(D)) {
4918 ABI->emitCXXStructor(GD);
4920 EmitMultiVersionFunctionDefinition(GD, GV);
4922 EmitGlobalFunctionDefinition(GD, GV);
4931 return EmitMultiVersionFunctionDefinition(GD, GV);
4932 return EmitGlobalFunctionDefinition(GD, GV);
4935 if (
const auto *VD = dyn_cast<VarDecl>(D))
4936 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
4938 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
4942 llvm::Function *NewFn);
4958static llvm::GlobalValue::LinkageTypes
4962 return llvm::GlobalValue::InternalLinkage;
4963 return llvm::GlobalValue::WeakODRLinkage;
4966void CodeGenModule::emitMultiVersionFunctions() {
4967 std::vector<GlobalDecl> MVFuncsToEmit;
4968 MultiVersionFuncs.swap(MVFuncsToEmit);
4969 for (GlobalDecl GD : MVFuncsToEmit) {
4971 assert(FD &&
"Expected a FunctionDecl");
4973 auto createFunction = [&](
const FunctionDecl *
Decl,
unsigned MVIdx = 0) {
4974 GlobalDecl CurGD{
Decl->isDefined() ?
Decl->getDefinition() :
Decl, MVIdx};
4978 if (
Decl->isDefined()) {
4979 EmitGlobalFunctionDefinition(CurGD,
nullptr);
4987 assert(
Func &&
"This should have just been created");
4995 bool ShouldEmitResolver = !
getTriple().isAArch64();
4996 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
4997 llvm::DenseMap<llvm::Function *, const FunctionDecl *> DeclMap;
5000 FD, [&](
const FunctionDecl *CurFD) {
5001 llvm::SmallVector<StringRef, 8> Feats;
5004 if (
const auto *TA = CurFD->
getAttr<TargetAttr>()) {
5006 TA->getX86AddedFeatures(Feats);
5007 llvm::Function *
Func = createFunction(CurFD);
5008 DeclMap.insert({
Func, CurFD});
5009 Options.emplace_back(
Func, Feats, TA->getX86Architecture());
5010 }
else if (
const auto *TVA = CurFD->
getAttr<TargetVersionAttr>()) {
5011 if (TVA->isDefaultVersion() && IsDefined)
5012 ShouldEmitResolver =
true;
5013 llvm::Function *
Func = createFunction(CurFD);
5014 DeclMap.insert({
Func, CurFD});
5016 TVA->getFeatures(Feats, Delim);
5017 Options.emplace_back(
Func, Feats);
5018 }
else if (
const auto *TC = CurFD->
getAttr<TargetClonesAttr>()) {
5019 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
5020 if (!TC->isFirstOfVersion(I))
5022 if (TC->isDefaultVersion(I) && IsDefined)
5023 ShouldEmitResolver =
true;
5024 llvm::Function *
Func = createFunction(CurFD, I);
5025 DeclMap.insert({
Func, CurFD});
5028 TC->getX86Feature(Feats, I);
5029 Options.emplace_back(
Func, Feats, TC->getX86Architecture(I));
5032 TC->getFeatures(Feats, I, Delim);
5033 Options.emplace_back(
Func, Feats);
5037 llvm_unreachable(
"unexpected MultiVersionKind");
5040 if (!ShouldEmitResolver)
5043 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
5044 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
5045 ResolverConstant = IFunc->getResolver();
5050 *
this, GD, FD,
true);
5057 auto *Alias = llvm::GlobalAlias::create(
5059 MangledName +
".ifunc", IFunc, &
getModule());
5068 Options, [&TI](
const CodeGenFunction::FMVResolverOption &LHS,
5069 const CodeGenFunction::FMVResolverOption &RHS) {
5075 for (
auto I = Options.begin() + 1, E = Options.end(); I != E; ++I) {
5076 llvm::APInt RHS = llvm::AArch64::getCpuSupportsMask(I->Features);
5077 if (std::any_of(Options.begin(), I, [RHS](
auto RO) {
5078 llvm::APInt LHS = llvm::AArch64::getCpuSupportsMask(RO.Features);
5079 return LHS.isSubsetOf(RHS);
5081 Diags.Report(DeclMap[I->Function]->getLocation(),
5082 diag::warn_unreachable_version)
5083 << I->Function->getName();
5084 assert(I->Function->user_empty() &&
"unexpected users");
5085 I->Function->eraseFromParent();
5086 I->Function =
nullptr;
5090 CodeGenFunction CGF(*
this);
5091 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
5093 setMultiVersionResolverAttributes(ResolverFunc, GD);
5095 ResolverFunc->setComdat(
5096 getModule().getOrInsertComdat(ResolverFunc->getName()));
5102 if (!MVFuncsToEmit.empty())
5107 if (!MultiVersionFuncs.empty())
5108 emitMultiVersionFunctions();
5118 llvm::GlobalValue *DS = TheModule.getNamedValue(DSName);
5120 DS =
new llvm::GlobalVariable(TheModule,
Int8Ty,
false,
5121 llvm::GlobalVariable::ExternalWeakLinkage,
5123 DS->setVisibility(llvm::GlobalValue::HiddenVisibility);
5128void CodeGenModule::emitPFPFieldsWithEvaluatedOffset() {
5129 llvm::Constant *Nop = llvm::ConstantExpr::getIntToPtr(
5131 for (
auto *FD :
getContext().PFPFieldsWithEvaluatedOffset) {
5133 llvm::GlobalValue *OldDS = TheModule.getNamedValue(DSName);
5134 llvm::GlobalValue *DS = llvm::GlobalAlias::create(
5135 Int8Ty, 0, llvm::GlobalValue::ExternalLinkage, DSName, Nop, &TheModule);
5136 DS->setVisibility(llvm::GlobalValue::HiddenVisibility);
5138 DS->takeName(OldDS);
5139 OldDS->replaceAllUsesWith(DS);
5140 OldDS->eraseFromParent();
5146 llvm::Constant *
New) {
5149 Old->replaceAllUsesWith(
New);
5150 Old->eraseFromParent();
5153void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
5155 assert(FD &&
"Not a FunctionDecl?");
5157 const auto *DD = FD->
getAttr<CPUDispatchAttr>();
5158 assert(DD &&
"Not a cpu_dispatch Function?");
5164 UpdateMultiVersionNames(GD, FD, ResolverName);
5166 llvm::Type *ResolverType;
5167 GlobalDecl ResolverGD;
5169 ResolverType = llvm::FunctionType::get(
5180 ResolverName, ResolverType, ResolverGD,
false));
5183 ResolverFunc->setComdat(
5184 getModule().getOrInsertComdat(ResolverFunc->getName()));
5186 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
5189 for (
const IdentifierInfo *II : DD->cpus()) {
5197 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
5200 EmitGlobalFunctionDefinition(ExistingDecl,
nullptr);
5206 Func = GetOrCreateLLVMFunction(
5207 MangledName, DeclTy, ExistingDecl,
5213 llvm::SmallVector<StringRef, 32> Features;
5214 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
5215 llvm::transform(Features, Features.begin(),
5216 [](StringRef Str) { return Str.substr(1); });
5217 llvm::erase_if(Features, [&Target](StringRef Feat) {
5218 return !Target.validateCpuSupports(Feat);
5224 llvm::stable_sort(Options, [](
const CodeGenFunction::FMVResolverOption &LHS,
5225 const CodeGenFunction::FMVResolverOption &RHS) {
5226 return llvm::X86::getCpuSupportsMask(LHS.
Features) >
5227 llvm::X86::getCpuSupportsMask(RHS.
Features);
5234 while (Options.size() > 1 && llvm::all_of(llvm::X86::getCpuSupportsMask(
5235 (Options.end() - 2)->Features),
5236 [](
auto X) { return X == 0; })) {
5237 StringRef LHSName = (Options.end() - 2)->Function->getName();
5238 StringRef RHSName = (Options.end() - 1)->Function->getName();
5239 if (LHSName.compare(RHSName) < 0)
5240 Options.erase(Options.end() - 2);
5242 Options.erase(Options.end() - 1);
5245 CodeGenFunction CGF(*
this);
5246 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
5247 setMultiVersionResolverAttributes(ResolverFunc, GD);
5252 unsigned AS = IFunc->getType()->getPointerAddressSpace();
5257 auto *GI = llvm::GlobalIFunc::create(DeclTy, AS,
Linkage,
"",
5264 *
this, GD, FD,
true);
5267 auto *GA = llvm::GlobalAlias::create(DeclTy, AS,
Linkage, AliasName,
5275void CodeGenModule::AddDeferredMultiVersionResolverToEmit(GlobalDecl GD) {
5277 assert(FD &&
"Not a FunctionDecl?");
5280 std::string MangledName =
5282 if (!DeferredResolversToEmit.insert(MangledName).second)
5285 MultiVersionFuncs.push_back(GD);
5291llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
5293 assert(FD &&
"Not a FunctionDecl?");
5295 std::string MangledName =
5300 std::string ResolverName = MangledName;
5304 llvm_unreachable(
"unexpected MultiVersionKind::None for resolver");
5308 ResolverName +=
".ifunc";
5315 ResolverName +=
".resolver";
5318 bool ShouldReturnIFunc =
5337 AddDeferredMultiVersionResolverToEmit(GD);
5341 if (ShouldReturnIFunc) {
5343 llvm::Type *ResolverType = llvm::FunctionType::get(
5345 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
5346 MangledName +
".resolver", ResolverType, GlobalDecl{},
5354 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(DeclTy, AS,
Linkage,
"",
5356 GIF->setName(ResolverName);
5363 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
5364 ResolverName, DeclTy, GlobalDecl{},
false);
5366 "Resolver should be created for the first time");
5371void CodeGenModule::setMultiVersionResolverAttributes(llvm::Function *Resolver,
5373 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(GD.
getDecl());
5386 Resolver->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
5397bool CodeGenModule::shouldDropDLLAttribute(
const Decl *D,
5398 const llvm::GlobalValue *GV)
const {
5399 auto SC = GV->getDLLStorageClass();
5400 if (SC == llvm::GlobalValue::DefaultStorageClass)
5403 return (((SC == llvm::GlobalValue::DLLImportStorageClass &&
5404 !MRD->
hasAttr<DLLImportAttr>()) ||
5405 (SC == llvm::GlobalValue::DLLExportStorageClass &&
5406 !MRD->
hasAttr<DLLExportAttr>())) &&
5417llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
5418 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD,
bool ForVTable,
5419 bool DontDefer,
bool IsThunk, llvm::AttributeList ExtraAttrs,
5423 std::string NameWithoutMultiVersionMangling;
5424 if (
const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
5426 if (
getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
5427 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->
isDefined() &&
5428 !DontDefer && !IsForDefinition) {
5431 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
5433 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
5436 GDDef = GlobalDecl(FDDef);
5444 UpdateMultiVersionNames(GD, FD, MangledName);
5445 if (!IsForDefinition) {
5451 AddDeferredMultiVersionResolverToEmit(GD);
5453 *
this, GD, FD,
true);
5462 *
this, GD, FD,
true);
5464 return GetOrCreateMultiVersionResolver(GD);
5469 if (!NameWithoutMultiVersionMangling.empty())
5470 MangledName = NameWithoutMultiVersionMangling;
5475 if (WeakRefReferences.erase(Entry)) {
5476 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
5477 if (FD && !FD->
hasAttr<WeakAttr>())
5478 Entry->setLinkage(llvm::Function::ExternalLinkage);
5482 if (D && shouldDropDLLAttribute(D, Entry)) {
5483 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5489 if (IsForDefinition && !Entry->isDeclaration()) {
5496 DiagnosedConflictingDefinitions.insert(GD).second) {
5500 diag::note_previous_definition);
5505 (Entry->getValueType() == Ty)) {
5512 if (!IsForDefinition)
5519 bool IsIncompleteFunction =
false;
5521 llvm::FunctionType *FTy;
5525 FTy = llvm::FunctionType::get(
VoidTy,
false);
5526 IsIncompleteFunction =
true;
5530 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
5531 Entry ? StringRef() : MangledName, &
getModule());
5535 if (D && D->
hasAttr<AnnotateAttr>())
5553 if (!Entry->use_empty()) {
5555 Entry->removeDeadConstantUsers();
5561 assert(F->getName() == MangledName &&
"name was uniqued!");
5563 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
5564 if (ExtraAttrs.hasFnAttrs()) {
5565 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
5573 if (isa_and_nonnull<CXXDestructorDecl>(D) &&
5576 addDeferredDeclToEmit(GD);
5581 auto DDI = DeferredDecls.find(MangledName);
5582 if (DDI != DeferredDecls.end()) {
5586 addDeferredDeclToEmit(DDI->second);
5587 DeferredDecls.erase(DDI);
5615 if (!IsIncompleteFunction) {
5616 assert(F->getFunctionType() == Ty);
5634 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
5644 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(GD.
getDecl())) {
5647 DD->getParent()->getNumVBases() == 0)
5652 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
5653 false, llvm::AttributeList(),
5656 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
5660 if (IsForDefinition)
5668 llvm::GlobalValue *F =
5671 return llvm::NoCFIValue::get(F);
5681 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
5684 if (!
C.getLangOpts().CPlusPlus)
5689 (Name ==
"_ZSt9terminatev" || Name ==
"?terminate@@YAXXZ")
5690 ?
C.Idents.get(
"terminate")
5691 :
C.Idents.get(Name);
5693 for (
const auto &N : {
"__cxxabiv1",
"std"}) {
5697 if (
auto *LSD = dyn_cast<LinkageSpecDecl>(
Result))
5698 for (
const auto *
Result : LSD->lookup(&NS))
5699 if ((ND = dyn_cast<NamespaceDecl>(
Result)))
5704 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
5713 llvm::Function *F, StringRef Name) {
5719 if (!Local && CGM.
getTriple().isWindowsItaniumEnvironment() &&
5722 if (!FD || FD->
hasAttr<DLLImportAttr>()) {
5723 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
5724 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
5731 llvm::AttributeList ExtraAttrs,
bool Local,
bool AssumeConvergent) {
5732 if (AssumeConvergent) {
5734 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5737 QualType FTy = Context.getFunctionType(ReturnTy, ArgTys,
5742 llvm::Constant *
C = GetOrCreateLLVMFunction(
5744 false,
false, ExtraAttrs);
5746 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
5762 llvm::AttributeList ExtraAttrs,
bool Local,
5763 bool AssumeConvergent) {
5764 if (AssumeConvergent) {
5766 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5770 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
5774 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
5783 markRegisterParameterAttributes(F);
5809 if (WeakRefReferences.erase(Entry)) {
5810 if (D && !D->
hasAttr<WeakAttr>())
5811 Entry->setLinkage(llvm::Function::ExternalLinkage);
5815 if (D && shouldDropDLLAttribute(D, Entry))
5816 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5818 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
5821 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
5826 if (IsForDefinition && !Entry->isDeclaration()) {
5834 (OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
5836 DiagnosedConflictingDefinitions.insert(D).second) {
5840 diag::note_previous_definition);
5845 if (Entry->getType()->getAddressSpace() != TargetAS)
5846 return llvm::ConstantExpr::getAddrSpaceCast(
5847 Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
5851 if (!IsForDefinition)
5857 auto *GV =
new llvm::GlobalVariable(
5858 getModule(), Ty,
false, llvm::GlobalValue::ExternalLinkage,
nullptr,
5859 MangledName,
nullptr, llvm::GlobalVariable::NotThreadLocal,
5860 getContext().getTargetAddressSpace(DAddrSpace));
5865 GV->takeName(Entry);
5867 if (!Entry->use_empty()) {
5868 Entry->replaceAllUsesWith(GV);
5871 Entry->eraseFromParent();
5877 auto DDI = DeferredDecls.find(MangledName);
5878 if (DDI != DeferredDecls.end()) {
5881 addDeferredDeclToEmit(DDI->second);
5882 DeferredDecls.erase(DDI);
5887 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
5894 GV->setAlignment(
getContext().getDeclAlign(D).getAsAlign());
5900 CXXThreadLocals.push_back(D);
5908 if (
getContext().isMSStaticDataMemberInlineDefinition(D)) {
5909 EmitGlobalVarDefinition(D);
5914 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>())
5915 GV->setSection(SA->getName());
5919 if (
getTriple().getArch() == llvm::Triple::xcore &&
5923 GV->setSection(
".cp.rodata");
5926 if (
const auto *CMA = D->
getAttr<CodeModelAttr>())
5927 GV->setCodeModel(CMA->getModel());
5932 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
5936 Context.getBaseElementType(D->
getType())->getAsCXXRecordDecl();
5937 bool HasMutableFields =
Record &&
Record->hasMutableFields();
5938 if (!HasMutableFields) {
5945 auto *InitType =
Init->getType();
5946 if (GV->getValueType() != InitType) {
5951 GV->setName(StringRef());
5956 ->stripPointerCasts());
5959 GV->eraseFromParent();
5962 GV->setInitializer(
Init);
5963 GV->setConstant(
true);
5964 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
5984 SanitizerMD->reportGlobal(GV, *D);
5989 assert(
getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
5990 if (DAddrSpace != ExpectedAS)
6003 false, IsForDefinition);
6024 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes
Linkage,
6025 llvm::Align Alignment) {
6026 llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
6027 llvm::GlobalVariable *OldGV =
nullptr;
6031 if (GV->getValueType() == Ty)
6036 assert(GV->isDeclaration() &&
"Declaration has wrong type!");
6041 GV =
new llvm::GlobalVariable(
getModule(), Ty,
true,
6046 GV->takeName(OldGV);
6048 if (!OldGV->use_empty()) {
6049 OldGV->replaceAllUsesWith(GV);
6052 OldGV->eraseFromParent();
6056 !GV->hasAvailableExternallyLinkage())
6057 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
6059 GV->setAlignment(Alignment);
6096 assert(!D->
getInit() &&
"Cannot emit definite definitions here!");
6104 if (GV && !GV->isDeclaration())
6109 if (!MustBeEmitted(D) && !GV) {
6110 DeferredDecls[MangledName] = D;
6115 EmitGlobalVarDefinition(D);
6120 if (
auto const *CD = dyn_cast<const CXXConstructorDecl>(D))
6122 else if (
auto const *DD = dyn_cast<const CXXDestructorDecl>(D))
6137 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(
Addr)) {
6141 if (
const auto *VD = dyn_cast<VarDecl>(D)) {
6144 }
else if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
6146 if (!Fn->getSubprogram())
6152 return Context.toCharUnitsFromBits(
6157 if (LangOpts.OpenCL) {
6168 if (LangOpts.SYCLIsDevice &&
6172 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
6174 if (D->
hasAttr<CUDAConstantAttr>())
6176 if (D->
hasAttr<CUDASharedAttr>())
6178 if (D->
hasAttr<CUDADeviceAttr>())
6186 if (LangOpts.OpenMP) {
6188 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
6196 if (LangOpts.OpenCL)
6198 if (LangOpts.SYCLIsDevice)
6200 if (LangOpts.HIP && LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())
6208 if (
auto AS =
getTarget().getConstantAddressSpace())
6221static llvm::Constant *
6223 llvm::GlobalVariable *GV) {
6224 llvm::Constant *Cast = GV;
6229 GV, llvm::PointerType::get(
6236template<
typename SomeDecl>
6238 llvm::GlobalValue *GV) {
6253 const SomeDecl *
First = D->getFirstDecl();
6254 if (
First->getDeclContext()->isRecord() || !
First->isInExternCContext())
6260 std::pair<StaticExternCMap::iterator, bool> R =
6261 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
6266 R.first->second =
nullptr;
6273 if (D.
hasAttr<SelectAnyAttr>())
6277 if (
auto *VD = dyn_cast<VarDecl>(&D))
6291 llvm_unreachable(
"No such linkage");
6299 llvm::GlobalObject &GO) {
6302 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
6310void CodeGenModule::EmitGlobalVarDefinition(
const VarDecl *D,
6325 if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
6326 OpenMPRuntime->emitTargetGlobalVariable(D))
6329 llvm::TrackingVH<llvm::Constant>
Init;
6330 bool NeedsGlobalCtor =
false;
6334 bool IsDefinitionAvailableExternally =
6336 bool NeedsGlobalDtor =
6337 !IsDefinitionAvailableExternally &&
6344 if (IsDefinitionAvailableExternally &&
6355 std::optional<ConstantEmitter> emitter;
6360 bool IsCUDASharedVar =
6365 bool IsCUDAShadowVar =
6367 (D->
hasAttr<CUDAConstantAttr>() || D->
hasAttr<CUDADeviceAttr>() ||
6368 D->
hasAttr<CUDASharedAttr>());
6369 bool IsCUDADeviceShadowVar =
6374 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) {
6375 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
6379 Init = llvm::PoisonValue::get(
getTypes().ConvertType(ASTTy));
6382 }
else if (D->
hasAttr<LoaderUninitializedAttr>()) {
6383 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
6384 }
else if (!InitExpr) {
6397 initializedGlobalDecl = GlobalDecl(D);
6398 emitter.emplace(*
this);
6399 llvm::Constant *
Initializer = emitter->tryEmitForInitializer(*InitDecl);
6401 QualType T = InitExpr->
getType();
6407 if (!IsDefinitionAvailableExternally)
6408 NeedsGlobalCtor =
true;
6412 NeedsGlobalCtor =
false;
6416 Init = llvm::PoisonValue::get(
getTypes().ConvertType(T));
6424 DelayedCXXInitPosition.erase(D);
6431 assert(VarSize == CstSize &&
"Emitted constant has unexpected size");
6436 llvm::Type* InitType =
Init->getType();
6437 llvm::Constant *Entry =
6441 Entry = Entry->stripPointerCasts();
6444 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
6455 if (!GV || GV->getValueType() != InitType ||
6456 GV->getType()->getAddressSpace() !=
6460 Entry->setName(StringRef());
6465 ->stripPointerCasts());
6468 llvm::Constant *NewPtrForOldDecl =
6469 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
6471 Entry->replaceAllUsesWith(NewPtrForOldDecl);
6479 if (D->
hasAttr<AnnotateAttr>())
6492 if (LangOpts.CUDA) {
6493 if (LangOpts.CUDAIsDevice) {
6496 (D->
hasAttr<CUDADeviceAttr>() || D->
hasAttr<CUDAConstantAttr>() ||
6499 GV->setExternallyInitialized(
true);
6506 if (LangOpts.HLSL &&
6511 GV->setExternallyInitialized(
true);
6513 GV->setInitializer(
Init);
6520 emitter->finalize(GV);
6523 GV->setConstant((D->
hasAttr<CUDAConstantAttr>() && LangOpts.CUDAIsDevice) ||
6524 (!NeedsGlobalCtor && !NeedsGlobalDtor &&
6528 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>()) {
6529 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
6531 GV->setConstant(
true);
6536 if (std::optional<CharUnits> AlignValFromAllocate =
6538 AlignVal = *AlignValFromAllocate;
6556 Linkage == llvm::GlobalValue::ExternalLinkage &&
6557 Context.getTargetInfo().getTriple().isOSDarwin() &&
6559 Linkage = llvm::GlobalValue::InternalLinkage;
6564 if (LangOpts.HLSL &&
6566 Linkage = llvm::GlobalValue::ExternalLinkage;
6569 if (D->
hasAttr<DLLImportAttr>())
6570 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
6571 else if (D->
hasAttr<DLLExportAttr>())
6572 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
6574 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6576 if (
Linkage == llvm::GlobalVariable::CommonLinkage) {
6578 GV->setConstant(
false);
6583 if (!GV->getInitializer()->isNullValue())
6584 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
6587 setNonAliasAttributes(D, GV);
6589 if (D->
getTLSKind() && !GV->isThreadLocal()) {
6591 CXXThreadLocals.push_back(D);
6598 if (NeedsGlobalCtor || NeedsGlobalDtor)
6599 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
6601 SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
6606 DI->EmitGlobalVariable(GV, D);
6614 if ((NoCommon || D->
hasAttr<NoCommonAttr>()) && !D->
hasAttr<CommonAttr>())
6625 if (D->
hasAttr<SectionAttr>())
6631 if (D->
hasAttr<PragmaClangBSSSectionAttr>() ||
6632 D->
hasAttr<PragmaClangDataSectionAttr>() ||
6633 D->
hasAttr<PragmaClangRelroSectionAttr>() ||
6634 D->
hasAttr<PragmaClangRodataSectionAttr>())
6642 if (D->
hasAttr<WeakImportAttr>())
6651 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6652 if (D->
hasAttr<AlignedAttr>())
6655 if (Context.isAlignmentRequired(VarType))
6659 for (
const FieldDecl *FD : RD->fields()) {
6660 if (FD->isBitField())
6662 if (FD->
hasAttr<AlignedAttr>())
6664 if (Context.isAlignmentRequired(FD->
getType()))
6676 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
6677 Context.getTypeAlignIfKnown(D->
getType()) >
6684llvm::GlobalValue::LinkageTypes
6688 return llvm::Function::InternalLinkage;
6691 return llvm::GlobalVariable::WeakAnyLinkage;
6695 return llvm::GlobalVariable::LinkOnceAnyLinkage;
6700 return llvm::GlobalValue::AvailableExternallyLinkage;
6714 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
6715 : llvm::Function::InternalLinkage;
6729 return llvm::Function::ExternalLinkage;
6732 return D->
hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
6733 : llvm::Function::InternalLinkage;
6734 return llvm::Function::WeakODRLinkage;
6741 CodeGenOpts.NoCommon))
6742 return llvm::GlobalVariable::CommonLinkage;
6748 if (D->
hasAttr<SelectAnyAttr>())
6749 return llvm::GlobalVariable::WeakODRLinkage;
6753 return llvm::GlobalVariable::ExternalLinkage;
6756llvm::GlobalValue::LinkageTypes
6765 llvm::Function *newFn) {
6767 if (old->use_empty())
6770 llvm::Type *newRetTy = newFn->getReturnType();
6775 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
6777 llvm::User *user = ui->getUser();
6781 if (
auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
6782 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
6788 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
6791 if (!callSite->isCallee(&*ui))
6796 if (callSite->getType() != newRetTy && !callSite->use_empty())
6801 llvm::AttributeList oldAttrs = callSite->getAttributes();
6804 unsigned newNumArgs = newFn->arg_size();
6805 if (callSite->arg_size() < newNumArgs)
6811 bool dontTransform =
false;
6812 for (llvm::Argument &A : newFn->args()) {
6813 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
6814 dontTransform =
true;
6819 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
6827 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
6831 callSite->getOperandBundlesAsDefs(newBundles);
6833 llvm::CallBase *newCall;
6835 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles,
"",
6836 callSite->getIterator());
6839 newCall = llvm::InvokeInst::Create(
6840 newFn, oldInvoke->getNormalDest(), oldInvoke->getUnwindDest(),
6841 newArgs, newBundles,
"", callSite->getIterator());
6845 if (!newCall->getType()->isVoidTy())
6846 newCall->takeName(callSite);
6847 newCall->setAttributes(
6848 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
6849 oldAttrs.getRetAttrs(), newArgAttrs));
6850 newCall->setCallingConv(callSite->getCallingConv());
6853 if (!callSite->use_empty())
6854 callSite->replaceAllUsesWith(newCall);
6857 if (callSite->getDebugLoc())
6858 newCall->setDebugLoc(callSite->getDebugLoc());
6860 callSitesToBeRemovedFromParent.push_back(callSite);
6863 for (
auto *callSite : callSitesToBeRemovedFromParent) {
6864 callSite->eraseFromParent();
6878 llvm::Function *NewFn) {
6888 (LangOpts.CUDA && !shouldEmitCUDAGlobalVar(VD)))
6900void CodeGenModule::EmitGlobalFunctionDefinition(
GlobalDecl GD,
6901 llvm::GlobalValue *GV) {
6909 if (!GV || (GV->getValueType() != Ty))
6915 if (!GV->isDeclaration())
6925 if (
getTriple().isOSAIX() && D->isTargetClonesMultiVersion())
6926 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
6938 setNonAliasAttributes(GD, Fn);
6940 bool ShouldAddOptNone = !CodeGenOpts.DisableO0ImplyOptNone &&
6941 (CodeGenOpts.OptimizationLevel == 0) &&
6944 if (DeviceKernelAttr::isOpenCLSpelling(D->
getAttr<DeviceKernelAttr>())) {
6946 !D->
hasAttr<NoInlineAttr>() &&
6947 !Fn->hasFnAttribute(llvm::Attribute::NoInline) &&
6948 !D->
hasAttr<OptimizeNoneAttr>() &&
6949 !Fn->hasFnAttribute(llvm::Attribute::OptimizeNone) &&
6950 !ShouldAddOptNone) {
6951 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
6961 auto UnwindMode = CodeGenOpts.getWinX64EHUnwind();
6962 if (UnwindMode != llvm::WinX64EHUnwindMode::Default &&
6963 UnwindMode != llvm::WinX64EHUnwindMode::V3 &&
6964 Fn->needsUnwindTableEntry()) {
6965 bool HasEGPR =
false;
6966 if (Fn->hasFnAttribute(
"target-features")) {
6968 Fn->getFnAttribute(
"target-features").getValueAsString();
6970 Feats.split(Tokens,
',', -1,
false);
6971 for (StringRef
Tok : Tokens) {
6974 else if (
Tok ==
"-egpr")
6978 HasEGPR = Context.getTargetInfo().hasFeature(
"egpr");
6981 unsigned DiagID = Diags.getCustomDiagID(
6983 "EGPR target feature requires unwind version 3");
6989 auto GetPriority = [
this](
const auto *Attr) ->
int {
6990 Expr *E = Attr->getPriority();
6994 return Attr->DefaultPriority;
6997 if (
const ConstructorAttr *CA = D->
getAttr<ConstructorAttr>())
6999 if (
const DestructorAttr *DA = D->
getAttr<DestructorAttr>())
7005void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
7007 const AliasAttr *AA = D->
getAttr<AliasAttr>();
7008 assert(AA &&
"Not an alias?");
7012 if (AA->getAliasee() == MangledName) {
7013 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
7020 if (Entry && !Entry->isDeclaration())
7023 Aliases.push_back(GD);
7029 llvm::Constant *Aliasee;
7030 llvm::GlobalValue::LinkageTypes
LT;
7032 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
7038 if (
const auto *VD = dyn_cast<VarDecl>(GD.
getDecl()))
7045 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
7047 llvm::GlobalAlias::create(DeclTy, AS, LT,
"", Aliasee, &
getModule());
7050 if (GA->getAliasee() == Entry) {
7051 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
7055 assert(Entry->isDeclaration());
7064 GA->takeName(Entry);
7066 Entry->replaceAllUsesWith(GA);
7067 Entry->eraseFromParent();
7069 GA->setName(MangledName);
7077 GA->setLinkage(llvm::Function::WeakAnyLinkage);
7080 if (
const auto *VD = dyn_cast<VarDecl>(D))
7081 if (VD->getTLSKind())
7092void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
7094 const IFuncAttr *IFA = D->
getAttr<IFuncAttr>();
7095 assert(IFA &&
"Not an ifunc?");
7099 if (IFA->getResolver() == MangledName) {
7100 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
7106 if (Entry && !Entry->isDeclaration()) {
7109 DiagnosedConflictingDefinitions.insert(GD).second) {
7110 Diags.Report(D->
getLocation(), diag::err_duplicate_mangled_name)
7113 diag::note_previous_definition);
7118 Aliases.push_back(GD);
7124 llvm::Constant *Resolver =
7125 GetOrCreateLLVMFunction(IFA->getResolver(),
VoidTy, {},
7129 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
7130 DeclTy, AS, llvm::Function::ExternalLinkage,
"", Resolver, &
getModule());
7132 if (GIF->getResolver() == Entry) {
7133 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
7136 assert(Entry->isDeclaration());
7145 GIF->takeName(Entry);
7147 Entry->replaceAllUsesWith(GIF);
7148 Entry->eraseFromParent();
7150 GIF->setName(MangledName);
7156 return llvm::Intrinsic::getOrInsertDeclaration(&
getModule(),
7157 (llvm::Intrinsic::ID)IID, Tys);
7160static llvm::StringMapEntry<llvm::GlobalVariable *> &
7163 bool &IsUTF16,
unsigned &StringLength) {
7164 StringRef String = Literal->getString();
7165 unsigned NumBytes = String.size();
7168 if (!Literal->containsNonAsciiOrNull()) {
7169 StringLength = NumBytes;
7170 return *Map.insert(std::make_pair(String,
nullptr)).first;
7177 const llvm::UTF8 *FromPtr = (
const llvm::UTF8 *)String.data();
7178 llvm::UTF16 *ToPtr = &ToBuf[0];
7180 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
7181 ToPtr + NumBytes, llvm::strictConversion);
7184 StringLength = ToPtr - &ToBuf[0];
7188 return *Map.insert(std::make_pair(
7189 StringRef(
reinterpret_cast<const char *
>(ToBuf.data()),
7190 (StringLength + 1) * 2),
7196 unsigned StringLength = 0;
7197 bool isUTF16 =
false;
7198 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
7203 if (
auto *
C = Entry.second)
7208 const llvm::Triple &Triple =
getTriple();
7211 const bool IsSwiftABI =
7212 static_cast<unsigned>(CFRuntime) >=
7217 if (!CFConstantStringClassRef) {
7218 const char *CFConstantStringClassName =
"__CFConstantStringClassReference";
7220 Ty = llvm::ArrayType::get(Ty, 0);
7222 switch (CFRuntime) {
7226 CFConstantStringClassName =
7227 Triple.isOSDarwin() ?
"$s15SwiftFoundation19_NSCFConstantStringCN"
7228 :
"$s10Foundation19_NSCFConstantStringCN";
7232 CFConstantStringClassName =
7233 Triple.isOSDarwin() ?
"$S15SwiftFoundation19_NSCFConstantStringCN"
7234 :
"$S10Foundation19_NSCFConstantStringCN";
7238 CFConstantStringClassName =
7239 Triple.isOSDarwin() ?
"__T015SwiftFoundation19_NSCFConstantStringCN"
7240 :
"__T010Foundation19_NSCFConstantStringCN";
7247 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
7248 llvm::GlobalValue *GV =
nullptr;
7250 if ((GV = dyn_cast<llvm::GlobalValue>(
C))) {
7257 if ((VD = dyn_cast<VarDecl>(
Result)))
7260 if (Triple.isOSBinFormatELF()) {
7262 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
7264 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
7265 if (!VD || !VD->
hasAttr<DLLExportAttr>())
7266 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
7268 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
7276 CFConstantStringClassRef =
7277 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(
C, Ty) :
C;
7280 QualType CFTy = Context.getCFConstantStringType();
7285 auto Fields = Builder.beginStruct(STy);
7294 Fields.addInt(
IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
7295 Fields.addInt(
Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
7297 Fields.addInt(
IntTy, isUTF16 ? 0x07d0 : 0x07C8);
7301 llvm::Constant *
C =
nullptr;
7304 reinterpret_cast<uint16_t *
>(
const_cast<char *
>(Entry.first().data())),
7305 Entry.first().size() / 2);
7306 C = llvm::ConstantDataArray::get(VMContext, Arr);
7308 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
7314 new llvm::GlobalVariable(
getModule(),
C->getType(),
true,
7315 llvm::GlobalValue::PrivateLinkage,
C,
".str");
7316 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
7319 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
7320 : Context.getTypeAlignInChars(Context.CharTy);
7326 if (Triple.isOSBinFormatMachO())
7327 GV->setSection(isUTF16 ?
"__TEXT,__ustring"
7328 :
"__TEXT,__cstring,cstring_literals");
7331 else if (Triple.isOSBinFormatELF())
7332 GV->setSection(
".rodata");
7338 llvm::IntegerType *LengthTy =
7348 Fields.addInt(LengthTy, StringLength);
7356 GV = Fields.finishAndCreateGlobal(
"_unnamed_cfstring_", Alignment,
7358 llvm::GlobalVariable::PrivateLinkage);
7359 GV->addAttribute(
"objc_arc_inert");
7360 switch (Triple.getObjectFormat()) {
7361 case llvm::Triple::UnknownObjectFormat:
7362 llvm_unreachable(
"unknown file format");
7363 case llvm::Triple::DXContainer:
7364 case llvm::Triple::GOFF:
7365 case llvm::Triple::SPIRV:
7366 case llvm::Triple::XCOFF:
7367 llvm_unreachable(
"unimplemented");
7368 case llvm::Triple::COFF:
7369 case llvm::Triple::ELF:
7370 case llvm::Triple::Wasm:
7371 GV->setSection(
"cfstring");
7373 case llvm::Triple::MachO:
7374 GV->setSection(
"__DATA,__cfstring");
7383 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
7387 if (ObjCFastEnumerationStateType.isNull()) {
7388 RecordDecl *D = Context.buildImplicitRecord(
"__objcFastEnumerationState");
7392 Context.UnsignedLongTy, Context.getPointerType(Context.getObjCIdType()),
7393 Context.getPointerType(Context.UnsignedLongTy),
7394 Context.getConstantArrayType(Context.UnsignedLongTy, llvm::APInt(32, 5),
7397 for (
size_t i = 0; i < 4; ++i) {
7402 FieldTypes[i],
nullptr,
7411 ObjCFastEnumerationStateType = Context.getCanonicalTagType(D);
7414 return ObjCFastEnumerationStateType;
7428 assert(CAT &&
"String literal not of constant array type!");
7430 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
7434 llvm::Type *ElemTy = AType->getElementType();
7435 unsigned NumElements = AType->getNumElements();
7438 if (ElemTy->getPrimitiveSizeInBits() == 16) {
7440 Elements.reserve(NumElements);
7442 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
7444 Elements.resize(NumElements);
7445 return llvm::ConstantDataArray::get(VMContext, Elements);
7448 assert(ElemTy->getPrimitiveSizeInBits() == 32);
7450 Elements.reserve(NumElements);
7452 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
7454 Elements.resize(NumElements);
7455 return llvm::ConstantDataArray::get(VMContext, Elements);
7458static llvm::GlobalVariable *
7467 auto *GV =
new llvm::GlobalVariable(
7468 M,
C->getType(), !CGM.
getLangOpts().WritableStrings, LT,
C, GlobalName,
7469 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
7471 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
7472 if (GV->isWeakForLinker()) {
7473 assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
7474 GV->setComdat(M.getOrInsertComdat(GV->getName()));
7490 llvm::GlobalVariable **Entry =
nullptr;
7491 if (!LangOpts.WritableStrings) {
7492 Entry = &ConstantStringMap[
C];
7493 if (
auto GV = *Entry) {
7494 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
7497 GV->getValueType(), Alignment);
7502 StringRef GlobalVariableName;
7503 llvm::GlobalValue::LinkageTypes LT;
7508 if (
getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
7509 !LangOpts.WritableStrings) {
7510 llvm::raw_svector_ostream Out(MangledNameBuffer);
7512 LT = llvm::GlobalValue::LinkOnceODRLinkage;
7513 GlobalVariableName = MangledNameBuffer;
7515 LT = llvm::GlobalValue::PrivateLinkage;
7516 GlobalVariableName = Name;
7528 SanitizerMD->reportGlobal(GV, S->
getStrTokenLoc(0),
"<string literal>");
7531 GV->getValueType(), Alignment);
7548 StringRef GlobalName) {
7549 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
7554 llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
7557 llvm::GlobalVariable **Entry =
nullptr;
7558 if (!LangOpts.WritableStrings) {
7559 Entry = &ConstantStringMap[
C];
7560 if (
auto GV = *Entry) {
7561 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
7564 GV->getValueType(), Alignment);
7570 GlobalName, Alignment);
7575 GV->getValueType(), Alignment);
7593 MaterializedType = E->
getType();
7597 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E,
nullptr});
7598 if (!InsertResult.second) {
7601 if (!InsertResult.first->second) {
7606 InsertResult.first->second =
new llvm::GlobalVariable(
7607 getModule(),
Type,
false, llvm::GlobalVariable::InternalLinkage,
7611 llvm::cast<llvm::GlobalVariable>(
7612 InsertResult.first->second->stripPointerCasts())
7621 llvm::raw_svector_ostream Out(Name);
7643 std::optional<ConstantEmitter> emitter;
7644 llvm::Constant *InitialValue =
nullptr;
7649 emitter.emplace(*
this);
7650 InitialValue = emitter->emitForInitializer(*
Value, AddrSpace,
7655 Type = InitialValue->getType();
7664 if (
Linkage == llvm::GlobalVariable::ExternalLinkage) {
7666 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
7670 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
7674 Linkage = llvm::GlobalVariable::InternalLinkage;
7678 auto *GV =
new llvm::GlobalVariable(
7680 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
7681 if (emitter) emitter->finalize(GV);
7683 if (!llvm::GlobalValue::isLocalLinkage(
Linkage)) {
7685 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
7687 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
7691 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
7692 if (VD->getTLSKind())
7694 llvm::Constant *CV = GV;
7697 GV, llvm::PointerType::get(
7703 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
7705 Entry->replaceAllUsesWith(CV);
7706 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
7715void CodeGenModule::EmitObjCPropertyImplementations(
const
7728 if (!Getter || Getter->isSynthesizedAccessorStub())
7731 auto *Setter = PID->getSetterMethodDecl();
7732 if (!PD->
isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
7743 if (ivar->getType().isDestructedType())
7764void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
7777 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod,
false);
7792 getContext().getObjCIdType(),
nullptr, D,
true,
7798 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod,
true);
7803void CodeGenModule::EmitLinkageSpec(
const LinkageSpecDecl *LSD) {
7810 EmitDeclContext(LSD);
7813void CodeGenModule::EmitTopLevelStmt(
const TopLevelStmtDecl *D) {
7815 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7818 std::unique_ptr<CodeGenFunction> &CurCGF =
7819 GlobalTopLevelStmtBlockInFlight.first;
7823 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
7831 std::string Name =
"__stmts__" + llvm::utostr(CXXGlobalInits.size());
7832 FunctionArgList Args;
7834 const CGFunctionInfo &FnInfo =
7837 llvm::Function *
Fn = llvm::Function::Create(
7838 FnTy, llvm::GlobalValue::InternalLinkage, Name, &
getModule());
7840 CurCGF.reset(
new CodeGenFunction(*
this));
7841 GlobalTopLevelStmtBlockInFlight.second = D;
7842 CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
7844 CXXGlobalInits.push_back(Fn);
7847 CurCGF->EmitStmt(D->
getStmt());
7850void CodeGenModule::EmitDeclContext(
const DeclContext *DC) {
7851 for (
auto *I : DC->
decls()) {
7857 if (
auto *OID = dyn_cast<ObjCImplDecl>(I)) {
7858 for (
auto *M : OID->methods())
7877 case Decl::CXXConversion:
7878 case Decl::CXXMethod:
7879 case Decl::Function:
7886 case Decl::CXXDeductionGuide:
7891 case Decl::Decomposition:
7892 case Decl::VarTemplateSpecialization:
7894 if (
auto *DD = dyn_cast<DecompositionDecl>(D))
7895 for (
auto *B : DD->flat_bindings())
7896 if (
auto *HD = B->getHoldingVar())
7903 case Decl::IndirectField:
7907 case Decl::Namespace:
7910 case Decl::ClassTemplateSpecialization: {
7913 if (Spec->getSpecializationKind() ==
7915 Spec->hasDefinition())
7916 DI->completeTemplateDefinition(*Spec);
7918 case Decl::CXXRecord: {
7922 DI->EmitAndRetainType(
7926 DI->completeUnusedClass(*CRD);
7929 for (
auto *I : CRD->
decls())
7935 case Decl::UsingShadow:
7936 case Decl::ClassTemplate:
7937 case Decl::VarTemplate:
7939 case Decl::VarTemplatePartialSpecialization:
7940 case Decl::FunctionTemplate:
7941 case Decl::TypeAliasTemplate:
7950 case Decl::UsingEnum:
7954 case Decl::NamespaceAlias:
7958 case Decl::UsingDirective:
7962 case Decl::CXXConstructor:
7965 case Decl::CXXDestructor:
7969 case Decl::StaticAssert:
7970 case Decl::ExplicitInstantiation:
7977 case Decl::ObjCInterface:
7978 case Decl::ObjCCategory:
7981 case Decl::ObjCProtocol: {
7983 if (Proto->isThisDeclarationADefinition())
7984 ObjCRuntime->GenerateProtocol(Proto);
7988 case Decl::ObjCCategoryImpl:
7994 case Decl::ObjCImplementation: {
7996 EmitObjCPropertyImplementations(OMD);
7997 EmitObjCIvarInitializations(OMD);
7998 ObjCRuntime->GenerateClass(OMD);
8002 DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
8003 OMD->getClassInterface()), OMD->getLocation());
8006 case Decl::ObjCMethod: {
8013 case Decl::ObjCCompatibleAlias:
8017 case Decl::PragmaComment: {
8019 switch (PCD->getCommentKind()) {
8021 llvm_unreachable(
"unexpected pragma comment kind");
8029 ProcessPragmaCommentCopyright(PCD->getArg(), PCD->isFromASTFile());
8039 case Decl::PragmaDetectMismatch: {
8045 case Decl::LinkageSpec:
8049 case Decl::FileScopeAsm: {
8051 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
8054 if (LangOpts.OpenMPIsTargetDevice)
8057 if (LangOpts.SYCLIsDevice)
8062 llvm::Module::GlobalAsmProperties Props;
8063 Props.TargetFeatures = llvm::join(TargetOpts.
Features,
",");
8064 Props.TargetCPU = TargetOpts.
CPU;
8066 llvm::Module::GlobalAsmFragment(AD->getAsmString(), Props));
8070 case Decl::TopLevelStmt:
8074 case Decl::Import: {
8078 if (!ImportedModules.insert(Import->getImportedModule()))
8082 if (!Import->getImportedOwningModule()) {
8084 DI->EmitImportDecl(*Import);
8090 if (CXX20ModuleInits && Import->getImportedModule() &&
8091 Import->getImportedModule()->isNamedModule())
8100 Visited.insert(Import->getImportedModule());
8101 Stack.push_back(Import->getImportedModule());
8103 while (!Stack.empty()) {
8105 if (!EmittedModuleInitializers.insert(Mod).second)
8108 for (
auto *D : Context.getModuleInitializers(Mod))
8115 if (Submodule->IsExplicit)
8118 if (Visited.insert(Submodule).second)
8119 Stack.push_back(Submodule);
8129 case Decl::OMPThreadPrivate:
8133 case Decl::OMPAllocate:
8137 case Decl::OMPDeclareReduction:
8141 case Decl::OMPDeclareMapper:
8145 case Decl::OMPRequires:
8150 case Decl::TypeAlias:
8152 DI->EmitAndRetainType(
getContext().getTypedefType(
8160 DI->EmitAndRetainType(
8167 DI->EmitAndRetainType(
8171 case Decl::HLSLRootSignature:
8174 case Decl::HLSLBuffer:
8178 case Decl::OpenACCDeclare:
8181 case Decl::OpenACCRoutine:
8196 if (!CodeGenOpts.CoverageMapping)
8199 case Decl::CXXConversion:
8200 case Decl::CXXMethod:
8201 case Decl::Function:
8202 case Decl::ObjCMethod:
8203 case Decl::CXXConstructor:
8204 case Decl::CXXDestructor: {
8213 DeferredEmptyCoverageMappingDecls.try_emplace(D,
true);
8223 if (!CodeGenOpts.CoverageMapping)
8225 if (
const auto *Fn = dyn_cast<FunctionDecl>(D)) {
8226 if (Fn->isTemplateInstantiation())
8229 DeferredEmptyCoverageMappingDecls.insert_or_assign(D,
false);
8237 for (
const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
8240 const Decl *D = Entry.first;
8242 case Decl::CXXConversion:
8243 case Decl::CXXMethod:
8244 case Decl::Function:
8245 case Decl::ObjCMethod: {
8252 case Decl::CXXConstructor: {
8259 case Decl::CXXDestructor: {
8276 if (llvm::Function *F =
getModule().getFunction(
"main")) {
8277 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
8278 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
8279 auto *GA = llvm::GlobalAlias::create(
"__main_void", F);
8280 GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
8289 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
8290 return llvm::ConstantInt::get(i64, PtrInt);
8294 llvm::NamedMDNode *&GlobalMetadata,
8296 llvm::GlobalValue *
Addr) {
8297 if (!GlobalMetadata)
8299 CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
8302 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(
Addr),
8305 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
8308bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
8309 llvm::GlobalValue *CppFunc) {
8311 llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
8314 llvm::SmallVector<llvm::ConstantExpr *> CEs;
8317 if (Elem == CppFunc)
8323 for (llvm::User *User : Elem->users()) {
8327 if (
auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
8328 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
8331 for (llvm::User *CEUser : ConstExpr->users()) {
8332 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
8333 IFuncs.push_back(IFunc);
8338 CEs.push_back(ConstExpr);
8339 }
else if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
8340 IFuncs.push_back(IFunc);
8352 for (llvm::GlobalIFunc *IFunc : IFuncs)
8353 IFunc->setResolver(
nullptr);
8354 for (llvm::ConstantExpr *ConstExpr : CEs)
8355 ConstExpr->destroyConstant();
8359 Elem->eraseFromParent();
8361 for (llvm::GlobalIFunc *IFunc : IFuncs) {
8366 llvm::FunctionType::get(IFunc->getType(),
false);
8367 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
8368 CppFunc->getName(), ResolverTy, {},
false);
8369 IFunc->setResolver(Resolver);
8379void CodeGenModule::EmitStaticExternCAliases() {
8382 for (
auto &I : StaticExternCValues) {
8383 const IdentifierInfo *Name = I.first;
8384 llvm::GlobalValue *Val = I.second;
8392 llvm::GlobalValue *ExistingElem =
8397 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
8404 auto Res = Manglings.find(MangledName);
8405 if (Res == Manglings.end())
8407 Result = Res->getValue();
8418void CodeGenModule::EmitDeclMetadata() {
8419 llvm::NamedMDNode *GlobalMetadata =
nullptr;
8421 for (
auto &I : MangledDeclNames) {
8422 llvm::GlobalValue *
Addr =
getModule().getNamedValue(I.second);
8432void CodeGenFunction::EmitDeclMetadata() {
8433 if (LocalDeclMap.empty())
return;
8438 unsigned DeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
8440 llvm::NamedMDNode *GlobalMetadata =
nullptr;
8442 for (
auto &I : LocalDeclMap) {
8443 const Decl *D = I.first;
8444 llvm::Value *
Addr = I.second.emitRawPointer(*
this);
8445 if (
auto *Alloca = dyn_cast<llvm::AllocaInst>(
Addr)) {
8447 Alloca->setMetadata(
8448 DeclPtrKind, llvm::MDNode::get(
8449 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
8450 }
else if (
auto *GV = dyn_cast<llvm::GlobalValue>(
Addr)) {
8457void CodeGenModule::EmitVersionIdentMetadata() {
8458 llvm::NamedMDNode *IdentMetadata =
8459 TheModule.getOrInsertNamedMetadata(
"llvm.ident");
8461 llvm::LLVMContext &Ctx = TheModule.getContext();
8463 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
8464 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
8467void CodeGenModule::EmitCommandLineMetadata() {
8468 llvm::NamedMDNode *CommandLineMetadata =
8469 TheModule.getOrInsertNamedMetadata(
"llvm.commandline");
8471 llvm::LLVMContext &Ctx = TheModule.getContext();
8473 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
8474 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
8477void CodeGenModule::EmitCoverageFile() {
8478 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu");
8482 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
8483 llvm::LLVMContext &Ctx = TheModule.getContext();
8484 auto *CoverageDataFile =
8486 auto *CoverageNotesFile =
8488 for (
int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
8489 llvm::MDNode *CU = CUNode->getOperand(i);
8490 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
8491 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
8504 LangOpts.ObjCRuntime.isGNUFamily())
8505 return ObjCRuntime->GetEHType(Ty);
8512 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
8514 for (
auto RefExpr : D->
varlist()) {
8517 VD->getAnyInitializer() &&
8518 !VD->getAnyInitializer()->isConstantInitializer(
getContext());
8524 VD,
Addr, RefExpr->getBeginLoc(), PerformInit))
8525 CXXGlobalInits.push_back(InitFunction);
8530CodeGenModule::CreateMetadataIdentifierImpl(
QualType T, MetadataTypeMap &Map,
8534 FnType->getReturnType(), FnType->getParamTypes(),
8535 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
8537 llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
8542 std::string OutName;
8543 llvm::raw_string_ostream Out(OutName);
8548 Out <<
".normalized";
8571 return CreateMetadataIdentifierImpl(T, MetadataIdMap,
"");
8576 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap,
".virtual");
8580 return CreateMetadataIdentifierImpl(T, GeneralizedMetadataIdMap,
8588 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
8589 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
8590 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
8591 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
8592 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
8593 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
8594 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
8595 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
8603 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8605 if (CodeGenOpts.SanitizeCfiCrossDso)
8607 VTable->addTypeMetadata(Offset.getQuantity(),
8608 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
8611 llvm::Metadata *MD = llvm::MDString::get(
getLLVMContext(),
"all-vtables");
8612 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8618 SanStats = std::make_unique<llvm::SanitizerStatReport>(&
getModule());
8628 auto *FTy = llvm::FunctionType::get(SamplerT, {
C->getType()},
false);
8643 bool forPointeeType) {
8654 if (
auto Align = TT->getDecl()->getMaxAlignment()) {
8661 bool AlignForArray = T->isArrayType();
8667 if (T->isIncompleteType()) {
8684 if (T.getQualifiers().hasUnaligned()) {
8686 }
else if (forPointeeType && !AlignForArray &&
8687 (RD = T->getAsCXXRecordDecl())) {
8698 if (
unsigned MaxAlign =
getLangOpts().MaxTypeAlign) {
8711 if (NumAutoVarInit >= StopAfter) {
8714 if (!NumAutoVarInit) {
8728 const Decl *D)
const {
8732 OS << (isa<VarDecl>(D) ?
".static." :
".intern.");
8734 OS << (isa<VarDecl>(D) ?
"__static__" :
"__intern__");
8740 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
8744 llvm::MD5::MD5Result
Result;
8745 for (
const auto &Arg : PreprocessorOpts.Macros)
8746 Hash.update(Arg.first);
8750 llvm::sys::fs::UniqueID ID;
8754 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
8758 SM.getDiagnostics().Report(diag::err_cannot_open_file)
8759 << PLoc.
getFilename() << Status.getError().message();
8761 ID = Status->getUniqueID();
8763 OS << llvm::format(
"%x", ID.getFile()) << llvm::format(
"%x", ID.getDevice())
8764 <<
"_" << llvm::utohexstr(
Result.low(),
true, 8);
8771 assert(DeferredDeclsToEmit.empty() &&
8772 "Should have emitted all decls deferred to emit.");
8773 assert(NewBuilder->DeferredDecls.empty() &&
8774 "Newly created module should not have deferred decls");
8775 NewBuilder->DeferredDecls = std::move(DeferredDecls);
8776 assert(EmittedDeferredDecls.empty() &&
8777 "Still have (unmerged) EmittedDeferredDecls deferred decls");
8779 assert(NewBuilder->DeferredVTables.empty() &&
8780 "Newly created module should not have deferred vtables");
8781 NewBuilder->DeferredVTables = std::move(DeferredVTables);
8783 assert(NewBuilder->EmittedVTables.empty() &&
8784 "Newly created module should not have defined vtables");
8785 NewBuilder->EmittedVTables = std::move(EmittedVTables);
8787 assert(NewBuilder->MangledDeclNames.empty() &&
8788 "Newly created module should not have mangled decl names");
8789 assert(NewBuilder->Manglings.empty() &&
8790 "Newly created module should not have manglings");
8791 NewBuilder->Manglings = std::move(Manglings);
8793 NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
8795 NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
8799 std::string OutName;
8800 llvm::raw_string_ostream Out(OutName);
8808 if (!Context.getTargetInfo().emitVectorDeletingDtors(Context.getLangOpts()))
8814 if (Dtor && Dtor->isVirtual() && Dtor->hasAttr<DLLExportAttr>())
8817 return RequireVectorDeletingDtor.count(RD);
8821 if (!Context.getTargetInfo().emitVectorDeletingDtors(Context.getLangOpts()))
8823 RequireVectorDeletingDtor.insert(RD);
8837 if (Entry && !Entry->isDeclaration()) {
8842 auto *NewFn = llvm::Function::Create(
8844 llvm::Function::ExternalLinkage, VDName, &
getModule());
8845 SetFunctionAttributes(VectorDtorGD, NewFn,
false,
8847 NewFn->takeName(VDEntry);
8848 VDEntry->replaceAllUsesWith(NewFn);
8849 VDEntry->eraseFromParent();
8850 Entry->replaceAllUsesWith(NewFn);
8851 Entry->eraseFromParent();
8856 addDeferredDeclToEmit(VectorDtorGD);
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines the Diagnostic-related interfaces.
Defines enum values for all the target-independent builtin functions.
static bool shouldAssumeDSOLocal(const CIRGenModule &cgm, cir::CIRGlobalValueInterface gv)
static bool shouldBeInCOMDAT(CIRGenModule &cgm, const Decl &d)
static bool hasUnwindExceptions(const LangOptions &langOpts)
Determines whether the language options require us to model unwind exceptions.
static void setWindowsItaniumDLLImport(CIRGenModule &cgm, bool isLocal, cir::FuncOp funcOp, StringRef name)
static std::string getMangledNameImpl(CIRGenModule &cgm, GlobalDecl gd, const NamedDecl *nd)
static bool hasImplicitAttr(const ValueDecl *decl)
static std::vector< std::string > getFeatureDeltaFromDefault(const CIRGenModule &cgm, llvm::StringRef targetCPU, llvm::StringMap< bool > &featureMap)
Get the feature delta from the default feature map for the given target CPU.
static CIRGenCXXABI * createCXXABI(CIRGenModule &cgm)
static bool isVarDeclStrongDefinition(const ASTContext &astContext, CIRGenModule &cgm, const VarDecl *vd, bool noCommon)
static void setLinkageForGV(cir::GlobalOp &gv, const NamedDecl *nd)
static void emitUsed(CIRGenModule &cgm, StringRef name, std::vector< cir::CIRGlobalValueInterface > &list)
static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, const CPUSpecificAttr *Attr, unsigned CPUIndex, raw_ostream &Out)
static bool AllTrivialInitializers(CodeGenModule &CGM, ObjCImplementationDecl *D)
static const FunctionDecl * GetRuntimeFunctionDecl(ASTContext &C, StringRef Name)
static GlobalDecl getBaseVariantGlobalDecl(const NamedDecl *D)
static void checkAliasForTocData(llvm::GlobalVariable *GVar, const CodeGenOptions &CodeGenOpts, DiagnosticsEngine &Diags, SourceLocation Location)
static const char PFPDeactivationSymbolPrefix[]
static bool HasNonDllImportDtor(QualType T)
static llvm::Constant * GetPointerConstant(llvm::LLVMContext &Context, const void *Ptr)
Turns the given pointer into a constant.
static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S)
static llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM, GlobalDecl GD)
static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO, llvm::Module &M)
static QualType GeneralizeTransparentUnion(QualType Ty)
static std::string getCPUSpecificMangling(const CodeGenModule &CGM, StringRef Name)
static const char AnnotationSection[]
static bool isUniqueInternalLinkageDecl(GlobalDecl GD, CodeGenModule &CGM)
static bool allowKCFIIdentifier(StringRef Name)
static void replaceUsesOfNonProtoConstant(llvm::Constant *old, llvm::Function *newFn)
Replace the uses of a function that was declared with a non-proto type.
static llvm::Constant * castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, llvm::GlobalVariable *GV)
static void checkDataLayoutConsistency(const TargetInfo &Target, llvm::LLVMContext &Context, const LangOptions &Opts)
static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty, bool GeneralizePointers)
static bool needsDestructMethod(ObjCImplementationDecl *impl)
static bool isStackProtectorOn(const LangOptions &LangOpts, const llvm::Triple &Triple, clang::LangOptions::StackProtectorMode Mode)
static void removeImageAccessQualifier(std::string &TyName)
static llvm::StringMapEntry< llvm::GlobalVariable * > & GetConstantCFStringEntry(llvm::StringMap< llvm::GlobalVariable * > &Map, const StringLiteral *Literal, bool TargetIsLSB, bool &IsUTF16, unsigned &StringLength)
static void setLLVMVisibility(llvm::GlobalValue &GV, std::optional< llvm::GlobalValue::VisibilityTypes > V)
static llvm::GlobalVariable * GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, CodeGenModule &CGM, StringRef GlobalName, CharUnits Alignment)
static llvm::APInt getFMVPriority(const TargetInfo &TI, const CodeGenFunction::FMVResolverOption &RO)
static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, SmallVectorImpl< llvm::MDNode * > &Metadata, llvm::SmallPtrSet< Module *, 16 > &Visited)
Add link options implied by the given module, including modules it depends on, using a postorder walk...
static llvm::cl::opt< bool > LimitedCoverage("limited-coverage-experimental", llvm::cl::Hidden, llvm::cl::desc("Emit limited coverage mapping information (experimental)"))
static CGCXXABI * createCXXABI(CodeGenModule &CGM)
static std::unique_ptr< TargetCodeGenInfo > createTargetCodeGenInfo(CodeGenModule &CGM)
static const llvm::GlobalValue * getAliasedGlobal(const llvm::GlobalValue *GV)
static QualType GeneralizeType(ASTContext &Ctx, QualType Ty, bool GeneralizePointers)
static bool shouldSkipAliasEmission(const CodeGenModule &CGM, const ValueDecl *Global)
static constexpr auto ErrnoTBAAMDName
static unsigned ArgInfoAddressSpace(LangAS AS)
static void replaceDeclarationWith(llvm::GlobalValue *Old, llvm::Constant *New)
static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, llvm::Function *NewFn)
ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we implement a function with...
static std::optional< llvm::GlobalValue::VisibilityTypes > getLLVMVisibility(clang::LangOptions::VisibilityFromDLLStorageClassKinds K)
static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, const CXXMethodDecl *MD)
static bool checkAliasedGlobal(const ASTContext &Context, DiagnosticsEngine &Diags, SourceLocation Location, bool IsIFunc, const llvm::GlobalValue *Alias, const llvm::GlobalValue *&GV, const llvm::MapVector< GlobalDecl, StringRef > &MangledDeclNames, SourceRange AliasRange)
static void EmitGlobalDeclMetadata(CodeGenModule &CGM, llvm::NamedMDNode *&GlobalMetadata, GlobalDecl D, llvm::GlobalValue *Addr)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Result
Implement __builtin_bit_cast and related operations.
llvm::MachO::Target Target
llvm::MachO::Record Record
Defines the clang::Module class, which describes a module in the source code.
Defines the clang::Preprocessor interface.
Maps Clang QualType instances to corresponding LLVM ABI type representations.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
static const NamedDecl * getDefinition(const Decl *D)
Defines the SourceManager interface.
static CharUnits getTypeAllocSize(CodeGenModule &CGM, llvm::Type *type)
Defines version macros and version-related utility functions for Clang.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
SourceManager & getSourceManager()
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
@ Strong
Strong definition.
@ WeakUnknown
Weak for now, might become strong later in this TU.
const ProfileList & getProfileList() const
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
const XRayFunctionFilter & getXRayFilter() const
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
StringRef getCUIDHash() const
const LangOptions & getLangOpts() const
SelectorTable & Selectors
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
const NoSanitizeList & getNoSanitizeList() const
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const
Return the alignment in characters that should be given to a global variable with type T.
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
DiagnosticsEngine & getDiagnostics() const
const TargetInfo & getTargetInfo() const
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
CanQualType getCanonicalTagType(const TagDecl *TD) const
unsigned getTargetAddressSpace(LangAS AS) const
Module * getCurrentNamedModule() const
Get module under construction, nullptr if this is not a C++20 module.
Attr - This represents one attribute.
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Represents a base class of a C++ class.
CXXTemporary * getTemporary()
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Represents a C++ base or member initializer.
Expr * getInit() const
Get the initializer.
FunctionDecl * getOperatorDelete() const
Represents a C++ destructor within a class.
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Represents a static or instance method of a struct/union/class.
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
FunctionDecl * getOperatorNew() const
Represents a C++ struct/union/class.
unsigned getNumBases() const
Retrieves the number of base classes of this class.
bool hasDefinition() const
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
const CXXDestructorDecl * getDestructor() const
CharUnits - This is an opaque type for sizes expressed in character units.
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
static CharUnits One()
One - Construct a CharUnits quantity of one.
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::string MSSecureHotPatchFunctionsFile
The name of a file that contains functions which will be compiled for hotpatching.
std::string RecordCommandLine
The string containing the commandline for the llvm.commandline metadata, if non-empty.
std::string FloatABI
The ABI to use for passing floating point arguments.
llvm::Reloc::Model RelocationModel
The name of the relocation model to use.
std::vector< std::string > TocDataVarsUserSpecified
List of global variables explicitly specified by the user as toc-data.
PointerAuthOptions PointerAuth
Configuration for pointer-signing.
std::vector< std::string > MSSecureHotPatchFunctionsList
A list of functions which will be compiled for hotpatching.
ABIInfo - Target specific hooks for defining how a type should be passed or returned from functions.
virtual void appendAttributeMangling(TargetAttr *Attr, raw_ostream &Out) const
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
virtual void handleVarRegistration(const VarDecl *VD, llvm::GlobalVariable &Var)=0
Check whether a variable is a device variable and register it if true.
virtual llvm::GlobalValue * getKernelHandle(llvm::Function *Stub, GlobalDecl GD)=0
Get kernel handle by stub function.
virtual void internalizeDeviceSideVar(const VarDecl *D, llvm::GlobalValue::LinkageTypes &Linkage)=0
Adjust linkage of shadow variables in host compilation.
Implements C++ ABI-specific code generation functions.
virtual void EmitCXXConstructors(const CXXConstructorDecl *D)=0
Emit constructor variants required by this ABI.
virtual llvm::Constant * getAddrOfRTTIDescriptor(QualType Ty)=0
virtual void EmitCXXDestructors(const CXXDestructorDecl *D)=0
Emit destructor variants required by this ABI.
virtual void setCXXDestructorDLLStorage(llvm::GlobalValue *GV, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
virtual llvm::GlobalValue::LinkageTypes getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
MangleContext & getMangleContext()
Gets the mangle context.
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
void EmitGlobalAlias(const llvm::GlobalValue *GV, const GlobalDecl Decl)
Emit information about global variable alias.
void EmitExternalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl)
Emit information about an external variable.
void EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc, QualType FnType, llvm::Function *Fn=nullptr)
Emit debug info for a function declaration.
void AddStringLiteralDebugInfo(llvm::GlobalVariable *GV, const StringLiteral *S)
DebugInfo isn't attached to string literals by default.
CGFunctionInfo - Class to encapsulate the information about a function definition.
void handleGlobalVarDefinition(const VarDecl *VD, llvm::GlobalVariable *Var)
void addRootSignature(const HLSLRootSignatureDecl *D)
void addBuffer(const HLSLBufferDecl *D)
llvm::Type * getSamplerType(const Type *T)
void emitDeferredTargetDecls() const
Emit deferred declare target variables marked for deferred emission.
virtual void emitDeclareTargetFunction(const FunctionDecl *FD, llvm::GlobalValue *GV)
Emit code for handling declare target functions in the runtime.
virtual ConstantAddress getAddrOfDeclareTargetVar(const VarDecl *VD)
Returns the address of the variable marked as declare target with link clause OR as declare target wi...
bool hasRequiresUnifiedSharedMemory() const
Return whether the unified_shared_memory has been specified.
virtual void emitDeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn)
Marks function Fn with properly mangled versions of vector functions.
virtual void registerTargetGlobalVariable(const VarDecl *VD, llvm::Constant *Addr)
Checks if the provided global decl GD is a declare target variable and registers it when emitting cod...
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
void EmitCfiCheckFail()
Emit a cross-DSO CFI failure handling function.
void GenerateObjCGetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCGetter - Synthesize an Objective-C property getter function.
void EmitCfiCheckStub()
Emit a stub for the cross-DSO CFI check function.
void GenerateObjCMethod(const ObjCMethodDecl *OMD)
Generate an Objective-C method.
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
void GenerateObjCSetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCSetter - Synthesize an Objective-C property setter function for the given property.
llvm::LLVMContext & getLLVMContext()
bool isTrivialInitializer(const Expr *Init)
Determine whether the given initializer is trivial in the sense that it requires no code to be genera...
This class organizes the cross-function state that is used while generating LLVM code.
StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD)
ConstantAddress GetAddrOfMSGuidDecl(const MSGuidDecl *GD)
Get the address of a GUID.
void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const
Set visibility, dllimport/dllexport and dso_local.
void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD)
Create and attach type metadata for the given vtable.
void UpdateCompletedType(const TagDecl *TD)
llvm::MDNode * getTBAAAccessTagInfo(TBAAAccessInfo Info)
getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
llvm::GlobalVariable::ThreadLocalMode GetDefaultLLVMTLSModel() const
Get LLVM TLS mode from CodeGenOptions.
void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F, const CGFunctionInfo &FI)
Set the attributes on the LLVM function for the given decl and function info.
void setDSOLocal(llvm::GlobalValue *GV) const
llvm::MDNode * getTBAAStructInfo(QualType QTy)
CGHLSLRuntime & getHLSLRuntime()
Return a reference to the configured HLSL runtime.
llvm::Constant * EmitAnnotationArgs(const AnnotateAttr *Attr)
Emit additional args of the annotation.
llvm::Module & getModule() const
std::optional< llvm::Attribute::AttrKind > StackProtectorAttribute(const Decl *D) const
llvm::GlobalValue * getPFPDeactivationSymbol(const FieldDecl *FD)
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
llvm::ConstantInt * CreateKCFITypeId(QualType T, StringRef Salt)
Generate a KCFI type identifier for T.
CGDebugInfo * getModuleDebugInfo()
llvm::Constant * performAddrSpaceCast(llvm::Constant *Src, llvm::Type *DestTy)
bool NeedAllVtablesTypeId() const
Returns whether this module needs the "all-vtables" type identifier.
void addCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
CodeGenVTables & getVTables()
llvm::ConstantInt * CreateCrossDsoCfiTypeId(llvm::Metadata *MD)
Generate a cross-DSO type identifier for MD.
CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const
Return the store size, in character units, of the given LLVM type.
void createFunctionTypeMetadataForIcall(const FunctionDecl *FD, llvm::Function *F)
Create and attach type metadata to the given function.
bool getExpressionLocationsEnabled() const
Return true if we should emit location information for expressions.
void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C)
bool classNeedsVectorDestructor(const CXXRecordDecl *RD)
Check that class need vector deleting destructor body.
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
void setGVPropertiesAux(llvm::GlobalValue *GV, const NamedDecl *D) const
const IntrusiveRefCntPtr< llvm::vfs::FileSystem > & getFileSystem() const
const ABIInfo & getABIInfo()
void EmitMainVoidAlias()
Emit an alias for "main" if it has no arguments (needed for wasm).
void DecorateInstructionWithInvariantGroup(llvm::Instruction *I, const CXXRecordDecl *RD)
Adds !invariant.barrier !tag to instruction.
DiagnosticsEngine & getDiags() const
bool isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, SourceLocation Loc) const
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
llvm::Constant * getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the constructor/destructor of the given type.
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
llvm::Constant * EmitAnnotateAttr(llvm::GlobalValue *GV, const AnnotateAttr *AA, SourceLocation L)
Generate the llvm::ConstantStruct which contains the annotation information for a given GlobalValue.
void EmitOpenACCDeclare(const OpenACCDeclareDecl *D, CodeGenFunction *CGF=nullptr)
llvm::GlobalValue::LinkageTypes getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage)
Returns LLVM linkage for a declarator.
TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, TBAAAccessInfo SrcInfo)
mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the purposes of memory transfer call...
const LangOptions & getLangOpts() const
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
llvm::Constant * EmitAnnotationLineNo(SourceLocation L)
Emit the annotation line number.
QualType getObjCFastEnumerationStateType()
Retrieve the record type that describes the state of an Objective-C fast enumeration loop (for....
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
CodeGenTypes & getTypes()
bool shouldMapVisibilityToDLLExport(const NamedDecl *D) const
CGOpenCLRuntime & getOpenCLRuntime()
Return a reference to the configured OpenCL runtime.
const std::string & getModuleNameHash() const
const TargetInfo & getTarget() const
bool shouldEmitRTTI(bool ForEH=false)
void EmitGlobal(GlobalDecl D)
Emit code for a single global function or var decl.
llvm::Metadata * CreateMetadataIdentifierForType(QualType T)
Create a metadata identifier for the given type.
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
void createIndirectFunctionTypeMD(const FunctionDecl *FD, llvm::Function *F)
Create and attach callgraph metadata if the function is a potential indirect call target to support c...
void AppendLinkerOptions(StringRef Opts)
Appends Opts to the "llvm.linker.options" metadata value.
void createCalleeTypeMetadataForIcall(const QualType &QT, llvm::CallBase *CB)
Create and attach callee_type metadata to the given call.
bool tryEmitCUDADeviceInvalidFunctionBody(GlobalDecl GD, llvm::Function *Fn)
Emit a trap stub body for functions in ASTContext::CUDADeviceInvalidFuncs.
void EmitExternalDeclaration(const DeclaratorDecl *D)
void AddDependentLib(StringRef Lib)
Appends a dependent lib to the appropriate metadata value.
void Release()
Finalize LLVM code generation.
ProfileList::ExclusionType isFunctionBlockedByProfileList(llvm::Function *Fn, SourceLocation Loc) const
llvm::MDNode * getTBAABaseTypeInfo(QualType QTy)
getTBAABaseTypeInfo - Get metadata that describes the given base access type.
bool lookupRepresentativeDecl(StringRef MangledName, GlobalDecl &Result) const
void EmitOMPAllocateDecl(const OMPAllocateDecl *D)
Emit a code for the allocate directive.
void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const
Set the visibility for the given LLVM GlobalValue.
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD)
Returns LLVM linkage for a declarator.
bool HasHiddenLTOVisibility(const CXXRecordDecl *RD)
Returns whether the given record has hidden LTO visibility and therefore may participate in (single-m...
const llvm::DataLayout & getDataLayout() const
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can't be done.
void requireVectorDestructorDefinition(const CXXRecordDecl *RD)
Record that new[] was called for the class, transform vector deleting destructor definition in a form...
TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType)
getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an access to a virtual table poi...
CGCXXABI & getCXXABI() const
ConstantAddress GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
std::string getPFPFieldName(const FieldDecl *FD)
llvm::Constant * GetFunctionStart(const ValueDecl *Decl)
static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V)
void EmitTentativeDefinition(const VarDecl *D)
void EmitDeferredUnusedCoverageMappings()
Emit all the deferred coverage mappings for the uninstrumented functions.
void addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, StringRef Category=StringRef()) const
Imbue XRay attributes to a function, applying the always/never attribute lists in the process.
SanitizerMetadata * getSanitizerMetadata()
llvm::Metadata * CreateMetadataIdentifierGeneralized(QualType T)
Create a metadata identifier for the generalization of the given type.
void EmitGlobalAnnotations()
Emit all the global annotations.
CharUnits getClassPointerAlignment(const CXXRecordDecl *CD)
Returns the assumed alignment of an opaque pointer to the given class.
const llvm::Triple & getTriple() const
SmallVector< const CXXRecordDecl *, 0 > getMostBaseClasses(const CXXRecordDecl *RD)
Return a vector of most-base classes for RD.
void AddDeferredUnusedCoverageMapping(Decl *D)
Stored a deferred empty coverage mapping for an unused and thus uninstrumented top level declaration.
void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV)
If the declaration has internal linkage but is inside an extern "C" linkage specification,...
void DecorateInstructionWithTBAA(llvm::Instruction *Inst, TBAAAccessInfo TBAAInfo)
DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD)
void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535, bool IsDtorAttrFunc=false)
AddGlobalDtor - Add a function to the list that will be called when the module is unloaded.
llvm::Constant * CreateRuntimeVariable(llvm::Type *Ty, StringRef Name)
Create a new runtime global variable with the specified type and name.
void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info, CGCalleeInfo CalleeInfo, llvm::AttributeList &Attrs, unsigned &CallingConv, bool AttrOnCallSite, bool IsThunk)
Get the LLVM attributes and calling convention to use for a particular function type.
llvm::Constant * GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, LangAS AddrSpace, const VarDecl *D, ForDefinition_t IsForDefinition=NotForDefinition)
GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, create and return an llvm...
const llvm::abi::TargetInfo & getLLVMABITargetInfo(llvm::abi::TypeBuilder &TB)
Lazily build and return the LLVMABI library's TargetInfo for the current target.
TBAAAccessInfo getTBAAAccessInfo(QualType AccessType)
getTBAAAccessInfo - Get TBAA information that describes an access to an object of the given type.
void setFunctionLinkage(GlobalDecl GD, llvm::Function *F)
llvm::Constant * GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition=NotForDefinition)
AtomicOptions getAtomicOpts()
Get the current Atomic options.
ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal)
Return a pointer to a constant CFString object for the given string.
ProfileList::ExclusionType isFunctionBlockedFromProfileInstr(llvm::Function *Fn, SourceLocation Loc) const
void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV)
Add global annotations that are set on D, for the global GV.
void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const
Set the TLS mode for the given LLVM GlobalValue for the thread-local variable declaration D.
bool shouldUseLLVMABILowering() const
True when -fexperimental-abi-lowering is in effect AND the active target has an LLVMABI implementatio...
ConstantAddress GetAddrOfConstantStringFromLiteral(const StringLiteral *S, StringRef Name=".str")
Return a pointer to a constant array for the given string literal.
ASTContext & getContext() const
ConstantAddress GetAddrOfTemplateParamObject(const TemplateParamObjectDecl *TPO)
Get the address of a template parameter object.
void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D)
Emit a code for threadprivate directive.
ConstantAddress GetAddrOfUnnamedGlobalConstantDecl(const UnnamedGlobalConstantDecl *GCD)
Get the address of a UnnamedGlobalConstant.
TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, TBAAAccessInfo TargetInfo)
mergeTBAAInfoForCast - Get merged TBAA information for the purposes of type casts.
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
llvm::SanitizerStatReport & getSanStats()
llvm::Constant * EmitAnnotationString(StringRef Str)
Emit an annotation string.
void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare mapper construct.
bool supportsCOMDAT() const
void RefreshTypeCacheForClass(const CXXRecordDecl *Class)
llvm::MDNode * getTBAATypeInfo(QualType QTy)
getTBAATypeInfo - Get metadata used to describe accesses to objects of the given type.
void EmitOMPRequiresDecl(const OMPRequiresDecl *D)
Emit a code for requires directive.
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD)
Tell the consumer that this variable has been instantiated.
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
llvm::Constant * GetConstantArrayFromStringLiteral(const StringLiteral *E)
Return a constant array for the given string.
void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV)
Set attributes which are common to any form of a global definition (alias, Objective-C method,...
std::optional< CharUnits > getOMPAllocateAlignment(const VarDecl *VD)
Return the alignment specified in an allocate directive, if present.
llvm::GlobalVariable * CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, llvm::Align Alignment)
Will return a global variable of the given type.
CharUnits getNaturalPointeeTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, TBAAAccessInfo InfoB)
mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the purposes of conditional ope...
llvm::LLVMContext & getLLVMContext()
llvm::GlobalValue * GetGlobalValue(StringRef Ref)
void GenKernelArgMetadata(llvm::Function *FN, const FunctionDecl *FD=nullptr, CodeGenFunction *CGF=nullptr)
OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument information in the program executab...
void setKCFIType(const FunctionDecl *FD, llvm::Function *F)
Set type metadata to the given function.
void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO)
void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare reduction construct.
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
void AddDetectMismatch(StringRef Name, StringRef Value)
Appends a detect mismatch command to the linker options.
void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const
llvm::Value * createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF)
ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
LangAS GetGlobalConstantAddressSpace() const
Return the AST address space of constant literal, which is used to emit the constant literal as globa...
LangAS GetGlobalVarAddressSpace(const VarDecl *D)
Return the AST address space of the underlying global variable for D, as determined by its declaratio...
void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info, llvm::Function *F, bool IsThunk)
Set the LLVM function attributes (sext, zext, etc).
void EmitOpenACCRoutine(const OpenACCRoutineDecl *D, CodeGenFunction *CGF=nullptr)
void addReplacement(StringRef Name, llvm::Constant *C)
llvm::Constant * getConstantSignedPointer(llvm::Constant *Pointer, const PointerAuthSchema &Schema, llvm::Constant *StorageAddress, GlobalDecl SchemaDecl, QualType SchemaType)
Sign a constant pointer using the given scheme, producing a constant with the same IR type.
void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535, unsigned LexOrder=~0U, llvm::Constant *AssociatedData=nullptr)
AddGlobalCtor - Add a function to the list that will be called before main() runs.
llvm::Metadata * CreateMetadataIdentifierForFnType(QualType T)
Create a metadata identifier for the given function type.
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
llvm::Metadata * CreateMetadataIdentifierForVirtualMemPtrType(QualType T)
Create a metadata identifier that is intended to be used to check virtual calls via a member function...
ConstantAddress GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *)
Return a pointer to a constant array for the given ObjCEncodeExpr node.
const GlobalDecl getMangledNameDecl(StringRef)
void ClearUnusedCoverageMapping(const Decl *D)
Remove the deferred empty coverage mapping as this declaration is actually instrumented.
void EmitTopLevelDecl(Decl *D)
Emit code for a single top level declaration.
llvm::Constant * EmitAnnotationUnit(SourceLocation Loc)
Emit the annotation's translation unit.
ConstantAddress GetAddrOfConstantCString(const std::string &Str, StringRef GlobalName=".str")
Returns a pointer to a character array containing the literal and a terminating '\0' character.
void printPostfixForExternalizedDecl(llvm::raw_ostream &OS, const Decl *D) const
Print the postfix for externalized static variable or kernels for single source offloading languages ...
void moveLazyEmissionStates(CodeGenModule *NewBuilder)
Move some lazily-emitted states to the NewBuilder.
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
void finalizeKCFITypes()
Emit KCFI type identifier constants and remove unused identifiers.
void setValueProfilingFlag(llvm::Module &M)
void setProfileVersion(llvm::Module &M)
void emitEmptyCounterMapping(const Decl *D, StringRef FuncName, llvm::GlobalValue::LinkageTypes Linkage)
Emit a coverage mapping range with a counter zero for an unused declaration.
CodeGenTBAA - This class organizes the cross-module state that is used while lowering AST types to LL...
This class organizes the cross-module state that is used while lowering AST types to LLVM types.
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
const CGFunctionInfo & arrangeCXXMethodDeclaration(const CXXMethodDecl *MD)
C++ methods have some special rules and also have implicit parameters.
const CGFunctionInfo & arrangeFreeFunctionType(CanQual< FunctionProtoType > Ty)
Arrange the argument and result information for a value of the given freestanding function type.
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
unsigned getTargetAddressSpace(QualType T) const
void RefreshTypeCacheForClass(const CXXRecordDecl *RD)
Remove stale types from the type cache when an inheritance model gets assigned to a class.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
void UpdateCompletedType(const TagDecl *TD)
UpdateCompletedType - When we find the full definition for a TagDecl, replace the 'opaque' type we pr...
const CGFunctionInfo & arrangeGlobalDeclaration(GlobalDecl GD)
void EmitThunks(GlobalDecl GD)
EmitThunks - Emit the associated thunks for the given global decl.
A specialization of Address that requires the address to be an LLVM Constant.
static ConstantAddress invalid()
llvm::Constant * tryEmitForInitializer(const VarDecl &D)
Try to emit the initiaizer of the given declaration as an abstract constant.
void finalize(llvm::GlobalVariable *global)
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded.
The standard implementation of ConstantInitBuilder used in Clang.
Organizes the cross-function state that is used while generating code coverage mapping data.
bool hasDiagnostics()
Whether or not the stats we've gathered indicate any potential problems.
void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile)
Report potential problems we've found to Diags.
TargetCodeGenInfo - This class organizes various target-specific codegeneration issues,...
virtual void getDependentLibraryOption(llvm::StringRef Lib, llvm::SmallString< 24 > &Opt) const
Gets the linker options necessary to link a dependent library on this platform.
const T & getABIInfo() const
virtual LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, const VarDecl *D) const
Get target favored AST address space of a global variable for languages other than OpenCL and CUDA.
virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const
setTargetAttributes - Provides a convenient hook to handle extra target-specific attributes for the g...
virtual void emitTargetMetadata(CodeGen::CodeGenModule &CGM, const llvm::MapVector< GlobalDecl, StringRef > &MangledDeclNames) const
emitTargetMetadata - Provides a convenient hook to handle extra target-specific metadata for the give...
virtual void emitTargetGlobals(CodeGen::CodeGenModule &CGM) const
Provides a convenient hook to handle extra target-specific globals.
virtual void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, llvm::SmallString< 32 > &Opt) const
Gets the linker options necessary to detect object file mismatches on this platform.
Represents the canonical version of C arrays with a specified constant size.
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Stores additional source code information like skipped ranges which is required by the coverage mappi...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
void addDecl(Decl *D)
Add the declaration D into this context.
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Decl - This represents one declaration (or definition), e.g.
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
SourceLocation getEndLoc() const LLVM_READONLY
ASTContext & getASTContext() const LLVM_READONLY
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
SourceLocation getLocation() const
SourceLocation getBeginLoc() const LLVM_READONLY
TranslationUnitDecl * getTranslationUnitDecl()
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Represents a ValueDecl that came out of a declarator.
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
This represents one expression.
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Represents a member of a struct/union/class.
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
StringRef getName() const
The name of this FileEntry.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Represents a function declaration or definition.
bool isTargetClonesMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target-clones functional...
bool isMultiVersion() const
True if this function is considered a multiversioned function.
const ParmVarDecl * getParamDecl(unsigned i) const
bool isImmediateFunction() const
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:
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
bool isInlineBuiltinDeclaration() const
Determine if this function provides an inline implementation of a builtin.
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
FunctionDecl * getDefinition()
Get the definition for this declaration.
bool isTargetVersionMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target-version functiona...
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
bool doesDeclarationForceExternallyVisibleDefinition() const
For a function declaration in C or C++, determine whether this declaration causes the definition to b...
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
bool isImplicitHDExplicitInstantiation() const
True if both host and device are implicit attributes and this is (or is a member of) an explicit temp...
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const override
Appends a human-readable name for this declaration into the given stream.
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Represents a prototype with parameter type info, e.g.
FunctionType - C99 6.7.5.3 - Function Declarators.
CallingConv getCallConv() const
QualType getReturnType() const
GlobalDecl - represents a global declaration.
GlobalDecl getWithMultiVersionIndex(unsigned Index)
CXXCtorType getCtorType() const
GlobalDecl getWithKernelReferenceKind(KernelReferenceKind Kind)
GlobalDecl getCanonicalDecl() const
KernelReferenceKind getKernelReferenceKind() const
GlobalDecl getWithDecl(const Decl *D)
unsigned getMultiVersionIndex() const
CXXDtorType getDtorType() const
const Decl * getDecl() const
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
@ None
No signing for any function.
@ Swift5_0
Interoperability with the Swift 5.0 runtime.
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
@ FPE_Ignore
Assume that floating-point exceptions are masked.
VisibilityFromDLLStorageClassKinds
@ Keep
Keep the IR-gen assigned visibility.
@ Protected
Override the IR-gen assigned visibility with protected visibility.
@ Default
Override the IR-gen assigned visibility with default visibility.
@ Hidden
Override the IR-gen assigned visibility with hidden visibility.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
clang::ObjCRuntime ObjCRuntime
CoreFoundationABI CFRuntime
std::string CUID
The user provided compilation unit ID, if non-empty.
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Visibility getVisibility() const
void setLinkage(Linkage L)
Linkage getLinkage() const
bool isVisibilityExplicit() const
LinkageSpecLanguageIDs getLanguage() const
Return the language specified by this linkage specification.
Parts getParts() const
Get the decomposed parts of this declaration.
APValue & getAsAPValue() const
Get the value of this MSGuidDecl as an APValue.
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
void mangleBlock(const DeclContext *DC, const BlockDecl *BD, raw_ostream &Out)
void mangleCtorBlock(const CXXConstructorDecl *CD, CXXCtorType CT, const BlockDecl *BD, raw_ostream &Out)
void mangleGlobalBlock(const BlockDecl *BD, const NamedDecl *ID, raw_ostream &Out)
bool isTriviallyRecursive(const FunctionDecl *FD)
Return true if FD's body contains a direct call back to the symbol it links as, through an asm label ...
bool shouldMangleDeclName(const NamedDecl *D)
void mangleName(GlobalDecl GD, raw_ostream &)
virtual void mangleCanonicalTypeName(QualType T, raw_ostream &, bool NormalizeIntegers=false)=0
Generates a unique string for an externally visible type for use with TBAA or type uniquing.
virtual void mangleStringLiteral(const StringLiteral *SL, raw_ostream &)=0
ManglerKind getKind() const
virtual void needsUniqueInternalLinkageNames()
virtual void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber, raw_ostream &)=0
void mangleDtorBlock(const CXXDestructorDecl *CD, CXXDtorType DT, const BlockDecl *BD, raw_ostream &Out)
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
unsigned getManglingNumber() const
Describes a module or submodule.
bool isInterfaceOrPartition() const
bool isNamedModuleUnit() const
Is this a C++20 named module unit.
Module * Parent
The parent of this module.
Module * getPrivateModuleFragment() const
Get the Private Module Fragment (sub-module) for this module, it there is one.
Module * getGlobalModuleFragment() const
Get the Global Module Fragment (sub-module) for this module, it there is one.
llvm::iterator_range< submodule_iterator > submodules()
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used.
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
llvm::SmallVector< ModuleRef, 2 > Imports
The set of modules imported by this module, and on which this module depends.
bool UseExportAsModuleLinkName
Autolinking uses the framework name for linking purposes when this is false and the export_as name ot...
This represents a decl that may have a name.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
LinkageInfo getLinkageAndVisibility() const
Determines the linkage and visibility of this entity.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
bool isExternallyVisible() const
Represent a C++ namespace.
This represents 'pragma omp threadprivate ...' directive.
ObjCEncodeExpr, used for @encode in Objective-C.
QualType getEncodedType() const
propimpl_range property_impls() const
const ObjCInterfaceDecl * getClassInterface() const
void addInstanceMethod(ObjCMethodDecl *method)
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
init_iterator init_end()
init_end() - Retrieve an iterator past the last initializer.
CXXCtorInitializer ** init_iterator
init_iterator - Iterates through the ivar initializer list.
init_iterator init_begin()
init_begin() - Retrieve an iterator to the first initializer.
unsigned getNumIvarInitializers() const
getNumArgs - Number of ivars which must be initialized.
void setHasDestructors(bool val)
void setHasNonZeroConstructors(bool val)
Represents an ObjC class declaration.
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
ObjCIvarDecl - Represents an ObjC instance variable.
ObjCIvarDecl * getNextIvar()
static ObjCMethodDecl * Create(ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc, Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo, DeclContext *contextDecl, bool isInstance=true, bool isVariadic=false, bool isPropertyAccessor=false, bool isSynthesizedAccessorStub=false, bool isImplicitlyDeclared=false, bool isDefined=false, ObjCImplementationControl impControl=ObjCImplementationControl::None, bool HasRelatedResultType=false)
Represents one property declaration in an Objective-C interface.
ObjCMethodDecl * getGetterMethodDecl() const
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
The basic abstraction for the target Objective-C runtime.
bool hasUnwindExceptions() const
Does this runtime use zero-cost exceptions?
@ MacOSX
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
@ FragileMacOSX
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
@ GNUstep
'gnustep' is the modern non-fragile GNUstep runtime.
@ ObjFW
'objfw' is the Objective-C runtime included in ObjFW
@ iOS
'ios' is the Apple-provided NeXT-derived runtime on iOS or the iOS simulator; it is always non-fragil...
@ GCC
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI
@ WatchOS
'watchos' is a variant of iOS for Apple's watchOS.
Represents a parameter to a function.
bool isAddressDiscriminated() const
uint16_t getConstantDiscrimination() const
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
static void processPathForFileMacro(SmallVectorImpl< char > &Path, const LangOptions &LangOpts, const TargetInfo &TI)
Represents an unpacked "presumed" location which can be presented to the user.
const char * getFilename() const
Return the presumed filename of this location.
unsigned getLine() const
Return the presumed line number of this location.
ExclusionType getDefault(llvm::driver::ProfileInstrKind Kind) const
std::optional< ExclusionType > isFunctionExcluded(StringRef FunctionName, llvm::driver::ProfileInstrKind Kind) const
std::optional< ExclusionType > isFileExcluded(StringRef FileName, llvm::driver::ProfileInstrKind Kind) const
ExclusionType
Represents if an how something should be excluded from profiling.
@ Skip
Profiling is skipped using the skipprofile attribute.
@ Allow
Profiling is allowed.
std::optional< ExclusionType > isLocationExcluded(SourceLocation Loc, llvm::driver::ProfileInstrKind Kind) const
A (possibly-)qualified type.
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
LangAS getAddressSpace() const
Return the address space of this type.
bool isConstant(const ASTContext &Ctx) const
QualType getCanonicalType() const
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
QualType withCVRQualifiers(unsigned CVR) const
bool isConstQualified() const
Determine whether this type is const-qualified.
bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Represents a struct/union/class.
field_range fields() const
virtual void completeDefinition()
Note that the definition of this type is now complete.
RecordDecl * getDefinitionOrSelf() const
Selector getSelector(unsigned NumArgs, const IdentifierInfo **IIV)
Can create any sort of selector.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
Stmt - This represents one statement.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
SourceLocation getBeginLoc() const LLVM_READONLY
StringLiteral - This represents a string literal expression, e.g.
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
unsigned getLength() const
uint32_t getCodeUnit(size_t i) const
StringRef getString() const
unsigned getCharByteWidth() const
Represents the declaration of a struct/union/class/enum.
void startDefinition()
Starts the definition of this tag declaration.
Exposes information about the current target.
TargetOptions & getTargetOpts() const
Retrieve the target options.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
bool isReadOnlyFeature(StringRef Feature) const
Determine whether the given target feature is read only.
virtual llvm::APInt getFMVPriority(ArrayRef< StringRef > Features) const
bool supportsIFunc() const
Identify whether this target supports IFuncs.
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
virtual bool initFeatureMap(llvm::StringMap< bool > &Features, DiagnosticsEngine &Diags, StringRef CPU, const std::vector< std::string > &FeatureVec) const
Initialize the map with the default set of target features for the CPU this should include all legal ...
Options for controlling the target.
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
std::string TuneCPU
If given, the name of the target CPU to tune code for.
std::string CPU
If given, the name of the target CPU to generate code for.
@ Hostcall
printf lowering scheme involving hostcalls, currently used by HIP programs by default
A template parameter object.
const APValue & getValue() const
A declaration that models statements at global scope.
The top declaration context.
static DeclContext * castToDeclContext(const TranslationUnitDecl *D)
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
bool isPointerType() const
const T * castAs() const
Member-template castAs<specific type>.
bool isReferenceType() const
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
bool isHLSLResourceRecord() const
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
bool isObjCObjectPointerType() const
Linkage getLinkage() const
Determine the linkage of this type.
const T * getAs() const
Member-template getAs<specific type>'.
bool isRecordType() const
bool isHLSLResourceRecordArray() const
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
const APValue & getValue() const
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Represents a variable declaration or definition.
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
TLSKind getTLSKind() const
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
bool hasFlexibleArrayInit(const ASTContext &Ctx) const
Whether this variable has a flexible array member initialized with one or more elements.
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
const Expr * getInit() const
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
@ TLS_Dynamic
TLS with a dynamic initializer.
@ DeclarationOnly
This declaration is only a declaration.
@ Definition
This declaration is definitely a definition.
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
StorageClass getStorageClass() const
Returns the storage class as written in the source.
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Defines the clang::TargetInfo interface.
std::unique_ptr< TargetCodeGenInfo > createARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind Kind)
std::unique_ptr< TargetCodeGenInfo > createM68kTargetCodeGenInfo(CodeGenModule &CGM)
@ AttributedType
The l-value was considered opaque, so the alignment was determined from a type, but that type was an ...
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
std::unique_ptr< TargetCodeGenInfo > createBPFTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createMSP430TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel)
std::unique_ptr< TargetCodeGenInfo > createWebAssemblyTargetCodeGenInfo(CodeGenModule &CGM, WebAssemblyABIKind K)
std::unique_ptr< TargetCodeGenInfo > createPPC64_SVR4_TargetCodeGenInfo(CodeGenModule &CGM, PPC64_SVR4_ABIKind Kind, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createMIPSTargetCodeGenInfo(CodeGenModule &CGM, bool IsOS32)
std::unique_ptr< TargetCodeGenInfo > createHexagonTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createNVPTXTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createSystemZTargetCodeGenInfo(CodeGenModule &CGM, bool HasVector, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createWinX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters)
std::unique_ptr< TargetCodeGenInfo > createAIXTargetCodeGenInfo(CodeGenModule &CGM, bool Is64Bit)
std::unique_ptr< TargetCodeGenInfo > createAMDGPUTargetCodeGenInfo(CodeGenModule &CGM)
CGObjCRuntime * CreateMacObjCRuntime(CodeGenModule &CGM)
X86AVXABILevel
The AVX ABI level for X86 targets.
std::unique_ptr< TargetCodeGenInfo > createTCETargetCodeGenInfo(CodeGenModule &CGM)
CGObjCRuntime * CreateGNUObjCRuntime(CodeGenModule &CGM)
Creates an instance of an Objective-C runtime class.
std::unique_ptr< TargetCodeGenInfo > createWindowsARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind K)
std::unique_ptr< TargetCodeGenInfo > createAVRTargetCodeGenInfo(CodeGenModule &CGM, unsigned NPR, unsigned NRR)
std::unique_ptr< TargetCodeGenInfo > createDirectXTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createARCTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createDefaultTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind Kind)
std::unique_ptr< TargetCodeGenInfo > createSPIRVTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createWindowsMIPSTargetCodeGenInfo(CodeGenModule &CGM, bool IsOS32)
std::unique_ptr< TargetCodeGenInfo > createSparcV8TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createVETargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createCommonSPIRTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createRISCVTargetCodeGenInfo(CodeGenModule &CGM, unsigned XLen, unsigned FLen, bool EABI)
std::unique_ptr< TargetCodeGenInfo > createWindowsAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind K)
std::unique_ptr< TargetCodeGenInfo > createSparcV9TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createLanaiTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createPPC32TargetCodeGenInfo(CodeGenModule &CGM, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createSystemZ_ZOS_TargetCodeGenInfo(CodeGenModule &CGM, bool HasVector, bool SoftFloatABI)
CGCUDARuntime * CreateNVCUDARuntime(CodeGenModule &CGM)
Creates an instance of a CUDA runtime class.
std::unique_ptr< TargetCodeGenInfo > createLoongArchTargetCodeGenInfo(CodeGenModule &CGM, unsigned GRLen, unsigned FLen)
std::unique_ptr< TargetCodeGenInfo > createPPC64TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createWinX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel)
std::unique_ptr< TargetCodeGenInfo > createXCoreTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createCSKYTargetCodeGenInfo(CodeGenModule &CGM, unsigned FLen)
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
constexpr bool isInitializedByPipeline(LangAS AS)
bool LT(InterpState &S, CodePtr OpPC)
llvm::PointerUnion< const Decl *, const Expr * > DeclTy
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
CXXCtorType
C++ constructor types.
@ Ctor_Base
Base object ctor.
@ Ctor_Complete
Complete object ctor.
bool isa(CodeGen::Address addr)
GVALinkage
A more specific kind of linkage than enum Linkage.
@ GVA_AvailableExternally
std::string getClangVendor()
Retrieves the Clang vendor tag.
@ ICIS_NoInit
No in-class initializer.
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
@ Asm
Assembly: we accept this only so that we can preprocess it.
@ SD_Thread
Thread storage duration.
@ SD_Static
Static storage duration.
bool isLambdaCallOperator(const CXXMethodDecl *MD)
@ Result
The result type of a method or function.
StringRef languageToString(Language L)
@ Dtor_VectorDeleting
Vector deleting dtor.
@ Dtor_Base
Base object dtor.
@ Dtor_Complete
Complete object dtor.
@ Dtor_Deleting
Deleting dtor.
LangAS
Defines the address space values used by the address space qualifier of QualType.
@ FirstTargetAddressSpace
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::vfs::FileSystem &VFS, DiagnosticsEngine &Diags)
static const char * getCFBranchLabelSchemeFlagVal(const CFBranchLabelSchemeKind Scheme)
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
U cast(CodeGen::Address addr)
@ None
No keyword precedes the qualified type name.
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
bool isExternallyVisible(Linkage L)
@ EST_None
no exception specification
std::string getClangFullVersion()
Retrieves a string representing the complete clang version, which includes the clang version number,...
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
@ DefaultVisibility
Objects with "default" visibility are seen by the dynamic linker and act like normal objects.
cl::opt< bool > SystemHeadersCoverage
int const char * function
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
std::optional< StringRef > Architecture
llvm::SmallVector< StringRef, 8 > Features
llvm::CallingConv::ID RuntimeCC
llvm::PointerType * VoidPtrTy
llvm::IntegerType * Int64Ty
llvm::PointerType * ConstGlobalsPtrTy
void* in the address space for constant globals
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::IntegerType * CharTy
char
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
unsigned char IntAlignInBytes
llvm::Type * HalfTy
half, bfloat, float, double
unsigned char SizeSizeInBytes
llvm::CallingConv::ID getRuntimeCC() const
llvm::IntegerType * SizeTy
llvm::PointerType * GlobalsInt8PtrTy
llvm::IntegerType * Int32Ty
llvm::IntegerType * IntPtrTy
llvm::IntegerType * IntTy
int
llvm::IntegerType * Int16Ty
llvm::PointerType * ProgramPtrTy
Pointer in program address space.
unsigned char PointerAlignInBytes
llvm::PointerType * Int8PtrTy
CharUnits getPointerAlign() const
llvm::PointerType * AllocaInt8PtrTy
EvalResult is a struct with detailed info about an evaluated expression.
APValue Val
Val - This is the value the expression can be folded to.
bool hasSideEffects() const
Return true if the evaluated expression has side effects.
Extra information about a function prototype.
static const LangStandard & getLangStandardForKind(Kind K)
uint16_t Part2
...-89ab-...
uint32_t Part1
{01234567-...
uint16_t Part3
...-cdef-...
uint8_t Part4And5[8]
...-0123-456789abcdef}
A library or framework to link against when an entity from this module is used.
PointerAuthSchema InitFiniPointers
The ABI for function addresses in .init_array and .fini_array.
Describes how types, statements, expressions, and declarations should be printed.