50#include "llvm/ADT/STLExtras.h"
51#include "llvm/ADT/StringExtras.h"
52#include "llvm/ADT/StringSwitch.h"
53#include "llvm/Analysis/TargetLibraryInfo.h"
54#include "llvm/BinaryFormat/ELF.h"
55#include "llvm/IR/AttributeMask.h"
56#include "llvm/IR/CallingConv.h"
57#include "llvm/IR/DataLayout.h"
58#include "llvm/IR/Intrinsics.h"
59#include "llvm/IR/LLVMContext.h"
60#include "llvm/IR/Module.h"
61#include "llvm/IR/ProfileSummary.h"
62#include "llvm/ProfileData/InstrProfReader.h"
63#include "llvm/ProfileData/SampleProf.h"
64#include "llvm/Support/ARMBuildAttributes.h"
65#include "llvm/Support/CRC.h"
66#include "llvm/Support/CodeGen.h"
67#include "llvm/Support/CommandLine.h"
68#include "llvm/Support/ConvertUTF.h"
69#include "llvm/Support/ErrorHandling.h"
70#include "llvm/Support/Hash.h"
71#include "llvm/Support/TimeProfiler.h"
72#include "llvm/TargetParser/AArch64TargetParser.h"
73#include "llvm/TargetParser/RISCVISAInfo.h"
74#include "llvm/TargetParser/Triple.h"
75#include "llvm/TargetParser/X86TargetParser.h"
76#include "llvm/Transforms/Instrumentation/KCFI.h"
77#include "llvm/Transforms/Utils/BuildLibCalls.h"
85 "limited-coverage-experimental", llvm::cl::Hidden,
86 llvm::cl::desc(
"Emit limited coverage mapping information (experimental)"));
93 case TargetCXXABI::AppleARM64:
94 case TargetCXXABI::Fuchsia:
95 case TargetCXXABI::GenericAArch64:
96 case TargetCXXABI::GenericARM:
97 case TargetCXXABI::iOS:
98 case TargetCXXABI::WatchOS:
99 case TargetCXXABI::GenericMIPS:
100 case TargetCXXABI::GenericItanium:
101 case TargetCXXABI::WebAssembly:
102 case TargetCXXABI::XL:
104 case TargetCXXABI::Microsoft:
108 llvm_unreachable(
"invalid C++ ABI kind");
111static std::unique_ptr<TargetCodeGenInfo>
114 const llvm::Triple &Triple =
Target.getTriple();
117 switch (Triple.getArch()) {
121 case llvm::Triple::m68k:
123 case llvm::Triple::mips:
124 case llvm::Triple::mipsel:
125 if (Triple.getOS() == llvm::Triple::Win32)
129 case llvm::Triple::mips64:
130 case llvm::Triple::mips64el:
133 case llvm::Triple::avr: {
137 unsigned NPR =
Target.getABI() ==
"avrtiny" ? 6 : 18;
138 unsigned NRR =
Target.getABI() ==
"avrtiny" ? 4 : 8;
142 case llvm::Triple::aarch64:
143 case llvm::Triple::aarch64_32:
144 case llvm::Triple::aarch64_be: {
146 if (
Target.getABI() ==
"darwinpcs")
147 Kind = AArch64ABIKind::DarwinPCS;
148 else if (Triple.isOSWindows())
150 else if (
Target.getABI() ==
"aapcs-soft")
151 Kind = AArch64ABIKind::AAPCSSoft;
156 case llvm::Triple::wasm32:
157 case llvm::Triple::wasm64: {
159 if (
Target.getABI() ==
"experimental-mv")
160 Kind = WebAssemblyABIKind::ExperimentalMV;
164 case llvm::Triple::arm:
165 case llvm::Triple::armeb:
166 case llvm::Triple::thumb:
167 case llvm::Triple::thumbeb: {
168 if (Triple.getOS() == llvm::Triple::Win32)
172 StringRef ABIStr =
Target.getABI();
173 if (ABIStr ==
"apcs-gnu")
174 Kind = ARMABIKind::APCS;
175 else if (ABIStr ==
"aapcs16")
176 Kind = ARMABIKind::AAPCS16_VFP;
177 else if (CodeGenOpts.
FloatABI ==
"hard" ||
178 (CodeGenOpts.
FloatABI !=
"soft" && Triple.isHardFloatABI()))
179 Kind = ARMABIKind::AAPCS_VFP;
184 case llvm::Triple::ppc: {
185 if (Triple.isOSAIX())
192 case llvm::Triple::ppcle: {
197 case llvm::Triple::ppc64:
198 if (Triple.isOSAIX())
201 if (Triple.isOSBinFormatELF()) {
203 if (
Target.getABI() ==
"elfv2")
204 Kind = PPC64_SVR4_ABIKind::ELFv2;
205 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
210 case llvm::Triple::ppc64le: {
211 assert(Triple.isOSBinFormatELF() &&
"PPC64 LE non-ELF not supported!");
213 if (
Target.getABI() ==
"elfv1")
214 Kind = PPC64_SVR4_ABIKind::ELFv1;
215 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
220 case llvm::Triple::nvptx:
221 case llvm::Triple::nvptx64:
224 case llvm::Triple::msp430:
227 case llvm::Triple::riscv32:
228 case llvm::Triple::riscv64:
229 case llvm::Triple::riscv32be:
230 case llvm::Triple::riscv64be: {
231 StringRef ABIStr =
Target.getABI();
233 unsigned ABIFLen = 0;
234 if (ABIStr.ends_with(
"f"))
236 else if (ABIStr.ends_with(
"d"))
238 bool EABI = ABIStr.ends_with(
"e");
242 case llvm::Triple::systemz: {
243 bool SoftFloat = CodeGenOpts.
FloatABI ==
"soft";
244 bool HasVector = !SoftFloat &&
Target.getABI() ==
"vector";
248 case llvm::Triple::tce:
249 case llvm::Triple::tcele:
252 case llvm::Triple::x86: {
253 bool IsDarwinVectorABI = Triple.isOSDarwin();
254 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
256 if (Triple.getOS() == llvm::Triple::Win32) {
258 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
259 CodeGenOpts.NumRegisterParameters);
262 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
263 CodeGenOpts.NumRegisterParameters, CodeGenOpts.
FloatABI ==
"soft");
266 case llvm::Triple::x86_64: {
267 StringRef ABI =
Target.getABI();
268 X86AVXABILevel AVXLevel = (ABI ==
"avx512" ? X86AVXABILevel::AVX512
269 : ABI ==
"avx" ? X86AVXABILevel::AVX
270 : X86AVXABILevel::None);
272 switch (Triple.getOS()) {
273 case llvm::Triple::UEFI:
274 case llvm::Triple::Win32:
280 case llvm::Triple::hexagon:
282 case llvm::Triple::lanai:
284 case llvm::Triple::r600:
286 case llvm::Triple::amdgcn:
288 case llvm::Triple::sparc:
290 case llvm::Triple::sparcv9:
292 case llvm::Triple::xcore:
294 case llvm::Triple::arc:
296 case llvm::Triple::spir:
297 case llvm::Triple::spir64:
299 case llvm::Triple::spirv32:
300 case llvm::Triple::spirv64:
301 case llvm::Triple::spirv:
303 case llvm::Triple::dxil:
305 case llvm::Triple::ve:
307 case llvm::Triple::csky: {
308 bool IsSoftFloat = !
Target.hasFeature(
"hard-float-abi");
310 Target.hasFeature(
"fpuv2_df") ||
Target.hasFeature(
"fpuv3_df");
315 case llvm::Triple::bpfeb:
316 case llvm::Triple::bpfel:
318 case llvm::Triple::loongarch32:
319 case llvm::Triple::loongarch64: {
320 StringRef ABIStr =
Target.getABI();
321 unsigned ABIFRLen = 0;
322 if (ABIStr.ends_with(
"f"))
324 else if (ABIStr.ends_with(
"d"))
333 if (!TheTargetCodeGenInfo)
335 return *TheTargetCodeGenInfo;
339 llvm::LLVMContext &Context,
343 if (Opts.AlignDouble || Opts.OpenCL || Opts.HLSL)
346 llvm::Triple Triple =
Target.getTriple();
347 llvm::DataLayout DL(
Target.getDataLayoutString());
348 auto Check = [&](
const char *Name, llvm::Type *Ty,
unsigned Alignment) {
349 llvm::Align DLAlign = DL.getABITypeAlign(Ty);
350 llvm::Align ClangAlign(Alignment / 8);
351 if (DLAlign != ClangAlign) {
352 llvm::errs() <<
"For target " << Triple.str() <<
" type " << Name
353 <<
" mapping to " << *Ty <<
" has data layout alignment "
354 << DLAlign.value() <<
" while clang specifies "
355 << ClangAlign.value() <<
"\n";
360 Check(
"bool", llvm::Type::getIntNTy(Context,
Target.BoolWidth),
362 Check(
"short", llvm::Type::getIntNTy(Context,
Target.ShortWidth),
364 Check(
"int", llvm::Type::getIntNTy(Context,
Target.IntWidth),
366 Check(
"long", llvm::Type::getIntNTy(Context,
Target.LongWidth),
369 if (Triple.getArch() != llvm::Triple::m68k)
370 Check(
"long long", llvm::Type::getIntNTy(Context,
Target.LongLongWidth),
373 if (
Target.hasInt128Type() && !
Target.getTargetOpts().ForceEnableInt128 &&
374 !Triple.isAMDGPU() && !Triple.isSPIRV() &&
375 Triple.getArch() != llvm::Triple::ve)
376 Check(
"__int128", llvm::Type::getIntNTy(Context, 128),
Target.Int128Align);
378 if (
Target.hasFloat16Type())
379 Check(
"half", llvm::Type::getFloatingPointTy(Context, *
Target.HalfFormat),
381 if (
Target.hasBFloat16Type())
382 Check(
"bfloat", llvm::Type::getBFloatTy(Context),
Target.BFloat16Align);
383 Check(
"float", llvm::Type::getFloatingPointTy(Context, *
Target.FloatFormat),
385 Check(
"double", llvm::Type::getFloatingPointTy(Context, *
Target.DoubleFormat),
388 llvm::Type::getFloatingPointTy(Context, *
Target.LongDoubleFormat),
390 if (
Target.hasFloat128Type())
391 Check(
"__float128", llvm::Type::getFP128Ty(Context),
Target.Float128Align);
392 if (
Target.hasIbm128Type())
393 Check(
"__ibm128", llvm::Type::getPPC_FP128Ty(Context),
Target.Ibm128Align);
395 Check(
"void*", llvm::PointerType::getUnqual(Context),
Target.PointerAlign);
406 : Context(
C), LangOpts(
C.
getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
407 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
409 VMContext(M.
getContext()), VTables(*this), StackHandler(diags),
415 llvm::LLVMContext &LLVMContext = M.getContext();
416 VoidTy = llvm::Type::getVoidTy(LLVMContext);
417 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
418 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
419 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
420 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
421 HalfTy = llvm::Type::getHalfTy(LLVMContext);
422 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
423 FloatTy = llvm::Type::getFloatTy(LLVMContext);
424 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
430 C.toCharUnitsFromBits(
C.getTargetInfo().getMaxPointerWidth()).getQuantity();
432 C.toCharUnitsFromBits(
C.getTargetInfo().getIntAlign()).getQuantity();
434 llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getCharWidth());
435 IntTy = llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getIntWidth());
436 IntPtrTy = llvm::IntegerType::get(LLVMContext,
437 C.getTargetInfo().getMaxPointerWidth());
438 Int8PtrTy = llvm::PointerType::get(LLVMContext,
440 const llvm::DataLayout &DL = M.getDataLayout();
442 llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
444 llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
461 createOpenCLRuntime();
463 createOpenMPRuntime();
470 if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Thread | SanitizerKind::Type) ||
471 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
477 if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
478 CodeGenOpts.CoverageNotesFile.size() ||
479 CodeGenOpts.CoverageDataFile.size())
487 Block.GlobalUniqueCount = 0;
489 if (
C.getLangOpts().ObjC)
492 if (CodeGenOpts.hasProfileClangUse()) {
493 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
494 CodeGenOpts.ProfileInstrumentUsePath, *FS,
495 CodeGenOpts.ProfileRemappingFile);
496 if (
auto E = ReaderOrErr.takeError()) {
497 llvm::handleAllErrors(std::move(E), [&](
const llvm::ErrorInfoBase &EI) {
498 Diags.Report(diag::err_reading_profile)
499 << CodeGenOpts.ProfileInstrumentUsePath << EI.message();
503 PGOReader = std::move(ReaderOrErr.get());
508 if (CodeGenOpts.CoverageMapping)
512 if (CodeGenOpts.UniqueInternalLinkageNames &&
513 !
getModule().getSourceFileName().empty()) {
514 std::string Path =
getModule().getSourceFileName();
516 for (
const auto &Entry : LangOpts.MacroPrefixMap)
517 if (Path.rfind(Entry.first, 0) != std::string::npos) {
518 Path = Entry.second + Path.substr(Entry.first.size());
521 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path);
525 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
526 getModule().addModuleFlag(llvm::Module::Error,
"NumRegisterParameters",
527 CodeGenOpts.NumRegisterParameters);
536 const llvm::MemoryBuffer &FileBuffer = **BufOrErr;
537 for (llvm::line_iterator I(FileBuffer.getMemBufferRef(),
true), E;
539 this->MSHotPatchFunctions.push_back(std::string{*I});
541 auto &DE = Context.getDiagnostics();
542 DE.Report(diag::err_open_hotpatch_file_failed)
544 << BufOrErr.getError().message();
549 this->MSHotPatchFunctions.push_back(FuncName);
551 llvm::sort(this->MSHotPatchFunctions);
554 if (!Context.getAuxTargetInfo())
560void CodeGenModule::createObjCRuntime() {
577 llvm_unreachable(
"bad runtime kind");
580void CodeGenModule::createOpenCLRuntime() {
584void CodeGenModule::createOpenMPRuntime() {
585 if (!LangOpts.OMPHostIRFile.empty() && !FS->exists(LangOpts.OMPHostIRFile))
586 Diags.Report(diag::err_omp_host_ir_file_not_found)
587 << LangOpts.OMPHostIRFile;
592 case llvm::Triple::nvptx:
593 case llvm::Triple::nvptx64:
594 case llvm::Triple::amdgcn:
595 case llvm::Triple::spirv64:
598 "OpenMP AMDGPU/NVPTX/SPIRV is only prepared to deal with device code.");
599 OpenMPRuntime.reset(
new CGOpenMPRuntimeGPU(*
this));
602 if (LangOpts.OpenMPSimd)
603 OpenMPRuntime.reset(
new CGOpenMPSIMDRuntime(*
this));
605 OpenMPRuntime.reset(
new CGOpenMPRuntime(*
this));
610void CodeGenModule::createCUDARuntime() {
614void CodeGenModule::createHLSLRuntime() {
615 HLSLRuntime.reset(
new CGHLSLRuntime(*
this));
619 Replacements[Name] =
C;
622void CodeGenModule::applyReplacements() {
623 for (
auto &I : Replacements) {
624 StringRef MangledName = I.first;
625 llvm::Constant *Replacement = I.second;
630 auto *NewF = dyn_cast<llvm::Function>(Replacement);
632 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
633 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
636 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
637 CE->getOpcode() == llvm::Instruction::GetElementPtr);
638 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
643 OldF->replaceAllUsesWith(Replacement);
645 NewF->removeFromParent();
646 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
649 OldF->eraseFromParent();
654 GlobalValReplacements.push_back(std::make_pair(GV,
C));
657void CodeGenModule::applyGlobalValReplacements() {
658 for (
auto &I : GlobalValReplacements) {
659 llvm::GlobalValue *GV = I.first;
660 llvm::Constant *
C = I.second;
662 GV->replaceAllUsesWith(
C);
663 GV->eraseFromParent();
670 const llvm::Constant *
C;
671 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
672 C = GA->getAliasee();
673 else if (
auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
674 C = GI->getResolver();
678 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(
C->stripPointerCasts());
682 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
691 bool IsIFunc,
const llvm::GlobalValue *Alias,
const llvm::GlobalValue *&GV,
692 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
696 Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
700 if (GV->hasCommonLinkage()) {
701 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
702 if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
703 Diags.
Report(Location, diag::err_alias_to_common);
708 if (GV->isDeclaration()) {
709 Diags.
Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
710 Diags.
Report(Location, diag::note_alias_requires_mangled_name)
711 << IsIFunc << IsIFunc;
714 for (
const auto &[
Decl, Name] : MangledDeclNames) {
715 if (
const auto *ND = dyn_cast<NamedDecl>(
Decl.getDecl())) {
717 if (II && II->
getName() == GV->getName()) {
718 Diags.
Report(Location, diag::note_alias_mangled_name_alternative)
722 (Twine(IsIFunc ?
"ifunc" :
"alias") +
"(\"" + Name +
"\")")
732 const auto *F = dyn_cast<llvm::Function>(GV);
734 Diags.
Report(Location, diag::err_alias_to_undefined)
735 << IsIFunc << IsIFunc;
739 llvm::FunctionType *FTy = F->getFunctionType();
740 if (!FTy->getReturnType()->isPointerTy()) {
741 Diags.
Report(Location, diag::err_ifunc_resolver_return);
755 if (GVar->hasAttribute(
"toc-data")) {
756 auto GVId = GVar->getName();
759 Diags.
Report(Location, diag::warn_toc_unsupported_type)
760 << GVId <<
"the variable has an alias";
762 llvm::AttributeSet CurrAttributes = GVar->getAttributes();
763 llvm::AttributeSet NewAttributes =
764 CurrAttributes.removeAttribute(GVar->getContext(),
"toc-data");
765 GVar->setAttributes(NewAttributes);
769void CodeGenModule::checkAliases() {
774 DiagnosticsEngine &Diags =
getDiags();
775 for (
const GlobalDecl &GD : Aliases) {
777 SourceLocation Location;
779 bool IsIFunc = D->hasAttr<IFuncAttr>();
780 if (
const Attr *A = D->getDefiningAttr()) {
781 Location = A->getLocation();
782 Range = A->getRange();
784 llvm_unreachable(
"Not an alias or ifunc?");
788 const llvm::GlobalValue *GV =
nullptr;
790 MangledDeclNames, Range)) {
796 if (
const llvm::GlobalVariable *GVar =
797 dyn_cast<const llvm::GlobalVariable>(GV))
801 llvm::Constant *Aliasee =
805 llvm::GlobalValue *AliaseeGV;
806 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
811 if (
const SectionAttr *SA = D->getAttr<SectionAttr>()) {
812 StringRef AliasSection = SA->getName();
813 if (AliasSection != AliaseeGV->getSection())
814 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
815 << AliasSection << IsIFunc << IsIFunc;
823 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
824 if (GA->isInterposable()) {
825 Diags.Report(Location, diag::warn_alias_to_weak_alias)
826 << GV->getName() << GA->getName() << IsIFunc;
827 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
828 GA->getAliasee(), Alias->getType());
840 llvm::Attribute::DisableSanitizerInstrumentation);
845 for (
const GlobalDecl &GD : Aliases) {
848 Alias->replaceAllUsesWith(llvm::PoisonValue::get(Alias->getType()));
849 Alias->eraseFromParent();
854 DeferredDeclsToEmit.clear();
855 EmittedDeferredDecls.clear();
856 DeferredAnnotations.clear();
858 OpenMPRuntime->clear();
862 StringRef MainFile) {
865 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
866 if (MainFile.empty())
867 MainFile =
"<stdin>";
868 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
871 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
874 Diags.
Report(diag::warn_profile_data_missing) << Visited << Missing;
878static std::optional<llvm::GlobalValue::VisibilityTypes>
885 return llvm::GlobalValue::DefaultVisibility;
887 return llvm::GlobalValue::HiddenVisibility;
889 return llvm::GlobalValue::ProtectedVisibility;
891 llvm_unreachable(
"unknown option value!");
896 std::optional<llvm::GlobalValue::VisibilityTypes>
V) {
905 GV.setDSOLocal(
false);
906 GV.setVisibility(*
V);
911 if (!LO.VisibilityFromDLLStorageClass)
914 std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
917 std::optional<llvm::GlobalValue::VisibilityTypes>
918 NoDLLStorageClassVisibility =
921 std::optional<llvm::GlobalValue::VisibilityTypes>
922 ExternDeclDLLImportVisibility =
925 std::optional<llvm::GlobalValue::VisibilityTypes>
926 ExternDeclNoDLLStorageClassVisibility =
929 for (llvm::GlobalValue &GV : M.global_values()) {
930 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
933 if (GV.isDeclarationForLinker())
935 llvm::GlobalValue::DLLImportStorageClass
936 ? ExternDeclDLLImportVisibility
937 : ExternDeclNoDLLStorageClassVisibility);
940 llvm::GlobalValue::DLLExportStorageClass
941 ? DLLExportVisibility
942 : NoDLLStorageClassVisibility);
944 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
949 const llvm::Triple &Triple,
953 return LangOpts.getStackProtector() == Mode;
956std::optional<llvm::Attribute::AttrKind>
958 if (D && D->
hasAttr<NoStackProtectorAttr>())
960 else if (D && D->
hasAttr<StrictGuardStackCheckAttr>() &&
962 return llvm::Attribute::StackProtectStrong;
964 return llvm::Attribute::StackProtect;
966 return llvm::Attribute::StackProtectStrong;
968 return llvm::Attribute::StackProtectReq;
975 EmitModuleInitializers(Primary);
977 DeferredDecls.insert_range(EmittedDeferredDecls);
978 EmittedDeferredDecls.clear();
979 EmitVTablesOpportunistically();
980 applyGlobalValReplacements();
982 emitMultiVersionFunctions();
983 emitPFPFieldsWithEvaluatedOffset();
985 if (Context.getLangOpts().IncrementalExtensions &&
986 GlobalTopLevelStmtBlockInFlight.first) {
988 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->
getEndLoc());
989 GlobalTopLevelStmtBlockInFlight = {
nullptr,
nullptr};
995 EmitCXXModuleInitFunc(Primary);
997 EmitCXXGlobalInitFunc();
998 EmitCXXGlobalCleanUpFunc();
999 registerGlobalDtorsWithAtExit();
1000 EmitCXXThreadLocalInitFunc();
1002 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
1004 if (Context.getLangOpts().CUDA && CUDARuntime) {
1005 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
1008 if (OpenMPRuntime) {
1009 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
1010 OpenMPRuntime->clear();
1014 PGOReader->getSummary(
false).getMD(VMContext),
1015 llvm::ProfileSummary::PSK_Instr);
1016 if (PGOStats.hasDiagnostics())
1022 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
1023 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
1025 EmitStaticExternCAliases();
1030 if (CoverageMapping)
1031 CoverageMapping->emit();
1032 if (CodeGenOpts.SanitizeCfiCrossDso) {
1036 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
1038 emitAtAvailableLinkGuard();
1039 if (Context.getTargetInfo().getTriple().isWasm())
1046 if (
getTarget().getTargetOpts().CodeObjectVersion !=
1047 llvm::CodeObjectVersionKind::COV_None) {
1048 getModule().addModuleFlag(llvm::Module::Error,
1049 "amdhsa_code_object_version",
1050 getTarget().getTargetOpts().CodeObjectVersion);
1055 auto *MDStr = llvm::MDString::get(
1060 getModule().addModuleFlag(llvm::Module::Error,
"amdgpu_printf_kind",
1069 if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) {
1071 for (
auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) {
1073 if (
auto *FD = dyn_cast<FunctionDecl>(D))
1077 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1081 llvm::ArrayType *ATy = llvm::ArrayType::get(
Int8PtrTy, UsedArray.size());
1083 auto *GV =
new llvm::GlobalVariable(
1084 getModule(), ATy,
false, llvm::GlobalValue::InternalLinkage,
1085 llvm::ConstantArray::get(ATy, UsedArray),
"__clang_gpu_used_external");
1091 auto *GV =
new llvm::GlobalVariable(
1093 llvm::Constant::getNullValue(
Int8Ty),
1102 if (CodeGenOpts.Autolink &&
1103 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
1104 EmitModuleLinkOptions();
1119 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
1120 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.dependent-libraries");
1121 for (
auto *MD : ELFDependentLibraries)
1122 NMD->addOperand(MD);
1125 if (CodeGenOpts.DwarfVersion) {
1126 getModule().addModuleFlag(llvm::Module::Max,
"Dwarf Version",
1127 CodeGenOpts.DwarfVersion);
1130 if (CodeGenOpts.Dwarf64)
1131 getModule().addModuleFlag(llvm::Module::Max,
"DWARF64", 1);
1133 if (Context.getLangOpts().SemanticInterposition)
1135 getModule().setSemanticInterposition(
true);
1137 if (CodeGenOpts.EmitCodeView) {
1139 getModule().addModuleFlag(llvm::Module::Warning,
"CodeView", 1);
1141 if (CodeGenOpts.CodeViewGHash) {
1142 getModule().addModuleFlag(llvm::Module::Warning,
"CodeViewGHash", 1);
1144 if (CodeGenOpts.ControlFlowGuard) {
1147 llvm::Module::Warning,
"cfguard",
1148 static_cast<unsigned>(llvm::ControlFlowGuardMode::Enabled));
1149 }
else if (CodeGenOpts.ControlFlowGuardNoChecks) {
1152 llvm::Module::Warning,
"cfguard",
1153 static_cast<unsigned>(llvm::ControlFlowGuardMode::TableOnly));
1155 if (CodeGenOpts.EHContGuard) {
1157 getModule().addModuleFlag(llvm::Module::Warning,
"ehcontguard", 1);
1159 if (Context.getLangOpts().Kernel) {
1161 getModule().addModuleFlag(llvm::Module::Warning,
"ms-kernel", 1);
1163 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
1168 getModule().addModuleFlag(llvm::Module::Error,
"StrictVTablePointers",1);
1170 llvm::Metadata *Ops[2] = {
1171 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
1172 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1173 llvm::Type::getInt32Ty(VMContext), 1))};
1175 getModule().addModuleFlag(llvm::Module::Require,
1176 "StrictVTablePointersRequirement",
1177 llvm::MDNode::get(VMContext, Ops));
1183 getModule().addModuleFlag(llvm::Module::Warning,
"Debug Info Version",
1184 llvm::DEBUG_METADATA_VERSION);
1189 uint64_t WCharWidth =
1190 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
1191 if (WCharWidth !=
getTriple().getDefaultWCharSize())
1192 getModule().addModuleFlag(llvm::Module::Error,
"wchar_size", WCharWidth);
1195 getModule().addModuleFlag(llvm::Module::Warning,
1196 "zos_product_major_version",
1197 uint32_t(CLANG_VERSION_MAJOR));
1198 getModule().addModuleFlag(llvm::Module::Warning,
1199 "zos_product_minor_version",
1200 uint32_t(CLANG_VERSION_MINOR));
1201 getModule().addModuleFlag(llvm::Module::Warning,
"zos_product_patchlevel",
1202 uint32_t(CLANG_VERSION_PATCHLEVEL));
1204 getModule().addModuleFlag(llvm::Module::Error,
"zos_product_id",
1205 llvm::MDString::get(VMContext, ProductId));
1210 getModule().addModuleFlag(llvm::Module::Error,
"zos_cu_language",
1211 llvm::MDString::get(VMContext, lang_str));
1213 time_t TT = PreprocessorOpts.SourceDateEpoch
1214 ? *PreprocessorOpts.SourceDateEpoch
1215 : std::time(
nullptr);
1216 getModule().addModuleFlag(llvm::Module::Max,
"zos_translation_time",
1217 static_cast<uint64_t
>(TT));
1220 getModule().addModuleFlag(llvm::Module::Error,
"zos_le_char_mode",
1221 llvm::MDString::get(VMContext,
"ascii"));
1224 llvm::Triple T = Context.getTargetInfo().getTriple();
1225 if (T.isARM() || T.isThumb()) {
1227 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
1228 getModule().addModuleFlag(llvm::Module::Error,
"min_enum_size", EnumWidth);
1232 StringRef ABIStr = Target.getABI();
1233 llvm::LLVMContext &Ctx = TheModule.getContext();
1234 getModule().addModuleFlag(llvm::Module::Error,
"target-abi",
1235 llvm::MDString::get(Ctx, ABIStr));
1240 const std::vector<std::string> &Features =
1243 llvm::RISCVISAInfo::parseFeatures(T.isRISCV64() ? 64 : 32, Features);
1244 if (!errorToBool(ParseResult.takeError()))
1246 llvm::Module::AppendUnique,
"riscv-isa",
1248 Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString())));
1251 if (CodeGenOpts.SanitizeCfiCrossDso) {
1253 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
1256 if (CodeGenOpts.WholeProgramVTables) {
1260 getModule().addModuleFlag(llvm::Module::Error,
"Virtual Function Elim",
1261 CodeGenOpts.VirtualFunctionElimination);
1264 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
1265 getModule().addModuleFlag(llvm::Module::Override,
1266 "CFI Canonical Jump Tables",
1267 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1270 if (CodeGenOpts.SanitizeCfiICallNormalizeIntegers) {
1271 getModule().addModuleFlag(llvm::Module::Override,
"cfi-normalize-integers",
1275 if (!CodeGenOpts.UniqueSourceFileIdentifier.empty()) {
1277 llvm::Module::Append,
"Unique Source File Identifier",
1279 TheModule.getContext(),
1280 llvm::MDString::get(TheModule.getContext(),
1281 CodeGenOpts.UniqueSourceFileIdentifier)));
1284 if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) {
1285 getModule().addModuleFlag(llvm::Module::Override,
"kcfi", 1);
1288 if (CodeGenOpts.PatchableFunctionEntryOffset)
1289 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-offset",
1290 CodeGenOpts.PatchableFunctionEntryOffset);
1291 if (CodeGenOpts.SanitizeKcfiArity)
1292 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-arity", 1);
1295 llvm::Module::Override,
"kcfi-hash",
1296 llvm::MDString::get(
1298 llvm::stringifyKCFIHashAlgorithm(CodeGenOpts.SanitizeKcfiHash)));
1301 if (CodeGenOpts.CFProtectionReturn &&
1302 Target.checkCFProtectionReturnSupported(
getDiags())) {
1304 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-return",
1308 if (CodeGenOpts.CFProtectionBranch &&
1309 Target.checkCFProtectionBranchSupported(
getDiags())) {
1311 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-branch",
1314 auto Scheme = CodeGenOpts.getCFBranchLabelScheme();
1315 if (Target.checkCFBranchLabelSchemeSupported(Scheme,
getDiags())) {
1317 Scheme = Target.getDefaultCFBranchLabelScheme();
1319 llvm::Module::Error,
"cf-branch-label-scheme",
1325 if (CodeGenOpts.FunctionReturnThunks)
1326 getModule().addModuleFlag(llvm::Module::Override,
"function_return_thunk_extern", 1);
1328 if (CodeGenOpts.IndirectBranchCSPrefix)
1329 getModule().addModuleFlag(llvm::Module::Override,
"indirect_branch_cs_prefix", 1);
1340 if (Context.getTargetInfo().hasFeature(
"ptrauth") &&
1341 LangOpts.getSignReturnAddressScope() !=
1343 getModule().addModuleFlag(llvm::Module::Override,
1344 "sign-return-address-buildattr", 1);
1345 if (LangOpts.Sanitize.has(SanitizerKind::MemtagStack))
1346 getModule().addModuleFlag(llvm::Module::Override,
1347 "tag-stack-memory-buildattr", 1);
1349 if (T.isARM() || T.isThumb() || T.isAArch64()) {
1357 if (LangOpts.BranchTargetEnforcement)
1358 getModule().addModuleFlag(llvm::Module::Min,
"branch-target-enforcement",
1360 if (LangOpts.BranchProtectionPAuthLR)
1361 getModule().addModuleFlag(llvm::Module::Min,
"branch-protection-pauth-lr",
1363 if (LangOpts.GuardedControlStack)
1364 getModule().addModuleFlag(llvm::Module::Min,
"guarded-control-stack", 2);
1365 if (LangOpts.hasSignReturnAddress())
1366 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address", 2);
1367 if (LangOpts.isSignReturnAddressScopeAll())
1368 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address-all",
1370 if (!LangOpts.isSignReturnAddressWithAKey())
1371 getModule().addModuleFlag(llvm::Module::Min,
1372 "sign-return-address-with-bkey", 2);
1374 if (LangOpts.PointerAuthELFGOT)
1375 getModule().addModuleFlag(llvm::Module::Min,
"ptrauth-elf-got", 1);
1378 if (LangOpts.PointerAuthCalls)
1379 getModule().addModuleFlag(llvm::Module::Min,
"ptrauth-sign-personality",
1382 using namespace llvm::ELF;
1383 uint64_t PAuthABIVersion =
1384 (LangOpts.PointerAuthIntrinsics
1385 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS) |
1386 (LangOpts.PointerAuthCalls
1387 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS) |
1388 (LangOpts.PointerAuthReturns
1389 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS) |
1390 (LangOpts.PointerAuthAuthTraps
1391 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS) |
1392 (LangOpts.PointerAuthVTPtrAddressDiscrimination
1393 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR) |
1394 (LangOpts.PointerAuthVTPtrTypeDiscrimination
1395 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR) |
1396 (LangOpts.PointerAuthInitFini
1397 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI) |
1398 (LangOpts.PointerAuthInitFiniAddressDiscrimination
1399 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC) |
1400 (LangOpts.PointerAuthELFGOT
1401 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT) |
1402 (LangOpts.PointerAuthIndirectGotos
1403 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS) |
1404 (LangOpts.PointerAuthTypeInfoVTPtrDiscrimination
1405 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR) |
1406 (LangOpts.PointerAuthFunctionTypeDiscrimination
1407 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR);
1408 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR ==
1409 AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
1410 "Update when new enum items are defined");
1411 if (PAuthABIVersion != 0) {
1412 getModule().addModuleFlag(llvm::Module::Error,
1413 "aarch64-elf-pauthabi-platform",
1414 AARCH64_PAUTH_PLATFORM_LLVM_LINUX);
1415 getModule().addModuleFlag(llvm::Module::Error,
1416 "aarch64-elf-pauthabi-version",
1421 if ((T.isARM() || T.isThumb()) &&
getTriple().isTargetAEABI() &&
1423 uint32_t TagVal = 0;
1424 llvm::Module::ModFlagBehavior DenormalTagBehavior = llvm::Module::Max;
1426 llvm::DenormalMode::getPositiveZero()) {
1427 TagVal = llvm::ARMBuildAttrs::PositiveZero;
1429 llvm::DenormalMode::getIEEE()) {
1430 TagVal = llvm::ARMBuildAttrs::IEEEDenormals;
1431 DenormalTagBehavior = llvm::Module::Override;
1433 llvm::DenormalMode::getPreserveSign()) {
1434 TagVal = llvm::ARMBuildAttrs::PreserveFPSign;
1436 getModule().addModuleFlag(DenormalTagBehavior,
"arm-eabi-fp-denormal",
1441 getModule().addModuleFlag(llvm::Module::Min,
"arm-eabi-fp-exceptions",
1442 llvm::ARMBuildAttrs::Allowed);
1445 TagVal = llvm::ARMBuildAttrs::AllowIEEENormal;
1447 TagVal = llvm::ARMBuildAttrs::AllowIEEE754;
1448 getModule().addModuleFlag(llvm::Module::Min,
"arm-eabi-fp-number-model",
1452 if (CodeGenOpts.StackClashProtector)
1454 llvm::Module::Override,
"probe-stack",
1455 llvm::MDString::get(TheModule.getContext(),
"inline-asm"));
1457 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
1458 getModule().addModuleFlag(llvm::Module::Min,
"stack-probe-size",
1459 CodeGenOpts.StackProbeSize);
1461 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1462 llvm::LLVMContext &Ctx = TheModule.getContext();
1464 llvm::Module::Error,
"MemProfProfileFilename",
1465 llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
1468 if (LangOpts.CUDAIsDevice &&
getTriple().isNVPTX()) {
1472 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
1473 CodeGenOpts.FP32DenormalMode.Output !=
1474 llvm::DenormalMode::IEEE);
1477 if (LangOpts.EHAsynch)
1478 getModule().addModuleFlag(llvm::Module::Warning,
"eh-asynch", 1);
1481 if (CodeGenOpts.ImportCallOptimization)
1482 getModule().addModuleFlag(llvm::Module::Warning,
"import-call-optimization",
1486 if (CodeGenOpts.getWinX64EHUnwindV2() != llvm::WinX64EHUnwindV2Mode::Disabled)
1488 llvm::Module::Warning,
"winx64-eh-unwindv2",
1489 static_cast<unsigned>(CodeGenOpts.getWinX64EHUnwindV2()));
1493 getModule().addModuleFlag(llvm::Module::Max,
"openmp", LangOpts.OpenMP);
1495 getModule().addModuleFlag(llvm::Module::Max,
"openmp-device",
1499 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())) {
1500 EmitOpenCLMetadata();
1507 auto Version = LangOpts.getOpenCLCompatibleVersion();
1508 llvm::Metadata *SPIRVerElts[] = {
1509 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1511 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1512 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
1513 llvm::NamedMDNode *SPIRVerMD =
1514 TheModule.getOrInsertNamedMetadata(
"opencl.spir.version");
1515 llvm::LLVMContext &Ctx = TheModule.getContext();
1516 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
1524 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
1525 assert(PLevel < 3 &&
"Invalid PIC Level");
1526 getModule().setPICLevel(
static_cast<llvm::PICLevel::Level
>(PLevel));
1527 if (Context.getLangOpts().PIE)
1528 getModule().setPIELevel(
static_cast<llvm::PIELevel::Level
>(PLevel));
1532 unsigned CM = llvm::StringSwitch<unsigned>(
getCodeGenOpts().CodeModel)
1533 .Case(
"tiny", llvm::CodeModel::Tiny)
1534 .Case(
"small", llvm::CodeModel::Small)
1535 .Case(
"kernel", llvm::CodeModel::Kernel)
1536 .Case(
"medium", llvm::CodeModel::Medium)
1537 .Case(
"large", llvm::CodeModel::Large)
1540 llvm::CodeModel::Model codeModel =
static_cast<llvm::CodeModel::Model
>(CM);
1543 if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
1544 Context.getTargetInfo().getTriple().getArch() ==
1545 llvm::Triple::x86_64) {
1551 if (CodeGenOpts.NoPLT)
1554 CodeGenOpts.DirectAccessExternalData !=
1555 getModule().getDirectAccessExternalData()) {
1556 getModule().setDirectAccessExternalData(
1557 CodeGenOpts.DirectAccessExternalData);
1559 if (CodeGenOpts.UnwindTables)
1560 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1562 switch (CodeGenOpts.getFramePointer()) {
1567 getModule().setFramePointer(llvm::FramePointerKind::Reserved);
1570 getModule().setFramePointer(llvm::FramePointerKind::NonLeafNoReserve);
1573 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1576 getModule().setFramePointer(llvm::FramePointerKind::All);
1580 SimplifyPersonality();
1593 EmitVersionIdentMetadata();
1596 EmitCommandLineMetadata();
1604 getModule().setStackProtectorGuardSymbol(
1607 getModule().setStackProtectorGuardOffset(
1612 getModule().addModuleFlag(llvm::Module::Override,
"SkipRaxSetup", 1);
1614 getModule().addModuleFlag(llvm::Module::Override,
"RegCallv4", 1);
1616 if (
getContext().getTargetInfo().getMaxTLSAlign())
1617 getModule().addModuleFlag(llvm::Module::Error,
"MaxTLSAlign",
1618 getContext().getTargetInfo().getMaxTLSAlign());
1636 if (!MustTailCallUndefinedGlobals.empty()) {
1638 for (
auto &I : MustTailCallUndefinedGlobals) {
1639 if (!I.first->isDefined())
1640 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1644 if (!Entry || Entry->isWeakForLinker() ||
1645 Entry->isDeclarationForLinker())
1646 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1650 for (
auto &I : MustTailCallUndefinedGlobals) {
1659 if (Entry->isDeclarationForLinker()) {
1662 Entry->hasHiddenVisibility() || Entry->hasProtectedVisibility();
1664 CalleeIsLocal = Entry->isDSOLocal();
1668 getDiags().
Report(I.second, diag::err_mips_impossible_musttail) << 1;
1679 auto *ErrnoTBAAMD = TheModule.getOrInsertNamedMetadata(
ErrnoTBAAMDName);
1680 ErrnoTBAAMD->addOperand(IntegerNode);
1685void CodeGenModule::EmitOpenCLMetadata() {
1691 auto EmitVersion = [
this](StringRef MDName,
int Version) {
1692 llvm::Metadata *OCLVerElts[] = {
1693 llvm::ConstantAsMetadata::get(
1694 llvm::ConstantInt::get(
Int32Ty, Version / 100)),
1695 llvm::ConstantAsMetadata::get(
1696 llvm::ConstantInt::get(
Int32Ty, (Version % 100) / 10))};
1697 llvm::NamedMDNode *OCLVerMD = TheModule.getOrInsertNamedMetadata(MDName);
1698 llvm::LLVMContext &Ctx = TheModule.getContext();
1699 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
1702 EmitVersion(
"opencl.ocl.version", CLVersion);
1703 if (LangOpts.OpenCLCPlusPlus) {
1705 EmitVersion(
"opencl.cxx.version", LangOpts.OpenCLCPlusPlusVersion);
1709void CodeGenModule::EmitBackendOptionsMetadata(
1710 const CodeGenOptions &CodeGenOpts) {
1712 getModule().addModuleFlag(llvm::Module::Min,
"SmallDataLimit",
1713 CodeGenOpts.SmallDataLimit);
1717 if (LangOpts.AllocTokenMode) {
1718 StringRef S = llvm::getAllocTokenModeAsString(*LangOpts.AllocTokenMode);
1719 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-mode",
1720 llvm::MDString::get(VMContext, S));
1722 if (LangOpts.AllocTokenMax)
1724 llvm::Module::Error,
"alloc-token-max",
1725 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1726 *LangOpts.AllocTokenMax));
1727 if (CodeGenOpts.SanitizeAllocTokenFastABI)
1728 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-fast-abi", 1);
1729 if (CodeGenOpts.SanitizeAllocTokenExtended)
1730 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-extended", 1);
1746 return TBAA->getTypeInfo(QTy);
1765 return TBAA->getAccessInfo(AccessType);
1772 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
1778 return TBAA->getTBAAStructInfo(QTy);
1784 return TBAA->getBaseTypeInfo(QTy);
1790 return TBAA->getAccessTagInfo(Info);
1797 return TBAA->mergeTBAAInfoForCast(SourceInfo,
TargetInfo);
1805 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
1813 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
1819 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
1824 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
1836 std::string Msg =
Type;
1838 diag::err_codegen_unsupported)
1844 diag::err_codegen_unsupported)
1851 std::string Msg =
Type;
1853 diag::err_codegen_unsupported)
1858 llvm::function_ref<
void()> Fn) {
1859 StackHandler.runWithSufficientStackSpace(Loc, Fn);
1869 if (GV->hasLocalLinkage()) {
1870 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1883 if (Context.getLangOpts().OpenMP &&
1884 Context.getLangOpts().OpenMPIsTargetDevice &&
isa<VarDecl>(D) &&
1885 D->
hasAttr<OMPDeclareTargetDeclAttr>() &&
1886 D->
getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
1887 OMPDeclareTargetDeclAttr::DT_NoHost &&
1889 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1894 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1898 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
1902 if (GV->hasDLLExportStorageClass()) {
1905 diag::err_hidden_visibility_dllexport);
1908 diag::err_non_default_visibility_dllimport);
1914 !GV->isDeclarationForLinker())
1919 llvm::GlobalValue *GV) {
1920 if (GV->hasLocalLinkage())
1923 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
1927 if (GV->hasDLLImportStorageClass())
1930 const llvm::Triple &TT = CGM.
getTriple();
1932 if (TT.isOSCygMing()) {
1950 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
1958 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
1962 if (!TT.isOSBinFormatELF())
1968 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1976 return !(CGM.
getLangOpts().SemanticInterposition ||
1981 if (!GV->isDeclarationForLinker())
1987 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
1994 if (CGOpts.DirectAccessExternalData) {
2000 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
2001 if (!Var->isThreadLocal())
2026 const auto *D = dyn_cast<NamedDecl>(GD.
getDecl());
2028 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
2038 if (D->
hasAttr<DLLImportAttr>())
2039 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2040 else if ((D->
hasAttr<DLLExportAttr>() ||
2042 !GV->isDeclarationForLinker())
2043 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2063 GV->setPartition(CodeGenOpts.SymbolPartition);
2067 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
2068 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
2069 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
2070 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
2071 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
2074llvm::GlobalVariable::ThreadLocalMode
2076 switch (CodeGenOpts.getDefaultTLSModel()) {
2078 return llvm::GlobalVariable::GeneralDynamicTLSModel;
2080 return llvm::GlobalVariable::LocalDynamicTLSModel;
2082 return llvm::GlobalVariable::InitialExecTLSModel;
2084 return llvm::GlobalVariable::LocalExecTLSModel;
2086 llvm_unreachable(
"Invalid TLS model!");
2090 assert(D.
getTLSKind() &&
"setting TLS mode on non-TLS var!");
2092 llvm::GlobalValue::ThreadLocalMode TLM;
2096 if (
const TLSModelAttr *
Attr = D.
getAttr<TLSModelAttr>()) {
2100 GV->setThreadLocalMode(TLM);
2106 return (Twine(
'.') + Twine(
Target.CPUSpecificManglingCharacter(Name))).str();
2110 const CPUSpecificAttr *
Attr,
2132 bool OmitMultiVersionMangling =
false) {
2134 llvm::raw_svector_ostream Out(Buffer);
2143 assert(II &&
"Attempt to mangle unnamed decl.");
2144 const auto *FD = dyn_cast<FunctionDecl>(ND);
2149 Out <<
"__regcall4__" << II->
getName();
2151 Out <<
"__regcall3__" << II->
getName();
2152 }
else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
2154 Out <<
"__device_stub__" << II->
getName();
2156 DeviceKernelAttr::isOpenCLSpelling(
2157 FD->getAttr<DeviceKernelAttr>()) &&
2159 Out <<
"__clang_ocl_kern_imp_" << II->
getName();
2175 "Hash computed when not explicitly requested");
2179 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
2180 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
2181 switch (FD->getMultiVersionKind()) {
2185 FD->getAttr<CPUSpecificAttr>(),
2189 auto *
Attr = FD->getAttr<TargetAttr>();
2190 assert(
Attr &&
"Expected TargetAttr to be present "
2191 "for attribute mangling");
2197 auto *
Attr = FD->getAttr<TargetVersionAttr>();
2198 assert(
Attr &&
"Expected TargetVersionAttr to be present "
2199 "for attribute mangling");
2205 auto *
Attr = FD->getAttr<TargetClonesAttr>();
2206 assert(
Attr &&
"Expected TargetClonesAttr to be present "
2207 "for attribute mangling");
2214 llvm_unreachable(
"None multiversion type isn't valid here");
2224 return std::string(Out.str());
2227void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
2228 const FunctionDecl *FD,
2229 StringRef &CurName) {
2236 std::string NonTargetName =
2244 "Other GD should now be a multiversioned function");
2254 if (OtherName != NonTargetName) {
2257 const auto ExistingRecord = Manglings.find(NonTargetName);
2258 if (ExistingRecord != std::end(Manglings))
2259 Manglings.remove(&(*ExistingRecord));
2260 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
2265 CurName = OtherNameRef;
2267 Entry->setName(OtherName);
2277 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
2291 auto FoundName = MangledDeclNames.find(CanonicalGD);
2292 if (FoundName != MangledDeclNames.end())
2293 return FoundName->second;
2330 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
2331 return MangledDeclNames[CanonicalGD] =
Result.first->first();
2340 llvm::raw_svector_ostream Out(Buffer);
2343 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
2344 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(D))
2346 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(D))
2351 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
2352 return Result.first->first();
2356 auto it = MangledDeclNames.begin();
2357 while (it != MangledDeclNames.end()) {
2358 if (it->second == Name)
2373 llvm::Constant *AssociatedData) {
2375 GlobalCtors.push_back(
Structor(Priority, LexOrder, Ctor, AssociatedData));
2381 bool IsDtorAttrFunc) {
2382 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2384 DtorsUsingAtExit[Priority].push_back(Dtor);
2389 GlobalDtors.push_back(
Structor(Priority, ~0
U, Dtor,
nullptr));
2392void CodeGenModule::EmitCtorList(CtorList &Fns,
const char *GlobalName) {
2393 if (Fns.empty())
return;
2399 llvm::PointerType *PtrTy = llvm::PointerType::get(
2400 getLLVMContext(), TheModule.getDataLayout().getProgramAddressSpace());
2403 llvm::StructType *CtorStructTy = llvm::StructType::get(
Int32Ty, PtrTy, PtrTy);
2407 auto Ctors = Builder.beginArray(CtorStructTy);
2408 for (
const auto &I : Fns) {
2409 auto Ctor = Ctors.beginStruct(CtorStructTy);
2410 Ctor.addInt(
Int32Ty, I.Priority);
2411 if (InitFiniAuthSchema) {
2412 llvm::Constant *StorageAddress =
2414 ? llvm::ConstantExpr::getIntToPtr(
2415 llvm::ConstantInt::get(
2417 llvm::ConstantPtrAuth::AddrDiscriminator_CtorsDtors),
2421 I.Initializer, InitFiniAuthSchema.
getKey(), StorageAddress,
2422 llvm::ConstantInt::get(
2424 Ctor.add(SignedCtorPtr);
2426 Ctor.add(I.Initializer);
2428 if (I.AssociatedData)
2429 Ctor.add(I.AssociatedData);
2431 Ctor.addNullPointer(PtrTy);
2432 Ctor.finishAndAddTo(Ctors);
2435 auto List = Ctors.finishAndCreateGlobal(GlobalName,
getPointerAlign(),
2437 llvm::GlobalValue::AppendingLinkage);
2441 List->setAlignment(std::nullopt);
2446llvm::GlobalValue::LinkageTypes
2452 if (
const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
2459 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2460 if (!MDS)
return nullptr;
2462 return llvm::ConstantInt::get(
Int64Ty, llvm::MD5Hash(MDS->getString()));
2469 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2470 if (!UD->
hasAttr<TransparentUnionAttr>())
2472 if (!UD->
fields().empty())
2473 return UD->
fields().begin()->getType();
2482 bool GeneralizePointers) {
2495 bool GeneralizePointers) {
2498 for (
auto &Param : FnType->param_types())
2499 GeneralizedParams.push_back(
2503 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers),
2504 GeneralizedParams, FnType->getExtProtoInfo());
2509 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers));
2511 llvm_unreachable(
"Encountered unknown FunctionType");
2519 FnType->getReturnType(), FnType->getParamTypes(),
2520 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
2522 std::string OutName;
2523 llvm::raw_string_ostream Out(OutName);
2531 Out <<
".normalized";
2533 Out <<
".generalized";
2535 return llvm::ConstantInt::get(
2541 llvm::Function *F,
bool IsThunk) {
2543 llvm::AttributeList PAL;
2546 if (
CallingConv == llvm::CallingConv::X86_VectorCall &&
2550 Loc = D->getLocation();
2552 Error(Loc,
"__vectorcall calling convention is not currently supported");
2554 F->setAttributes(PAL);
2555 F->setCallingConv(
static_cast<llvm::CallingConv::ID
>(
CallingConv));
2559 std::string ReadOnlyQual(
"__read_only");
2560 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2561 if (ReadOnlyPos != std::string::npos)
2563 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2565 std::string WriteOnlyQual(
"__write_only");
2566 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2567 if (WriteOnlyPos != std::string::npos)
2568 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2570 std::string ReadWriteQual(
"__read_write");
2571 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2572 if (ReadWritePos != std::string::npos)
2573 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2606 assert(((FD && CGF) || (!FD && !CGF)) &&
2607 "Incorrect use - FD and CGF should either be both null or not!");
2633 for (
unsigned i = 0, e = FD->
getNumParams(); i != e; ++i) {
2636 argNames.push_back(llvm::MDString::get(VMContext, parm->
getName()));
2641 std::string typeQuals;
2645 const Decl *PDecl = parm;
2647 PDecl = TD->getDecl();
2648 const OpenCLAccessAttr *A = PDecl->
getAttr<OpenCLAccessAttr>();
2649 if (A && A->isWriteOnly())
2650 accessQuals.push_back(llvm::MDString::get(VMContext,
"write_only"));
2651 else if (A && A->isReadWrite())
2652 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_write"));
2654 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_only"));
2656 accessQuals.push_back(llvm::MDString::get(VMContext,
"none"));
2658 auto getTypeSpelling = [&](
QualType Ty) {
2659 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2661 if (Ty.isCanonical()) {
2662 StringRef typeNameRef = typeName;
2664 if (typeNameRef.consume_front(
"unsigned "))
2665 return std::string(
"u") + typeNameRef.str();
2666 if (typeNameRef.consume_front(
"signed "))
2667 return typeNameRef.str();
2677 addressQuals.push_back(
2678 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(
2682 std::string typeName = getTypeSpelling(pointeeTy) +
"*";
2683 std::string baseTypeName =
2685 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2686 argBaseTypeNames.push_back(
2687 llvm::MDString::get(VMContext, baseTypeName));
2691 typeQuals =
"restrict";
2694 typeQuals += typeQuals.empty() ?
"const" :
" const";
2696 typeQuals += typeQuals.empty() ?
"volatile" :
" volatile";
2698 uint32_t AddrSpc = 0;
2703 addressQuals.push_back(
2704 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(AddrSpc)));
2708 std::string typeName = getTypeSpelling(ty);
2720 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2721 argBaseTypeNames.push_back(
2722 llvm::MDString::get(VMContext, baseTypeName));
2727 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
2731 Fn->setMetadata(
"kernel_arg_addr_space",
2732 llvm::MDNode::get(VMContext, addressQuals));
2733 Fn->setMetadata(
"kernel_arg_access_qual",
2734 llvm::MDNode::get(VMContext, accessQuals));
2735 Fn->setMetadata(
"kernel_arg_type",
2736 llvm::MDNode::get(VMContext, argTypeNames));
2737 Fn->setMetadata(
"kernel_arg_base_type",
2738 llvm::MDNode::get(VMContext, argBaseTypeNames));
2739 Fn->setMetadata(
"kernel_arg_type_qual",
2740 llvm::MDNode::get(VMContext, argTypeQuals));
2744 Fn->setMetadata(
"kernel_arg_name",
2745 llvm::MDNode::get(VMContext, argNames));
2755 if (!LangOpts.Exceptions)
return false;
2758 if (LangOpts.CXXExceptions)
return true;
2761 if (LangOpts.ObjCExceptions) {
2781SmallVector<const CXXRecordDecl *, 0>
2783 llvm::SetVector<const CXXRecordDecl *> MostBases;
2788 MostBases.insert(RD);
2790 CollectMostBases(B.getType()->getAsCXXRecordDecl());
2792 CollectMostBases(RD);
2793 return MostBases.takeVector();
2797 llvm::Function *F) {
2798 llvm::AttrBuilder B(F->getContext());
2800 if ((!D || !D->
hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2801 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2803 if (CodeGenOpts.StackClashProtector)
2804 B.addAttribute(
"probe-stack",
"inline-asm");
2806 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
2807 B.addAttribute(
"stack-probe-size",
2808 std::to_string(CodeGenOpts.StackProbeSize));
2811 B.addAttribute(llvm::Attribute::NoUnwind);
2813 if (std::optional<llvm::Attribute::AttrKind>
Attr =
2815 B.addAttribute(*
Attr);
2820 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline))
2821 B.addAttribute(llvm::Attribute::AlwaysInline);
2825 else if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2827 B.addAttribute(llvm::Attribute::NoInline);
2835 if (D->
hasAttr<ArmLocallyStreamingAttr>())
2836 B.addAttribute(
"aarch64_pstate_sm_body");
2839 if (
Attr->isNewZA())
2840 B.addAttribute(
"aarch64_new_za");
2841 if (
Attr->isNewZT0())
2842 B.addAttribute(
"aarch64_new_zt0");
2847 bool ShouldAddOptNone =
2848 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
2850 ShouldAddOptNone &= !D->
hasAttr<MinSizeAttr>();
2851 ShouldAddOptNone &= !D->
hasAttr<AlwaysInlineAttr>();
2854 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline) &&
2855 !D->
hasAttr<NoInlineAttr>()) {
2856 B.addAttribute(llvm::Attribute::AlwaysInline);
2857 }
else if ((ShouldAddOptNone || D->
hasAttr<OptimizeNoneAttr>()) &&
2858 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2860 B.addAttribute(llvm::Attribute::OptimizeNone);
2863 B.addAttribute(llvm::Attribute::NoInline);
2868 B.addAttribute(llvm::Attribute::Naked);
2871 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
2872 F->removeFnAttr(llvm::Attribute::MinSize);
2873 }
else if (D->
hasAttr<NakedAttr>()) {
2875 B.addAttribute(llvm::Attribute::Naked);
2876 B.addAttribute(llvm::Attribute::NoInline);
2877 }
else if (D->
hasAttr<NoDuplicateAttr>()) {
2878 B.addAttribute(llvm::Attribute::NoDuplicate);
2879 }
else if (D->
hasAttr<NoInlineAttr>() &&
2880 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2882 B.addAttribute(llvm::Attribute::NoInline);
2883 }
else if (D->
hasAttr<AlwaysInlineAttr>() &&
2884 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
2886 B.addAttribute(llvm::Attribute::AlwaysInline);
2890 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
2891 B.addAttribute(llvm::Attribute::NoInline);
2895 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
2898 auto CheckRedeclForInline = [](
const FunctionDecl *Redecl) {
2899 return Redecl->isInlineSpecified();
2901 if (any_of(FD->
redecls(), CheckRedeclForInline))
2906 return any_of(Pattern->
redecls(), CheckRedeclForInline);
2908 if (CheckForInline(FD)) {
2909 B.addAttribute(llvm::Attribute::InlineHint);
2910 }
else if (CodeGenOpts.getInlining() ==
2913 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2914 B.addAttribute(llvm::Attribute::NoInline);
2921 if (!D->
hasAttr<OptimizeNoneAttr>()) {
2923 if (!ShouldAddOptNone)
2924 B.addAttribute(llvm::Attribute::OptimizeForSize);
2925 B.addAttribute(llvm::Attribute::Cold);
2928 B.addAttribute(llvm::Attribute::Hot);
2929 if (D->
hasAttr<MinSizeAttr>())
2930 B.addAttribute(llvm::Attribute::MinSize);
2935 if (CodeGenOpts.DisableOutlining || D->
hasAttr<NoOutlineAttr>())
2936 B.addAttribute(llvm::Attribute::NoOutline);
2940 llvm::MaybeAlign ExplicitAlignment;
2941 if (
unsigned alignment = D->
getMaxAlignment() / Context.getCharWidth())
2942 ExplicitAlignment = llvm::Align(alignment);
2943 else if (LangOpts.FunctionAlignment)
2944 ExplicitAlignment = llvm::Align(1ull << LangOpts.FunctionAlignment);
2946 if (ExplicitAlignment) {
2947 F->setAlignment(ExplicitAlignment);
2948 F->setPreferredAlignment(ExplicitAlignment);
2949 }
else if (LangOpts.PreferredFunctionAlignment) {
2950 F->setPreferredAlignment(llvm::Align(LangOpts.PreferredFunctionAlignment));
2959 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
2964 if (CodeGenOpts.SanitizeCfiCrossDso &&
2965 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2966 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
2974 if (CodeGenOpts.CallGraphSection) {
2975 if (
auto *FD = dyn_cast<FunctionDecl>(D))
2982 auto *MD = dyn_cast<CXXMethodDecl>(D);
2985 llvm::Metadata *Id =
2987 MD->getType(), std::nullopt,
Base));
2988 F->addTypeMetadata(0, Id);
2995 if (isa_and_nonnull<NamedDecl>(D))
2998 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
3000 if (D && D->
hasAttr<UsedAttr>())
3003 if (
const auto *VD = dyn_cast_if_present<VarDecl>(D);
3005 ((CodeGenOpts.KeepPersistentStorageVariables &&
3006 (VD->getStorageDuration() ==
SD_Static ||
3007 VD->getStorageDuration() ==
SD_Thread)) ||
3008 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
3009 VD->getType().isConstQualified())))
3014static std::vector<std::string>
3016 llvm::StringMap<bool> &FeatureMap) {
3017 llvm::StringMap<bool> DefaultFeatureMap;
3021 std::vector<std::string> Delta;
3022 for (
const auto &[K,
V] : FeatureMap) {
3023 auto DefaultIt = DefaultFeatureMap.find(K);
3024 if (DefaultIt == DefaultFeatureMap.end() || DefaultIt->getValue() !=
V)
3025 Delta.push_back((
V ?
"+" :
"-") + K.str());
3031bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
3032 llvm::AttrBuilder &Attrs,
3033 bool SetTargetFeatures) {
3039 std::vector<std::string> Features;
3040 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.
getDecl());
3043 const auto *TV = FD ? FD->
getAttr<TargetVersionAttr>() :
nullptr;
3044 assert((!TD || !TV) &&
"both target_version and target specified");
3047 bool AddedAttr =
false;
3048 if (TD || TV || SD || TC) {
3049 llvm::StringMap<bool> FeatureMap;
3057 ParsedTargetAttr ParsedAttr =
3058 Target.parseTargetAttr(TD->getFeaturesStr());
3059 if (!ParsedAttr.
CPU.empty() &&
3061 TargetCPU = ParsedAttr.
CPU;
3064 if (!ParsedAttr.
Tune.empty() &&
3066 TuneCPU = ParsedAttr.
Tune;
3082 for (
const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
3083 Features.push_back((Entry.getValue() ?
"+" :
"-") +
3084 Entry.getKey().str());
3090 llvm::StringMap<bool> FeatureMap;
3104 if (!TargetCPU.empty()) {
3105 Attrs.addAttribute(
"target-cpu", TargetCPU);
3108 if (!TuneCPU.empty()) {
3109 Attrs.addAttribute(
"tune-cpu", TuneCPU);
3112 if (!Features.empty() && SetTargetFeatures) {
3113 llvm::erase_if(Features, [&](
const std::string& F) {
3116 llvm::sort(Features);
3117 Attrs.addAttribute(
"target-features", llvm::join(Features,
","));
3122 llvm::SmallVector<StringRef, 8> Feats;
3123 bool IsDefault =
false;
3125 IsDefault = TV->isDefaultVersion();
3126 TV->getFeatures(Feats);
3132 Attrs.addAttribute(
"fmv-features");
3134 }
else if (!Feats.empty()) {
3136 std::set<StringRef> OrderedFeats(Feats.begin(), Feats.end());
3137 std::string FMVFeatures;
3138 for (StringRef F : OrderedFeats)
3139 FMVFeatures.append(
"," + F.str());
3140 Attrs.addAttribute(
"fmv-features", FMVFeatures.substr(1));
3147void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
3148 llvm::GlobalObject *GO) {
3153 if (
auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
3156 if (
auto *SA = D->
getAttr<PragmaClangBSSSectionAttr>())
3157 GV->addAttribute(
"bss-section", SA->getName());
3158 if (
auto *SA = D->
getAttr<PragmaClangDataSectionAttr>())
3159 GV->addAttribute(
"data-section", SA->getName());
3160 if (
auto *SA = D->
getAttr<PragmaClangRodataSectionAttr>())
3161 GV->addAttribute(
"rodata-section", SA->getName());
3162 if (
auto *SA = D->
getAttr<PragmaClangRelroSectionAttr>())
3163 GV->addAttribute(
"relro-section", SA->getName());
3166 if (
auto *F = dyn_cast<llvm::Function>(GO)) {
3169 if (
auto *SA = D->
getAttr<PragmaClangTextSectionAttr>())
3170 if (!D->
getAttr<SectionAttr>())
3171 F->setSection(SA->getName());
3173 llvm::AttrBuilder Attrs(F->getContext());
3174 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
3178 llvm::AttributeMask RemoveAttrs;
3179 RemoveAttrs.addAttribute(
"target-cpu");
3180 RemoveAttrs.addAttribute(
"target-features");
3181 RemoveAttrs.addAttribute(
"fmv-features");
3182 RemoveAttrs.addAttribute(
"tune-cpu");
3183 F->removeFnAttrs(RemoveAttrs);
3184 F->addFnAttrs(Attrs);
3188 if (
const auto *CSA = D->
getAttr<CodeSegAttr>())
3189 GO->setSection(CSA->getName());
3190 else if (
const auto *SA = D->
getAttr<SectionAttr>())
3191 GO->setSection(SA->getName());
3204 F->setLinkage(llvm::Function::InternalLinkage);
3206 setNonAliasAttributes(GD, F);
3217 GV->
setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
3221 llvm::MDNode *MD = F->getMetadata(llvm::LLVMContext::MD_type);
3222 return MD && MD->hasGeneralizedMDString();
3226 llvm::Function *F) {
3233 if (!F->hasLocalLinkage() ||
3234 F->getFunction().hasAddressTaken(
nullptr,
true,
3241 llvm::Function *F) {
3243 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
3254 F->addTypeMetadata(0, MD);
3263 if (CodeGenOpts.SanitizeCfiCrossDso)
3265 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
3269 llvm::CallBase *CB) {
3271 if (!CodeGenOpts.CallGraphSection || !CB->isIndirectCall())
3275 llvm::MDTuple *TypeTuple = llvm::MDTuple::get(
3276 getLLVMContext(), {llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
3279 llvm::MDTuple *MDN = llvm::MDNode::get(
getLLVMContext(), {TypeTuple});
3280 CB->setMetadata(llvm::LLVMContext::MD_callee_type, MDN);
3284 llvm::LLVMContext &Ctx = F->getContext();
3285 llvm::MDBuilder MDB(Ctx);
3286 llvm::StringRef Salt;
3289 if (
const auto &Info = FP->getExtraAttributeInfo())
3290 Salt = Info.CFISalt;
3292 F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
3301 return llvm::all_of(Name, [](
const char &
C) {
3302 return llvm::isAlnum(
C) ||
C ==
'_' ||
C ==
'.';
3308 for (
auto &F : M.functions()) {
3310 bool AddressTaken = F.hasAddressTaken();
3311 if (!AddressTaken && F.hasLocalLinkage())
3312 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
3317 if (!AddressTaken || !F.isDeclaration())
3320 const llvm::ConstantInt *
Type;
3321 if (
const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
3322 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
3326 StringRef Name = F.getName();
3330 std::string
Asm = (
".weak __kcfi_typeid_" + Name +
"\n.set __kcfi_typeid_" +
3331 Name +
", " + Twine(
Type->getZExtValue()) +
" /* " +
3332 Twine(
Type->getSExtValue()) +
" */\n")
3334 M.appendModuleInlineAsm(
Asm);
3338void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
3339 bool IsIncompleteFunction,
3342 if (F->getIntrinsicID() != llvm::Intrinsic::not_intrinsic) {
3350 if (!IsIncompleteFunction)
3357 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
3359 assert(!F->arg_empty() &&
3360 F->arg_begin()->getType()
3361 ->canLosslesslyBitCastTo(F->getReturnType()) &&
3362 "unexpected this return");
3363 F->addParamAttr(0, llvm::Attribute::Returned);
3373 if (!IsIncompleteFunction && F->isDeclaration())
3376 if (
const auto *CSA = FD->
getAttr<CodeSegAttr>())
3377 F->setSection(CSA->getName());
3378 else if (
const auto *SA = FD->
getAttr<SectionAttr>())
3379 F->setSection(SA->getName());
3381 if (
const auto *EA = FD->
getAttr<ErrorAttr>()) {
3383 F->addFnAttr(
"dontcall-error", EA->getUserDiagnostic());
3384 else if (EA->isWarning())
3385 F->addFnAttr(
"dontcall-warn", EA->getUserDiagnostic());
3390 const FunctionDecl *FDBody;
3391 bool HasBody = FD->
hasBody(FDBody);
3393 assert(HasBody &&
"Inline builtin declarations should always have an "
3395 if (shouldEmitFunction(FDBody))
3396 F->addFnAttr(llvm::Attribute::NoBuiltin);
3402 F->addFnAttr(llvm::Attribute::NoBuiltin);
3406 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3407 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
3408 if (MD->isVirtual())
3409 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3415 if (!CodeGenOpts.SanitizeCfiCrossDso ||
3416 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
3419 if (CodeGenOpts.CallGraphSection)
3422 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
3428 if (CodeGenOpts.InlineMaxStackSize !=
UINT_MAX)
3429 F->addFnAttr(
"inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
3431 if (
const auto *CB = FD->
getAttr<CallbackAttr>()) {
3435 llvm::LLVMContext &Ctx = F->getContext();
3436 llvm::MDBuilder MDB(Ctx);
3440 int CalleeIdx = *CB->encoding_begin();
3441 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
3442 F->addMetadata(llvm::LLVMContext::MD_callback,
3443 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
3444 CalleeIdx, PayloadIndices,
3451 "Only globals with definition can force usage.");
3452 LLVMUsed.emplace_back(GV);
3456 assert(!GV->isDeclaration() &&
3457 "Only globals with definition can force usage.");
3458 LLVMCompilerUsed.emplace_back(GV);
3463 "Only globals with definition can force usage.");
3465 LLVMCompilerUsed.emplace_back(GV);
3467 LLVMUsed.emplace_back(GV);
3471 std::vector<llvm::WeakTrackingVH> &List) {
3478 UsedArray.resize(List.size());
3479 for (
unsigned i = 0, e = List.size(); i != e; ++i) {
3481 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3485 if (UsedArray.empty())
3487 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
3489 auto *GV =
new llvm::GlobalVariable(
3490 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
3491 llvm::ConstantArray::get(ATy, UsedArray), Name);
3493 GV->setSection(
"llvm.metadata");
3496void CodeGenModule::emitLLVMUsed() {
3497 emitUsed(*
this,
"llvm.used", LLVMUsed);
3498 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
3503 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3512 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3518 ELFDependentLibraries.push_back(
3519 llvm::MDNode::get(
C, llvm::MDString::get(
C, Lib)));
3526 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
C, MDOpts));
3535 if (Mod->
Parent && Visited.insert(Mod->
Parent).second) {
3541 if (Visited.insert(Import).second)
3558 if (LL.IsFramework) {
3559 llvm::Metadata *Args[2] = {llvm::MDString::get(Context,
"-framework"),
3560 llvm::MDString::get(Context, LL.Library)};
3562 Metadata.push_back(llvm::MDNode::get(Context, Args));
3568 llvm::Metadata *Args[2] = {
3569 llvm::MDString::get(Context,
"lib"),
3570 llvm::MDString::get(Context, LL.Library),
3572 Metadata.push_back(llvm::MDNode::get(Context, Args));
3576 auto *OptString = llvm::MDString::get(Context, Opt);
3577 Metadata.push_back(llvm::MDNode::get(Context, OptString));
3582void CodeGenModule::EmitModuleInitializers(
clang::Module *Primary) {
3584 "We should only emit module initializers for named modules.");
3592 assert(
isa<VarDecl>(D) &&
"GMF initializer decl is not a var?");
3609 assert(
isa<VarDecl>(D) &&
"PMF initializer decl is not a var?");
3615void CodeGenModule::EmitModuleLinkOptions() {
3619 llvm::SetVector<clang::Module *> LinkModules;
3620 llvm::SmallPtrSet<clang::Module *, 16> Visited;
3621 SmallVector<clang::Module *, 16> Stack;
3624 for (
Module *M : ImportedModules) {
3627 if (M->getTopLevelModuleName() ==
getLangOpts().CurrentModule &&
3630 if (Visited.insert(M).second)
3636 while (!Stack.empty()) {
3639 bool AnyChildren =
false;
3648 if (Visited.insert(
SM).second) {
3649 Stack.push_back(
SM);
3657 LinkModules.insert(Mod);
3664 SmallVector<llvm::MDNode *, 16> MetadataArgs;
3666 for (
Module *M : LinkModules)
3667 if (Visited.insert(M).second)
3669 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
3670 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
3673 if (!LinkerOptionsMetadata.empty()) {
3674 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.linker.options");
3675 for (
auto *MD : LinkerOptionsMetadata)
3676 NMD->addOperand(MD);
3680void CodeGenModule::EmitDeferred() {
3689 if (!DeferredVTables.empty()) {
3690 EmitDeferredVTables();
3695 assert(DeferredVTables.empty());
3702 llvm::append_range(DeferredDeclsToEmit,
3706 if (DeferredDeclsToEmit.empty())
3711 std::vector<GlobalDecl> CurDeclsToEmit;
3712 CurDeclsToEmit.swap(DeferredDeclsToEmit);
3714 for (GlobalDecl &D : CurDeclsToEmit) {
3720 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>() &&
3724 if (!FD->
getAttr<SYCLKernelEntryPointAttr>()->isInvalidAttr()) {
3740 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
3758 if (!GV->isDeclaration())
3762 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
3766 EmitGlobalDefinition(D, GV);
3771 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
3773 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
3778void CodeGenModule::EmitVTablesOpportunistically() {
3784 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
3785 &&
"Only emit opportunistic vtables with optimizations");
3787 for (
const CXXRecordDecl *RD : OpportunisticVTables) {
3789 "This queue should only contain external vtables");
3790 if (
getCXXABI().canSpeculativelyEmitVTable(RD))
3791 VTables.GenerateClassData(RD);
3793 OpportunisticVTables.clear();
3797 for (
const auto& [MangledName, VD] : DeferredAnnotations) {
3802 DeferredAnnotations.clear();
3804 if (Annotations.empty())
3808 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
3809 Annotations[0]->
getType(), Annotations.size()), Annotations);
3810 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
3811 llvm::GlobalValue::AppendingLinkage,
3812 Array,
"llvm.global.annotations");
3817 llvm::Constant *&AStr = AnnotationStrings[Str];
3822 llvm::Constant *
s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
3823 auto *gv =
new llvm::GlobalVariable(
3824 getModule(),
s->getType(),
true, llvm::GlobalValue::PrivateLinkage,
s,
3825 ".str",
nullptr, llvm::GlobalValue::NotThreadLocal,
3828 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3845 SM.getExpansionLineNumber(L);
3846 return llvm::ConstantInt::get(
Int32Ty, LineNo);
3854 llvm::FoldingSetNodeID ID;
3855 for (
Expr *E : Exprs) {
3858 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
3863 LLVMArgs.reserve(Exprs.size());
3865 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](
const Expr *E) {
3867 return ConstEmiter.
emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
3870 auto *
Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
3871 auto *GV =
new llvm::GlobalVariable(
getModule(),
Struct->getType(),
true,
3872 llvm::GlobalValue::PrivateLinkage,
Struct,
3875 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3882 const AnnotateAttr *AA,
3890 llvm::Constant *GVInGlobalsAS = GV;
3891 if (GV->getAddressSpace() !=
3893 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
3895 llvm::PointerType::get(
3896 GV->getContext(),
getDataLayout().getDefaultGlobalsAddressSpace()));
3900 llvm::Constant *Fields[] = {
3901 GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
3903 return llvm::ConstantStruct::getAnon(Fields);
3907 llvm::GlobalValue *GV) {
3908 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
3918 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
3921 auto &
SM = Context.getSourceManager();
3923 if (NoSanitizeL.containsMainFile(Kind, MainFile.
getName()))
3928 return NoSanitizeL.containsLocation(Kind, Loc);
3931 return NoSanitizeL.containsFile(Kind, MainFile.
getName());
3935 llvm::GlobalVariable *GV,
3937 StringRef Category)
const {
3939 if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
3941 auto &
SM = Context.getSourceManager();
3942 if (NoSanitizeL.containsMainFile(
3943 Kind,
SM.getFileEntryRefForID(
SM.getMainFileID())->getName(),
3946 if (NoSanitizeL.containsLocation(Kind, Loc, Category))
3953 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
3954 Ty = AT->getElementType();
3959 if (NoSanitizeL.containsType(Kind, TypeStr, Category))
3967 StringRef Category)
const {
3970 auto Attr = ImbueAttr::NONE;
3972 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
3973 if (
Attr == ImbueAttr::NONE)
3974 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
3976 case ImbueAttr::NONE:
3978 case ImbueAttr::ALWAYS:
3979 Fn->addFnAttr(
"function-instrument",
"xray-always");
3981 case ImbueAttr::ALWAYS_ARG1:
3982 Fn->addFnAttr(
"function-instrument",
"xray-always");
3983 Fn->addFnAttr(
"xray-log-args",
"1");
3985 case ImbueAttr::NEVER:
3986 Fn->addFnAttr(
"function-instrument",
"xray-never");
3999 llvm::driver::ProfileInstrKind Kind =
getCodeGenOpts().getProfileInstr();
4009 auto &
SM = Context.getSourceManager();
4010 if (
auto MainFile =
SM.getFileEntryRefForID(
SM.getMainFileID()))
4024 if (NumGroups > 1) {
4025 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
4034 if (LangOpts.EmitAllDecls)
4037 const auto *VD = dyn_cast<VarDecl>(
Global);
4039 ((CodeGenOpts.KeepPersistentStorageVariables &&
4040 (VD->getStorageDuration() ==
SD_Static ||
4041 VD->getStorageDuration() ==
SD_Thread)) ||
4042 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
4043 VD->getType().isConstQualified())))
4056 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
4057 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
4058 OMPDeclareTargetDeclAttr::getActiveAttr(
Global);
4059 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (
unsigned)-1)
4063 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
4073 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>())
4076 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
4077 if (Context.getInlineVariableDefinitionKind(VD) ==
4082 if (CXX20ModuleInits && VD->getOwningModule() &&
4083 !VD->getOwningModule()->isModuleMapModule()) {
4092 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
4095 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
Global))
4108 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
4112 llvm::Constant *
Init;
4115 if (!
V.isAbsent()) {
4126 llvm::Constant *Fields[4] = {
4130 llvm::ConstantDataArray::getRaw(
4131 StringRef(
reinterpret_cast<char *
>(Parts.
Part4And5), 8), 8,
4133 Init = llvm::ConstantStruct::getAnon(Fields);
4136 auto *GV =
new llvm::GlobalVariable(
4138 true, llvm::GlobalValue::LinkOnceODRLinkage,
Init, Name);
4140 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4143 if (!
V.isAbsent()) {
4156 llvm::GlobalVariable **Entry =
nullptr;
4157 Entry = &UnnamedGlobalConstantDeclMap[GCD];
4162 llvm::Constant *
Init;
4166 assert(!
V.isAbsent());
4170 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
4172 llvm::GlobalValue::PrivateLinkage,
Init,
4174 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4188 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
4192 llvm::Constant *
Init =
Emitter.emitForInitializer(
4200 llvm::GlobalValue::LinkageTypes
Linkage =
4202 ? llvm::GlobalValue::LinkOnceODRLinkage
4203 : llvm::GlobalValue::InternalLinkage;
4204 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
4208 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4215 const AliasAttr *AA = VD->
getAttr<AliasAttr>();
4216 assert(AA &&
"No alias?");
4226 llvm::Constant *Aliasee;
4228 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
4236 F->setLinkage(llvm::Function::ExternalWeakLinkage);
4237 WeakRefReferences.insert(F);
4245 if (
auto *A = D->
getAttr<AttrT>())
4246 return A->isImplicit();
4253 if (!LangOpts.OpenMPIsTargetDevice && !LangOpts.CUDA)
4256 const auto *AA =
Global->getAttr<AliasAttr>();
4264 const auto *AliaseeDecl = dyn_cast<ValueDecl>(AliaseeGD.getDecl());
4265 if (LangOpts.OpenMPIsTargetDevice)
4266 return !AliaseeDecl ||
4267 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(AliaseeDecl);
4270 const bool HasDeviceAttr =
Global->hasAttr<CUDADeviceAttr>();
4271 const bool AliaseeHasDeviceAttr =
4272 AliaseeDecl && AliaseeDecl->hasAttr<CUDADeviceAttr>();
4274 if (LangOpts.CUDAIsDevice)
4275 return !HasDeviceAttr || !AliaseeHasDeviceAttr;
4282bool CodeGenModule::shouldEmitCUDAGlobalVar(
const VarDecl *
Global)
const {
4283 assert(LangOpts.CUDA &&
"Should not be called by non-CUDA languages");
4288 return !LangOpts.CUDAIsDevice ||
Global->hasAttr<CUDADeviceAttr>() ||
4289 Global->hasAttr<CUDAConstantAttr>() ||
4290 Global->hasAttr<CUDASharedAttr>() ||
4291 Global->getType()->isCUDADeviceBuiltinSurfaceType() ||
4292 Global->getType()->isCUDADeviceBuiltinTextureType();
4299 if (
Global->hasAttr<WeakRefAttr>())
4304 if (
Global->hasAttr<AliasAttr>()) {
4307 return EmitAliasDefinition(GD);
4311 if (
Global->hasAttr<IFuncAttr>())
4312 return emitIFuncDefinition(GD);
4315 if (
Global->hasAttr<CPUDispatchAttr>())
4316 return emitCPUDispatchDefinition(GD);
4321 if (LangOpts.CUDA) {
4323 "Expected Variable or Function");
4324 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
4325 if (!shouldEmitCUDAGlobalVar(VD))
4327 }
else if (LangOpts.CUDAIsDevice) {
4328 const auto *FD = dyn_cast<FunctionDecl>(
Global);
4329 if ((!
Global->hasAttr<CUDADeviceAttr>() ||
4330 (LangOpts.OffloadImplicitHostDeviceTemplates &&
4334 !
getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
4335 !
Global->hasAttr<CUDAGlobalAttr>() &&
4337 !
Global->hasAttr<CUDAHostAttr>()))
4340 }
else if (!
Global->hasAttr<CUDAHostAttr>() &&
4341 Global->hasAttr<CUDADeviceAttr>())
4345 if (LangOpts.OpenMP) {
4347 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
4349 if (
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(
Global)) {
4350 if (MustBeEmitted(
Global))
4354 if (
auto *DMD = dyn_cast<OMPDeclareMapperDecl>(
Global)) {
4355 if (MustBeEmitted(
Global))
4362 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
4363 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
4369 if (FD->
hasAttr<AnnotateAttr>()) {
4372 DeferredAnnotations[MangledName] = FD;
4387 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
4393 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
4395 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
4396 if (LangOpts.OpenMP) {
4398 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
4399 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
4403 if (VD->hasExternalStorage() &&
4404 Res != OMPDeclareTargetDeclAttr::MT_Link)
4407 bool UnifiedMemoryEnabled =
4409 if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4410 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4411 !UnifiedMemoryEnabled) {
4414 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
4415 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4416 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4417 UnifiedMemoryEnabled)) &&
4418 "Link clause or to clause with unified memory expected.");
4427 if (Context.getInlineVariableDefinitionKind(VD) ==
4437 if (MustBeEmitted(
Global) && MayBeEmittedEagerly(
Global)) {
4439 EmitGlobalDefinition(GD);
4440 addEmittedDeferredDecl(GD);
4448 DelayedCXXInitPosition[
Global] = CXXGlobalInits.size();
4449 CXXGlobalInits.push_back(
nullptr);
4455 addDeferredDeclToEmit(GD);
4456 }
else if (MustBeEmitted(
Global)) {
4458 assert(!MayBeEmittedEagerly(
Global));
4459 addDeferredDeclToEmit(GD);
4464 DeferredDecls[MangledName] = GD;
4470 if (
const auto *RT =
4471 T->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
4472 if (
auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
4473 RD = RD->getDefinitionOrSelf();
4474 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
4482 struct FunctionIsDirectlyRecursive
4483 :
public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
4484 const StringRef Name;
4485 const Builtin::Context &BI;
4486 FunctionIsDirectlyRecursive(StringRef N,
const Builtin::Context &
C)
4489 bool VisitCallExpr(
const CallExpr *E) {
4493 AsmLabelAttr *Attr = FD->
getAttr<AsmLabelAttr>();
4494 if (Attr && Name == Attr->getLabel())
4499 std::string BuiltinNameStr = BI.
getName(BuiltinID);
4500 StringRef BuiltinName = BuiltinNameStr;
4501 return BuiltinName.consume_front(
"__builtin_") && Name == BuiltinName;
4504 bool VisitStmt(
const Stmt *S) {
4505 for (
const Stmt *Child : S->
children())
4506 if (Child && this->Visit(Child))
4513 struct DLLImportFunctionVisitor
4514 :
public RecursiveASTVisitor<DLLImportFunctionVisitor> {
4515 bool SafeToInline =
true;
4517 bool shouldVisitImplicitCode()
const {
return true; }
4519 bool VisitVarDecl(VarDecl *VD) {
4522 SafeToInline =
false;
4523 return SafeToInline;
4530 return SafeToInline;
4533 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
4535 SafeToInline = D->
hasAttr<DLLImportAttr>();
4536 return SafeToInline;
4539 bool VisitDeclRefExpr(DeclRefExpr *E) {
4542 SafeToInline = VD->
hasAttr<DLLImportAttr>();
4543 else if (VarDecl *
V = dyn_cast<VarDecl>(VD))
4544 SafeToInline = !
V->hasGlobalStorage() ||
V->hasAttr<DLLImportAttr>();
4545 return SafeToInline;
4548 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
4550 return SafeToInline;
4553 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4557 SafeToInline =
true;
4559 SafeToInline = M->
hasAttr<DLLImportAttr>();
4561 return SafeToInline;
4564 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
4566 return SafeToInline;
4569 bool VisitCXXNewExpr(CXXNewExpr *E) {
4571 return SafeToInline;
4580CodeGenModule::isTriviallyRecursive(
const FunctionDecl *FD) {
4582 if (
getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
4584 AsmLabelAttr *Attr = FD->
getAttr<AsmLabelAttr>();
4587 Name = Attr->getLabel();
4592 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
4593 const Stmt *Body = FD->
getBody();
4594 return Body ? Walker.Visit(Body) :
false;
4597bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
4604 if (F->isInlineBuiltinDeclaration())
4607 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
4612 if (
const Module *M = F->getOwningModule();
4613 M && M->getTopLevelModule()->isNamedModule() &&
4614 getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
4624 if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
4629 if (F->hasAttr<NoInlineAttr>())
4632 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
4634 DLLImportFunctionVisitor Visitor;
4635 Visitor.TraverseFunctionDecl(
const_cast<FunctionDecl*
>(F));
4636 if (!Visitor.SafeToInline)
4639 if (
const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
4642 for (
const Decl *
Member : Dtor->getParent()->decls())
4646 for (
const CXXBaseSpecifier &B : Dtor->getParent()->bases())
4657 return !isTriviallyRecursive(F);
4660bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
4661 return CodeGenOpts.OptimizationLevel > 0;
4664void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
4665 llvm::GlobalValue *GV) {
4669 auto *Spec = FD->
getAttr<CPUSpecificAttr>();
4670 for (
unsigned I = 0; I < Spec->cpus_size(); ++I)
4672 }
else if (
auto *TC = FD->
getAttr<TargetClonesAttr>()) {
4673 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I)
4674 if (TC->isFirstOfVersion(I))
4677 EmitGlobalFunctionDefinition(GD, GV);
4683 AddDeferredMultiVersionResolverToEmit(GD);
4685 GetOrCreateMultiVersionResolver(GD);
4689void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
4692 PrettyStackTraceDecl CrashInfo(
const_cast<ValueDecl *
>(D), D->
getLocation(),
4693 Context.getSourceManager(),
4694 "Generating code for declaration");
4696 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
4699 if (!shouldEmitFunction(GD))
4702 llvm::TimeTraceScope TimeScope(
"CodeGen Function", [&]() {
4704 llvm::raw_string_ostream
OS(Name);
4710 if (
const auto *
Method = dyn_cast<CXXMethodDecl>(D)) {
4714 ABI->emitCXXStructor(GD);
4716 EmitMultiVersionFunctionDefinition(GD, GV);
4718 EmitGlobalFunctionDefinition(GD, GV);
4727 return EmitMultiVersionFunctionDefinition(GD, GV);
4728 return EmitGlobalFunctionDefinition(GD, GV);
4731 if (
const auto *VD = dyn_cast<VarDecl>(D))
4732 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
4734 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
4738 llvm::Function *NewFn);
4754static llvm::GlobalValue::LinkageTypes
4758 return llvm::GlobalValue::InternalLinkage;
4759 return llvm::GlobalValue::WeakODRLinkage;
4762void CodeGenModule::emitMultiVersionFunctions() {
4763 std::vector<GlobalDecl> MVFuncsToEmit;
4764 MultiVersionFuncs.swap(MVFuncsToEmit);
4765 for (GlobalDecl GD : MVFuncsToEmit) {
4767 assert(FD &&
"Expected a FunctionDecl");
4769 auto createFunction = [&](
const FunctionDecl *
Decl,
unsigned MVIdx = 0) {
4770 GlobalDecl CurGD{
Decl->isDefined() ?
Decl->getDefinition() :
Decl, MVIdx};
4774 if (
Decl->isDefined()) {
4775 EmitGlobalFunctionDefinition(CurGD,
nullptr);
4783 assert(
Func &&
"This should have just been created");
4792 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
4793 llvm::DenseMap<llvm::Function *, const FunctionDecl *> DeclMap;
4796 FD, [&](
const FunctionDecl *CurFD) {
4797 llvm::SmallVector<StringRef, 8> Feats;
4800 if (
const auto *TA = CurFD->
getAttr<TargetAttr>()) {
4802 TA->getX86AddedFeatures(Feats);
4803 llvm::Function *
Func = createFunction(CurFD);
4804 DeclMap.insert({
Func, CurFD});
4805 Options.emplace_back(
Func, Feats, TA->getX86Architecture());
4806 }
else if (
const auto *TVA = CurFD->
getAttr<TargetVersionAttr>()) {
4807 if (TVA->isDefaultVersion() && IsDefined)
4808 ShouldEmitResolver =
true;
4809 llvm::Function *
Func = createFunction(CurFD);
4810 DeclMap.insert({
Func, CurFD});
4812 TVA->getFeatures(Feats, Delim);
4813 Options.emplace_back(
Func, Feats);
4814 }
else if (
const auto *TC = CurFD->
getAttr<TargetClonesAttr>()) {
4815 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
4816 if (!TC->isFirstOfVersion(I))
4818 if (TC->isDefaultVersion(I) && IsDefined)
4819 ShouldEmitResolver =
true;
4820 llvm::Function *
Func = createFunction(CurFD, I);
4821 DeclMap.insert({
Func, CurFD});
4824 TC->getX86Feature(Feats, I);
4825 Options.emplace_back(
Func, Feats, TC->getX86Architecture(I));
4828 TC->getFeatures(Feats, I, Delim);
4829 Options.emplace_back(
Func, Feats);
4833 llvm_unreachable(
"unexpected MultiVersionKind");
4836 if (!ShouldEmitResolver)
4839 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
4840 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
4841 ResolverConstant = IFunc->getResolver();
4845 *
this, GD, FD,
true);
4852 auto *Alias = llvm::GlobalAlias::create(
4854 MangledName +
".ifunc", IFunc, &
getModule());
4863 Options, [&TI](
const CodeGenFunction::FMVResolverOption &LHS,
4864 const CodeGenFunction::FMVResolverOption &RHS) {
4870 for (
auto I = Options.begin() + 1, E = Options.end(); I != E; ++I) {
4871 llvm::APInt RHS = llvm::AArch64::getCpuSupportsMask(I->Features);
4872 if (std::any_of(Options.begin(), I, [RHS](
auto RO) {
4873 llvm::APInt LHS = llvm::AArch64::getCpuSupportsMask(RO.Features);
4874 return LHS.isSubsetOf(RHS);
4876 Diags.Report(DeclMap[I->Function]->getLocation(),
4877 diag::warn_unreachable_version)
4878 << I->Function->getName();
4879 assert(I->Function->user_empty() &&
"unexpected users");
4880 I->Function->eraseFromParent();
4881 I->Function =
nullptr;
4885 CodeGenFunction CGF(*
this);
4886 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4888 setMultiVersionResolverAttributes(ResolverFunc, GD);
4890 ResolverFunc->setComdat(
4891 getModule().getOrInsertComdat(ResolverFunc->getName()));
4897 if (!MVFuncsToEmit.empty())
4902 if (!MultiVersionFuncs.empty())
4903 emitMultiVersionFunctions();
4913 llvm::GlobalValue *DS = TheModule.getNamedValue(DSName);
4915 DS =
new llvm::GlobalVariable(TheModule,
Int8Ty,
false,
4916 llvm::GlobalVariable::ExternalWeakLinkage,
4918 DS->setVisibility(llvm::GlobalValue::HiddenVisibility);
4923void CodeGenModule::emitPFPFieldsWithEvaluatedOffset() {
4924 llvm::Constant *Nop = llvm::ConstantExpr::getIntToPtr(
4926 for (
auto *FD :
getContext().PFPFieldsWithEvaluatedOffset) {
4928 llvm::GlobalValue *OldDS = TheModule.getNamedValue(DSName);
4929 llvm::GlobalValue *DS = llvm::GlobalAlias::create(
4930 Int8Ty, 0, llvm::GlobalValue::ExternalLinkage, DSName, Nop, &TheModule);
4931 DS->setVisibility(llvm::GlobalValue::HiddenVisibility);
4933 DS->takeName(OldDS);
4934 OldDS->replaceAllUsesWith(DS);
4935 OldDS->eraseFromParent();
4941 llvm::Constant *
New) {
4944 Old->replaceAllUsesWith(
New);
4945 Old->eraseFromParent();
4948void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
4950 assert(FD &&
"Not a FunctionDecl?");
4952 const auto *DD = FD->
getAttr<CPUDispatchAttr>();
4953 assert(DD &&
"Not a cpu_dispatch Function?");
4959 UpdateMultiVersionNames(GD, FD, ResolverName);
4961 llvm::Type *ResolverType;
4962 GlobalDecl ResolverGD;
4964 ResolverType = llvm::FunctionType::get(
4975 ResolverName, ResolverType, ResolverGD,
false));
4978 ResolverFunc->setComdat(
4979 getModule().getOrInsertComdat(ResolverFunc->getName()));
4981 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
4984 for (
const IdentifierInfo *II : DD->cpus()) {
4992 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
4995 EmitGlobalFunctionDefinition(ExistingDecl,
nullptr);
5001 Func = GetOrCreateLLVMFunction(
5002 MangledName, DeclTy, ExistingDecl,
5008 llvm::SmallVector<StringRef, 32> Features;
5009 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
5010 llvm::transform(Features, Features.begin(),
5011 [](StringRef Str) { return Str.substr(1); });
5012 llvm::erase_if(Features, [&Target](StringRef Feat) {
5013 return !Target.validateCpuSupports(Feat);
5019 llvm::stable_sort(Options, [](
const CodeGenFunction::FMVResolverOption &LHS,
5020 const CodeGenFunction::FMVResolverOption &RHS) {
5021 return llvm::X86::getCpuSupportsMask(LHS.
Features) >
5022 llvm::X86::getCpuSupportsMask(RHS.
Features);
5029 while (Options.size() > 1 && llvm::all_of(llvm::X86::getCpuSupportsMask(
5030 (Options.end() - 2)->Features),
5031 [](
auto X) { return X == 0; })) {
5032 StringRef LHSName = (Options.end() - 2)->Function->getName();
5033 StringRef RHSName = (Options.end() - 1)->Function->getName();
5034 if (LHSName.compare(RHSName) < 0)
5035 Options.erase(Options.end() - 2);
5037 Options.erase(Options.end() - 1);
5040 CodeGenFunction CGF(*
this);
5041 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
5042 setMultiVersionResolverAttributes(ResolverFunc, GD);
5047 unsigned AS = IFunc->getType()->getPointerAddressSpace();
5052 auto *GI = llvm::GlobalIFunc::create(DeclTy, AS,
Linkage,
"",
5059 *
this, GD, FD,
true);
5062 auto *GA = llvm::GlobalAlias::create(DeclTy, AS,
Linkage, AliasName,
5070void CodeGenModule::AddDeferredMultiVersionResolverToEmit(GlobalDecl GD) {
5072 assert(FD &&
"Not a FunctionDecl?");
5075 std::string MangledName =
5077 if (!DeferredResolversToEmit.insert(MangledName).second)
5080 MultiVersionFuncs.push_back(GD);
5086llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
5088 assert(FD &&
"Not a FunctionDecl?");
5090 std::string MangledName =
5095 std::string ResolverName = MangledName;
5099 llvm_unreachable(
"unexpected MultiVersionKind::None for resolver");
5103 ResolverName +=
".ifunc";
5110 ResolverName +=
".resolver";
5113 bool ShouldReturnIFunc =
5132 AddDeferredMultiVersionResolverToEmit(GD);
5136 if (ShouldReturnIFunc) {
5138 llvm::Type *ResolverType = llvm::FunctionType::get(
5140 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
5141 MangledName +
".resolver", ResolverType, GlobalDecl{},
5143 llvm::GlobalIFunc *GIF =
5146 GIF->setName(ResolverName);
5153 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
5154 ResolverName, DeclTy, GlobalDecl{},
false);
5156 "Resolver should be created for the first time");
5161void CodeGenModule::setMultiVersionResolverAttributes(llvm::Function *Resolver,
5163 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(GD.
getDecl());
5175 Resolver->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
5186bool CodeGenModule::shouldDropDLLAttribute(
const Decl *D,
5187 const llvm::GlobalValue *GV)
const {
5188 auto SC = GV->getDLLStorageClass();
5189 if (SC == llvm::GlobalValue::DefaultStorageClass)
5192 return (((SC == llvm::GlobalValue::DLLImportStorageClass &&
5193 !MRD->
hasAttr<DLLImportAttr>()) ||
5194 (SC == llvm::GlobalValue::DLLExportStorageClass &&
5195 !MRD->
hasAttr<DLLExportAttr>())) &&
5206llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
5207 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD,
bool ForVTable,
5208 bool DontDefer,
bool IsThunk, llvm::AttributeList ExtraAttrs,
5212 std::string NameWithoutMultiVersionMangling;
5213 if (
const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
5215 if (
getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
5216 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->
isDefined() &&
5217 !DontDefer && !IsForDefinition) {
5220 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
5222 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
5225 GDDef = GlobalDecl(FDDef);
5233 UpdateMultiVersionNames(GD, FD, MangledName);
5234 if (!IsForDefinition) {
5240 AddDeferredMultiVersionResolverToEmit(GD);
5242 *
this, GD, FD,
true);
5244 return GetOrCreateMultiVersionResolver(GD);
5249 if (!NameWithoutMultiVersionMangling.empty())
5250 MangledName = NameWithoutMultiVersionMangling;
5255 if (WeakRefReferences.erase(Entry)) {
5256 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
5257 if (FD && !FD->
hasAttr<WeakAttr>())
5258 Entry->setLinkage(llvm::Function::ExternalLinkage);
5262 if (D && shouldDropDLLAttribute(D, Entry)) {
5263 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5269 if (IsForDefinition && !Entry->isDeclaration()) {
5276 DiagnosedConflictingDefinitions.insert(GD).second) {
5280 diag::note_previous_definition);
5285 (Entry->getValueType() == Ty)) {
5292 if (!IsForDefinition)
5299 bool IsIncompleteFunction =
false;
5301 llvm::FunctionType *FTy;
5305 FTy = llvm::FunctionType::get(
VoidTy,
false);
5306 IsIncompleteFunction =
true;
5310 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
5311 Entry ? StringRef() : MangledName, &
getModule());
5315 if (D && D->
hasAttr<AnnotateAttr>())
5333 if (!Entry->use_empty()) {
5335 Entry->removeDeadConstantUsers();
5341 assert(F->getName() == MangledName &&
"name was uniqued!");
5343 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
5344 if (ExtraAttrs.hasFnAttrs()) {
5345 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
5353 if (isa_and_nonnull<CXXDestructorDecl>(D) &&
5356 addDeferredDeclToEmit(GD);
5361 auto DDI = DeferredDecls.find(MangledName);
5362 if (DDI != DeferredDecls.end()) {
5366 addDeferredDeclToEmit(DDI->second);
5367 DeferredDecls.erase(DDI);
5395 if (!IsIncompleteFunction) {
5396 assert(F->getFunctionType() == Ty);
5414 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
5424 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(GD.
getDecl())) {
5427 DD->getParent()->getNumVBases() == 0)
5432 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
5433 false, llvm::AttributeList(),
5436 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
5440 if (IsForDefinition)
5448 llvm::GlobalValue *F =
5451 return llvm::NoCFIValue::get(F);
5460 for (
const auto *Result : DC->
lookup(&CII))
5461 if (
const auto *FD = dyn_cast<FunctionDecl>(Result))
5464 if (!
C.getLangOpts().CPlusPlus)
5469 (Name ==
"_ZSt9terminatev" || Name ==
"?terminate@@YAXXZ")
5470 ?
C.Idents.get(
"terminate")
5471 :
C.Idents.get(Name);
5473 for (
const auto &N : {
"__cxxabiv1",
"std"}) {
5475 for (
const auto *Result : DC->
lookup(&NS)) {
5477 if (
auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
5478 for (
const auto *Result : LSD->lookup(&NS))
5479 if ((ND = dyn_cast<NamespaceDecl>(Result)))
5483 for (
const auto *Result : ND->
lookup(&CXXII))
5484 if (
const auto *FD = dyn_cast<FunctionDecl>(Result))
5493 llvm::Function *F, StringRef Name) {
5499 if (!Local && CGM.
getTriple().isWindowsItaniumEnvironment() &&
5502 if (!FD || FD->
hasAttr<DLLImportAttr>()) {
5503 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
5504 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
5511 llvm::AttributeList ExtraAttrs,
bool Local,
bool AssumeConvergent) {
5512 if (AssumeConvergent) {
5514 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5517 QualType FTy = Context.getFunctionType(ReturnTy, ArgTys,
5522 llvm::Constant *
C = GetOrCreateLLVMFunction(
5524 false,
false, ExtraAttrs);
5526 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
5542 llvm::AttributeList ExtraAttrs,
bool Local,
5543 bool AssumeConvergent) {
5544 if (AssumeConvergent) {
5546 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5550 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
5554 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
5563 markRegisterParameterAttributes(F);
5589 if (WeakRefReferences.erase(Entry)) {
5590 if (D && !D->
hasAttr<WeakAttr>())
5591 Entry->setLinkage(llvm::Function::ExternalLinkage);
5595 if (D && shouldDropDLLAttribute(D, Entry))
5596 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5598 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
5601 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
5606 if (IsForDefinition && !Entry->isDeclaration()) {
5614 (OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
5616 DiagnosedConflictingDefinitions.insert(D).second) {
5620 diag::note_previous_definition);
5625 if (Entry->getType()->getAddressSpace() != TargetAS)
5626 return llvm::ConstantExpr::getAddrSpaceCast(
5627 Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
5631 if (!IsForDefinition)
5637 auto *GV =
new llvm::GlobalVariable(
5638 getModule(), Ty,
false, llvm::GlobalValue::ExternalLinkage,
nullptr,
5639 MangledName,
nullptr, llvm::GlobalVariable::NotThreadLocal,
5640 getContext().getTargetAddressSpace(DAddrSpace));
5645 GV->takeName(Entry);
5647 if (!Entry->use_empty()) {
5648 Entry->replaceAllUsesWith(GV);
5651 Entry->eraseFromParent();
5657 auto DDI = DeferredDecls.find(MangledName);
5658 if (DDI != DeferredDecls.end()) {
5661 addDeferredDeclToEmit(DDI->second);
5662 DeferredDecls.erase(DDI);
5667 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
5674 GV->setAlignment(
getContext().getDeclAlign(D).getAsAlign());
5680 CXXThreadLocals.push_back(D);
5688 if (
getContext().isMSStaticDataMemberInlineDefinition(D)) {
5689 EmitGlobalVarDefinition(D);
5694 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>())
5695 GV->setSection(SA->getName());
5699 if (
getTriple().getArch() == llvm::Triple::xcore &&
5703 GV->setSection(
".cp.rodata");
5706 if (
const auto *CMA = D->
getAttr<CodeModelAttr>())
5707 GV->setCodeModel(CMA->getModel());
5712 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
5716 Context.getBaseElementType(D->
getType())->getAsCXXRecordDecl();
5717 bool HasMutableFields =
Record &&
Record->hasMutableFields();
5718 if (!HasMutableFields) {
5725 auto *InitType =
Init->getType();
5726 if (GV->getValueType() != InitType) {
5731 GV->setName(StringRef());
5736 ->stripPointerCasts());
5739 GV->eraseFromParent();
5742 GV->setInitializer(
Init);
5743 GV->setConstant(
true);
5744 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
5764 SanitizerMD->reportGlobal(GV, *D);
5769 assert(
getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
5770 if (DAddrSpace != ExpectedAS)
5783 false, IsForDefinition);
5804 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes
Linkage,
5805 llvm::Align Alignment) {
5806 llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
5807 llvm::GlobalVariable *OldGV =
nullptr;
5811 if (GV->getValueType() == Ty)
5816 assert(GV->isDeclaration() &&
"Declaration has wrong type!");
5821 GV =
new llvm::GlobalVariable(
getModule(), Ty,
true,
5826 GV->takeName(OldGV);
5828 if (!OldGV->use_empty()) {
5829 OldGV->replaceAllUsesWith(GV);
5832 OldGV->eraseFromParent();
5836 !GV->hasAvailableExternallyLinkage())
5837 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5839 GV->setAlignment(Alignment);
5876 assert(!D->
getInit() &&
"Cannot emit definite definitions here!");
5884 if (GV && !GV->isDeclaration())
5889 if (!MustBeEmitted(D) && !GV) {
5890 DeferredDecls[MangledName] = D;
5895 EmitGlobalVarDefinition(D);
5900 if (
auto const *CD = dyn_cast<const CXXConstructorDecl>(D))
5902 else if (
auto const *DD = dyn_cast<const CXXDestructorDecl>(D))
5917 if (
const auto *VD = dyn_cast<VarDecl>(D)) {
5920 }
else if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
5922 if (!Fn->getSubprogram())
5928 return Context.toCharUnitsFromBits(
5933 if (LangOpts.OpenCL) {
5944 if (LangOpts.SYCLIsDevice &&
5948 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
5950 if (D->
hasAttr<CUDAConstantAttr>())
5952 if (D->
hasAttr<CUDASharedAttr>())
5954 if (D->
hasAttr<CUDADeviceAttr>())
5962 if (LangOpts.OpenMP) {
5964 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
5972 if (LangOpts.OpenCL)
5974 if (LangOpts.SYCLIsDevice)
5976 if (LangOpts.HIP && LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())
5984 if (
auto AS =
getTarget().getConstantAddressSpace())
5997static llvm::Constant *
5999 llvm::GlobalVariable *GV) {
6000 llvm::Constant *Cast = GV;
6005 GV, llvm::PointerType::get(
6012template<
typename SomeDecl>
6014 llvm::GlobalValue *GV) {
6029 const SomeDecl *
First = D->getFirstDecl();
6030 if (
First->getDeclContext()->isRecord() || !
First->isInExternCContext())
6036 std::pair<StaticExternCMap::iterator, bool> R =
6037 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
6042 R.first->second =
nullptr;
6049 if (D.
hasAttr<SelectAnyAttr>())
6053 if (
auto *VD = dyn_cast<VarDecl>(&D))
6067 llvm_unreachable(
"No such linkage");
6075 llvm::GlobalObject &GO) {
6078 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
6086void CodeGenModule::EmitGlobalVarDefinition(
const VarDecl *D,
6101 if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
6102 OpenMPRuntime->emitTargetGlobalVariable(D))
6105 llvm::TrackingVH<llvm::Constant>
Init;
6106 bool NeedsGlobalCtor =
false;
6110 bool IsDefinitionAvailableExternally =
6112 bool NeedsGlobalDtor =
6113 !IsDefinitionAvailableExternally &&
6120 if (IsDefinitionAvailableExternally &&
6131 std::optional<ConstantEmitter> emitter;
6136 bool IsCUDASharedVar =
6141 bool IsCUDAShadowVar =
6143 (D->
hasAttr<CUDAConstantAttr>() || D->
hasAttr<CUDADeviceAttr>() ||
6144 D->
hasAttr<CUDASharedAttr>());
6145 bool IsCUDADeviceShadowVar =
6150 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) {
6151 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
6155 Init = llvm::PoisonValue::get(
getTypes().ConvertType(ASTTy));
6158 }
else if (D->
hasAttr<LoaderUninitializedAttr>()) {
6159 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
6160 }
else if (!InitExpr) {
6173 initializedGlobalDecl = GlobalDecl(D);
6174 emitter.emplace(*
this);
6175 llvm::Constant *
Initializer = emitter->tryEmitForInitializer(*InitDecl);
6177 QualType T = InitExpr->
getType();
6183 if (!IsDefinitionAvailableExternally)
6184 NeedsGlobalCtor =
true;
6188 NeedsGlobalCtor =
false;
6192 Init = llvm::PoisonValue::get(
getTypes().ConvertType(T));
6200 DelayedCXXInitPosition.erase(D);
6207 assert(VarSize == CstSize &&
"Emitted constant has unexpected size");
6212 llvm::Type* InitType =
Init->getType();
6213 llvm::Constant *Entry =
6217 Entry = Entry->stripPointerCasts();
6220 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
6231 if (!GV || GV->getValueType() != InitType ||
6232 GV->getType()->getAddressSpace() !=
6236 Entry->setName(StringRef());
6241 ->stripPointerCasts());
6244 llvm::Constant *NewPtrForOldDecl =
6245 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
6247 Entry->replaceAllUsesWith(NewPtrForOldDecl);
6255 if (D->
hasAttr<AnnotateAttr>())
6268 if (LangOpts.CUDA) {
6269 if (LangOpts.CUDAIsDevice) {
6272 (D->
hasAttr<CUDADeviceAttr>() || D->
hasAttr<CUDAConstantAttr>() ||
6275 GV->setExternallyInitialized(
true);
6282 if (LangOpts.HLSL &&
6287 GV->setExternallyInitialized(
true);
6289 GV->setInitializer(
Init);
6296 emitter->finalize(GV);
6299 GV->setConstant((D->
hasAttr<CUDAConstantAttr>() && LangOpts.CUDAIsDevice) ||
6300 (!NeedsGlobalCtor && !NeedsGlobalDtor &&
6304 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>()) {
6305 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
6307 GV->setConstant(
true);
6312 if (std::optional<CharUnits> AlignValFromAllocate =
6314 AlignVal = *AlignValFromAllocate;
6332 Linkage == llvm::GlobalValue::ExternalLinkage &&
6333 Context.getTargetInfo().getTriple().isOSDarwin() &&
6335 Linkage = llvm::GlobalValue::InternalLinkage;
6340 if (LangOpts.HLSL &&
6342 Linkage = llvm::GlobalValue::ExternalLinkage;
6345 if (D->
hasAttr<DLLImportAttr>())
6346 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
6347 else if (D->
hasAttr<DLLExportAttr>())
6348 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
6350 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6352 if (
Linkage == llvm::GlobalVariable::CommonLinkage) {
6354 GV->setConstant(
false);
6359 if (!GV->getInitializer()->isNullValue())
6360 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
6363 setNonAliasAttributes(D, GV);
6365 if (D->
getTLSKind() && !GV->isThreadLocal()) {
6367 CXXThreadLocals.push_back(D);
6374 if (NeedsGlobalCtor || NeedsGlobalDtor)
6375 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
6377 SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
6382 DI->EmitGlobalVariable(GV, D);
6390 if ((NoCommon || D->
hasAttr<NoCommonAttr>()) && !D->
hasAttr<CommonAttr>())
6401 if (D->
hasAttr<SectionAttr>())
6407 if (D->
hasAttr<PragmaClangBSSSectionAttr>() ||
6408 D->
hasAttr<PragmaClangDataSectionAttr>() ||
6409 D->
hasAttr<PragmaClangRelroSectionAttr>() ||
6410 D->
hasAttr<PragmaClangRodataSectionAttr>())
6418 if (D->
hasAttr<WeakImportAttr>())
6427 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6428 if (D->
hasAttr<AlignedAttr>())
6431 if (Context.isAlignmentRequired(VarType))
6435 for (
const FieldDecl *FD : RD->fields()) {
6436 if (FD->isBitField())
6438 if (FD->
hasAttr<AlignedAttr>())
6440 if (Context.isAlignmentRequired(FD->
getType()))
6452 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
6453 Context.getTypeAlignIfKnown(D->
getType()) >
6460llvm::GlobalValue::LinkageTypes
6464 return llvm::Function::InternalLinkage;
6467 return llvm::GlobalVariable::WeakAnyLinkage;
6471 return llvm::GlobalVariable::LinkOnceAnyLinkage;
6476 return llvm::GlobalValue::AvailableExternallyLinkage;
6490 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
6491 : llvm::Function::InternalLinkage;
6505 return llvm::Function::ExternalLinkage;
6508 return D->
hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
6509 : llvm::Function::InternalLinkage;
6510 return llvm::Function::WeakODRLinkage;
6517 CodeGenOpts.NoCommon))
6518 return llvm::GlobalVariable::CommonLinkage;
6524 if (D->
hasAttr<SelectAnyAttr>())
6525 return llvm::GlobalVariable::WeakODRLinkage;
6529 return llvm::GlobalVariable::ExternalLinkage;
6532llvm::GlobalValue::LinkageTypes
6541 llvm::Function *newFn) {
6543 if (old->use_empty())
6546 llvm::Type *newRetTy = newFn->getReturnType();
6551 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
6553 llvm::User *user = ui->getUser();
6557 if (
auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
6558 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
6564 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
6567 if (!callSite->isCallee(&*ui))
6572 if (callSite->getType() != newRetTy && !callSite->use_empty())
6577 llvm::AttributeList oldAttrs = callSite->getAttributes();
6580 unsigned newNumArgs = newFn->arg_size();
6581 if (callSite->arg_size() < newNumArgs)
6587 bool dontTransform =
false;
6588 for (llvm::Argument &A : newFn->args()) {
6589 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
6590 dontTransform =
true;
6595 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
6603 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
6607 callSite->getOperandBundlesAsDefs(newBundles);
6609 llvm::CallBase *newCall;
6611 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles,
"",
6612 callSite->getIterator());
6615 newCall = llvm::InvokeInst::Create(
6616 newFn, oldInvoke->getNormalDest(), oldInvoke->getUnwindDest(),
6617 newArgs, newBundles,
"", callSite->getIterator());
6621 if (!newCall->getType()->isVoidTy())
6622 newCall->takeName(callSite);
6623 newCall->setAttributes(
6624 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
6625 oldAttrs.getRetAttrs(), newArgAttrs));
6626 newCall->setCallingConv(callSite->getCallingConv());
6629 if (!callSite->use_empty())
6630 callSite->replaceAllUsesWith(newCall);
6633 if (callSite->getDebugLoc())
6634 newCall->setDebugLoc(callSite->getDebugLoc());
6636 callSitesToBeRemovedFromParent.push_back(callSite);
6639 for (
auto *callSite : callSitesToBeRemovedFromParent) {
6640 callSite->eraseFromParent();
6654 llvm::Function *NewFn) {
6664 (LangOpts.CUDA && !shouldEmitCUDAGlobalVar(VD)))
6676void CodeGenModule::EmitGlobalFunctionDefinition(
GlobalDecl GD,
6677 llvm::GlobalValue *GV) {
6685 if (!GV || (GV->getValueType() != Ty))
6691 if (!GV->isDeclaration())
6710 setNonAliasAttributes(GD, Fn);
6712 bool ShouldAddOptNone = !CodeGenOpts.DisableO0ImplyOptNone &&
6713 (CodeGenOpts.OptimizationLevel == 0) &&
6716 if (DeviceKernelAttr::isOpenCLSpelling(D->
getAttr<DeviceKernelAttr>())) {
6718 !D->
hasAttr<NoInlineAttr>() &&
6719 !Fn->hasFnAttribute(llvm::Attribute::NoInline) &&
6720 !D->
hasAttr<OptimizeNoneAttr>() &&
6721 !Fn->hasFnAttribute(llvm::Attribute::OptimizeNone) &&
6722 !ShouldAddOptNone) {
6723 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
6729 auto GetPriority = [
this](
const auto *
Attr) ->
int {
6734 return Attr->DefaultPriority;
6737 if (
const ConstructorAttr *CA = D->
getAttr<ConstructorAttr>())
6739 if (
const DestructorAttr *DA = D->
getAttr<DestructorAttr>())
6745void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
6747 const AliasAttr *AA = D->
getAttr<AliasAttr>();
6748 assert(AA &&
"Not an alias?");
6752 if (AA->getAliasee() == MangledName) {
6753 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6760 if (Entry && !Entry->isDeclaration())
6763 Aliases.push_back(GD);
6769 llvm::Constant *Aliasee;
6770 llvm::GlobalValue::LinkageTypes
LT;
6772 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
6778 if (
const auto *VD = dyn_cast<VarDecl>(GD.
getDecl()))
6785 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
6787 llvm::GlobalAlias::create(DeclTy, AS, LT,
"", Aliasee, &
getModule());
6790 if (GA->getAliasee() == Entry) {
6791 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6795 assert(Entry->isDeclaration());
6804 GA->takeName(Entry);
6806 Entry->replaceAllUsesWith(GA);
6807 Entry->eraseFromParent();
6809 GA->setName(MangledName);
6817 GA->setLinkage(llvm::Function::WeakAnyLinkage);
6820 if (
const auto *VD = dyn_cast<VarDecl>(D))
6821 if (VD->getTLSKind())
6832void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
6834 const IFuncAttr *IFA = D->
getAttr<IFuncAttr>();
6835 assert(IFA &&
"Not an ifunc?");
6839 if (IFA->getResolver() == MangledName) {
6840 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6846 if (Entry && !Entry->isDeclaration()) {
6849 DiagnosedConflictingDefinitions.insert(GD).second) {
6850 Diags.Report(D->
getLocation(), diag::err_duplicate_mangled_name)
6853 diag::note_previous_definition);
6858 Aliases.push_back(GD);
6864 llvm::Constant *Resolver =
6865 GetOrCreateLLVMFunction(IFA->getResolver(),
VoidTy, {},
6869 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
6870 DeclTy, AS, llvm::Function::ExternalLinkage,
"", Resolver, &
getModule());
6872 if (GIF->getResolver() == Entry) {
6873 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6876 assert(Entry->isDeclaration());
6885 GIF->takeName(Entry);
6887 Entry->replaceAllUsesWith(GIF);
6888 Entry->eraseFromParent();
6890 GIF->setName(MangledName);
6896 return llvm::Intrinsic::getOrInsertDeclaration(&
getModule(),
6897 (llvm::Intrinsic::ID)IID, Tys);
6900static llvm::StringMapEntry<llvm::GlobalVariable *> &
6903 bool &IsUTF16,
unsigned &StringLength) {
6904 StringRef String = Literal->getString();
6905 unsigned NumBytes = String.size();
6908 if (!Literal->containsNonAsciiOrNull()) {
6909 StringLength = NumBytes;
6910 return *Map.insert(std::make_pair(String,
nullptr)).first;
6917 const llvm::UTF8 *FromPtr = (
const llvm::UTF8 *)String.data();
6918 llvm::UTF16 *ToPtr = &ToBuf[0];
6920 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6921 ToPtr + NumBytes, llvm::strictConversion);
6924 StringLength = ToPtr - &ToBuf[0];
6928 return *Map.insert(std::make_pair(
6929 StringRef(
reinterpret_cast<const char *
>(ToBuf.data()),
6930 (StringLength + 1) * 2),
6936 unsigned StringLength = 0;
6937 bool isUTF16 =
false;
6938 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
6943 if (
auto *
C = Entry.second)
6948 const llvm::Triple &Triple =
getTriple();
6951 const bool IsSwiftABI =
6952 static_cast<unsigned>(CFRuntime) >=
6957 if (!CFConstantStringClassRef) {
6958 const char *CFConstantStringClassName =
"__CFConstantStringClassReference";
6960 Ty = llvm::ArrayType::get(Ty, 0);
6962 switch (CFRuntime) {
6966 CFConstantStringClassName =
6967 Triple.isOSDarwin() ?
"$s15SwiftFoundation19_NSCFConstantStringCN"
6968 :
"$s10Foundation19_NSCFConstantStringCN";
6972 CFConstantStringClassName =
6973 Triple.isOSDarwin() ?
"$S15SwiftFoundation19_NSCFConstantStringCN"
6974 :
"$S10Foundation19_NSCFConstantStringCN";
6978 CFConstantStringClassName =
6979 Triple.isOSDarwin() ?
"__T015SwiftFoundation19_NSCFConstantStringCN"
6980 :
"__T010Foundation19_NSCFConstantStringCN";
6987 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
6988 llvm::GlobalValue *GV =
nullptr;
6990 if ((GV = dyn_cast<llvm::GlobalValue>(
C))) {
6997 if ((VD = dyn_cast<VarDecl>(
Result)))
7000 if (Triple.isOSBinFormatELF()) {
7002 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
7004 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
7005 if (!VD || !VD->
hasAttr<DLLExportAttr>())
7006 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
7008 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
7016 CFConstantStringClassRef =
7017 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(
C, Ty) :
C;
7020 QualType CFTy = Context.getCFConstantStringType();
7025 auto Fields = Builder.beginStruct(STy);
7034 Fields.addInt(
IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
7035 Fields.addInt(
Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
7037 Fields.addInt(
IntTy, isUTF16 ? 0x07d0 : 0x07C8);
7041 llvm::Constant *
C =
nullptr;
7044 reinterpret_cast<uint16_t *
>(
const_cast<char *
>(Entry.first().data())),
7045 Entry.first().size() / 2);
7046 C = llvm::ConstantDataArray::get(VMContext, Arr);
7048 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
7054 new llvm::GlobalVariable(
getModule(),
C->getType(),
true,
7055 llvm::GlobalValue::PrivateLinkage,
C,
".str");
7056 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
7059 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
7060 : Context.getTypeAlignInChars(Context.CharTy);
7066 if (Triple.isOSBinFormatMachO())
7067 GV->setSection(isUTF16 ?
"__TEXT,__ustring"
7068 :
"__TEXT,__cstring,cstring_literals");
7071 else if (Triple.isOSBinFormatELF())
7072 GV->setSection(
".rodata");
7078 llvm::IntegerType *LengthTy =
7088 Fields.addInt(LengthTy, StringLength);
7096 GV = Fields.finishAndCreateGlobal(
"_unnamed_cfstring_", Alignment,
7098 llvm::GlobalVariable::PrivateLinkage);
7099 GV->addAttribute(
"objc_arc_inert");
7100 switch (Triple.getObjectFormat()) {
7101 case llvm::Triple::UnknownObjectFormat:
7102 llvm_unreachable(
"unknown file format");
7103 case llvm::Triple::DXContainer:
7104 case llvm::Triple::GOFF:
7105 case llvm::Triple::SPIRV:
7106 case llvm::Triple::XCOFF:
7107 llvm_unreachable(
"unimplemented");
7108 case llvm::Triple::COFF:
7109 case llvm::Triple::ELF:
7110 case llvm::Triple::Wasm:
7111 GV->setSection(
"cfstring");
7113 case llvm::Triple::MachO:
7114 GV->setSection(
"__DATA,__cfstring");
7123 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
7127 if (ObjCFastEnumerationStateType.isNull()) {
7128 RecordDecl *D = Context.buildImplicitRecord(
"__objcFastEnumerationState");
7132 Context.UnsignedLongTy, Context.getPointerType(Context.getObjCIdType()),
7133 Context.getPointerType(Context.UnsignedLongTy),
7134 Context.getConstantArrayType(Context.UnsignedLongTy, llvm::APInt(32, 5),
7137 for (
size_t i = 0; i < 4; ++i) {
7142 FieldTypes[i],
nullptr,
7151 ObjCFastEnumerationStateType = Context.getCanonicalTagType(D);
7154 return ObjCFastEnumerationStateType;
7168 assert(CAT &&
"String literal not of constant array type!");
7170 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
7174 llvm::Type *ElemTy = AType->getElementType();
7175 unsigned NumElements = AType->getNumElements();
7178 if (ElemTy->getPrimitiveSizeInBits() == 16) {
7180 Elements.reserve(NumElements);
7182 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
7184 Elements.resize(NumElements);
7185 return llvm::ConstantDataArray::get(VMContext, Elements);
7188 assert(ElemTy->getPrimitiveSizeInBits() == 32);
7190 Elements.reserve(NumElements);
7192 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
7194 Elements.resize(NumElements);
7195 return llvm::ConstantDataArray::get(VMContext, Elements);
7198static llvm::GlobalVariable *
7207 auto *GV =
new llvm::GlobalVariable(
7208 M,
C->getType(), !CGM.
getLangOpts().WritableStrings, LT,
C, GlobalName,
7209 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
7211 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
7212 if (GV->isWeakForLinker()) {
7213 assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
7214 GV->setComdat(M.getOrInsertComdat(GV->getName()));
7230 llvm::GlobalVariable **Entry =
nullptr;
7231 if (!LangOpts.WritableStrings) {
7232 Entry = &ConstantStringMap[
C];
7233 if (
auto GV = *Entry) {
7234 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
7237 GV->getValueType(), Alignment);
7242 StringRef GlobalVariableName;
7243 llvm::GlobalValue::LinkageTypes LT;
7248 if (
getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
7249 !LangOpts.WritableStrings) {
7250 llvm::raw_svector_ostream Out(MangledNameBuffer);
7252 LT = llvm::GlobalValue::LinkOnceODRLinkage;
7253 GlobalVariableName = MangledNameBuffer;
7255 LT = llvm::GlobalValue::PrivateLinkage;
7256 GlobalVariableName = Name;
7268 SanitizerMD->reportGlobal(GV, S->
getStrTokenLoc(0),
"<string literal>");
7271 GV->getValueType(), Alignment);
7288 StringRef GlobalName) {
7289 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
7294 llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
7297 llvm::GlobalVariable **Entry =
nullptr;
7298 if (!LangOpts.WritableStrings) {
7299 Entry = &ConstantStringMap[
C];
7300 if (
auto GV = *Entry) {
7301 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
7304 GV->getValueType(), Alignment);
7310 GlobalName, Alignment);
7315 GV->getValueType(), Alignment);
7328 MaterializedType = E->
getType();
7332 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E,
nullptr});
7333 if (!InsertResult.second) {
7336 if (!InsertResult.first->second) {
7341 InsertResult.first->second =
new llvm::GlobalVariable(
7342 getModule(),
Type,
false, llvm::GlobalVariable::InternalLinkage,
7346 llvm::cast<llvm::GlobalVariable>(
7347 InsertResult.first->second->stripPointerCasts())
7356 llvm::raw_svector_ostream Out(Name);
7378 std::optional<ConstantEmitter> emitter;
7379 llvm::Constant *InitialValue =
nullptr;
7380 bool Constant =
false;
7384 emitter.emplace(*
this);
7385 InitialValue = emitter->emitForInitializer(*
Value, AddrSpace,
7390 Type = InitialValue->getType();
7399 if (
Linkage == llvm::GlobalVariable::ExternalLinkage) {
7401 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
7405 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
7409 Linkage = llvm::GlobalVariable::InternalLinkage;
7413 auto *GV =
new llvm::GlobalVariable(
7415 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
7416 if (emitter) emitter->finalize(GV);
7418 if (!llvm::GlobalValue::isLocalLinkage(
Linkage)) {
7420 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
7422 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
7426 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
7427 if (VD->getTLSKind())
7429 llvm::Constant *CV = GV;
7432 GV, llvm::PointerType::get(
7438 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
7440 Entry->replaceAllUsesWith(CV);
7441 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
7450void CodeGenModule::EmitObjCPropertyImplementations(
const
7463 if (!Getter || Getter->isSynthesizedAccessorStub())
7466 auto *Setter = PID->getSetterMethodDecl();
7467 if (!PD->
isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
7478 if (ivar->getType().isDestructedType())
7499void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
7512 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod,
false);
7527 getContext().getObjCIdType(),
nullptr, D,
true,
7533 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod,
true);
7538void CodeGenModule::EmitLinkageSpec(
const LinkageSpecDecl *LSD) {
7545 EmitDeclContext(LSD);
7548void CodeGenModule::EmitTopLevelStmt(
const TopLevelStmtDecl *D) {
7550 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7553 std::unique_ptr<CodeGenFunction> &CurCGF =
7554 GlobalTopLevelStmtBlockInFlight.first;
7558 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
7566 std::string Name =
"__stmts__" + llvm::utostr(CXXGlobalInits.size());
7567 FunctionArgList Args;
7569 const CGFunctionInfo &FnInfo =
7572 llvm::Function *
Fn = llvm::Function::Create(
7573 FnTy, llvm::GlobalValue::InternalLinkage, Name, &
getModule());
7575 CurCGF.reset(
new CodeGenFunction(*
this));
7576 GlobalTopLevelStmtBlockInFlight.second = D;
7577 CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
7579 CXXGlobalInits.push_back(Fn);
7582 CurCGF->EmitStmt(D->
getStmt());
7585void CodeGenModule::EmitDeclContext(
const DeclContext *DC) {
7586 for (
auto *I : DC->
decls()) {
7592 if (
auto *OID = dyn_cast<ObjCImplDecl>(I)) {
7593 for (
auto *M : OID->methods())
7612 case Decl::CXXConversion:
7613 case Decl::CXXMethod:
7614 case Decl::Function:
7621 case Decl::CXXDeductionGuide:
7626 case Decl::Decomposition:
7627 case Decl::VarTemplateSpecialization:
7629 if (
auto *DD = dyn_cast<DecompositionDecl>(D))
7630 for (
auto *B : DD->flat_bindings())
7631 if (
auto *HD = B->getHoldingVar())
7638 case Decl::IndirectField:
7642 case Decl::Namespace:
7645 case Decl::ClassTemplateSpecialization: {
7648 if (Spec->getSpecializationKind() ==
7650 Spec->hasDefinition())
7651 DI->completeTemplateDefinition(*Spec);
7653 case Decl::CXXRecord: {
7657 DI->EmitAndRetainType(
7661 DI->completeUnusedClass(*CRD);
7664 for (
auto *I : CRD->
decls())
7670 case Decl::UsingShadow:
7671 case Decl::ClassTemplate:
7672 case Decl::VarTemplate:
7674 case Decl::VarTemplatePartialSpecialization:
7675 case Decl::FunctionTemplate:
7676 case Decl::TypeAliasTemplate:
7685 case Decl::UsingEnum:
7689 case Decl::NamespaceAlias:
7693 case Decl::UsingDirective:
7697 case Decl::CXXConstructor:
7700 case Decl::CXXDestructor:
7704 case Decl::StaticAssert:
7711 case Decl::ObjCInterface:
7712 case Decl::ObjCCategory:
7715 case Decl::ObjCProtocol: {
7717 if (Proto->isThisDeclarationADefinition())
7718 ObjCRuntime->GenerateProtocol(Proto);
7722 case Decl::ObjCCategoryImpl:
7728 case Decl::ObjCImplementation: {
7730 EmitObjCPropertyImplementations(OMD);
7731 EmitObjCIvarInitializations(OMD);
7732 ObjCRuntime->GenerateClass(OMD);
7736 DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
7737 OMD->getClassInterface()), OMD->getLocation());
7740 case Decl::ObjCMethod: {
7747 case Decl::ObjCCompatibleAlias:
7751 case Decl::PragmaComment: {
7753 switch (PCD->getCommentKind()) {
7755 llvm_unreachable(
"unexpected pragma comment kind");
7770 case Decl::PragmaDetectMismatch: {
7776 case Decl::LinkageSpec:
7780 case Decl::FileScopeAsm: {
7782 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7785 if (LangOpts.OpenMPIsTargetDevice)
7788 if (LangOpts.SYCLIsDevice)
7791 getModule().appendModuleInlineAsm(AD->getAsmString());
7795 case Decl::TopLevelStmt:
7799 case Decl::Import: {
7803 if (!ImportedModules.insert(Import->getImportedModule()))
7807 if (!Import->getImportedOwningModule()) {
7809 DI->EmitImportDecl(*Import);
7815 if (CXX20ModuleInits && Import->getImportedModule() &&
7816 Import->getImportedModule()->isNamedModule())
7825 Visited.insert(Import->getImportedModule());
7826 Stack.push_back(Import->getImportedModule());
7828 while (!Stack.empty()) {
7830 if (!EmittedModuleInitializers.insert(Mod).second)
7833 for (
auto *D : Context.getModuleInitializers(Mod))
7840 if (Submodule->IsExplicit)
7843 if (Visited.insert(Submodule).second)
7844 Stack.push_back(Submodule);
7854 case Decl::OMPThreadPrivate:
7858 case Decl::OMPAllocate:
7862 case Decl::OMPDeclareReduction:
7866 case Decl::OMPDeclareMapper:
7870 case Decl::OMPRequires:
7875 case Decl::TypeAlias:
7877 DI->EmitAndRetainType(
getContext().getTypedefType(
7885 DI->EmitAndRetainType(
7892 DI->EmitAndRetainType(
7896 case Decl::HLSLRootSignature:
7899 case Decl::HLSLBuffer:
7903 case Decl::OpenACCDeclare:
7906 case Decl::OpenACCRoutine:
7921 if (!CodeGenOpts.CoverageMapping)
7924 case Decl::CXXConversion:
7925 case Decl::CXXMethod:
7926 case Decl::Function:
7927 case Decl::ObjCMethod:
7928 case Decl::CXXConstructor:
7929 case Decl::CXXDestructor: {
7938 DeferredEmptyCoverageMappingDecls.try_emplace(D,
true);
7948 if (!CodeGenOpts.CoverageMapping)
7950 if (
const auto *Fn = dyn_cast<FunctionDecl>(D)) {
7951 if (Fn->isTemplateInstantiation())
7954 DeferredEmptyCoverageMappingDecls.insert_or_assign(D,
false);
7962 for (
const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
7965 const Decl *D = Entry.first;
7967 case Decl::CXXConversion:
7968 case Decl::CXXMethod:
7969 case Decl::Function:
7970 case Decl::ObjCMethod: {
7977 case Decl::CXXConstructor: {
7984 case Decl::CXXDestructor: {
8001 if (llvm::Function *F =
getModule().getFunction(
"main")) {
8002 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
8003 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
8004 auto *GA = llvm::GlobalAlias::create(
"__main_void", F);
8005 GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
8014 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
8015 return llvm::ConstantInt::get(i64, PtrInt);
8019 llvm::NamedMDNode *&GlobalMetadata,
8021 llvm::GlobalValue *
Addr) {
8022 if (!GlobalMetadata)
8024 CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
8027 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(
Addr),
8030 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
8033bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
8034 llvm::GlobalValue *CppFunc) {
8036 llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
8039 llvm::SmallVector<llvm::ConstantExpr *> CEs;
8042 if (Elem == CppFunc)
8048 for (llvm::User *User : Elem->users()) {
8052 if (
auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
8053 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
8056 for (llvm::User *CEUser : ConstExpr->users()) {
8057 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
8058 IFuncs.push_back(IFunc);
8063 CEs.push_back(ConstExpr);
8064 }
else if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
8065 IFuncs.push_back(IFunc);
8077 for (llvm::GlobalIFunc *IFunc : IFuncs)
8078 IFunc->setResolver(
nullptr);
8079 for (llvm::ConstantExpr *ConstExpr : CEs)
8080 ConstExpr->destroyConstant();
8084 Elem->eraseFromParent();
8086 for (llvm::GlobalIFunc *IFunc : IFuncs) {
8091 llvm::FunctionType::get(IFunc->getType(),
false);
8092 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
8093 CppFunc->getName(), ResolverTy, {},
false);
8094 IFunc->setResolver(Resolver);
8104void CodeGenModule::EmitStaticExternCAliases() {
8107 for (
auto &I : StaticExternCValues) {
8108 const IdentifierInfo *Name = I.first;
8109 llvm::GlobalValue *Val = I.second;
8117 llvm::GlobalValue *ExistingElem =
8122 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
8129 auto Res = Manglings.find(MangledName);
8130 if (Res == Manglings.end())
8132 Result = Res->getValue();
8143void CodeGenModule::EmitDeclMetadata() {
8144 llvm::NamedMDNode *GlobalMetadata =
nullptr;
8146 for (
auto &I : MangledDeclNames) {
8147 llvm::GlobalValue *
Addr =
getModule().getNamedValue(I.second);
8157void CodeGenFunction::EmitDeclMetadata() {
8158 if (LocalDeclMap.empty())
return;
8163 unsigned DeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
8165 llvm::NamedMDNode *GlobalMetadata =
nullptr;
8167 for (
auto &I : LocalDeclMap) {
8168 const Decl *D = I.first;
8169 llvm::Value *
Addr = I.second.emitRawPointer(*
this);
8170 if (
auto *Alloca = dyn_cast<llvm::AllocaInst>(
Addr)) {
8172 Alloca->setMetadata(
8173 DeclPtrKind, llvm::MDNode::get(
8174 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
8175 }
else if (
auto *GV = dyn_cast<llvm::GlobalValue>(
Addr)) {
8182void CodeGenModule::EmitVersionIdentMetadata() {
8183 llvm::NamedMDNode *IdentMetadata =
8184 TheModule.getOrInsertNamedMetadata(
"llvm.ident");
8186 llvm::LLVMContext &Ctx = TheModule.getContext();
8188 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
8189 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
8192void CodeGenModule::EmitCommandLineMetadata() {
8193 llvm::NamedMDNode *CommandLineMetadata =
8194 TheModule.getOrInsertNamedMetadata(
"llvm.commandline");
8196 llvm::LLVMContext &Ctx = TheModule.getContext();
8198 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
8199 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
8202void CodeGenModule::EmitCoverageFile() {
8203 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu");
8207 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
8208 llvm::LLVMContext &Ctx = TheModule.getContext();
8209 auto *CoverageDataFile =
8211 auto *CoverageNotesFile =
8213 for (
int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
8214 llvm::MDNode *CU = CUNode->getOperand(i);
8215 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
8216 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
8229 LangOpts.ObjCRuntime.isGNUFamily())
8230 return ObjCRuntime->GetEHType(Ty);
8237 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
8239 for (
auto RefExpr : D->
varlist()) {
8242 VD->getAnyInitializer() &&
8243 !VD->getAnyInitializer()->isConstantInitializer(
getContext(),
8250 VD,
Addr, RefExpr->getBeginLoc(), PerformInit))
8251 CXXGlobalInits.push_back(InitFunction);
8256CodeGenModule::CreateMetadataIdentifierImpl(
QualType T, MetadataTypeMap &Map,
8260 FnType->getReturnType(), FnType->getParamTypes(),
8261 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
8263 llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
8268 std::string OutName;
8269 llvm::raw_string_ostream Out(OutName);
8274 Out <<
".normalized";
8297 return CreateMetadataIdentifierImpl(T, MetadataIdMap,
"");
8302 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap,
".virtual");
8306 return CreateMetadataIdentifierImpl(T, GeneralizedMetadataIdMap,
8314 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
8315 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
8316 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
8317 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
8318 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
8319 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
8320 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
8321 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
8329 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8331 if (CodeGenOpts.SanitizeCfiCrossDso)
8333 VTable->addTypeMetadata(Offset.getQuantity(),
8334 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
8337 llvm::Metadata *MD = llvm::MDString::get(
getLLVMContext(),
"all-vtables");
8338 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8344 SanStats = std::make_unique<llvm::SanitizerStatReport>(&
getModule());
8354 auto *FTy = llvm::FunctionType::get(SamplerT, {
C->getType()},
false);
8369 bool forPointeeType) {
8380 if (
auto Align = TT->getDecl()->getMaxAlignment()) {
8387 bool AlignForArray = T->isArrayType();
8393 if (T->isIncompleteType()) {
8410 if (T.getQualifiers().hasUnaligned()) {
8412 }
else if (forPointeeType && !AlignForArray &&
8413 (RD = T->getAsCXXRecordDecl())) {
8424 if (
unsigned MaxAlign =
getLangOpts().MaxTypeAlign) {
8437 if (NumAutoVarInit >= StopAfter) {
8440 if (!NumAutoVarInit) {
8454 const Decl *D)
const {
8458 OS << (isa<VarDecl>(D) ?
".static." :
".intern.");
8460 OS << (isa<VarDecl>(D) ?
"__static__" :
"__intern__");
8466 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
8470 llvm::MD5::MD5Result
Result;
8471 for (
const auto &Arg : PreprocessorOpts.Macros)
8472 Hash.update(Arg.first);
8476 llvm::sys::fs::UniqueID ID;
8480 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
8484 SM.getDiagnostics().Report(diag::err_cannot_open_file)
8485 << PLoc.
getFilename() << Status.getError().message();
8487 ID = Status->getUniqueID();
8489 OS << llvm::format(
"%x", ID.getFile()) << llvm::format(
"%x", ID.getDevice())
8490 <<
"_" << llvm::utohexstr(
Result.low(),
true, 8);
8497 assert(DeferredDeclsToEmit.empty() &&
8498 "Should have emitted all decls deferred to emit.");
8499 assert(NewBuilder->DeferredDecls.empty() &&
8500 "Newly created module should not have deferred decls");
8501 NewBuilder->DeferredDecls = std::move(DeferredDecls);
8502 assert(EmittedDeferredDecls.empty() &&
8503 "Still have (unmerged) EmittedDeferredDecls deferred decls");
8505 assert(NewBuilder->DeferredVTables.empty() &&
8506 "Newly created module should not have deferred vtables");
8507 NewBuilder->DeferredVTables = std::move(DeferredVTables);
8509 assert(NewBuilder->MangledDeclNames.empty() &&
8510 "Newly created module should not have mangled decl names");
8511 assert(NewBuilder->Manglings.empty() &&
8512 "Newly created module should not have manglings");
8513 NewBuilder->Manglings = std::move(Manglings);
8515 NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
8517 NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
8521 std::string OutName;
8522 llvm::raw_string_ostream Out(OutName);
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 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 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 bool hasExistingGeneralizedTypeMD(llvm::Function *F)
static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, const CPUSpecificAttr *Attr, unsigned CPUIndex, raw_ostream &Out)
static bool AllTrivialInitializers(CodeGenModule &CGM, ObjCImplementationDecl *D)
static const FunctionDecl * GetRuntimeFunctionDecl(ASTContext &C, StringRef Name)
static GlobalDecl getBaseVariantGlobalDecl(const NamedDecl *D)
static void checkAliasForTocData(llvm::GlobalVariable *GVar, const CodeGenOptions &CodeGenOpts, DiagnosticsEngine &Diags, SourceLocation Location)
static const char PFPDeactivationSymbolPrefix[]
static void emitUsed(CodeGenModule &CGM, StringRef Name, std::vector< llvm::WeakTrackingVH > &List)
static bool HasNonDllImportDtor(QualType T)
static llvm::Constant * GetPointerConstant(llvm::LLVMContext &Context, const void *Ptr)
Turns the given pointer into a constant.
static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S)
static llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM, GlobalDecl GD)
static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO, llvm::Module &M)
static 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 std::vector< std::string > getFeatureDeltaFromDefault(const CodeGenModule &CGM, StringRef TargetCPU, llvm::StringMap< bool > &FeatureMap)
Get the feature delta from the default feature map for the given target CPU.
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 bool hasUnwindExceptions(const LangOptions &LangOpts)
Determines whether the language options require us to model unwind exceptions.
static llvm::APInt getFMVPriority(const TargetInfo &TI, const CodeGenFunction::FMVResolverOption &RO)
static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, SmallVectorImpl< llvm::MDNode * > &Metadata, llvm::SmallPtrSet< Module *, 16 > &Visited)
Add link options implied by the given module, including modules it depends on, using a postorder walk...
static llvm::cl::opt< bool > LimitedCoverage("limited-coverage-experimental", llvm::cl::Hidden, llvm::cl::desc("Emit limited coverage mapping information (experimental)"))
static CGCXXABI * createCXXABI(CodeGenModule &CGM)
static std::unique_ptr< TargetCodeGenInfo > createTargetCodeGenInfo(CodeGenModule &CGM)
static const llvm::GlobalValue * getAliasedGlobal(const llvm::GlobalValue *GV)
static 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.
llvm::MachO::Target Target
llvm::MachO::Record Record
Defines the clang::Module class, which describes a module in the source code.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
static const NamedDecl * getDefinition(const Decl *D)
Defines the SourceManager interface.
static CharUnits getTypeAllocSize(CodeGenModule &CGM, llvm::Type *type)
Defines version macros and version-related utility functions for Clang.
__device__ __2f16 float __ockl_bool s
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
SourceManager & getSourceManager()
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
@ Strong
Strong definition.
@ WeakUnknown
Weak for now, might become strong later in this TU.
const ProfileList & getProfileList() const
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
const XRayFunctionFilter & getXRayFilter() const
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
StringRef getCUIDHash() const
const LangOptions & getLangOpts() const
SelectorTable & Selectors
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
const NoSanitizeList & getNoSanitizeList() const
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const
Return the alignment in characters that should be given to a global variable with type T.
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
DiagnosticsEngine & getDiagnostics() const
const TargetInfo & getTargetInfo() const
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
CanQualType getCanonicalTagType(const TagDecl *TD) const
unsigned getTargetAddressSpace(LangAS AS) const
Module * getCurrentNamedModule() const
Get module under construction, nullptr if this is not a C++20 module.
Attr - This represents one attribute.
Represents a block literal declaration, which is like an unnamed FunctionDecl.
bool isLibFunction(unsigned ID) const
Return true if this is a builtin for a libc/libm function, with a "__builtin_" prefix (e....
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Represents a base class of a C++ class.
CXXTemporary * getTemporary()
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Represents a C++ base or member initializer.
Expr * getInit() const
Get the initializer.
FunctionDecl * getOperatorDelete() const
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
const CXXDestructorDecl * getDestructor() const
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
CharUnits - This is an opaque type for sizes expressed in character units.
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
static CharUnits One()
One - Construct a CharUnits quantity of one.
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::string MSSecureHotPatchFunctionsFile
The name of a file that contains functions which will be compiled for hotpatching.
std::string RecordCommandLine
The string containing the commandline for the llvm.commandline metadata, if non-empty.
std::string FloatABI
The ABI to use for passing floating point arguments.
llvm::Reloc::Model RelocationModel
The name of the relocation model to use.
std::vector< std::string > TocDataVarsUserSpecified
List of global variables explicitly specified by the user as toc-data.
PointerAuthOptions PointerAuth
Configuration for pointer-signing.
std::vector< std::string > MSSecureHotPatchFunctionsList
A list of functions which will be compiled for hotpatching.
ABIInfo - Target specific hooks for defining how a type should be passed or returned from functions.
virtual void appendAttributeMangling(TargetAttr *Attr, raw_ostream &Out) const
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
virtual void handleVarRegistration(const VarDecl *VD, llvm::GlobalVariable &Var)=0
Check whether a variable is a device variable and register it if true.
virtual llvm::GlobalValue * getKernelHandle(llvm::Function *Stub, GlobalDecl GD)=0
Get kernel handle by stub function.
virtual void internalizeDeviceSideVar(const VarDecl *D, llvm::GlobalValue::LinkageTypes &Linkage)=0
Adjust linkage of shadow variables in host compilation.
Implements C++ ABI-specific code generation functions.
virtual void EmitCXXConstructors(const CXXConstructorDecl *D)=0
Emit constructor variants required by this ABI.
virtual llvm::Constant * getAddrOfRTTIDescriptor(QualType Ty)=0
virtual void EmitCXXDestructors(const CXXDestructorDecl *D)=0
Emit destructor variants required by this ABI.
virtual void setCXXDestructorDLLStorage(llvm::GlobalValue *GV, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
virtual llvm::GlobalValue::LinkageTypes getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
MangleContext & getMangleContext()
Gets the mangle context.
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
void 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)
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
void setGVPropertiesAux(llvm::GlobalValue *GV, const NamedDecl *D) const
const IntrusiveRefCntPtr< llvm::vfs::FileSystem > & getFileSystem() const
const ABIInfo & getABIInfo()
void EmitMainVoidAlias()
Emit an alias for "main" if it has no arguments (needed for wasm).
void DecorateInstructionWithInvariantGroup(llvm::Instruction *I, const CXXRecordDecl *RD)
Adds !invariant.barrier !tag to instruction.
DiagnosticsEngine & getDiags() const
bool isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, SourceLocation Loc) const
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
llvm::Constant * getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the constructor/destructor of the given type.
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
llvm::Constant * EmitAnnotateAttr(llvm::GlobalValue *GV, const AnnotateAttr *AA, SourceLocation L)
Generate the llvm::ConstantStruct which contains the annotation information for a given GlobalValue.
void EmitOpenACCDeclare(const OpenACCDeclareDecl *D, CodeGenFunction *CGF=nullptr)
llvm::GlobalValue::LinkageTypes getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage)
Returns LLVM linkage for a declarator.
TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, TBAAAccessInfo SrcInfo)
mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the purposes of memory transfer call...
const LangOptions & getLangOpts() const
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
llvm::Constant * EmitAnnotationLineNo(SourceLocation L)
Emit the annotation line number.
QualType getObjCFastEnumerationStateType()
Retrieve the record type that describes the state of an Objective-C fast enumeration loop (for....
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
CodeGenTypes & getTypes()
bool shouldMapVisibilityToDLLExport(const NamedDecl *D) const
CGOpenCLRuntime & getOpenCLRuntime()
Return a reference to the configured OpenCL runtime.
const std::string & getModuleNameHash() const
const TargetInfo & getTarget() const
bool shouldEmitRTTI(bool ForEH=false)
void EmitGlobal(GlobalDecl D)
Emit code for a single global function or var decl.
llvm::Metadata * CreateMetadataIdentifierForType(QualType T)
Create a metadata identifier for the given type.
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
void createIndirectFunctionTypeMD(const FunctionDecl *FD, llvm::Function *F)
Create and attach type metadata if the function is a potential indirect call target to support call g...
void AppendLinkerOptions(StringRef Opts)
Appends Opts to the "llvm.linker.options" metadata value.
void createCalleeTypeMetadataForIcall(const QualType &QT, llvm::CallBase *CB)
Create and attach type metadata to the given call.
void EmitExternalDeclaration(const DeclaratorDecl *D)
void AddDependentLib(StringRef Lib)
Appends a dependent lib to the appropriate metadata value.
void Release()
Finalize LLVM code generation.
ProfileList::ExclusionType isFunctionBlockedByProfileList(llvm::Function *Fn, SourceLocation Loc) const
llvm::MDNode * getTBAABaseTypeInfo(QualType QTy)
getTBAABaseTypeInfo - Get metadata that describes the given base access type.
bool lookupRepresentativeDecl(StringRef MangledName, GlobalDecl &Result) const
void EmitOMPAllocateDecl(const OMPAllocateDecl *D)
Emit a code for the allocate directive.
void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const
Set the visibility for the given LLVM GlobalValue.
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD)
Returns LLVM linkage for a declarator.
bool HasHiddenLTOVisibility(const CXXRecordDecl *RD)
Returns whether the given record has hidden LTO visibility and therefore may participate in (single-m...
const llvm::DataLayout & getDataLayout() const
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can't be done.
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...
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.
ConstantAddress GetAddrOfConstantStringFromLiteral(const StringLiteral *S, StringRef Name=".str")
Return a pointer to a constant array for the given string literal.
ASTContext & getContext() const
ConstantAddress GetAddrOfTemplateParamObject(const TemplateParamObjectDecl *TPO)
Get the address of a template parameter object.
void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D)
Emit a code for threadprivate directive.
ConstantAddress GetAddrOfUnnamedGlobalConstantDecl(const UnnamedGlobalConstantDecl *GCD)
Get the address of a UnnamedGlobalConstant.
TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, TBAAAccessInfo TargetInfo)
mergeTBAAInfoForCast - Get merged TBAA information for the purposes of type casts.
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
llvm::SanitizerStatReport & getSanStats()
llvm::Constant * EmitAnnotationString(StringRef Str)
Emit an annotation string.
void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare mapper construct.
bool supportsCOMDAT() const
void RefreshTypeCacheForClass(const CXXRecordDecl *Class)
llvm::MDNode * getTBAATypeInfo(QualType QTy)
getTBAATypeInfo - Get metadata used to describe accesses to objects of the given type.
void EmitOMPRequiresDecl(const OMPRequiresDecl *D)
Emit a code for requires directive.
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD)
Tell the consumer that this variable has been instantiated.
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
llvm::Constant * GetConstantArrayFromStringLiteral(const StringLiteral *E)
Return a constant array for the given string.
void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV)
Set attributes which are common to any form of a global definition (alias, Objective-C method,...
std::optional< CharUnits > getOMPAllocateAlignment(const VarDecl *VD)
Return the alignment specified in an allocate directive, if present.
llvm::GlobalVariable * CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, llvm::Align Alignment)
Will return a global variable of the given type.
CharUnits getNaturalPointeeTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, TBAAAccessInfo InfoB)
mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the purposes of conditional ope...
llvm::LLVMContext & getLLVMContext()
llvm::GlobalValue * GetGlobalValue(StringRef Ref)
void GenKernelArgMetadata(llvm::Function *FN, const FunctionDecl *FD=nullptr, CodeGenFunction *CGF=nullptr)
OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument information in the program executab...
void setKCFIType(const FunctionDecl *FD, llvm::Function *F)
Set type metadata to the given function.
void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO)
void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare reduction construct.
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
void AddDetectMismatch(StringRef Name, StringRef Value)
Appends a detect mismatch command to the linker options.
void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const
llvm::Value * createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF)
ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
LangAS GetGlobalConstantAddressSpace() const
Return the AST address space of constant literal, which is used to emit the constant literal as globa...
LangAS GetGlobalVarAddressSpace(const VarDecl *D)
Return the AST address space of the underlying global variable for D, as determined by its declaratio...
void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info, llvm::Function *F, bool IsThunk)
Set the LLVM function attributes (sext, zext, etc).
void EmitOpenACCRoutine(const OpenACCRoutineDecl *D, CodeGenFunction *CGF=nullptr)
void addReplacement(StringRef Name, llvm::Constant *C)
llvm::Constant * getConstantSignedPointer(llvm::Constant *Pointer, const PointerAuthSchema &Schema, llvm::Constant *StorageAddress, GlobalDecl SchemaDecl, QualType SchemaType)
Sign a constant pointer using the given scheme, producing a constant with the same IR type.
void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535, unsigned LexOrder=~0U, llvm::Constant *AssociatedData=nullptr)
AddGlobalCtor - Add a function to the list that will be called before main() runs.
llvm::Metadata * CreateMetadataIdentifierForFnType(QualType T)
Create a metadata identifier for the given function type.
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
llvm::Metadata * CreateMetadataIdentifierForVirtualMemPtrType(QualType T)
Create a metadata identifier that is intended to be used to check virtual calls via a member function...
ConstantAddress GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *)
Return a pointer to a constant array for the given ObjCEncodeExpr node.
const GlobalDecl getMangledNameDecl(StringRef)
void ClearUnusedCoverageMapping(const Decl *D)
Remove the deferred empty coverage mapping as this declaration is actually instrumented.
void EmitTopLevelDecl(Decl *D)
Emit code for a single top level declaration.
llvm::Constant * EmitAnnotationUnit(SourceLocation Loc)
Emit the annotation's translation unit.
ConstantAddress GetAddrOfConstantCString(const std::string &Str, StringRef GlobalName=".str")
Returns a pointer to a character array containing the literal and a terminating '\0' character.
void printPostfixForExternalizedDecl(llvm::raw_ostream &OS, const Decl *D) const
Print the postfix for externalized static variable or kernels for single source offloading languages ...
void moveLazyEmissionStates(CodeGenModule *NewBuilder)
Move some lazily-emitted states to the NewBuilder.
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
void finalizeKCFITypes()
Emit KCFI type identifier constants and remove unused identifiers.
void setValueProfilingFlag(llvm::Module &M)
void setProfileVersion(llvm::Module &M)
void emitEmptyCounterMapping(const Decl *D, StringRef FuncName, llvm::GlobalValue::LinkageTypes Linkage)
Emit a coverage mapping range with a counter zero for an unused declaration.
CodeGenTBAA - This class organizes the cross-module state that is used while lowering AST types to LL...
This class organizes the cross-module state that is used while lowering AST types to LLVM types.
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
const CGFunctionInfo & arrangeCXXMethodDeclaration(const CXXMethodDecl *MD)
C++ methods have some special rules and also have implicit parameters.
const CGFunctionInfo & arrangeFreeFunctionType(CanQual< FunctionProtoType > Ty)
Arrange the argument and result information for a value of the given freestanding function type.
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
unsigned getTargetAddressSpace(QualType T) const
void RefreshTypeCacheForClass(const CXXRecordDecl *RD)
Remove stale types from the type cache when an inheritance model gets assigned to a class.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
void UpdateCompletedType(const TagDecl *TD)
UpdateCompletedType - When we find the full definition for a TagDecl, replace the 'opaque' type we pr...
const CGFunctionInfo & arrangeGlobalDeclaration(GlobalDecl GD)
void EmitThunks(GlobalDecl GD)
EmitThunks - Emit the associated thunks for the given global decl.
A specialization of Address that requires the address to be an LLVM Constant.
static ConstantAddress invalid()
llvm::Constant * tryEmitForInitializer(const VarDecl &D)
Try to emit the initiaizer of the given declaration as an abstract constant.
void finalize(llvm::GlobalVariable *global)
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded.
The standard implementation of ConstantInitBuilder used in Clang.
Organizes the cross-function state that is used while generating code coverage mapping data.
bool hasDiagnostics()
Whether or not the stats we've gathered indicate any potential problems.
void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile)
Report potential problems we've found to Diags.
TargetCodeGenInfo - This class organizes various target-specific codegeneration issues,...
virtual void getDependentLibraryOption(llvm::StringRef Lib, llvm::SmallString< 24 > &Opt) const
Gets the linker options necessary to link a dependent library on this platform.
const T & getABIInfo() const
virtual LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, const VarDecl *D) const
Get target favored AST address space of a global variable for languages other than OpenCL and CUDA.
virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const
setTargetAttributes - Provides a convenient hook to handle extra target-specific attributes for the g...
virtual LangAS getASTAllocaAddressSpace() const
Get the AST address space for alloca.
virtual void emitTargetMetadata(CodeGen::CodeGenModule &CGM, const llvm::MapVector< GlobalDecl, StringRef > &MangledDeclNames) const
emitTargetMetadata - Provides a convenient hook to handle extra target-specific metadata for the give...
virtual void emitTargetGlobals(CodeGen::CodeGenModule &CGM) const
Provides a convenient hook to handle extra target-specific globals.
virtual void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, llvm::SmallString< 32 > &Opt) const
Gets the linker options necessary to detect object file mismatches on this platform.
Represents the canonical version of C arrays with a specified constant size.
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Stores additional source code information like skipped ranges which is required by the coverage mappi...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
void addDecl(Decl *D)
Add the declaration D into this context.
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Decl - This represents one declaration (or definition), e.g.
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
SourceLocation getEndLoc() const LLVM_READONLY
ASTContext & getASTContext() const LLVM_READONLY
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
SourceLocation getLocation() const
SourceLocation getBeginLoc() const LLVM_READONLY
TranslationUnitDecl * getTranslationUnitDecl()
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Represents a ValueDecl that came out of a declarator.
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
This represents one expression.
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Represents a member of a struct/union/class.
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
StringRef getName() const
The name of this FileEntry.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Represents a function declaration or definition.
bool isTargetClonesMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target-clones functional...
bool isMultiVersion() const
True if this function is considered a multiversioned function.
const ParmVarDecl * getParamDecl(unsigned i) const
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
bool isImmediateFunction() const
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
bool isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
bool isInlineBuiltinDeclaration() const
Determine if this function provides an inline implementation of a builtin.
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
FunctionDecl * getDefinition()
Get the definition for this declaration.
bool isTargetVersionMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target-version functiona...
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
bool doesDeclarationForceExternallyVisibleDefinition() const
For a function declaration in C or C++, determine whether this declaration causes the definition to b...
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const override
Appends a human-readable name for this declaration into the given stream.
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Represents a prototype with parameter type info, e.g.
FunctionType - C99 6.7.5.3 - Function Declarators.
CallingConv getCallConv() const
GlobalDecl - represents a global declaration.
GlobalDecl getWithMultiVersionIndex(unsigned Index)
CXXCtorType getCtorType() const
GlobalDecl getWithKernelReferenceKind(KernelReferenceKind Kind)
GlobalDecl getCanonicalDecl() const
KernelReferenceKind getKernelReferenceKind() const
GlobalDecl getWithDecl(const Decl *D)
unsigned getMultiVersionIndex() const
CXXDtorType getDtorType() const
const Decl * getDecl() const
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
@ None
No signing for any function.
@ Swift5_0
Interoperability with the Swift 5.0 runtime.
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
@ FPE_Ignore
Assume that floating-point exceptions are masked.
VisibilityFromDLLStorageClassKinds
@ Keep
Keep the IR-gen assigned visibility.
@ Protected
Override the IR-gen assigned visibility with protected visibility.
@ Default
Override the IR-gen assigned visibility with default visibility.
@ Hidden
Override the IR-gen assigned visibility with hidden visibility.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
clang::ObjCRuntime ObjCRuntime
CoreFoundationABI CFRuntime
std::string CUID
The user provided compilation unit ID, if non-empty.
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Visibility getVisibility() const
void setLinkage(Linkage L)
Linkage getLinkage() const
bool isVisibilityExplicit() const
LinkageSpecLanguageIDs getLanguage() const
Return the language specified by this linkage specification.
Parts getParts() const
Get the decomposed parts of this declaration.
APValue & getAsAPValue() const
Get the value of this MSGuidDecl as an APValue.
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
void mangleBlock(const DeclContext *DC, const BlockDecl *BD, raw_ostream &Out)
void mangleCtorBlock(const CXXConstructorDecl *CD, CXXCtorType CT, const BlockDecl *BD, raw_ostream &Out)
void mangleGlobalBlock(const BlockDecl *BD, const NamedDecl *ID, raw_ostream &Out)
bool shouldMangleDeclName(const NamedDecl *D)
void mangleName(GlobalDecl GD, raw_ostream &)
virtual void mangleCanonicalTypeName(QualType T, raw_ostream &, bool NormalizeIntegers=false)=0
Generates a unique string for an externally visible type for use with TBAA or type uniquing.
virtual void mangleStringLiteral(const StringLiteral *SL, raw_ostream &)=0
ManglerKind getKind() const
virtual void needsUniqueInternalLinkageNames()
virtual void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber, raw_ostream &)=0
void mangleDtorBlock(const CXXDestructorDecl *CD, CXXDtorType DT, const BlockDecl *BD, raw_ostream &Out)
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
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.
llvm::SmallSetVector< Module *, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Module * getGlobalModuleFragment() const
Get the Global Module Fragment (sub-module) for this module, it there is one.
llvm::iterator_range< submodule_iterator > submodules()
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used.
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
bool UseExportAsModuleLinkName
Autolinking uses the framework name for linking purposes when this is false and the export_as name ot...
This represents a decl that may have a name.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
LinkageInfo getLinkageAndVisibility() const
Determines the linkage and visibility of this entity.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
bool isExternallyVisible() const
Represent a C++ namespace.
This represents 'pragma omp threadprivate ...' directive.
ObjCEncodeExpr, used for @encode in Objective-C.
QualType getEncodedType() const
propimpl_range property_impls() const
const ObjCInterfaceDecl * getClassInterface() const
void addInstanceMethod(ObjCMethodDecl *method)
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
init_iterator init_end()
init_end() - Retrieve an iterator past the last initializer.
CXXCtorInitializer ** init_iterator
init_iterator - Iterates through the ivar initializer list.
init_iterator init_begin()
init_begin() - Retrieve an iterator to the first initializer.
unsigned getNumIvarInitializers() const
getNumArgs - Number of ivars which must be initialized.
void setHasDestructors(bool val)
void setHasNonZeroConstructors(bool val)
Represents an ObjC class declaration.
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
ObjCIvarDecl - Represents an ObjC instance variable.
ObjCIvarDecl * getNextIvar()
static ObjCMethodDecl * Create(ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc, Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo, DeclContext *contextDecl, bool isInstance=true, bool isVariadic=false, bool isPropertyAccessor=false, bool isSynthesizedAccessorStub=false, bool isImplicitlyDeclared=false, bool isDefined=false, ObjCImplementationControl impControl=ObjCImplementationControl::None, bool HasRelatedResultType=false)
Represents one property declaration in an Objective-C interface.
ObjCMethodDecl * getGetterMethodDecl() const
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
The basic abstraction for the target Objective-C runtime.
bool hasUnwindExceptions() const
Does this runtime use zero-cost exceptions?
@ MacOSX
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
@ FragileMacOSX
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
@ GNUstep
'gnustep' is the modern non-fragile GNUstep runtime.
@ ObjFW
'objfw' is the Objective-C runtime included in ObjFW
@ iOS
'ios' is the Apple-provided NeXT-derived runtime on iOS or the iOS simulator; it is always non-fragil...
@ GCC
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI
@ WatchOS
'watchos' is a variant of iOS for Apple's watchOS.
Represents a parameter to a function.
bool isAddressDiscriminated() const
uint16_t getConstantDiscrimination() const
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
Represents an unpacked "presumed" location which can be presented to the user.
const char * getFilename() const
Return the presumed filename of this location.
unsigned getLine() const
Return the presumed line number of this location.
ExclusionType getDefault(llvm::driver::ProfileInstrKind Kind) const
std::optional< ExclusionType > isFunctionExcluded(StringRef FunctionName, llvm::driver::ProfileInstrKind Kind) const
std::optional< ExclusionType > isFileExcluded(StringRef FileName, llvm::driver::ProfileInstrKind Kind) const
ExclusionType
Represents if an how something should be excluded from profiling.
@ Skip
Profiling is skipped using the skipprofile attribute.
@ Allow
Profiling is allowed.
std::optional< ExclusionType > isLocationExcluded(SourceLocation Loc, llvm::driver::ProfileInstrKind Kind) const
A (possibly-)qualified type.
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
LangAS getAddressSpace() const
Return the address space of this type.
bool isConstant(const ASTContext &Ctx) const
QualType getCanonicalType() const
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
QualType withCVRQualifiers(unsigned CVR) const
bool isConstQualified() const
Determine whether this type is const-qualified.
bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Represents a struct/union/class.
field_range fields() const
virtual void completeDefinition()
Note that the definition of this type is now complete.
Selector getSelector(unsigned NumArgs, const IdentifierInfo **IIV)
Can create any sort of selector.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
Stmt - This represents one statement.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
SourceLocation getBeginLoc() const LLVM_READONLY
StringLiteral - This represents a string literal expression, e.g.
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
unsigned getLength() const
uint32_t getCodeUnit(size_t i) const
StringRef getString() const
unsigned getCharByteWidth() const
Represents the declaration of a struct/union/class/enum.
void startDefinition()
Starts the definition of this tag declaration.
Exposes information about the current target.
TargetOptions & getTargetOpts() const
Retrieve the target options.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
bool isReadOnlyFeature(StringRef Feature) const
Determine whether the given target feature is read only.
virtual llvm::APInt getFMVPriority(ArrayRef< StringRef > Features) const
bool supportsIFunc() const
Identify whether this target supports IFuncs.
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
virtual bool initFeatureMap(llvm::StringMap< bool > &Features, DiagnosticsEngine &Diags, StringRef CPU, const std::vector< std::string > &FeatureVec) const
Initialize the map with the default set of target features for the CPU this should include all legal ...
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
std::string TuneCPU
If given, the name of the target CPU to tune code for.
std::string CPU
If given, the name of the target CPU to generate code for.
@ Hostcall
printf lowering scheme involving hostcalls, currently used by HIP programs by default
A template parameter object.
const APValue & getValue() const
A declaration that models statements at global scope.
The top declaration context.
static DeclContext * castToDeclContext(const TranslationUnitDecl *D)
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
bool isPointerType() const
const T * castAs() const
Member-template castAs<specific type>.
bool isReferenceType() const
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
bool isHLSLResourceRecord() const
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
bool isObjCObjectPointerType() const
const T * getAs() const
Member-template getAs<specific type>'.
bool isRecordType() const
bool isHLSLResourceRecordArray() const
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
const APValue & getValue() const
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Represents a variable declaration or definition.
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
TLSKind getTLSKind() const
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
bool hasFlexibleArrayInit(const ASTContext &Ctx) const
Whether this variable has a flexible array member initialized with one or more elements.
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
const Expr * getInit() const
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
@ TLS_Dynamic
TLS with a dynamic initializer.
@ DeclarationOnly
This declaration is only a declaration.
@ Definition
This declaration is definitely a definition.
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
StorageClass getStorageClass() const
Returns the storage class as written in the source.
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Defines the clang::TargetInfo interface.
std::unique_ptr< TargetCodeGenInfo > createARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind Kind)
std::unique_ptr< TargetCodeGenInfo > createM68kTargetCodeGenInfo(CodeGenModule &CGM)
@ AttributedType
The l-value was considered opaque, so the alignment was determined from a type, but that type was an ...
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
std::unique_ptr< TargetCodeGenInfo > createBPFTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createMSP430TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel)
std::unique_ptr< TargetCodeGenInfo > createWebAssemblyTargetCodeGenInfo(CodeGenModule &CGM, WebAssemblyABIKind K)
std::unique_ptr< TargetCodeGenInfo > createPPC64_SVR4_TargetCodeGenInfo(CodeGenModule &CGM, PPC64_SVR4_ABIKind Kind, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createMIPSTargetCodeGenInfo(CodeGenModule &CGM, bool IsOS32)
std::unique_ptr< TargetCodeGenInfo > createHexagonTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createNVPTXTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createSystemZTargetCodeGenInfo(CodeGenModule &CGM, bool HasVector, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createWinX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters)
std::unique_ptr< TargetCodeGenInfo > createAIXTargetCodeGenInfo(CodeGenModule &CGM, bool Is64Bit)
std::unique_ptr< TargetCodeGenInfo > createAMDGPUTargetCodeGenInfo(CodeGenModule &CGM)
CGObjCRuntime * CreateMacObjCRuntime(CodeGenModule &CGM)
X86AVXABILevel
The AVX ABI level for X86 targets.
std::unique_ptr< TargetCodeGenInfo > createTCETargetCodeGenInfo(CodeGenModule &CGM)
CGObjCRuntime * CreateGNUObjCRuntime(CodeGenModule &CGM)
Creates an instance of an Objective-C runtime class.
std::unique_ptr< TargetCodeGenInfo > createWindowsARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind K)
std::unique_ptr< TargetCodeGenInfo > createAVRTargetCodeGenInfo(CodeGenModule &CGM, unsigned NPR, unsigned NRR)
std::unique_ptr< TargetCodeGenInfo > createDirectXTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createARCTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createDefaultTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind Kind)
std::unique_ptr< TargetCodeGenInfo > createSPIRVTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createWindowsMIPSTargetCodeGenInfo(CodeGenModule &CGM, bool IsOS32)
std::unique_ptr< TargetCodeGenInfo > createSparcV8TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createVETargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createCommonSPIRTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createRISCVTargetCodeGenInfo(CodeGenModule &CGM, unsigned XLen, unsigned FLen, bool EABI)
std::unique_ptr< TargetCodeGenInfo > createWindowsAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind K)
std::unique_ptr< TargetCodeGenInfo > createSparcV9TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createLanaiTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createPPC32TargetCodeGenInfo(CodeGenModule &CGM, bool SoftFloatABI)
CGCUDARuntime * CreateNVCUDARuntime(CodeGenModule &CGM)
Creates an instance of a CUDA runtime class.
std::unique_ptr< TargetCodeGenInfo > createLoongArchTargetCodeGenInfo(CodeGenModule &CGM, unsigned GRLen, unsigned FLen)
std::unique_ptr< TargetCodeGenInfo > createPPC64TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createWinX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel)
std::unique_ptr< TargetCodeGenInfo > createXCoreTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createCSKYTargetCodeGenInfo(CodeGenModule &CGM, unsigned FLen)
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
constexpr bool isInitializedByPipeline(LangAS AS)
bool LT(InterpState &S, CodePtr OpPC)
llvm::PointerUnion< const Decl *, const Expr * > DeclTy
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
CXXCtorType
C++ constructor types.
@ Ctor_Base
Base object ctor.
@ Ctor_Complete
Complete object ctor.
bool isa(CodeGen::Address addr)
GVALinkage
A more specific kind of linkage than enum Linkage.
@ GVA_AvailableExternally
std::string getClangVendor()
Retrieves the Clang vendor tag.
@ ICIS_NoInit
No in-class initializer.
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
@ Asm
Assembly: we accept this only so that we can preprocess it.
@ SD_Thread
Thread storage duration.
@ SD_Static
Static storage duration.
bool isLambdaCallOperator(const CXXMethodDecl *MD)
@ Result
The result type of a method or function.
StringRef languageToString(Language L)
@ Dtor_Base
Base object dtor.
@ Dtor_Complete
Complete object dtor.
LangAS
Defines the address space values used by the address space qualifier of QualType.
@ FirstTargetAddressSpace
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::vfs::FileSystem &VFS, DiagnosticsEngine &Diags)
static const char * getCFBranchLabelSchemeFlagVal(const CFBranchLabelSchemeKind Scheme)
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
U cast(CodeGen::Address addr)
@ None
No keyword precedes the qualified type name.
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
bool isExternallyVisible(Linkage L)
@ EST_None
no exception specification
std::string getClangFullVersion()
Retrieves a string representing the complete clang version, which includes the clang version number,...
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
@ DefaultVisibility
Objects with "default" visibility are seen by the dynamic linker and act like normal objects.
cl::opt< bool > SystemHeadersCoverage
int const char * function
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
std::optional< StringRef > Architecture
llvm::SmallVector< StringRef, 8 > Features
llvm::CallingConv::ID RuntimeCC
llvm::PointerType * VoidPtrTy
llvm::IntegerType * Int64Ty
llvm::PointerType * ConstGlobalsPtrTy
void* in the address space for constant globals
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::IntegerType * CharTy
char
LangAS ASTAllocaAddressSpace
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
unsigned char IntAlignInBytes
llvm::Type * HalfTy
half, bfloat, float, double
unsigned char SizeSizeInBytes
llvm::CallingConv::ID getRuntimeCC() const
llvm::IntegerType * SizeTy
llvm::PointerType * GlobalsInt8PtrTy
llvm::IntegerType * Int32Ty
llvm::IntegerType * IntPtrTy
llvm::IntegerType * IntTy
int
llvm::IntegerType * Int16Ty
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.