52#include "llvm/ADT/STLExtras.h"
53#include "llvm/ADT/StringExtras.h"
54#include "llvm/ADT/StringSwitch.h"
55#include "llvm/Analysis/TargetLibraryInfo.h"
56#include "llvm/BinaryFormat/ELF.h"
57#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
58#include "llvm/IR/AttributeMask.h"
59#include "llvm/IR/CallingConv.h"
60#include "llvm/IR/DataLayout.h"
61#include "llvm/IR/Intrinsics.h"
62#include "llvm/IR/LLVMContext.h"
63#include "llvm/IR/Module.h"
64#include "llvm/IR/ProfileSummary.h"
65#include "llvm/ProfileData/InstrProfReader.h"
66#include "llvm/ProfileData/SampleProf.h"
67#include "llvm/Support/CRC.h"
68#include "llvm/Support/CodeGen.h"
69#include "llvm/Support/CommandLine.h"
70#include "llvm/Support/ConvertUTF.h"
71#include "llvm/Support/ErrorHandling.h"
72#include "llvm/Support/TimeProfiler.h"
73#include "llvm/Support/xxhash.h"
74#include "llvm/TargetParser/RISCVISAInfo.h"
75#include "llvm/TargetParser/Triple.h"
76#include "llvm/TargetParser/X86TargetParser.h"
77#include "llvm/Transforms/Utils/BuildLibCalls.h"
81using namespace CodeGen;
84 "limited-coverage-experimental", llvm::cl::Hidden,
85 llvm::cl::desc(
"Emit limited coverage mapping information (experimental)"));
91 case TargetCXXABI::AppleARM64:
92 case TargetCXXABI::Fuchsia:
93 case TargetCXXABI::GenericAArch64:
94 case TargetCXXABI::GenericARM:
95 case TargetCXXABI::iOS:
96 case TargetCXXABI::WatchOS:
97 case TargetCXXABI::GenericMIPS:
98 case TargetCXXABI::GenericItanium:
99 case TargetCXXABI::WebAssembly:
100 case TargetCXXABI::XL:
102 case TargetCXXABI::Microsoft:
106 llvm_unreachable(
"invalid C++ ABI kind");
109static std::unique_ptr<TargetCodeGenInfo>
115 switch (Triple.getArch()) {
119 case llvm::Triple::m68k:
121 case llvm::Triple::mips:
122 case llvm::Triple::mipsel:
123 if (Triple.getOS() == llvm::Triple::NaCl)
127 case llvm::Triple::mips64:
128 case llvm::Triple::mips64el:
131 case llvm::Triple::avr: {
135 unsigned NPR =
Target.getABI() ==
"avrtiny" ? 6 : 18;
136 unsigned NRR =
Target.getABI() ==
"avrtiny" ? 4 : 8;
140 case llvm::Triple::aarch64:
141 case llvm::Triple::aarch64_32:
142 case llvm::Triple::aarch64_be: {
144 if (
Target.getABI() ==
"darwinpcs")
145 Kind = AArch64ABIKind::DarwinPCS;
146 else if (Triple.isOSWindows())
148 else if (
Target.getABI() ==
"aapcs-soft")
149 Kind = AArch64ABIKind::AAPCSSoft;
150 else if (
Target.getABI() ==
"pauthtest")
151 Kind = AArch64ABIKind::PAuthTest;
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" ||
179 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
180 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
181 Triple.getEnvironment() == llvm::Triple::EABIHF)))
182 Kind = ARMABIKind::AAPCS_VFP;
187 case llvm::Triple::ppc: {
188 if (Triple.isOSAIX())
195 case llvm::Triple::ppcle: {
196 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
199 case llvm::Triple::ppc64:
200 if (Triple.isOSAIX())
203 if (Triple.isOSBinFormatELF()) {
205 if (
Target.getABI() ==
"elfv2")
206 Kind = PPC64_SVR4_ABIKind::ELFv2;
207 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
212 case llvm::Triple::ppc64le: {
213 assert(Triple.isOSBinFormatELF() &&
"PPC64 LE non-ELF not supported!");
215 if (
Target.getABI() ==
"elfv1")
216 Kind = PPC64_SVR4_ABIKind::ELFv1;
217 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
222 case llvm::Triple::nvptx:
223 case llvm::Triple::nvptx64:
226 case llvm::Triple::msp430:
229 case llvm::Triple::riscv32:
230 case llvm::Triple::riscv64: {
231 StringRef ABIStr =
Target.getABI();
232 unsigned XLen =
Target.getPointerWidth(LangAS::Default);
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::Win32:
279 case llvm::Triple::hexagon:
281 case llvm::Triple::lanai:
283 case llvm::Triple::r600:
285 case llvm::Triple::amdgcn:
287 case llvm::Triple::sparc:
289 case llvm::Triple::sparcv9:
291 case llvm::Triple::xcore:
293 case llvm::Triple::arc:
295 case llvm::Triple::spir:
296 case llvm::Triple::spir64:
298 case llvm::Triple::spirv32:
299 case llvm::Triple::spirv64:
301 case llvm::Triple::ve:
303 case llvm::Triple::csky: {
304 bool IsSoftFloat = !
Target.hasFeature(
"hard-float-abi");
306 Target.hasFeature(
"fpuv2_df") ||
Target.hasFeature(
"fpuv3_df");
311 case llvm::Triple::bpfeb:
312 case llvm::Triple::bpfel:
314 case llvm::Triple::loongarch32:
315 case llvm::Triple::loongarch64: {
316 StringRef ABIStr =
Target.getABI();
317 unsigned ABIFRLen = 0;
318 if (ABIStr.ends_with(
"f"))
320 else if (ABIStr.ends_with(
"d"))
323 CGM,
Target.getPointerWidth(LangAS::Default), ABIFRLen);
329 if (!TheTargetCodeGenInfo)
331 return *TheTargetCodeGenInfo;
341 : Context(
C), LangOpts(
C.getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
342 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
344 VMContext(M.getContext()), Types(*this), VTables(*this),
348 llvm::LLVMContext &LLVMContext = M.getContext();
349 VoidTy = llvm::Type::getVoidTy(LLVMContext);
350 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
351 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
352 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
353 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
354 HalfTy = llvm::Type::getHalfTy(LLVMContext);
355 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
356 FloatTy = llvm::Type::getFloatTy(LLVMContext);
357 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
363 C.toCharUnitsFromBits(
C.getTargetInfo().getMaxPointerWidth()).getQuantity();
365 C.toCharUnitsFromBits(
C.getTargetInfo().getIntAlign()).getQuantity();
367 llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getCharWidth());
368 IntTy = llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getIntWidth());
369 IntPtrTy = llvm::IntegerType::get(LLVMContext,
370 C.getTargetInfo().getMaxPointerWidth());
371 Int8PtrTy = llvm::PointerType::get(LLVMContext,
373 const llvm::DataLayout &DL = M.getDataLayout();
375 llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
377 llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
394 createOpenCLRuntime();
396 createOpenMPRuntime();
403 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread) ||
404 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
410 if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
415 Block.GlobalUniqueCount = 0;
417 if (
C.getLangOpts().ObjC)
421 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
428 PGOReader = std::move(ReaderOrErr.get());
433 if (CodeGenOpts.CoverageMapping)
437 if (CodeGenOpts.UniqueInternalLinkageNames &&
438 !
getModule().getSourceFileName().empty()) {
442 if (
Path.rfind(Entry.first, 0) != std::string::npos) {
443 Path = Entry.second +
Path.substr(Entry.first.size());
446 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(
Path);
451 getModule().addModuleFlag(llvm::Module::Error,
"NumRegisterParameters",
452 CodeGenOpts.NumRegisterParameters);
457void CodeGenModule::createObjCRuntime() {
474 llvm_unreachable(
"bad runtime kind");
477void CodeGenModule::createOpenCLRuntime() {
481void CodeGenModule::createOpenMPRuntime() {
485 case llvm::Triple::nvptx:
486 case llvm::Triple::nvptx64:
487 case llvm::Triple::amdgcn:
489 "OpenMP AMDGPU/NVPTX is only prepared to deal with device code.");
493 if (LangOpts.OpenMPSimd)
501void CodeGenModule::createCUDARuntime() {
505void CodeGenModule::createHLSLRuntime() {
510 Replacements[Name] =
C;
513void CodeGenModule::applyReplacements() {
514 for (
auto &I : Replacements) {
515 StringRef MangledName = I.first;
516 llvm::Constant *Replacement = I.second;
520 auto *OldF = cast<llvm::Function>(Entry);
521 auto *NewF = dyn_cast<llvm::Function>(Replacement);
523 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
524 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
526 auto *CE = cast<llvm::ConstantExpr>(Replacement);
527 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
528 CE->getOpcode() == llvm::Instruction::GetElementPtr);
529 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
534 OldF->replaceAllUsesWith(Replacement);
536 NewF->removeFromParent();
537 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
540 OldF->eraseFromParent();
545 GlobalValReplacements.push_back(std::make_pair(GV,
C));
548void CodeGenModule::applyGlobalValReplacements() {
549 for (
auto &I : GlobalValReplacements) {
550 llvm::GlobalValue *GV = I.first;
551 llvm::Constant *
C = I.second;
553 GV->replaceAllUsesWith(
C);
554 GV->eraseFromParent();
561 const llvm::Constant *
C;
562 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
563 C = GA->getAliasee();
564 else if (
auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
565 C = GI->getResolver();
569 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(
C->stripPointerCasts());
573 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
582 bool IsIFunc,
const llvm::GlobalValue *Alias,
const llvm::GlobalValue *&GV,
583 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
587 Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
591 if (GV->hasCommonLinkage()) {
593 if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
594 Diags.
Report(Location, diag::err_alias_to_common);
599 if (GV->isDeclaration()) {
600 Diags.
Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
601 Diags.
Report(Location, diag::note_alias_requires_mangled_name)
602 << IsIFunc << IsIFunc;
605 for (
const auto &[
Decl, Name] : MangledDeclNames) {
606 if (
const auto *ND = dyn_cast<NamedDecl>(
Decl.getDecl())) {
607 if (ND->getName() == GV->getName()) {
608 Diags.
Report(Location, diag::note_alias_mangled_name_alternative)
612 (Twine(IsIFunc ?
"ifunc" :
"alias") +
"(\"" + Name +
"\")")
622 const auto *F = dyn_cast<llvm::Function>(GV);
624 Diags.
Report(Location, diag::err_alias_to_undefined)
625 << IsIFunc << IsIFunc;
629 llvm::FunctionType *FTy = F->getFunctionType();
630 if (!FTy->getReturnType()->isPointerTy()) {
631 Diags.
Report(Location, diag::err_ifunc_resolver_return);
645 if (GVar->hasAttribute(
"toc-data")) {
646 auto GVId = GVar->getName();
649 Diags.
Report(Location, diag::warn_toc_unsupported_type)
650 << GVId <<
"the variable has an alias";
652 llvm::AttributeSet CurrAttributes = GVar->getAttributes();
653 llvm::AttributeSet NewAttributes =
654 CurrAttributes.removeAttribute(GVar->getContext(),
"toc-data");
655 GVar->setAttributes(NewAttributes);
659void CodeGenModule::checkAliases() {
666 const auto *
D = cast<ValueDecl>(GD.getDecl());
669 bool IsIFunc =
D->
hasAttr<IFuncAttr>();
671 Location = A->getLocation();
672 Range = A->getRange();
674 llvm_unreachable(
"Not an alias or ifunc?");
678 const llvm::GlobalValue *GV =
nullptr;
680 MangledDeclNames,
Range)) {
686 if (
const llvm::GlobalVariable *GVar =
687 dyn_cast<const llvm::GlobalVariable>(GV))
691 llvm::Constant *Aliasee =
692 IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver()
693 : cast<llvm::GlobalAlias>(Alias)->getAliasee();
695 llvm::GlobalValue *AliaseeGV;
696 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
697 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
699 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
701 if (
const SectionAttr *SA =
D->
getAttr<SectionAttr>()) {
702 StringRef AliasSection = SA->getName();
703 if (AliasSection != AliaseeGV->getSection())
704 Diags.
Report(SA->getLocation(), diag::warn_alias_with_section)
705 << AliasSection << IsIFunc << IsIFunc;
713 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
714 if (GA->isInterposable()) {
715 Diags.
Report(Location, diag::warn_alias_to_weak_alias)
716 << GV->getName() << GA->getName() << IsIFunc;
717 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
718 GA->getAliasee(), Alias->getType());
721 cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee);
723 cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee);
729 cast<llvm::Function>(Aliasee)->addFnAttr(
730 llvm::Attribute::DisableSanitizerInstrumentation);
738 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
739 Alias->eraseFromParent();
744 DeferredDeclsToEmit.clear();
745 EmittedDeferredDecls.clear();
746 DeferredAnnotations.clear();
748 OpenMPRuntime->clear();
752 StringRef MainFile) {
755 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
756 if (MainFile.empty())
757 MainFile =
"<stdin>";
758 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
761 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
764 Diags.
Report(diag::warn_profile_data_missing) << Visited << Missing;
768static std::optional<llvm::GlobalValue::VisibilityTypes>
775 return llvm::GlobalValue::DefaultVisibility;
777 return llvm::GlobalValue::HiddenVisibility;
779 return llvm::GlobalValue::ProtectedVisibility;
781 llvm_unreachable(
"unknown option value!");
785 std::optional<llvm::GlobalValue::VisibilityTypes>
V) {
794 GV.setDSOLocal(
false);
795 GV.setVisibility(*
V);
800 if (!LO.VisibilityFromDLLStorageClass)
803 std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
806 std::optional<llvm::GlobalValue::VisibilityTypes>
807 NoDLLStorageClassVisibility =
810 std::optional<llvm::GlobalValue::VisibilityTypes>
811 ExternDeclDLLImportVisibility =
814 std::optional<llvm::GlobalValue::VisibilityTypes>
815 ExternDeclNoDLLStorageClassVisibility =
818 for (llvm::GlobalValue &GV : M.global_values()) {
819 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
822 if (GV.isDeclarationForLinker())
824 llvm::GlobalValue::DLLImportStorageClass
825 ? ExternDeclDLLImportVisibility
826 : ExternDeclNoDLLStorageClassVisibility);
829 llvm::GlobalValue::DLLExportStorageClass
830 ? DLLExportVisibility
831 : NoDLLStorageClassVisibility);
833 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
838 const llvm::Triple &Triple,
840 if (Triple.isAMDGPU() || Triple.isNVPTX())
842 return LangOpts.getStackProtector() == Mode;
848 EmitModuleInitializers(Primary);
850 DeferredDecls.insert(EmittedDeferredDecls.begin(),
851 EmittedDeferredDecls.end());
852 EmittedDeferredDecls.clear();
853 EmitVTablesOpportunistically();
854 applyGlobalValReplacements();
856 emitMultiVersionFunctions();
859 GlobalTopLevelStmtBlockInFlight.first) {
861 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->
getEndLoc());
862 GlobalTopLevelStmtBlockInFlight = {
nullptr,
nullptr};
868 EmitCXXModuleInitFunc(Primary);
870 EmitCXXGlobalInitFunc();
871 EmitCXXGlobalCleanUpFunc();
872 registerGlobalDtorsWithAtExit();
873 EmitCXXThreadLocalInitFunc();
875 if (llvm::Function *ObjCInitFunction =
ObjCRuntime->ModuleInitFunction())
878 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
882 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
883 OpenMPRuntime->clear();
887 PGOReader->getSummary(
false).getMD(VMContext),
888 llvm::ProfileSummary::PSK_Instr);
895 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
896 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
898 EmitStaticExternCAliases();
904 CoverageMapping->emit();
905 if (CodeGenOpts.SanitizeCfiCrossDso) {
911 emitAtAvailableLinkGuard();
919 if (
getTarget().getTargetOpts().CodeObjectVersion !=
920 llvm::CodeObjectVersionKind::COV_None) {
921 getModule().addModuleFlag(llvm::Module::Error,
922 "amdhsa_code_object_version",
923 getTarget().getTargetOpts().CodeObjectVersion);
928 auto *MDStr = llvm::MDString::get(
933 getModule().addModuleFlag(llvm::Module::Error,
"amdgpu_printf_kind",
946 if (
auto *FD = dyn_cast<FunctionDecl>(
D))
950 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
954 llvm::ArrayType *ATy = llvm::ArrayType::get(
Int8PtrTy, UsedArray.size());
956 auto *GV =
new llvm::GlobalVariable(
957 getModule(), ATy,
false, llvm::GlobalValue::InternalLinkage,
958 llvm::ConstantArray::get(ATy, UsedArray),
"__clang_gpu_used_external");
961 if (LangOpts.HIP && !
getLangOpts().OffloadingNewDriver) {
964 auto *GV =
new llvm::GlobalVariable(
966 llvm::Constant::getNullValue(
Int8Ty),
974 if (CodeGenOpts.Autolink &&
975 (Context.
getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
976 EmitModuleLinkOptions();
991 if (!ELFDependentLibraries.empty() && !Context.
getLangOpts().CUDAIsDevice) {
992 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.dependent-libraries");
993 for (
auto *MD : ELFDependentLibraries)
997 if (CodeGenOpts.DwarfVersion) {
998 getModule().addModuleFlag(llvm::Module::Max,
"Dwarf Version",
999 CodeGenOpts.DwarfVersion);
1002 if (CodeGenOpts.Dwarf64)
1003 getModule().addModuleFlag(llvm::Module::Max,
"DWARF64", 1);
1007 getModule().setSemanticInterposition(
true);
1009 if (CodeGenOpts.EmitCodeView) {
1011 getModule().addModuleFlag(llvm::Module::Warning,
"CodeView", 1);
1013 if (CodeGenOpts.CodeViewGHash) {
1014 getModule().addModuleFlag(llvm::Module::Warning,
"CodeViewGHash", 1);
1016 if (CodeGenOpts.ControlFlowGuard) {
1018 getModule().addModuleFlag(llvm::Module::Warning,
"cfguard", 2);
1019 }
else if (CodeGenOpts.ControlFlowGuardNoChecks) {
1021 getModule().addModuleFlag(llvm::Module::Warning,
"cfguard", 1);
1023 if (CodeGenOpts.EHContGuard) {
1025 getModule().addModuleFlag(llvm::Module::Warning,
"ehcontguard", 1);
1029 getModule().addModuleFlag(llvm::Module::Warning,
"ms-kernel", 1);
1031 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
1036 getModule().addModuleFlag(llvm::Module::Error,
"StrictVTablePointers",1);
1038 llvm::Metadata *Ops[2] = {
1039 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
1040 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1041 llvm::Type::getInt32Ty(VMContext), 1))};
1043 getModule().addModuleFlag(llvm::Module::Require,
1044 "StrictVTablePointersRequirement",
1045 llvm::MDNode::get(VMContext, Ops));
1051 getModule().addModuleFlag(llvm::Module::Warning,
"Debug Info Version",
1052 llvm::DEBUG_METADATA_VERSION);
1057 uint64_t WCharWidth =
1059 getModule().addModuleFlag(llvm::Module::Error,
"wchar_size", WCharWidth);
1062 getModule().addModuleFlag(llvm::Module::Warning,
1063 "zos_product_major_version",
1064 uint32_t(CLANG_VERSION_MAJOR));
1065 getModule().addModuleFlag(llvm::Module::Warning,
1066 "zos_product_minor_version",
1067 uint32_t(CLANG_VERSION_MINOR));
1068 getModule().addModuleFlag(llvm::Module::Warning,
"zos_product_patchlevel",
1069 uint32_t(CLANG_VERSION_PATCHLEVEL));
1071 getModule().addModuleFlag(llvm::Module::Error,
"zos_product_id",
1072 llvm::MDString::get(VMContext, ProductId));
1077 getModule().addModuleFlag(llvm::Module::Error,
"zos_cu_language",
1078 llvm::MDString::get(VMContext, lang_str));
1082 : std::time(
nullptr);
1083 getModule().addModuleFlag(llvm::Module::Max,
"zos_translation_time",
1084 static_cast<uint64_t
>(TT));
1087 getModule().addModuleFlag(llvm::Module::Error,
"zos_le_char_mode",
1088 llvm::MDString::get(VMContext,
"ascii"));
1092 if (
T.isARM() ||
T.isThumb()) {
1094 uint64_t EnumWidth = Context.
getLangOpts().ShortEnums ? 1 : 4;
1095 getModule().addModuleFlag(llvm::Module::Error,
"min_enum_size", EnumWidth);
1099 StringRef ABIStr =
Target.getABI();
1100 llvm::LLVMContext &Ctx = TheModule.getContext();
1101 getModule().addModuleFlag(llvm::Module::Error,
"target-abi",
1102 llvm::MDString::get(Ctx, ABIStr));
1107 const std::vector<std::string> &Features =
1110 llvm::RISCVISAInfo::parseFeatures(
T.isRISCV64() ? 64 : 32, Features);
1111 if (!errorToBool(ParseResult.takeError()))
1113 llvm::Module::AppendUnique,
"riscv-isa",
1115 Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString())));
1118 if (CodeGenOpts.SanitizeCfiCrossDso) {
1120 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
1123 if (CodeGenOpts.WholeProgramVTables) {
1127 getModule().addModuleFlag(llvm::Module::Error,
"Virtual Function Elim",
1128 CodeGenOpts.VirtualFunctionElimination);
1131 if (LangOpts.
Sanitize.
has(SanitizerKind::CFIICall)) {
1132 getModule().addModuleFlag(llvm::Module::Override,
1133 "CFI Canonical Jump Tables",
1134 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1137 if (CodeGenOpts.SanitizeCfiICallNormalizeIntegers) {
1138 getModule().addModuleFlag(llvm::Module::Override,
"cfi-normalize-integers",
1143 getModule().addModuleFlag(llvm::Module::Override,
"kcfi", 1);
1146 if (CodeGenOpts.PatchableFunctionEntryOffset)
1147 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-offset",
1148 CodeGenOpts.PatchableFunctionEntryOffset);
1151 if (CodeGenOpts.CFProtectionReturn &&
1154 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-return",
1158 if (CodeGenOpts.CFProtectionBranch &&
1161 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-branch",
1165 if (CodeGenOpts.FunctionReturnThunks)
1166 getModule().addModuleFlag(llvm::Module::Override,
"function_return_thunk_extern", 1);
1168 if (CodeGenOpts.IndirectBranchCSPrefix)
1169 getModule().addModuleFlag(llvm::Module::Override,
"indirect_branch_cs_prefix", 1);
1181 LangOpts.getSignReturnAddressScope() !=
1183 getModule().addModuleFlag(llvm::Module::Override,
1184 "sign-return-address-buildattr", 1);
1185 if (LangOpts.
Sanitize.
has(SanitizerKind::MemtagStack))
1186 getModule().addModuleFlag(llvm::Module::Override,
1187 "tag-stack-memory-buildattr", 1);
1189 if (
T.isARM() ||
T.isThumb() ||
T.isAArch64()) {
1190 if (LangOpts.BranchTargetEnforcement)
1191 getModule().addModuleFlag(llvm::Module::Min,
"branch-target-enforcement",
1193 if (LangOpts.BranchProtectionPAuthLR)
1194 getModule().addModuleFlag(llvm::Module::Min,
"branch-protection-pauth-lr",
1196 if (LangOpts.GuardedControlStack)
1197 getModule().addModuleFlag(llvm::Module::Min,
"guarded-control-stack", 1);
1199 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address", 1);
1201 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address-all",
1204 getModule().addModuleFlag(llvm::Module::Min,
1205 "sign-return-address-with-bkey", 1);
1209 using namespace llvm::ELF;
1210 uint64_t PAuthABIVersion =
1211 (LangOpts.PointerAuthIntrinsics
1212 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS) |
1213 (LangOpts.PointerAuthCalls
1214 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS) |
1215 (LangOpts.PointerAuthReturns
1216 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS) |
1217 (LangOpts.PointerAuthAuthTraps
1218 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS) |
1219 (LangOpts.PointerAuthVTPtrAddressDiscrimination
1220 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR) |
1221 (LangOpts.PointerAuthVTPtrTypeDiscrimination
1222 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR) |
1223 (LangOpts.PointerAuthInitFini
1224 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI) |
1225 (LangOpts.PointerAuthInitFiniAddressDiscrimination
1226 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC) |
1227 (LangOpts.PointerAuthELFGOT
1228 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT) |
1229 (LangOpts.PointerAuthIndirectGotos
1230 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS) |
1231 (LangOpts.PointerAuthTypeInfoVTPtrDiscrimination
1232 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR) |
1233 (LangOpts.PointerAuthFunctionTypeDiscrimination
1234 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR);
1235 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR ==
1236 AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
1237 "Update when new enum items are defined");
1238 if (PAuthABIVersion != 0) {
1239 getModule().addModuleFlag(llvm::Module::Error,
1240 "aarch64-elf-pauthabi-platform",
1241 AARCH64_PAUTH_PLATFORM_LLVM_LINUX);
1242 getModule().addModuleFlag(llvm::Module::Error,
1243 "aarch64-elf-pauthabi-version",
1249 if (CodeGenOpts.StackClashProtector)
1251 llvm::Module::Override,
"probe-stack",
1252 llvm::MDString::get(TheModule.getContext(),
"inline-asm"));
1254 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
1255 getModule().addModuleFlag(llvm::Module::Min,
"stack-probe-size",
1256 CodeGenOpts.StackProbeSize);
1259 llvm::LLVMContext &Ctx = TheModule.getContext();
1261 llvm::Module::Error,
"MemProfProfileFilename",
1265 if (LangOpts.CUDAIsDevice &&
getTriple().isNVPTX()) {
1269 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
1271 llvm::DenormalMode::IEEE);
1274 if (LangOpts.EHAsynch)
1275 getModule().addModuleFlag(llvm::Module::Warning,
"eh-asynch", 1);
1279 getModule().addModuleFlag(llvm::Module::Max,
"openmp", LangOpts.OpenMP);
1281 getModule().addModuleFlag(llvm::Module::Max,
"openmp-device",
1285 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())) {
1286 EmitOpenCLMetadata();
1294 llvm::Metadata *SPIRVerElts[] = {
1295 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1297 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1298 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
1299 llvm::NamedMDNode *SPIRVerMD =
1300 TheModule.getOrInsertNamedMetadata(
"opencl.spir.version");
1301 llvm::LLVMContext &Ctx = TheModule.getContext();
1302 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
1310 if (uint32_t PLevel = Context.
getLangOpts().PICLevel) {
1311 assert(PLevel < 3 &&
"Invalid PIC Level");
1312 getModule().setPICLevel(
static_cast<llvm::PICLevel::Level
>(PLevel));
1314 getModule().setPIELevel(
static_cast<llvm::PIELevel::Level
>(PLevel));
1318 unsigned CM = llvm::StringSwitch<unsigned>(
getCodeGenOpts().CodeModel)
1319 .Case(
"tiny", llvm::CodeModel::Tiny)
1320 .Case(
"small", llvm::CodeModel::Small)
1321 .Case(
"kernel", llvm::CodeModel::Kernel)
1322 .Case(
"medium", llvm::CodeModel::Medium)
1323 .Case(
"large", llvm::CodeModel::Large)
1326 llvm::CodeModel::Model codeModel =
static_cast<llvm::CodeModel::Model
>(CM);
1329 if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
1331 llvm::Triple::x86_64) {
1337 if (CodeGenOpts.NoPLT)
1340 CodeGenOpts.DirectAccessExternalData !=
1341 getModule().getDirectAccessExternalData()) {
1342 getModule().setDirectAccessExternalData(
1343 CodeGenOpts.DirectAccessExternalData);
1345 if (CodeGenOpts.UnwindTables)
1346 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1348 switch (CodeGenOpts.getFramePointer()) {
1353 getModule().setFramePointer(llvm::FramePointerKind::Reserved);
1356 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1359 getModule().setFramePointer(llvm::FramePointerKind::All);
1363 SimplifyPersonality();
1376 EmitVersionIdentMetadata();
1379 EmitCommandLineMetadata();
1387 getModule().setStackProtectorGuardSymbol(
1390 getModule().setStackProtectorGuardOffset(
1395 getModule().addModuleFlag(llvm::Module::Override,
"SkipRaxSetup", 1);
1397 getModule().addModuleFlag(llvm::Module::Override,
"RegCallv4", 1);
1399 if (
getContext().getTargetInfo().getMaxTLSAlign())
1400 getModule().addModuleFlag(llvm::Module::Error,
"MaxTLSAlign",
1401 getContext().getTargetInfo().getMaxTLSAlign());
1419 if (
getTriple().isPPC() && !MustTailCallUndefinedGlobals.empty()) {
1420 for (
auto &I : MustTailCallUndefinedGlobals) {
1421 if (!I.first->isDefined())
1422 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1426 if (!Entry || Entry->isWeakForLinker() ||
1427 Entry->isDeclarationForLinker())
1428 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1434void CodeGenModule::EmitOpenCLMetadata() {
1440 auto EmitVersion = [
this](StringRef MDName,
int Version) {
1441 llvm::Metadata *OCLVerElts[] = {
1442 llvm::ConstantAsMetadata::get(
1443 llvm::ConstantInt::get(
Int32Ty, Version / 100)),
1444 llvm::ConstantAsMetadata::get(
1445 llvm::ConstantInt::get(
Int32Ty, (Version % 100) / 10))};
1446 llvm::NamedMDNode *OCLVerMD = TheModule.getOrInsertNamedMetadata(MDName);
1447 llvm::LLVMContext &Ctx = TheModule.getContext();
1448 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
1451 EmitVersion(
"opencl.ocl.version", CLVersion);
1452 if (LangOpts.OpenCLCPlusPlus) {
1454 EmitVersion(
"opencl.cxx.version", LangOpts.OpenCLCPlusPlusVersion);
1458void CodeGenModule::EmitBackendOptionsMetadata(
1461 getModule().addModuleFlag(llvm::Module::Min,
"SmallDataLimit",
1462 CodeGenOpts.SmallDataLimit);
1479 return TBAA->getTypeInfo(QTy);
1498 return TBAA->getAccessInfo(AccessType);
1505 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
1511 return TBAA->getTBAAStructInfo(QTy);
1517 return TBAA->getBaseTypeInfo(QTy);
1523 return TBAA->getAccessTagInfo(Info);
1530 return TBAA->mergeTBAAInfoForCast(SourceInfo,
TargetInfo);
1538 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
1546 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
1552 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
1557 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
1570 "cannot compile this %0 yet");
1571 std::string Msg =
Type;
1573 << Msg << S->getSourceRange();
1580 "cannot compile this %0 yet");
1581 std::string Msg =
Type;
1592 if (GV->hasLocalLinkage()) {
1593 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1607 Context.
getLangOpts().OpenMPIsTargetDevice && isa<VarDecl>(
D) &&
1608 D->
hasAttr<OMPDeclareTargetDeclAttr>() &&
1609 D->
getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
1610 OMPDeclareTargetDeclAttr::DT_NoHost &&
1612 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1616 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
1620 if (GV->hasDLLExportStorageClass()) {
1623 diag::err_hidden_visibility_dllexport);
1626 diag::err_non_default_visibility_dllimport);
1632 !GV->isDeclarationForLinker())
1637 llvm::GlobalValue *GV) {
1638 if (GV->hasLocalLinkage())
1641 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
1645 if (GV->hasDLLImportStorageClass())
1648 const llvm::Triple &TT = CGM.
getTriple();
1650 if (TT.isWindowsGNUEnvironment()) {
1659 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
1668 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
1676 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
1680 if (!TT.isOSBinFormatELF())
1686 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1692 if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias()))
1694 return !(CGM.
getLangOpts().SemanticInterposition ||
1699 if (!GV->isDeclarationForLinker())
1705 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
1712 if (CGOpts.DirectAccessExternalData) {
1718 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1719 if (!Var->isThreadLocal())
1728 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
1744 const auto *
D = dyn_cast<NamedDecl>(GD.
getDecl());
1746 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(
D)) {
1755 if (
D &&
D->isExternallyVisible()) {
1757 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1758 else if ((
D->
hasAttr<DLLExportAttr>() ||
1760 !GV->isDeclarationForLinker())
1761 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
1785 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
1786 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
1787 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
1788 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
1789 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
1792llvm::GlobalVariable::ThreadLocalMode
1794 switch (CodeGenOpts.getDefaultTLSModel()) {
1796 return llvm::GlobalVariable::GeneralDynamicTLSModel;
1798 return llvm::GlobalVariable::LocalDynamicTLSModel;
1800 return llvm::GlobalVariable::InitialExecTLSModel;
1802 return llvm::GlobalVariable::LocalExecTLSModel;
1804 llvm_unreachable(
"Invalid TLS model!");
1808 assert(
D.getTLSKind() &&
"setting TLS mode on non-TLS var!");
1810 llvm::GlobalValue::ThreadLocalMode TLM;
1814 if (
const TLSModelAttr *
Attr =
D.
getAttr<TLSModelAttr>()) {
1818 GV->setThreadLocalMode(TLM);
1824 return (Twine(
'.') + Twine(
Target.CPUSpecificManglingCharacter(Name))).str();
1828 const CPUSpecificAttr *
Attr,
1850 bool OmitMultiVersionMangling =
false) {
1852 llvm::raw_svector_ostream Out(Buffer);
1861 assert(II &&
"Attempt to mangle unnamed decl.");
1862 const auto *FD = dyn_cast<FunctionDecl>(ND);
1867 Out <<
"__regcall4__" << II->
getName();
1869 Out <<
"__regcall3__" << II->
getName();
1870 }
else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
1872 Out <<
"__device_stub__" << II->
getName();
1888 "Hash computed when not explicitly requested");
1892 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
1893 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
1894 switch (FD->getMultiVersionKind()) {
1898 FD->getAttr<CPUSpecificAttr>(),
1902 auto *
Attr = FD->getAttr<TargetAttr>();
1903 assert(
Attr &&
"Expected TargetAttr to be present "
1904 "for attribute mangling");
1910 auto *
Attr = FD->getAttr<TargetVersionAttr>();
1911 assert(
Attr &&
"Expected TargetVersionAttr to be present "
1912 "for attribute mangling");
1918 auto *
Attr = FD->getAttr<TargetClonesAttr>();
1919 assert(
Attr &&
"Expected TargetClonesAttr to be present "
1920 "for attribute mangling");
1927 llvm_unreachable(
"None multiversion type isn't valid here");
1937 return std::string(Out.str());
1940void CodeGenModule::UpdateMultiVersionNames(
GlobalDecl GD,
1942 StringRef &CurName) {
1949 std::string NonTargetName =
1957 "Other GD should now be a multiversioned function");
1967 if (OtherName != NonTargetName) {
1970 const auto ExistingRecord = Manglings.find(NonTargetName);
1971 if (ExistingRecord != std::end(Manglings))
1972 Manglings.remove(&(*ExistingRecord));
1973 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1978 CurName = OtherNameRef;
1980 Entry->setName(OtherName);
1990 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
2004 auto FoundName = MangledDeclNames.find(CanonicalGD);
2005 if (FoundName != MangledDeclNames.end())
2006 return FoundName->second;
2010 const auto *ND = cast<NamedDecl>(GD.
getDecl());
2022 assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
2033 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
2034 return MangledDeclNames[CanonicalGD] =
Result.first->first();
2043 llvm::raw_svector_ostream Out(Buffer);
2046 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.
getDecl()), Out);
2047 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(
D))
2049 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(
D))
2054 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
2055 return Result.first->first();
2059 auto it = MangledDeclNames.begin();
2060 while (it != MangledDeclNames.end()) {
2061 if (it->second == Name)
2076 llvm::Constant *AssociatedData) {
2084 bool IsDtorAttrFunc) {
2085 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2087 DtorsUsingAtExit[
Priority].push_back(Dtor);
2095void CodeGenModule::EmitCtorList(CtorList &Fns,
const char *GlobalName) {
2096 if (Fns.empty())
return;
2102 llvm::PointerType *PtrTy = llvm::PointerType::get(
2103 getLLVMContext(), TheModule.getDataLayout().getProgramAddressSpace());
2106 llvm::StructType *CtorStructTy = llvm::StructType::get(
Int32Ty, PtrTy, PtrTy);
2110 auto Ctors = Builder.beginArray(CtorStructTy);
2111 for (
const auto &I : Fns) {
2112 auto Ctor = Ctors.beginStruct(CtorStructTy);
2113 Ctor.addInt(
Int32Ty, I.Priority);
2114 if (InitFiniAuthSchema) {
2115 llvm::Constant *StorageAddress =
2117 ? llvm::ConstantExpr::getIntToPtr(
2118 llvm::ConstantInt::get(
2120 llvm::ConstantPtrAuth::AddrDiscriminator_CtorsDtors),
2124 I.Initializer, InitFiniAuthSchema.
getKey(), StorageAddress,
2125 llvm::ConstantInt::get(
2127 Ctor.add(SignedCtorPtr);
2129 Ctor.add(I.Initializer);
2131 if (I.AssociatedData)
2132 Ctor.add(I.AssociatedData);
2134 Ctor.addNullPointer(PtrTy);
2135 Ctor.finishAndAddTo(Ctors);
2138 auto List = Ctors.finishAndCreateGlobal(GlobalName,
getPointerAlign(),
2140 llvm::GlobalValue::AppendingLinkage);
2144 List->setAlignment(std::nullopt);
2149llvm::GlobalValue::LinkageTypes
2151 const auto *
D = cast<FunctionDecl>(GD.
getDecl());
2155 if (
const auto *Dtor = dyn_cast<CXXDestructorDecl>(
D))
2162 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2163 if (!MDS)
return nullptr;
2165 return llvm::ConstantInt::get(
Int64Ty, llvm::MD5Hash(MDS->getString()));
2171 FnType->getReturnType(), FnType->getParamTypes(),
2172 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
2174 std::string OutName;
2175 llvm::raw_string_ostream Out(OutName);
2180 Out <<
".normalized";
2182 return llvm::ConstantInt::get(
Int32Ty,
2183 static_cast<uint32_t
>(llvm::xxHash64(OutName)));
2188 llvm::Function *F,
bool IsThunk) {
2190 llvm::AttributeList PAL;
2193 if (
CallingConv == llvm::CallingConv::X86_VectorCall &&
2199 Error(
Loc,
"__vectorcall calling convention is not currently supported");
2201 F->setAttributes(PAL);
2202 F->setCallingConv(
static_cast<llvm::CallingConv::ID
>(
CallingConv));
2206 std::string ReadOnlyQual(
"__read_only");
2207 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2208 if (ReadOnlyPos != std::string::npos)
2210 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2212 std::string WriteOnlyQual(
"__write_only");
2213 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2214 if (WriteOnlyPos != std::string::npos)
2215 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2217 std::string ReadWriteQual(
"__read_write");
2218 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2219 if (ReadWritePos != std::string::npos)
2220 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2253 assert(((FD && CGF) || (!FD && !CGF)) &&
2254 "Incorrect use - FD and CGF should either be both null or not!");
2280 for (
unsigned i = 0, e = FD->
getNumParams(); i != e; ++i) {
2283 argNames.push_back(llvm::MDString::get(VMContext, parm->
getName()));
2288 std::string typeQuals;
2292 const Decl *PDecl = parm;
2294 PDecl = TD->getDecl();
2295 const OpenCLAccessAttr *A = PDecl->
getAttr<OpenCLAccessAttr>();
2296 if (A && A->isWriteOnly())
2297 accessQuals.push_back(llvm::MDString::get(VMContext,
"write_only"));
2298 else if (A && A->isReadWrite())
2299 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_write"));
2301 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_only"));
2303 accessQuals.push_back(llvm::MDString::get(VMContext,
"none"));
2305 auto getTypeSpelling = [&](
QualType Ty) {
2306 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2308 if (Ty.isCanonical()) {
2309 StringRef typeNameRef = typeName;
2311 if (typeNameRef.consume_front(
"unsigned "))
2312 return std::string(
"u") + typeNameRef.str();
2313 if (typeNameRef.consume_front(
"signed "))
2314 return typeNameRef.str();
2324 addressQuals.push_back(
2325 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(
2329 std::string typeName = getTypeSpelling(pointeeTy) +
"*";
2330 std::string baseTypeName =
2332 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2333 argBaseTypeNames.push_back(
2334 llvm::MDString::get(VMContext, baseTypeName));
2338 typeQuals =
"restrict";
2341 typeQuals += typeQuals.empty() ?
"const" :
" const";
2343 typeQuals += typeQuals.empty() ?
"volatile" :
" volatile";
2345 uint32_t AddrSpc = 0;
2350 addressQuals.push_back(
2351 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(AddrSpc)));
2355 std::string typeName = getTypeSpelling(ty);
2367 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2368 argBaseTypeNames.push_back(
2369 llvm::MDString::get(VMContext, baseTypeName));
2374 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
2378 Fn->setMetadata(
"kernel_arg_addr_space",
2379 llvm::MDNode::get(VMContext, addressQuals));
2380 Fn->setMetadata(
"kernel_arg_access_qual",
2381 llvm::MDNode::get(VMContext, accessQuals));
2382 Fn->setMetadata(
"kernel_arg_type",
2383 llvm::MDNode::get(VMContext, argTypeNames));
2384 Fn->setMetadata(
"kernel_arg_base_type",
2385 llvm::MDNode::get(VMContext, argBaseTypeNames));
2386 Fn->setMetadata(
"kernel_arg_type_qual",
2387 llvm::MDNode::get(VMContext, argTypeQuals));
2391 Fn->setMetadata(
"kernel_arg_name",
2392 llvm::MDNode::get(VMContext, argNames));
2402 if (!LangOpts.Exceptions)
return false;
2405 if (LangOpts.CXXExceptions)
return true;
2408 if (LangOpts.ObjCExceptions) {
2425 !isa<CXXConstructorDecl, CXXDestructorDecl>(MD);
2430 llvm::SetVector<const CXXRecordDecl *> MostBases;
2432 std::function<void (
const CXXRecordDecl *)> CollectMostBases;
2435 MostBases.insert(RD);
2437 CollectMostBases(B.getType()->getAsCXXRecordDecl());
2439 CollectMostBases(RD);
2440 return MostBases.takeVector();
2444 llvm::Function *F) {
2445 llvm::AttrBuilder B(F->getContext());
2447 if ((!
D || !
D->
hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2448 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2450 if (CodeGenOpts.StackClashProtector)
2451 B.addAttribute(
"probe-stack",
"inline-asm");
2453 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
2454 B.addAttribute(
"stack-probe-size",
2455 std::to_string(CodeGenOpts.StackProbeSize));
2458 B.addAttribute(llvm::Attribute::NoUnwind);
2460 if (
D &&
D->
hasAttr<NoStackProtectorAttr>())
2462 else if (
D &&
D->
hasAttr<StrictGuardStackCheckAttr>() &&
2464 B.addAttribute(llvm::Attribute::StackProtectStrong);
2466 B.addAttribute(llvm::Attribute::StackProtect);
2468 B.addAttribute(llvm::Attribute::StackProtectStrong);
2470 B.addAttribute(llvm::Attribute::StackProtectReq);
2476 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2478 B.addAttribute(llvm::Attribute::NoInline);
2486 if (
D->
hasAttr<ArmLocallyStreamingAttr>())
2487 B.addAttribute(
"aarch64_pstate_sm_body");
2490 if (
Attr->isNewZA())
2491 B.addAttribute(
"aarch64_new_za");
2492 if (
Attr->isNewZT0())
2493 B.addAttribute(
"aarch64_new_zt0");
2498 bool ShouldAddOptNone =
2499 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
2501 ShouldAddOptNone &= !
D->
hasAttr<MinSizeAttr>();
2502 ShouldAddOptNone &= !
D->
hasAttr<AlwaysInlineAttr>();
2505 if ((ShouldAddOptNone ||
D->
hasAttr<OptimizeNoneAttr>()) &&
2506 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2507 B.addAttribute(llvm::Attribute::OptimizeNone);
2510 B.addAttribute(llvm::Attribute::NoInline);
2515 B.addAttribute(llvm::Attribute::Naked);
2518 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
2519 F->removeFnAttr(llvm::Attribute::MinSize);
2520 }
else if (
D->
hasAttr<NakedAttr>()) {
2522 B.addAttribute(llvm::Attribute::Naked);
2523 B.addAttribute(llvm::Attribute::NoInline);
2524 }
else if (
D->
hasAttr<NoDuplicateAttr>()) {
2525 B.addAttribute(llvm::Attribute::NoDuplicate);
2526 }
else if (
D->
hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2528 B.addAttribute(llvm::Attribute::NoInline);
2529 }
else if (
D->
hasAttr<AlwaysInlineAttr>() &&
2530 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
2532 B.addAttribute(llvm::Attribute::AlwaysInline);
2536 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
2537 B.addAttribute(llvm::Attribute::NoInline);
2541 if (
auto *FD = dyn_cast<FunctionDecl>(
D)) {
2544 auto CheckRedeclForInline = [](
const FunctionDecl *Redecl) {
2545 return Redecl->isInlineSpecified();
2547 if (any_of(FD->
redecls(), CheckRedeclForInline))
2552 return any_of(Pattern->
redecls(), CheckRedeclForInline);
2554 if (CheckForInline(FD)) {
2555 B.addAttribute(llvm::Attribute::InlineHint);
2556 }
else if (CodeGenOpts.getInlining() ==
2559 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2560 B.addAttribute(llvm::Attribute::NoInline);
2567 if (!
D->
hasAttr<OptimizeNoneAttr>()) {
2569 if (!ShouldAddOptNone)
2570 B.addAttribute(llvm::Attribute::OptimizeForSize);
2571 B.addAttribute(llvm::Attribute::Cold);
2574 B.addAttribute(llvm::Attribute::Hot);
2576 B.addAttribute(llvm::Attribute::MinSize);
2583 F->setAlignment(llvm::Align(alignment));
2586 if (LangOpts.FunctionAlignment)
2587 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
2594 if (isa<CXXMethodDecl>(
D) && F->getPointerAlignment(
getDataLayout()) < 2)
2595 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
2600 if (CodeGenOpts.SanitizeCfiCrossDso &&
2601 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2602 if (
auto *FD = dyn_cast<FunctionDecl>(
D)) {
2613 auto *MD = dyn_cast<CXXMethodDecl>(
D);
2616 llvm::Metadata *
Id =
2619 F->addTypeMetadata(0,
Id);
2626 if (isa_and_nonnull<NamedDecl>(
D))
2629 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2634 if (
const auto *VD = dyn_cast_if_present<VarDecl>(
D);
2636 ((CodeGenOpts.KeepPersistentStorageVariables &&
2637 (VD->getStorageDuration() ==
SD_Static ||
2638 VD->getStorageDuration() ==
SD_Thread)) ||
2639 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
2640 VD->getType().isConstQualified())))
2644bool CodeGenModule::GetCPUAndFeaturesAttributes(
GlobalDecl GD,
2645 llvm::AttrBuilder &Attrs,
2646 bool SetTargetFeatures) {
2652 std::vector<std::string> Features;
2653 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.
getDecl());
2655 const auto *TD = FD ? FD->
getAttr<TargetAttr>() :
nullptr;
2656 const auto *TV = FD ? FD->
getAttr<TargetVersionAttr>() :
nullptr;
2657 assert((!TD || !TV) &&
"both target_version and target specified");
2658 const auto *SD = FD ? FD->
getAttr<CPUSpecificAttr>() :
nullptr;
2659 const auto *TC = FD ? FD->
getAttr<TargetClonesAttr>() :
nullptr;
2660 bool AddedAttr =
false;
2661 if (TD || TV || SD || TC) {
2662 llvm::StringMap<bool> FeatureMap;
2666 for (
const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
2667 Features.push_back((Entry.getValue() ?
"+" :
"-") + Entry.getKey().str());
2675 Target.parseTargetAttr(TD->getFeaturesStr());
2697 if (!TargetCPU.empty()) {
2698 Attrs.addAttribute(
"target-cpu", TargetCPU);
2701 if (!TuneCPU.empty()) {
2702 Attrs.addAttribute(
"tune-cpu", TuneCPU);
2705 if (!Features.empty() && SetTargetFeatures) {
2706 llvm::erase_if(Features, [&](
const std::string& F) {
2709 llvm::sort(Features);
2710 Attrs.addAttribute(
"target-features", llvm::join(Features,
","));
2717void CodeGenModule::setNonAliasAttributes(
GlobalDecl GD,
2718 llvm::GlobalObject *GO) {
2723 if (
auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
2726 if (
auto *SA =
D->
getAttr<PragmaClangBSSSectionAttr>())
2727 GV->addAttribute(
"bss-section", SA->getName());
2728 if (
auto *SA =
D->
getAttr<PragmaClangDataSectionAttr>())
2729 GV->addAttribute(
"data-section", SA->getName());
2730 if (
auto *SA =
D->
getAttr<PragmaClangRodataSectionAttr>())
2731 GV->addAttribute(
"rodata-section", SA->getName());
2732 if (
auto *SA =
D->
getAttr<PragmaClangRelroSectionAttr>())
2733 GV->addAttribute(
"relro-section", SA->getName());
2736 if (
auto *F = dyn_cast<llvm::Function>(GO)) {
2739 if (
auto *SA =
D->
getAttr<PragmaClangTextSectionAttr>())
2741 F->setSection(SA->getName());
2743 llvm::AttrBuilder Attrs(F->getContext());
2744 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
2748 llvm::AttributeMask RemoveAttrs;
2749 RemoveAttrs.addAttribute(
"target-cpu");
2750 RemoveAttrs.addAttribute(
"target-features");
2751 RemoveAttrs.addAttribute(
"tune-cpu");
2752 F->removeFnAttrs(RemoveAttrs);
2753 F->addFnAttrs(Attrs);
2757 if (
const auto *CSA =
D->
getAttr<CodeSegAttr>())
2758 GO->setSection(CSA->getName());
2759 else if (
const auto *SA =
D->
getAttr<SectionAttr>())
2760 GO->setSection(SA->getName());
2773 F->setLinkage(llvm::Function::InternalLinkage);
2775 setNonAliasAttributes(GD, F);
2786 GV->
setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2790 llvm::Function *F) {
2792 if (!LangOpts.
Sanitize.
has(SanitizerKind::CFIICall))
2797 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2801 F->addTypeMetadata(0, MD);
2805 if (CodeGenOpts.SanitizeCfiCrossDso)
2807 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
2811 llvm::LLVMContext &Ctx = F->getContext();
2812 llvm::MDBuilder MDB(Ctx);
2813 F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
2822 return llvm::all_of(Name, [](
const char &
C) {
2823 return llvm::isAlnum(
C) ||
C ==
'_' ||
C ==
'.';
2829 for (
auto &F : M.functions()) {
2831 bool AddressTaken = F.hasAddressTaken();
2832 if (!AddressTaken && F.hasLocalLinkage())
2833 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
2838 if (!AddressTaken || !F.isDeclaration())
2841 const llvm::ConstantInt *
Type;
2842 if (
const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
2843 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
2847 StringRef Name = F.getName();
2851 std::string
Asm = (
".weak __kcfi_typeid_" + Name +
"\n.set __kcfi_typeid_" +
2852 Name +
", " + Twine(
Type->getZExtValue()) +
"\n")
2854 M.appendModuleInlineAsm(
Asm);
2858void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
2859 bool IsIncompleteFunction,
2862 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
2865 F->setAttributes(llvm::Intrinsic::getAttributes(
getLLVMContext(), IID));
2869 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
2871 if (!IsIncompleteFunction)
2878 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
2880 assert(!F->arg_empty() &&
2881 F->arg_begin()->getType()
2882 ->canLosslesslyBitCastTo(F->getReturnType()) &&
2883 "unexpected this return");
2884 F->addParamAttr(0, llvm::Attribute::Returned);
2894 if (!IsIncompleteFunction && F->isDeclaration())
2897 if (
const auto *CSA = FD->
getAttr<CodeSegAttr>())
2898 F->setSection(CSA->getName());
2899 else if (
const auto *SA = FD->
getAttr<SectionAttr>())
2900 F->setSection(SA->getName());
2902 if (
const auto *EA = FD->
getAttr<ErrorAttr>()) {
2904 F->addFnAttr(
"dontcall-error", EA->getUserDiagnostic());
2905 else if (EA->isWarning())
2906 F->addFnAttr(
"dontcall-warn", EA->getUserDiagnostic());
2912 bool HasBody = FD->
hasBody(FDBody);
2914 assert(HasBody &&
"Inline builtin declarations should always have an "
2916 if (shouldEmitFunction(FDBody))
2917 F->addFnAttr(llvm::Attribute::NoBuiltin);
2923 F->addFnAttr(llvm::Attribute::NoBuiltin);
2926 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
2927 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2928 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
2929 if (MD->isVirtual())
2930 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2936 if (!CodeGenOpts.SanitizeCfiCrossDso ||
2937 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
2946 if (CodeGenOpts.InlineMaxStackSize !=
UINT_MAX)
2947 F->addFnAttr(
"inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
2949 if (
const auto *CB = FD->
getAttr<CallbackAttr>()) {
2953 llvm::LLVMContext &Ctx = F->getContext();
2954 llvm::MDBuilder MDB(Ctx);
2958 int CalleeIdx = *CB->encoding_begin();
2959 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
2960 F->addMetadata(llvm::LLVMContext::MD_callback,
2961 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
2962 CalleeIdx, PayloadIndices,
2968 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2969 "Only globals with definition can force usage.");
2970 LLVMUsed.emplace_back(GV);
2974 assert(!GV->isDeclaration() &&
2975 "Only globals with definition can force usage.");
2976 LLVMCompilerUsed.emplace_back(GV);
2980 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2981 "Only globals with definition can force usage.");
2983 LLVMCompilerUsed.emplace_back(GV);
2985 LLVMUsed.emplace_back(GV);
2989 std::vector<llvm::WeakTrackingVH> &List) {
2996 UsedArray.resize(List.size());
2997 for (
unsigned i = 0, e = List.size(); i != e; ++i) {
2999 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3000 cast<llvm::Constant>(&*List[i]), CGM.
Int8PtrTy);
3003 if (UsedArray.empty())
3005 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
3007 auto *GV =
new llvm::GlobalVariable(
3008 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
3009 llvm::ConstantArray::get(ATy, UsedArray), Name);
3011 GV->setSection(
"llvm.metadata");
3014void CodeGenModule::emitLLVMUsed() {
3015 emitUsed(*
this,
"llvm.used", LLVMUsed);
3016 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
3021 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3030 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3036 ELFDependentLibraries.push_back(
3037 llvm::MDNode::get(
C, llvm::MDString::get(
C, Lib)));
3044 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
C, MDOpts));
3059 if (
Visited.insert(Import).second)
3076 if (LL.IsFramework) {
3077 llvm::Metadata *Args[2] = {llvm::MDString::get(Context,
"-framework"),
3078 llvm::MDString::get(Context, LL.Library)};
3080 Metadata.push_back(llvm::MDNode::get(Context, Args));
3086 llvm::Metadata *Args[2] = {
3087 llvm::MDString::get(Context,
"lib"),
3088 llvm::MDString::get(Context, LL.Library),
3090 Metadata.push_back(llvm::MDNode::get(Context, Args));
3094 auto *OptString = llvm::MDString::get(Context, Opt);
3095 Metadata.push_back(llvm::MDNode::get(Context, OptString));
3100void CodeGenModule::EmitModuleInitializers(
clang::Module *Primary) {
3102 "We should only emit module initializers for named modules.");
3108 if (isa<ImportDecl>(
D))
3110 assert(isa<VarDecl>(
D) &&
"GMF initializer decl is not a var?");
3117 if (isa<ImportDecl>(
D))
3125 if (isa<ImportDecl>(
D))
3127 assert(isa<VarDecl>(
D) &&
"PMF initializer decl is not a var?");
3133void CodeGenModule::EmitModuleLinkOptions() {
3137 llvm::SetVector<clang::Module *> LinkModules;
3142 for (
Module *M : ImportedModules) {
3145 if (M->getTopLevelModuleName() ==
getLangOpts().CurrentModule &&
3154 while (!Stack.empty()) {
3157 bool AnyChildren =
false;
3167 Stack.push_back(
SM);
3175 LinkModules.insert(Mod);
3184 for (
Module *M : LinkModules)
3187 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
3188 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
3191 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.linker.options");
3192 for (
auto *MD : LinkerOptionsMetadata)
3193 NMD->addOperand(MD);
3196void CodeGenModule::EmitDeferred() {
3205 if (!DeferredVTables.empty()) {
3206 EmitDeferredVTables();
3211 assert(DeferredVTables.empty());
3218 llvm::append_range(DeferredDeclsToEmit,
3222 if (DeferredDeclsToEmit.empty())
3227 std::vector<GlobalDecl> CurDeclsToEmit;
3228 CurDeclsToEmit.swap(DeferredDeclsToEmit);
3235 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
3253 if (!GV->isDeclaration())
3257 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(
D))
3261 EmitGlobalDefinition(
D, GV);
3266 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
3268 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
3273void CodeGenModule::EmitVTablesOpportunistically() {
3279 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
3280 &&
"Only emit opportunistic vtables with optimizations");
3284 "This queue should only contain external vtables");
3285 if (
getCXXABI().canSpeculativelyEmitVTable(RD))
3288 OpportunisticVTables.clear();
3292 for (
const auto& [MangledName, VD] : DeferredAnnotations) {
3297 DeferredAnnotations.clear();
3299 if (Annotations.empty())
3303 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
3304 Annotations[0]->getType(), Annotations.size()), Annotations);
3305 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
3306 llvm::GlobalValue::AppendingLinkage,
3307 Array,
"llvm.global.annotations");
3312 llvm::Constant *&AStr = AnnotationStrings[Str];
3317 llvm::Constant *
s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
3318 auto *gv =
new llvm::GlobalVariable(
3319 getModule(),
s->getType(),
true, llvm::GlobalValue::PrivateLinkage,
s,
3320 ".str",
nullptr, llvm::GlobalValue::NotThreadLocal,
3323 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3340 SM.getExpansionLineNumber(L);
3341 return llvm::ConstantInt::get(
Int32Ty, LineNo);
3349 llvm::FoldingSetNodeID ID;
3350 for (
Expr *
E : Exprs) {
3351 ID.Add(cast<clang::ConstantExpr>(
E)->getAPValueResult());
3353 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
3358 LLVMArgs.reserve(Exprs.size());
3360 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](
const Expr *
E) {
3361 const auto *CE = cast<clang::ConstantExpr>(
E);
3362 return ConstEmiter.
emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
3365 auto *
Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
3366 auto *GV =
new llvm::GlobalVariable(
getModule(),
Struct->getType(),
true,
3367 llvm::GlobalValue::PrivateLinkage,
Struct,
3370 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3377 const AnnotateAttr *AA,
3385 llvm::Constant *GVInGlobalsAS = GV;
3386 if (GV->getAddressSpace() !=
3388 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
3390 llvm::PointerType::get(
3391 GV->getContext(),
getDataLayout().getDefaultGlobalsAddressSpace()));
3395 llvm::Constant *Fields[] = {
3396 GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
3398 return llvm::ConstantStruct::getAnon(Fields);
3402 llvm::GlobalValue *GV) {
3403 assert(
D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
3413 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
3418 if (NoSanitizeL.containsMainFile(Kind, MainFile.
getName()))
3423 return NoSanitizeL.containsLocation(Kind,
Loc);
3426 return NoSanitizeL.containsFile(Kind, MainFile.
getName());
3430 llvm::GlobalVariable *GV,
3434 if (NoSanitizeL.containsGlobal(Kind, GV->getName(),
Category))
3437 if (NoSanitizeL.containsMainFile(
3438 Kind,
SM.getFileEntryRefForID(
SM.getMainFileID())->getName(),
3441 if (NoSanitizeL.containsLocation(Kind,
Loc,
Category))
3448 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
3449 Ty = AT->getElementType();
3454 if (NoSanitizeL.containsType(Kind, TypeStr,
Category))
3465 auto Attr = ImbueAttr::NONE;
3468 if (
Attr == ImbueAttr::NONE)
3469 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
3471 case ImbueAttr::NONE:
3473 case ImbueAttr::ALWAYS:
3474 Fn->addFnAttr(
"function-instrument",
"xray-always");
3476 case ImbueAttr::ALWAYS_ARG1:
3477 Fn->addFnAttr(
"function-instrument",
"xray-always");
3478 Fn->addFnAttr(
"xray-log-args",
"1");
3480 case ImbueAttr::NEVER:
3481 Fn->addFnAttr(
"function-instrument",
"xray-never");
3505 if (
auto MainFile =
SM.getFileEntryRefForID(
SM.getMainFileID()))
3519 if (NumGroups > 1) {
3520 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
3529 if (LangOpts.EmitAllDecls)
3532 const auto *VD = dyn_cast<VarDecl>(
Global);
3534 ((CodeGenOpts.KeepPersistentStorageVariables &&
3535 (VD->getStorageDuration() ==
SD_Static ||
3536 VD->getStorageDuration() ==
SD_Thread)) ||
3537 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
3538 VD->getType().isConstQualified())))
3551 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
3552 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
3553 OMPDeclareTargetDeclAttr::getActiveAttr(
Global);
3554 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (
unsigned)-1)
3558 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
3567 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
3573 if (CXX20ModuleInits && VD->getOwningModule() &&
3574 !VD->getOwningModule()->isModuleMapModule()) {
3583 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
3586 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
Global))
3599 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
3603 llvm::Constant *
Init;
3606 if (!
V.isAbsent()) {
3617 llvm::Constant *Fields[4] = {
3621 llvm::ConstantDataArray::getRaw(
3622 StringRef(
reinterpret_cast<char *
>(Parts.
Part4And5), 8), 8,
3624 Init = llvm::ConstantStruct::getAnon(Fields);
3627 auto *GV =
new llvm::GlobalVariable(
3629 true, llvm::GlobalValue::LinkOnceODRLinkage,
Init, Name);
3631 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3634 if (!
V.isAbsent()) {
3647 llvm::GlobalVariable **Entry =
nullptr;
3648 Entry = &UnnamedGlobalConstantDeclMap[GCD];
3653 llvm::Constant *
Init;
3657 assert(!
V.isAbsent());
3661 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
3663 llvm::GlobalValue::PrivateLinkage,
Init,
3665 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3679 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
3683 llvm::Constant *
Init =
Emitter.emitForInitializer(
3691 llvm::GlobalValue::LinkageTypes
Linkage =
3693 ? llvm::GlobalValue::LinkOnceODRLinkage
3694 : llvm::GlobalValue::InternalLinkage;
3695 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
3699 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3706 const AliasAttr *AA = VD->
getAttr<AliasAttr>();
3707 assert(AA &&
"No alias?");
3717 llvm::Constant *Aliasee;
3718 if (isa<llvm::FunctionType>(DeclTy))
3719 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
3726 auto *F = cast<llvm::GlobalValue>(Aliasee);
3727 F->setLinkage(llvm::Function::ExternalWeakLinkage);
3728 WeakRefReferences.insert(F);
3737 return A->isImplicit();
3741bool CodeGenModule::shouldEmitCUDAGlobalVar(
const VarDecl *
Global)
const {
3742 assert(LangOpts.CUDA &&
"Should not be called by non-CUDA languages");
3747 return !LangOpts.CUDAIsDevice ||
Global->hasAttr<CUDADeviceAttr>() ||
3748 Global->hasAttr<CUDAConstantAttr>() ||
3749 Global->hasAttr<CUDASharedAttr>() ||
3750 Global->getType()->isCUDADeviceBuiltinSurfaceType() ||
3751 Global->getType()->isCUDADeviceBuiltinTextureType();
3758 if (
Global->hasAttr<WeakRefAttr>())
3763 if (
Global->hasAttr<AliasAttr>())
3764 return EmitAliasDefinition(GD);
3767 if (
Global->hasAttr<IFuncAttr>())
3768 return emitIFuncDefinition(GD);
3771 if (
Global->hasAttr<CPUDispatchAttr>())
3772 return emitCPUDispatchDefinition(GD);
3777 if (LangOpts.CUDA) {
3778 assert((isa<FunctionDecl>(
Global) || isa<VarDecl>(
Global)) &&
3779 "Expected Variable or Function");
3780 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
3781 if (!shouldEmitCUDAGlobalVar(VD))
3783 }
else if (LangOpts.CUDAIsDevice) {
3784 const auto *FD = dyn_cast<FunctionDecl>(
Global);
3785 if ((!
Global->hasAttr<CUDADeviceAttr>() ||
3786 (LangOpts.OffloadImplicitHostDeviceTemplates &&
3787 hasImplicitAttr<CUDAHostAttr>(FD) &&
3788 hasImplicitAttr<CUDADeviceAttr>(FD) && !FD->
isConstexpr() &&
3790 !
getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
3791 !
Global->hasAttr<CUDAGlobalAttr>() &&
3792 !(LangOpts.HIPStdPar && isa<FunctionDecl>(
Global) &&
3793 !
Global->hasAttr<CUDAHostAttr>()))
3796 }
else if (!
Global->hasAttr<CUDAHostAttr>() &&
3797 Global->hasAttr<CUDADeviceAttr>())
3801 if (LangOpts.OpenMP) {
3803 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
3805 if (
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(
Global)) {
3806 if (MustBeEmitted(
Global))
3810 if (
auto *DMD = dyn_cast<OMPDeclareMapperDecl>(
Global)) {
3811 if (MustBeEmitted(
Global))
3818 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
3821 if (FD->
hasAttr<AnnotateAttr>()) {
3824 DeferredAnnotations[MangledName] = FD;
3839 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
3844 const auto *VD = cast<VarDecl>(
Global);
3845 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
3848 if (LangOpts.OpenMP) {
3850 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3851 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
3855 if (VD->hasExternalStorage() &&
3856 Res != OMPDeclareTargetDeclAttr::MT_Link)
3859 bool UnifiedMemoryEnabled =
3861 if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3862 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3863 !UnifiedMemoryEnabled) {
3866 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3867 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3868 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3869 UnifiedMemoryEnabled)) &&
3870 "Link clause or to clause with unified memory expected.");
3889 if (MustBeEmitted(
Global) && MayBeEmittedEagerly(
Global)) {
3891 EmitGlobalDefinition(GD);
3892 addEmittedDeferredDecl(GD);
3899 cast<VarDecl>(
Global)->hasInit()) {
3900 DelayedCXXInitPosition[
Global] = CXXGlobalInits.size();
3901 CXXGlobalInits.push_back(
nullptr);
3907 addDeferredDeclToEmit(GD);
3908 }
else if (MustBeEmitted(
Global)) {
3910 assert(!MayBeEmittedEagerly(
Global));
3911 addDeferredDeclToEmit(GD);
3916 DeferredDecls[MangledName] = GD;
3923 if (
CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
3924 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
3931 struct FunctionIsDirectlyRecursive
3933 const StringRef Name;
3943 if (
Attr && Name ==
Attr->getLabel())
3948 StringRef BuiltinName = BI.
getName(BuiltinID);
3949 if (BuiltinName.starts_with(
"__builtin_") &&
3950 Name == BuiltinName.slice(strlen(
"__builtin_"), StringRef::npos)) {
3956 bool VisitStmt(
const Stmt *S) {
3957 for (
const Stmt *Child : S->children())
3958 if (Child && this->Visit(Child))
3965 struct DLLImportFunctionVisitor
3967 bool SafeToInline =
true;
3969 bool shouldVisitImplicitCode()
const {
return true; }
3971 bool VisitVarDecl(
VarDecl *VD) {
3974 SafeToInline =
false;
3975 return SafeToInline;
3982 return SafeToInline;
3986 if (
const auto *
D =
E->getTemporary()->getDestructor())
3987 SafeToInline =
D->
hasAttr<DLLImportAttr>();
3988 return SafeToInline;
3993 if (isa<FunctionDecl>(VD))
3994 SafeToInline = VD->
hasAttr<DLLImportAttr>();
3995 else if (
VarDecl *
V = dyn_cast<VarDecl>(VD))
3996 SafeToInline = !
V->hasGlobalStorage() ||
V->hasAttr<DLLImportAttr>();
3997 return SafeToInline;
4001 SafeToInline =
E->getConstructor()->hasAttr<DLLImportAttr>();
4002 return SafeToInline;
4009 SafeToInline =
true;
4011 SafeToInline = M->
hasAttr<DLLImportAttr>();
4013 return SafeToInline;
4017 SafeToInline =
E->getOperatorDelete()->hasAttr<DLLImportAttr>();
4018 return SafeToInline;
4022 SafeToInline =
E->getOperatorNew()->hasAttr<DLLImportAttr>();
4023 return SafeToInline;
4032CodeGenModule::isTriviallyRecursive(
const FunctionDecl *FD) {
4034 if (
getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
4039 Name =
Attr->getLabel();
4044 FunctionIsDirectlyRecursive Walker(Name, Context.
BuiltinInfo);
4046 return Body ? Walker.Visit(Body) :
false;
4049bool CodeGenModule::shouldEmitFunction(
GlobalDecl GD) {
4053 const auto *F = cast<FunctionDecl>(GD.
getDecl());
4056 if (F->isInlineBuiltinDeclaration())
4059 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
4064 if (
const Module *M = F->getOwningModule();
4065 M && M->getTopLevelModule()->isNamedModule() &&
4066 getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
4076 if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
4081 if (F->hasAttr<NoInlineAttr>())
4084 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
4086 DLLImportFunctionVisitor Visitor;
4087 Visitor.TraverseFunctionDecl(
const_cast<FunctionDecl*
>(F));
4088 if (!Visitor.SafeToInline)
4094 for (
const Decl *
Member : Dtor->getParent()->decls())
4095 if (isa<FieldDecl>(
Member))
4109 return !isTriviallyRecursive(F);
4112bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
4113 return CodeGenOpts.OptimizationLevel > 0;
4116void CodeGenModule::EmitMultiVersionFunctionDefinition(
GlobalDecl GD,
4117 llvm::GlobalValue *GV) {
4118 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4121 auto *Spec = FD->
getAttr<CPUSpecificAttr>();
4122 for (
unsigned I = 0; I < Spec->cpus_size(); ++I)
4124 }
else if (
auto *TC = FD->
getAttr<TargetClonesAttr>()) {
4125 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I)
4128 TC->isFirstOfVersion(I))
4131 GetOrCreateMultiVersionResolver(GD);
4133 EmitGlobalFunctionDefinition(GD, GV);
4138 AddDeferredMultiVersionResolverToEmit(GD);
4141void CodeGenModule::EmitGlobalDefinition(
GlobalDecl GD, llvm::GlobalValue *GV) {
4142 const auto *
D = cast<ValueDecl>(GD.
getDecl());
4146 "Generating code for declaration");
4148 if (
const auto *FD = dyn_cast<FunctionDecl>(
D)) {
4151 if (!shouldEmitFunction(GD))
4154 llvm::TimeTraceScope TimeScope(
"CodeGen Function", [&]() {
4156 llvm::raw_string_ostream OS(Name);
4162 if (
const auto *Method = dyn_cast<CXXMethodDecl>(
D)) {
4165 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
4166 ABI->emitCXXStructor(GD);
4168 EmitMultiVersionFunctionDefinition(GD, GV);
4170 EmitGlobalFunctionDefinition(GD, GV);
4172 if (Method->isVirtual())
4179 return EmitMultiVersionFunctionDefinition(GD, GV);
4180 return EmitGlobalFunctionDefinition(GD, GV);
4183 if (
const auto *VD = dyn_cast<VarDecl>(
D))
4184 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
4186 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
4190 llvm::Function *NewFn);
4194 const CodeGenFunction::MultiVersionResolverOption &RO) {
4196 unsigned NumFeatures = 0;
4197 for (StringRef Feat : RO.Conditions.Features) {
4202 if (!RO.Conditions.Architecture.empty())
4220 return llvm::GlobalValue::InternalLinkage;
4221 return llvm::GlobalValue::WeakODRLinkage;
4224void CodeGenModule::emitMultiVersionFunctions() {
4225 std::vector<GlobalDecl> MVFuncsToEmit;
4226 MultiVersionFuncs.swap(MVFuncsToEmit);
4228 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4229 assert(FD &&
"Expected a FunctionDecl");
4236 if (
Decl->isDefined()) {
4237 EmitGlobalFunctionDefinition(CurGD,
nullptr);
4245 assert(
Func &&
"This should have just been created");
4247 return cast<llvm::Function>(
Func);
4261 if (
const auto *TA = CurFD->
getAttr<TargetAttr>()) {
4262 TA->getAddedFeatures(Feats);
4263 llvm::Function *Func = createFunction(CurFD);
4264 Options.emplace_back(Func, TA->getArchitecture(), Feats);
4265 }
else if (
const auto *TVA = CurFD->
getAttr<TargetVersionAttr>()) {
4266 if (TVA->isDefaultVersion() && IsDefined)
4267 ShouldEmitResolver = true;
4268 TVA->getFeatures(Feats);
4269 llvm::Function *Func = createFunction(CurFD);
4270 Options.emplace_back(Func,
"", Feats);
4271 }
else if (
const auto *TC = CurFD->
getAttr<TargetClonesAttr>()) {
4273 ShouldEmitResolver = true;
4274 for (unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
4275 if (!TC->isFirstOfVersion(I))
4278 llvm::Function *Func = createFunction(CurFD, I);
4279 StringRef Architecture;
4281 if (getTarget().getTriple().isAArch64())
4282 TC->getFeatures(Feats, I);
4284 StringRef Version = TC->getFeatureStr(I);
4285 if (Version.starts_with(
"arch="))
4286 Architecture = Version.drop_front(sizeof(
"arch=") - 1);
4287 else if (Version !=
"default")
4288 Feats.push_back(Version);
4290 Options.emplace_back(Func, Architecture, Feats);
4293 llvm_unreachable(
"unexpected MultiVersionKind");
4296 if (!ShouldEmitResolver)
4299 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
4300 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
4301 ResolverConstant = IFunc->getResolver();
4305 *
this, GD, FD,
true);
4312 auto *Alias = llvm::GlobalAlias::create(
4314 MangledName +
".ifunc", IFunc, &
getModule());
4319 llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant);
4324 ResolverFunc->setComdat(
4325 getModule().getOrInsertComdat(ResolverFunc->getName()));
4329 Options, [&TI](
const CodeGenFunction::MultiVersionResolverOption &LHS,
4330 const CodeGenFunction::MultiVersionResolverOption &RHS) {
4334 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4340 if (!MVFuncsToEmit.empty())
4345 if (!MultiVersionFuncs.empty())
4346 emitMultiVersionFunctions();
4350 llvm::Constant *New) {
4351 assert(cast<llvm::Function>(Old)->isDeclaration() &&
"Not a declaration");
4353 Old->replaceAllUsesWith(New);
4354 Old->eraseFromParent();
4357void CodeGenModule::emitCPUDispatchDefinition(
GlobalDecl GD) {
4358 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4359 assert(FD &&
"Not a FunctionDecl?");
4361 const auto *DD = FD->
getAttr<CPUDispatchAttr>();
4362 assert(DD &&
"Not a cpu_dispatch Function?");
4368 UpdateMultiVersionNames(GD, FD, ResolverName);
4370 llvm::Type *ResolverType;
4373 ResolverType = llvm::FunctionType::get(
4374 llvm::PointerType::get(DeclTy,
4383 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
4384 ResolverName, ResolverType, ResolverGD,
false));
4387 ResolverFunc->setComdat(
4388 getModule().getOrInsertComdat(ResolverFunc->getName()));
4401 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
4404 EmitGlobalFunctionDefinition(ExistingDecl,
nullptr);
4410 Func = GetOrCreateLLVMFunction(
4411 MangledName, DeclTy, ExistingDecl,
4418 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
4419 llvm::transform(Features, Features.begin(),
4420 [](StringRef Str) { return Str.substr(1); });
4421 llvm::erase_if(Features, [&
Target](StringRef Feat) {
4422 return !
Target.validateCpuSupports(Feat);
4424 Options.emplace_back(cast<llvm::Function>(
Func), StringRef{}, Features);
4429 Options, [](
const CodeGenFunction::MultiVersionResolverOption &LHS,
4430 const CodeGenFunction::MultiVersionResolverOption &RHS) {
4431 return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) >
4432 llvm::X86::getCpuSupportsMask(RHS.Conditions.Features);
4439 while (Options.size() > 1 &&
4440 llvm::all_of(llvm::X86::getCpuSupportsMask(
4441 (Options.end() - 2)->Conditions.Features),
4442 [](
auto X) { return X == 0; })) {
4443 StringRef LHSName = (Options.end() - 2)->
Function->getName();
4444 StringRef RHSName = (Options.end() - 1)->
Function->getName();
4445 if (LHSName.compare(RHSName) < 0)
4446 Options.erase(Options.end() - 2);
4448 Options.erase(Options.end() - 1);
4452 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4456 auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD));
4460 if (!isa<llvm::GlobalIFunc>(IFunc)) {
4461 auto *GI = llvm::GlobalIFunc::create(DeclTy, 0,
Linkage,
"", ResolverFunc,
4468 *
this, GD, FD,
true);
4471 auto *GA = llvm::GlobalAlias::create(DeclTy, 0,
Linkage, AliasName, IFunc,
4479void CodeGenModule::AddDeferredMultiVersionResolverToEmit(
GlobalDecl GD) {
4480 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4481 assert(FD &&
"Not a FunctionDecl?");
4484 std::string MangledName =
4486 if (!DeferredResolversToEmit.insert(MangledName).second)
4489 MultiVersionFuncs.push_back(GD);
4495llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
GlobalDecl GD) {
4496 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4497 assert(FD &&
"Not a FunctionDecl?");
4499 std::string MangledName =
4504 std::string ResolverName = MangledName;
4508 llvm_unreachable(
"unexpected MultiVersionKind::None for resolver");
4512 ResolverName +=
".ifunc";
4519 ResolverName +=
".resolver";
4530 (isa<llvm::GlobalIFunc>(ResolverGV) || !
getTarget().supportsIFunc()))
4539 AddDeferredMultiVersionResolverToEmit(GD);
4544 llvm::Type *ResolverType = llvm::FunctionType::get(
4545 llvm::PointerType::get(DeclTy,
4548 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4549 MangledName +
".resolver", ResolverType,
GlobalDecl{},
4551 llvm::GlobalIFunc *GIF =
4554 GIF->setName(ResolverName);
4561 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4563 assert(isa<llvm::GlobalValue>(Resolver) &&
4564 "Resolver should be created for the first time");
4571bool CodeGenModule::shouldDropDLLAttribute(
const Decl *
D,
4572 const llvm::GlobalValue *GV)
const {
4573 auto SC = GV->getDLLStorageClass();
4574 if (SC == llvm::GlobalValue::DefaultStorageClass)
4577 return (((SC == llvm::GlobalValue::DLLImportStorageClass &&
4578 !MRD->
hasAttr<DLLImportAttr>()) ||
4579 (SC == llvm::GlobalValue::DLLExportStorageClass &&
4580 !MRD->
hasAttr<DLLExportAttr>())) &&
4591llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
4592 StringRef MangledName, llvm::Type *Ty,
GlobalDecl GD,
bool ForVTable,
4593 bool DontDefer,
bool IsThunk, llvm::AttributeList ExtraAttrs,
4597 std::string NameWithoutMultiVersionMangling;
4600 if (
const FunctionDecl *FD = cast_or_null<FunctionDecl>(
D)) {
4602 if (
getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
4603 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->
isDefined() &&
4604 !DontDefer && !IsForDefinition) {
4607 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
4609 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
4618 UpdateMultiVersionNames(GD, FD, MangledName);
4619 if (!IsForDefinition) {
4625 AddDeferredMultiVersionResolverToEmit(GD);
4627 *
this, GD, FD,
true);
4629 return GetOrCreateMultiVersionResolver(GD);
4634 if (!NameWithoutMultiVersionMangling.empty())
4635 MangledName = NameWithoutMultiVersionMangling;
4640 if (WeakRefReferences.erase(Entry)) {
4642 if (FD && !FD->
hasAttr<WeakAttr>())
4643 Entry->setLinkage(llvm::Function::ExternalLinkage);
4647 if (
D && shouldDropDLLAttribute(
D, Entry)) {
4648 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4654 if (IsForDefinition && !Entry->isDeclaration()) {
4661 DiagnosedConflictingDefinitions.insert(GD).second) {
4665 diag::note_previous_definition);
4669 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
4670 (Entry->getValueType() == Ty)) {
4677 if (!IsForDefinition)
4684 bool IsIncompleteFunction =
false;
4686 llvm::FunctionType *FTy;
4687 if (isa<llvm::FunctionType>(Ty)) {
4688 FTy = cast<llvm::FunctionType>(Ty);
4690 FTy = llvm::FunctionType::get(
VoidTy,
false);
4691 IsIncompleteFunction =
true;
4695 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
4696 Entry ? StringRef() : MangledName, &
getModule());
4701 DeferredAnnotations[MangledName] = cast<ValueDecl>(
D);
4718 if (!Entry->use_empty()) {
4720 Entry->removeDeadConstantUsers();
4726 assert(F->getName() == MangledName &&
"name was uniqued!");
4728 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
4729 if (ExtraAttrs.hasFnAttrs()) {
4730 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
4738 if (isa_and_nonnull<CXXDestructorDecl>(
D) &&
4739 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(
D),
4741 addDeferredDeclToEmit(GD);
4746 auto DDI = DeferredDecls.find(MangledName);
4747 if (DDI != DeferredDecls.end()) {
4751 addDeferredDeclToEmit(DDI->second);
4752 DeferredDecls.erase(DDI);
4767 for (
const auto *FD = cast<FunctionDecl>(
D)->getMostRecentDecl(); FD;
4780 if (!IsIncompleteFunction) {
4781 assert(F->getFunctionType() == Ty);
4797 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4804 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(GD.
getDecl())) {
4807 DD->getParent()->getNumVBases() == 0)
4812 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
4813 false, llvm::AttributeList(),
4816 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
4817 cast<FunctionDecl>(GD.
getDecl())->hasAttr<CUDAGlobalAttr>()) {
4819 cast<llvm::Function>(F->stripPointerCasts()), GD);
4820 if (IsForDefinition)
4828 llvm::GlobalValue *F =
4831 return llvm::NoCFIValue::get(F);
4841 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
4844 if (!
C.getLangOpts().CPlusPlus)
4849 (Name ==
"_ZSt9terminatev" || Name ==
"?terminate@@YAXXZ")
4850 ?
C.Idents.get(
"terminate")
4851 :
C.Idents.get(Name);
4853 for (
const auto &N : {
"__cxxabiv1",
"std"}) {
4857 if (
auto *LSD = dyn_cast<LinkageSpecDecl>(
Result))
4858 for (
const auto *
Result : LSD->lookup(&NS))
4859 if ((ND = dyn_cast<NamespaceDecl>(
Result)))
4864 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
4876 llvm::AttributeList ExtraAttrs,
bool Local,
4877 bool AssumeConvergent) {
4878 if (AssumeConvergent) {
4880 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
4884 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
4888 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
4897 if (!Local &&
getTriple().isWindowsItaniumEnvironment() &&
4900 if (!FD || FD->
hasAttr<DLLImportAttr>()) {
4901 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4902 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
4909 markRegisterParameterAttributes(F);
4935 if (WeakRefReferences.erase(Entry)) {
4937 Entry->setLinkage(llvm::Function::ExternalLinkage);
4941 if (
D && shouldDropDLLAttribute(
D, Entry))
4942 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4944 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd &&
D)
4947 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
4952 if (IsForDefinition && !Entry->isDeclaration()) {
4960 (OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
4962 DiagnosedConflictingDefinitions.insert(
D).second) {
4966 diag::note_previous_definition);
4971 if (Entry->getType()->getAddressSpace() != TargetAS)
4972 return llvm::ConstantExpr::getAddrSpaceCast(
4973 Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
4977 if (!IsForDefinition)
4983 auto *GV =
new llvm::GlobalVariable(
4984 getModule(), Ty,
false, llvm::GlobalValue::ExternalLinkage,
nullptr,
4985 MangledName,
nullptr, llvm::GlobalVariable::NotThreadLocal,
4986 getContext().getTargetAddressSpace(DAddrSpace));
4991 GV->takeName(Entry);
4993 if (!Entry->use_empty()) {
4994 Entry->replaceAllUsesWith(GV);
4997 Entry->eraseFromParent();
5003 auto DDI = DeferredDecls.find(MangledName);
5004 if (DDI != DeferredDecls.end()) {
5007 addDeferredDeclToEmit(DDI->second);
5008 DeferredDecls.erase(DDI);
5013 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
5018 GV->setConstant(
D->getType().isConstantStorage(
getContext(),
false,
false));
5020 GV->setAlignment(
getContext().getDeclAlign(
D).getAsAlign());
5024 if (
D->getTLSKind()) {
5026 CXXThreadLocals.push_back(
D);
5034 if (
getContext().isMSStaticDataMemberInlineDefinition(
D)) {
5035 EmitGlobalVarDefinition(
D);
5039 if (
D->hasExternalStorage()) {
5040 if (
const SectionAttr *SA =
D->
getAttr<SectionAttr>())
5041 GV->setSection(SA->getName());
5045 if (
getTriple().getArch() == llvm::Triple::xcore &&
5047 D->getType().isConstant(Context) &&
5049 GV->setSection(
".cp.rodata");
5052 if (
const auto *CMA =
D->
getAttr<CodeModelAttr>())
5053 GV->setCodeModel(CMA->getModel());
5058 if (Context.
getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
5059 D->getType().isConstQualified() && !GV->hasInitializer() &&
5060 !
D->hasDefinition() &&
D->hasInit() && !
D->
hasAttr<DLLImportAttr>()) {
5064 if (!HasMutableFields) {
5066 const Expr *InitExpr =
D->getAnyInitializer(InitDecl);
5071 auto *InitType =
Init->getType();
5072 if (GV->getValueType() != InitType) {
5077 GV->setName(StringRef());
5080 auto *NewGV = cast<llvm::GlobalVariable>(
5082 ->stripPointerCasts());
5085 GV->eraseFromParent();
5088 GV->setInitializer(
Init);
5089 GV->setConstant(
true);
5090 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
5105 D->hasExternalStorage())
5110 SanitizerMD->reportGlobal(GV, *
D);
5113 D ?
D->getType().getAddressSpace()
5115 assert(
getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
5116 if (DAddrSpace != ExpectedAS) {
5118 *
this, GV, DAddrSpace, ExpectedAS,
5129 if (isa<CXXConstructorDecl>(
D) || isa<CXXDestructorDecl>(
D))
5131 false, IsForDefinition);
5133 if (isa<CXXMethodDecl>(
D)) {
5141 if (isa<FunctionDecl>(
D)) {
5152 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes
Linkage,
5153 llvm::Align Alignment) {
5154 llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
5155 llvm::GlobalVariable *OldGV =
nullptr;
5159 if (GV->getValueType() == Ty)
5164 assert(GV->isDeclaration() &&
"Declaration has wrong type!");
5169 GV =
new llvm::GlobalVariable(
getModule(), Ty,
true,
5174 GV->takeName(OldGV);
5176 if (!OldGV->use_empty()) {
5177 OldGV->replaceAllUsesWith(GV);
5180 OldGV->eraseFromParent();
5184 !GV->hasAvailableExternallyLinkage())
5185 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5187 GV->setAlignment(Alignment);
5201 assert(
D->hasGlobalStorage() &&
"Not a global variable");
5219 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
5224 assert(!
D->getInit() &&
"Cannot emit definite definitions here!");
5232 if (GV && !GV->isDeclaration())
5237 if (!MustBeEmitted(
D) && !GV) {
5238 DeferredDecls[MangledName] =
D;
5243 EmitGlobalVarDefinition(
D);
5247 if (
auto const *
V = dyn_cast<const VarDecl>(
D))
5248 EmitExternalVarDeclaration(
V);
5249 if (
auto const *FD = dyn_cast<const FunctionDecl>(
D))
5250 EmitExternalFunctionDeclaration(FD);
5259 if (LangOpts.OpenCL) {
5270 if (LangOpts.SYCLIsDevice &&
5274 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
5276 if (
D->
hasAttr<CUDAConstantAttr>())
5282 if (
D->getType().isConstQualified())
5288 if (LangOpts.OpenMP) {
5290 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(
D, AS))
5298 if (LangOpts.OpenCL)
5300 if (LangOpts.SYCLIsDevice)
5302 if (LangOpts.HIP && LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())
5310 if (
auto AS =
getTarget().getConstantAddressSpace())
5323static llvm::Constant *
5325 llvm::GlobalVariable *GV) {
5326 llvm::Constant *Cast = GV;
5332 llvm::PointerType::get(
5339template<
typename SomeDecl>
5341 llvm::GlobalValue *GV) {
5347 if (!
D->template hasAttr<UsedAttr>())
5356 const SomeDecl *
First =
D->getFirstDecl();
5357 if (
First->getDeclContext()->isRecord() || !
First->isInExternCContext())
5363 std::pair<StaticExternCMap::iterator, bool> R =
5364 StaticExternCValues.insert(std::make_pair(
D->getIdentifier(), GV));
5369 R.first->second =
nullptr;
5380 if (
auto *VD = dyn_cast<VarDecl>(&
D))
5394 llvm_unreachable(
"No such linkage");
5402 llvm::GlobalObject &GO) {
5405 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
5409void CodeGenModule::EmitGlobalVarDefinition(
const VarDecl *
D,
5419 if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
5420 OpenMPRuntime->emitTargetGlobalVariable(
D))
5423 llvm::TrackingVH<llvm::Constant>
Init;
5424 bool NeedsGlobalCtor =
false;
5428 bool IsDefinitionAvailableExternally =
5430 bool NeedsGlobalDtor =
5431 !IsDefinitionAvailableExternally &&
5438 if (IsDefinitionAvailableExternally &&
5439 (!
D->hasConstantInitialization() ||
5443 !
D->getType().isConstantStorage(
getContext(),
true,
true)))
5447 const Expr *InitExpr =
D->getAnyInitializer(InitDecl);
5449 std::optional<ConstantEmitter> emitter;
5454 bool IsCUDASharedVar =
5459 bool IsCUDAShadowVar =
5463 bool IsCUDADeviceShadowVar =
5465 (
D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5466 D->getType()->isCUDADeviceBuiltinTextureType());
5468 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
5469 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
5470 else if (
D->
hasAttr<LoaderUninitializedAttr>())
5471 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
5472 else if (!InitExpr) {
5486 emitter.emplace(*
this);
5487 llvm::Constant *
Initializer = emitter->tryEmitForInitializer(*InitDecl);
5490 if (
D->getType()->isReferenceType())
5498 if (!IsDefinitionAvailableExternally)
5499 NeedsGlobalCtor =
true;
5510 DelayedCXXInitPosition.erase(
D);
5517 assert(VarSize == CstSize &&
"Emitted constant has unexpected size");
5522 llvm::Type* InitType =
Init->getType();
5523 llvm::Constant *Entry =
5527 Entry = Entry->stripPointerCasts();
5530 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
5541 if (!GV || GV->getValueType() != InitType ||
5542 GV->getType()->getAddressSpace() !=
5546 Entry->setName(StringRef());
5549 GV = cast<llvm::GlobalVariable>(
5551 ->stripPointerCasts());
5554 llvm::Constant *NewPtrForOldDecl =
5555 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5557 Entry->replaceAllUsesWith(NewPtrForOldDecl);
5560 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
5578 if (LangOpts.CUDA) {
5579 if (LangOpts.CUDAIsDevice) {
5580 if (
Linkage != llvm::GlobalValue::InternalLinkage &&
5582 D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5583 D->getType()->isCUDADeviceBuiltinTextureType()))
5584 GV->setExternallyInitialized(
true);
5591 GV->setInitializer(
Init);
5593 emitter->finalize(GV);
5596 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
5597 D->getType().isConstantStorage(
getContext(),
true,
true));
5600 if (
const SectionAttr *SA =
D->
getAttr<SectionAttr>()) {
5603 GV->setConstant(
true);
5608 if (std::optional<CharUnits> AlignValFromAllocate =
5610 AlignVal = *AlignValFromAllocate;
5628 Linkage == llvm::GlobalValue::ExternalLinkage &&
5631 Linkage = llvm::GlobalValue::InternalLinkage;
5635 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
5636 else if (
D->
hasAttr<DLLExportAttr>())
5637 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
5639 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
5641 if (
Linkage == llvm::GlobalVariable::CommonLinkage) {
5643 GV->setConstant(
false);
5648 if (!GV->getInitializer()->isNullValue())
5649 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
5652 setNonAliasAttributes(
D, GV);
5654 if (
D->getTLSKind() && !GV->isThreadLocal()) {
5656 CXXThreadLocals.push_back(
D);
5663 if (NeedsGlobalCtor || NeedsGlobalDtor)
5664 EmitCXXGlobalVarDeclInitFunc(
D, GV, NeedsGlobalCtor);
5666 SanitizerMD->reportGlobal(GV, *
D, NeedsGlobalCtor);
5671 DI->EmitGlobalVariable(GV,
D);
5674void CodeGenModule::EmitExternalVarDeclaration(
const VarDecl *
D) {
5679 llvm::Constant *GV =
5681 DI->EmitExternalVariable(
5682 cast<llvm::GlobalVariable>(GV->stripPointerCasts()),
D);
5686void CodeGenModule::EmitExternalFunctionDeclaration(
const FunctionDecl *FD) {
5691 auto *
Fn = cast<llvm::Function>(
5692 GetOrCreateLLVMFunction(MangledName, Ty, FD,
false));
5693 if (!
Fn->getSubprogram())
5710 if (
D->getInit() ||
D->hasExternalStorage())
5720 if (
D->
hasAttr<PragmaClangBSSSectionAttr>() ||
5721 D->
hasAttr<PragmaClangDataSectionAttr>() ||
5722 D->
hasAttr<PragmaClangRelroSectionAttr>() ||
5723 D->
hasAttr<PragmaClangRodataSectionAttr>())
5727 if (
D->getTLSKind())
5750 if (FD->isBitField())
5752 if (FD->
hasAttr<AlignedAttr>())
5774llvm::GlobalValue::LinkageTypes
5778 return llvm::Function::InternalLinkage;
5781 return llvm::GlobalVariable::WeakAnyLinkage;
5785 return llvm::GlobalVariable::LinkOnceAnyLinkage;
5790 return llvm::GlobalValue::AvailableExternallyLinkage;
5804 return !Context.
getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
5805 : llvm::Function::InternalLinkage;
5819 return llvm::Function::ExternalLinkage;
5822 return D->
hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
5823 : llvm::Function::InternalLinkage;
5824 return llvm::Function::WeakODRLinkage;
5831 CodeGenOpts.NoCommon))
5832 return llvm::GlobalVariable::CommonLinkage;
5839 return llvm::GlobalVariable::WeakODRLinkage;
5843 return llvm::GlobalVariable::ExternalLinkage;
5846llvm::GlobalValue::LinkageTypes
5855 llvm::Function *newFn) {
5857 if (old->use_empty())
5860 llvm::Type *newRetTy = newFn->getReturnType();
5865 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
5867 llvm::User *user = ui->getUser();
5871 if (
auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
5872 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
5878 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
5881 if (!callSite->isCallee(&*ui))
5886 if (callSite->getType() != newRetTy && !callSite->use_empty())
5891 llvm::AttributeList oldAttrs = callSite->getAttributes();
5894 unsigned newNumArgs = newFn->arg_size();
5895 if (callSite->arg_size() < newNumArgs)
5901 bool dontTransform =
false;
5902 for (llvm::Argument &A : newFn->args()) {
5903 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
5904 dontTransform =
true;
5909 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
5917 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
5921 callSite->getOperandBundlesAsDefs(newBundles);
5923 llvm::CallBase *newCall;
5924 if (isa<llvm::CallInst>(callSite)) {
5925 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles,
"",
5926 callSite->getIterator());
5928 auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
5929 newCall = llvm::InvokeInst::Create(
5930 newFn, oldInvoke->getNormalDest(), oldInvoke->getUnwindDest(),
5931 newArgs, newBundles,
"", callSite->getIterator());
5935 if (!newCall->getType()->isVoidTy())
5936 newCall->takeName(callSite);
5937 newCall->setAttributes(
5938 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
5939 oldAttrs.getRetAttrs(), newArgAttrs));
5940 newCall->setCallingConv(callSite->getCallingConv());
5943 if (!callSite->use_empty())
5944 callSite->replaceAllUsesWith(newCall);
5947 if (callSite->getDebugLoc())
5948 newCall->setDebugLoc(callSite->getDebugLoc());
5950 callSitesToBeRemovedFromParent.push_back(callSite);
5953 for (
auto *callSite : callSitesToBeRemovedFromParent) {
5954 callSite->eraseFromParent();
5968 llvm::Function *NewFn) {
5970 if (!isa<llvm::Function>(Old))
return;
5978 (LangOpts.CUDA && !shouldEmitCUDAGlobalVar(VD)))
5990void CodeGenModule::EmitGlobalFunctionDefinition(
GlobalDecl GD,
5991 llvm::GlobalValue *GV) {
5992 const auto *
D = cast<FunctionDecl>(GD.
getDecl());
5999 if (!GV || (GV->getValueType() != Ty))
6005 if (!GV->isDeclaration())
6012 auto *Fn = cast<llvm::Function>(GV);
6024 setNonAliasAttributes(GD, Fn);
6027 if (
const ConstructorAttr *CA =
D->
getAttr<ConstructorAttr>())
6029 if (
const DestructorAttr *DA =
D->
getAttr<DestructorAttr>())
6035void CodeGenModule::EmitAliasDefinition(
GlobalDecl GD) {
6036 const auto *
D = cast<ValueDecl>(GD.
getDecl());
6037 const AliasAttr *AA =
D->
getAttr<AliasAttr>();
6038 assert(AA &&
"Not an alias?");
6042 if (AA->getAliasee() == MangledName) {
6043 Diags.
Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6050 if (Entry && !Entry->isDeclaration())
6053 Aliases.push_back(GD);
6059 llvm::Constant *Aliasee;
6060 llvm::GlobalValue::LinkageTypes
LT;
6061 if (isa<llvm::FunctionType>(DeclTy)) {
6062 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
6068 if (
const auto *VD = dyn_cast<VarDecl>(GD.
getDecl()))
6075 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
6077 llvm::GlobalAlias::create(DeclTy, AS,
LT,
"", Aliasee, &
getModule());
6080 if (GA->getAliasee() == Entry) {
6081 Diags.
Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6085 assert(Entry->isDeclaration());
6094 GA->takeName(Entry);
6096 Entry->replaceAllUsesWith(GA);
6097 Entry->eraseFromParent();
6099 GA->setName(MangledName);
6107 GA->setLinkage(llvm::Function::WeakAnyLinkage);
6110 if (
const auto *VD = dyn_cast<VarDecl>(
D))
6111 if (VD->getTLSKind())
6117 if (isa<VarDecl>(
D))
6119 DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD);
6122void CodeGenModule::emitIFuncDefinition(
GlobalDecl GD) {
6123 const auto *
D = cast<ValueDecl>(GD.
getDecl());
6124 const IFuncAttr *IFA =
D->
getAttr<IFuncAttr>();
6125 assert(IFA &&
"Not an ifunc?");
6129 if (IFA->getResolver() == MangledName) {
6130 Diags.
Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6136 if (Entry && !Entry->isDeclaration()) {
6139 DiagnosedConflictingDefinitions.insert(GD).second) {
6143 diag::note_previous_definition);
6148 Aliases.push_back(GD);
6154 llvm::Constant *Resolver =
6155 GetOrCreateLLVMFunction(IFA->getResolver(),
VoidTy, {},
6158 llvm::GlobalIFunc *GIF =
6159 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
6162 if (GIF->getResolver() == Entry) {
6163 Diags.
Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6166 assert(Entry->isDeclaration());
6175 GIF->takeName(Entry);
6177 Entry->replaceAllUsesWith(GIF);
6178 Entry->eraseFromParent();
6180 GIF->setName(MangledName);
6186 return llvm::Intrinsic::getDeclaration(&
getModule(), (llvm::Intrinsic::ID)IID,
6190static llvm::StringMapEntry<llvm::GlobalVariable *> &
6193 bool &IsUTF16,
unsigned &StringLength) {
6194 StringRef String = Literal->getString();
6195 unsigned NumBytes = String.size();
6198 if (!Literal->containsNonAsciiOrNull()) {
6199 StringLength = NumBytes;
6200 return *Map.insert(std::make_pair(String,
nullptr)).first;
6207 const llvm::UTF8 *FromPtr = (
const llvm::UTF8 *)String.data();
6208 llvm::UTF16 *ToPtr = &ToBuf[0];
6210 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6211 ToPtr + NumBytes, llvm::strictConversion);
6214 StringLength = ToPtr - &ToBuf[0];
6218 return *Map.insert(std::make_pair(
6219 StringRef(
reinterpret_cast<const char *
>(ToBuf.data()),
6220 (StringLength + 1) * 2),
6226 unsigned StringLength = 0;
6227 bool isUTF16 =
false;
6228 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
6233 if (
auto *
C = Entry.second)
6238 const llvm::Triple &Triple =
getTriple();
6241 const bool IsSwiftABI =
6242 static_cast<unsigned>(CFRuntime) >=
6247 if (!CFConstantStringClassRef) {
6248 const char *CFConstantStringClassName =
"__CFConstantStringClassReference";
6250 Ty = llvm::ArrayType::get(Ty, 0);
6252 switch (CFRuntime) {
6256 CFConstantStringClassName =
6257 Triple.isOSDarwin() ?
"$s15SwiftFoundation19_NSCFConstantStringCN"
6258 :
"$s10Foundation19_NSCFConstantStringCN";
6262 CFConstantStringClassName =
6263 Triple.isOSDarwin() ?
"$S15SwiftFoundation19_NSCFConstantStringCN"
6264 :
"$S10Foundation19_NSCFConstantStringCN";
6268 CFConstantStringClassName =
6269 Triple.isOSDarwin() ?
"__T015SwiftFoundation19_NSCFConstantStringCN"
6270 :
"__T010Foundation19_NSCFConstantStringCN";
6277 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
6278 llvm::GlobalValue *GV =
nullptr;
6280 if ((GV = dyn_cast<llvm::GlobalValue>(
C))) {
6287 if ((VD = dyn_cast<VarDecl>(
Result)))
6290 if (Triple.isOSBinFormatELF()) {
6292 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6294 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6295 if (!VD || !VD->
hasAttr<DLLExportAttr>())
6296 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
6298 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
6306 CFConstantStringClassRef =
6307 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(
C, Ty) :
C;
6312 auto *STy = cast<llvm::StructType>(
getTypes().ConvertType(CFTy));
6315 auto Fields = Builder.beginStruct(STy);
6318 Fields.add(cast<llvm::Constant>(CFConstantStringClassRef));
6322 Fields.addInt(
IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
6323 Fields.addInt(
Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
6325 Fields.addInt(
IntTy, isUTF16 ? 0x07d0 : 0x07C8);
6329 llvm::Constant *
C =
nullptr;
6332 reinterpret_cast<uint16_t *
>(
const_cast<char *
>(Entry.first().data())),
6333 Entry.first().size() / 2);
6334 C = llvm::ConstantDataArray::get(VMContext, Arr);
6336 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
6342 new llvm::GlobalVariable(
getModule(),
C->getType(),
true,
6343 llvm::GlobalValue::PrivateLinkage,
C,
".str");
6344 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6354 if (Triple.isOSBinFormatMachO())
6355 GV->setSection(isUTF16 ?
"__TEXT,__ustring"
6356 :
"__TEXT,__cstring,cstring_literals");
6359 else if (Triple.isOSBinFormatELF())
6360 GV->setSection(
".rodata");
6366 llvm::IntegerType *LengthTy =
6376 Fields.addInt(LengthTy, StringLength);
6384 GV = Fields.finishAndCreateGlobal(
"_unnamed_cfstring_", Alignment,
6386 llvm::GlobalVariable::PrivateLinkage);
6387 GV->addAttribute(
"objc_arc_inert");
6388 switch (Triple.getObjectFormat()) {
6389 case llvm::Triple::UnknownObjectFormat:
6390 llvm_unreachable(
"unknown file format");
6391 case llvm::Triple::DXContainer:
6392 case llvm::Triple::GOFF:
6393 case llvm::Triple::SPIRV:
6394 case llvm::Triple::XCOFF:
6395 llvm_unreachable(
"unimplemented");
6396 case llvm::Triple::COFF:
6397 case llvm::Triple::ELF:
6398 case llvm::Triple::Wasm:
6399 GV->setSection(
"cfstring");
6401 case llvm::Triple::MachO:
6402 GV->setSection(
"__DATA,__cfstring");
6411 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
6415 if (ObjCFastEnumerationStateType.
isNull()) {
6417 D->startDefinition();
6425 for (
size_t i = 0; i < 4; ++i) {
6430 FieldTypes[i],
nullptr,
6438 D->completeDefinition();
6442 return ObjCFastEnumerationStateType;
6451 if (
E->getCharByteWidth() == 1) {
6456 assert(CAT &&
"String literal not of constant array type!");
6458 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
6462 llvm::Type *ElemTy = AType->getElementType();
6463 unsigned NumElements = AType->getNumElements();
6466 if (ElemTy->getPrimitiveSizeInBits() == 16) {
6468 Elements.reserve(NumElements);
6470 for(
unsigned i = 0, e =
E->getLength(); i != e; ++i)
6471 Elements.push_back(
E->getCodeUnit(i));
6472 Elements.resize(NumElements);
6473 return llvm::ConstantDataArray::get(VMContext, Elements);
6476 assert(ElemTy->getPrimitiveSizeInBits() == 32);
6478 Elements.reserve(NumElements);
6480 for(
unsigned i = 0, e =
E->getLength(); i != e; ++i)
6481 Elements.push_back(
E->getCodeUnit(i));
6482 Elements.resize(NumElements);
6483 return llvm::ConstantDataArray::get(VMContext, Elements);
6486static llvm::GlobalVariable *
6495 auto *GV =
new llvm::GlobalVariable(
6496 M,
C->getType(), !CGM.
getLangOpts().WritableStrings,
LT,
C, GlobalName,
6497 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
6499 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6500 if (GV->isWeakForLinker()) {
6501 assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
6502 GV->setComdat(M.getOrInsertComdat(GV->getName()));
6518 llvm::GlobalVariable **Entry =
nullptr;
6519 if (!LangOpts.WritableStrings) {
6520 Entry = &ConstantStringMap[
C];
6521 if (
auto GV = *Entry) {
6522 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
6525 GV->getValueType(), Alignment);
6530 StringRef GlobalVariableName;
6531 llvm::GlobalValue::LinkageTypes
LT;
6536 if (
getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
6537 !LangOpts.WritableStrings) {
6538 llvm::raw_svector_ostream Out(MangledNameBuffer);
6540 LT = llvm::GlobalValue::LinkOnceODRLinkage;
6541 GlobalVariableName = MangledNameBuffer;
6543 LT = llvm::GlobalValue::PrivateLinkage;
6544 GlobalVariableName = Name;
6556 SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0),
"<string literal>");
6559 GV->getValueType(), Alignment);
6576 const std::string &Str,
const char *GlobalName) {
6577 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
6582 llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
6585 llvm::GlobalVariable **Entry =
nullptr;
6586 if (!LangOpts.WritableStrings) {
6587 Entry = &ConstantStringMap[
C];
6588 if (
auto GV = *Entry) {
6589 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
6592 GV->getValueType(), Alignment);
6598 GlobalName =
".str";
6601 GlobalName, Alignment);
6606 GV->getValueType(), Alignment);
6611 assert((
E->getStorageDuration() ==
SD_Static ||
6612 E->getStorageDuration() ==
SD_Thread) &&
"not a global temporary");
6613 const auto *VD = cast<VarDecl>(
E->getExtendingDecl());
6618 if (
Init ==
E->getSubExpr())
6623 auto InsertResult = MaterializedGlobalTemporaryMap.insert({
E,
nullptr});
6624 if (!InsertResult.second) {
6627 if (!InsertResult.first->second) {
6632 InsertResult.first->second =
new llvm::GlobalVariable(
6633 getModule(),
Type,
false, llvm::GlobalVariable::InternalLinkage,
6637 llvm::cast<llvm::GlobalVariable>(
6638 InsertResult.first->second->stripPointerCasts())
6647 llvm::raw_svector_ostream Out(Name);
6649 VD,
E->getManglingNumber(), Out);
6652 if (
E->getStorageDuration() ==
SD_Static && VD->evaluateValue()) {
6658 Value =
E->getOrCreateValue(
false);
6669 std::optional<ConstantEmitter> emitter;
6670 llvm::Constant *InitialValue =
nullptr;
6671 bool Constant =
false;
6675 emitter.emplace(*
this);
6676 InitialValue = emitter->emitForInitializer(*
Value, AddrSpace,
6681 Type = InitialValue->getType();
6690 if (
Linkage == llvm::GlobalVariable::ExternalLinkage) {
6692 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
6696 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
6700 Linkage = llvm::GlobalVariable::InternalLinkage;
6704 auto *GV =
new llvm::GlobalVariable(
6706 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
6707 if (emitter) emitter->finalize(GV);
6709 if (!llvm::GlobalValue::isLocalLinkage(
Linkage)) {
6711 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
6713 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6717 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
6718 if (VD->getTLSKind())
6720 llvm::Constant *CV = GV;
6724 llvm::PointerType::get(
6730 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[
E];
6732 Entry->replaceAllUsesWith(CV);
6733 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
6742void CodeGenModule::EmitObjCPropertyImplementations(
const
6744 for (
const auto *PID :
D->property_impls()) {
6755 if (!Getter || Getter->isSynthesizedAccessorStub())
6758 auto *Setter = PID->getSetterMethodDecl();
6759 if (!PD->
isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
6770 if (ivar->getType().isDestructedType())
6780 E =
D->init_end(); B !=
E; ++B) {
6803 D->addInstanceMethod(DTORMethod);
6805 D->setHasDestructors(
true);
6810 if (
D->getNumIvarInitializers() == 0 ||
6824 D->addInstanceMethod(CTORMethod);
6826 D->setHasNonZeroConstructors(
true);
6837 EmitDeclContext(LSD);
6842 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
6845 std::unique_ptr<CodeGenFunction> &CurCGF =
6846 GlobalTopLevelStmtBlockInFlight.first;
6850 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
6858 std::string Name =
"__stmts__" + llvm::utostr(CXXGlobalInits.size());
6864 llvm::Function *
Fn = llvm::Function::Create(
6865 FnTy, llvm::GlobalValue::InternalLinkage, Name, &
getModule());
6868 GlobalTopLevelStmtBlockInFlight.second =
D;
6869 CurCGF->StartFunction(
GlobalDecl(), RetTy, Fn, FnInfo, Args,
6871 CXXGlobalInits.push_back(Fn);
6874 CurCGF->EmitStmt(
D->getStmt());
6877void CodeGenModule::EmitDeclContext(
const DeclContext *DC) {
6878 for (
auto *I : DC->
decls()) {
6884 if (
auto *OID = dyn_cast<ObjCImplDecl>(I)) {
6885 for (
auto *M : OID->methods())
6904 case Decl::CXXConversion:
6905 case Decl::CXXMethod:
6906 case Decl::Function:
6913 case Decl::CXXDeductionGuide:
6918 case Decl::Decomposition:
6919 case Decl::VarTemplateSpecialization:
6921 if (
auto *DD = dyn_cast<DecompositionDecl>(
D))
6922 for (
auto *B : DD->bindings())
6923 if (
auto *HD = B->getHoldingVar())
6929 case Decl::IndirectField:
6933 case Decl::Namespace:
6934 EmitDeclContext(cast<NamespaceDecl>(
D));
6936 case Decl::ClassTemplateSpecialization: {
6937 const auto *Spec = cast<ClassTemplateSpecializationDecl>(
D);
6939 if (Spec->getSpecializationKind() ==
6941 Spec->hasDefinition())
6942 DI->completeTemplateDefinition(*Spec);
6944 case Decl::CXXRecord: {
6951 DI->completeUnusedClass(*CRD);
6954 for (
auto *I : CRD->
decls())
6955 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
6960 case Decl::UsingShadow:
6961 case Decl::ClassTemplate:
6962 case Decl::VarTemplate:
6964 case Decl::VarTemplatePartialSpecialization:
6965 case Decl::FunctionTemplate:
6966 case Decl::TypeAliasTemplate:
6973 DI->EmitUsingDecl(cast<UsingDecl>(*
D));
6975 case Decl::UsingEnum:
6977 DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*
D));
6979 case Decl::NamespaceAlias:
6981 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*
D));
6983 case Decl::UsingDirective:
6985 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*
D));
6987 case Decl::CXXConstructor:
6990 case Decl::CXXDestructor:
6994 case Decl::StaticAssert:
7001 case Decl::ObjCInterface:
7002 case Decl::ObjCCategory:
7005 case Decl::ObjCProtocol: {
7006 auto *Proto = cast<ObjCProtocolDecl>(
D);
7007 if (Proto->isThisDeclarationADefinition())
7012 case Decl::ObjCCategoryImpl:
7015 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(
D));
7018 case Decl::ObjCImplementation: {
7019 auto *OMD = cast<ObjCImplementationDecl>(
D);
7020 EmitObjCPropertyImplementations(OMD);
7021 EmitObjCIvarInitializations(OMD);
7026 DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
7027 OMD->getClassInterface()), OMD->getLocation());
7030 case Decl::ObjCMethod: {
7031 auto *OMD = cast<ObjCMethodDecl>(
D);
7037 case Decl::ObjCCompatibleAlias:
7038 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(
D));
7041 case Decl::PragmaComment: {
7042 const auto *PCD = cast<PragmaCommentDecl>(
D);
7043 switch (PCD->getCommentKind()) {
7045 llvm_unreachable(
"unexpected pragma comment kind");
7060 case Decl::PragmaDetectMismatch: {
7061 const auto *PDMD = cast<PragmaDetectMismatchDecl>(
D);
7066 case Decl::LinkageSpec:
7067 EmitLinkageSpec(cast<LinkageSpecDecl>(
D));
7070 case Decl::FileScopeAsm: {
7072 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7075 if (LangOpts.OpenMPIsTargetDevice)
7078 if (LangOpts.SYCLIsDevice)
7080 auto *AD = cast<FileScopeAsmDecl>(
D);
7081 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
7085 case Decl::TopLevelStmt:
7086 EmitTopLevelStmt(cast<TopLevelStmtDecl>(
D));
7089 case Decl::Import: {
7090 auto *Import = cast<ImportDecl>(
D);
7093 if (!ImportedModules.insert(Import->getImportedModule()))
7097 if (!Import->getImportedOwningModule()) {
7099 DI->EmitImportDecl(*Import);
7105 if (CXX20ModuleInits && Import->getImportedOwningModule() &&
7106 !Import->getImportedOwningModule()->isModuleMapModule())
7115 Visited.insert(Import->getImportedModule());
7116 Stack.push_back(Import->getImportedModule());
7118 while (!Stack.empty()) {
7120 if (!EmittedModuleInitializers.insert(Mod).second)
7130 if (Submodule->IsExplicit)
7133 if (
Visited.insert(Submodule).second)
7134 Stack.push_back(Submodule);
7141 EmitDeclContext(cast<ExportDecl>(
D));
7144 case Decl::OMPThreadPrivate:
7148 case Decl::OMPAllocate:
7152 case Decl::OMPDeclareReduction:
7156 case Decl::OMPDeclareMapper:
7160 case Decl::OMPRequires:
7165 case Decl::TypeAlias:
7167 DI->EmitAndRetainType(
7168 getContext().getTypedefType(cast<TypedefNameDecl>(
D)));
7180 DI->EmitAndRetainType(
getContext().getEnumType(cast<EnumDecl>(
D)));
7183 case Decl::HLSLBuffer:
7191 assert(isa<TypeDecl>(
D) &&
"Unsupported decl kind");
7198 if (!CodeGenOpts.CoverageMapping)
7201 case Decl::CXXConversion:
7202 case Decl::CXXMethod:
7203 case Decl::Function:
7204 case Decl::ObjCMethod:
7205 case Decl::CXXConstructor:
7206 case Decl::CXXDestructor: {
7207 if (!cast<FunctionDecl>(
D)->doesThisDeclarationHaveABody())
7215 DeferredEmptyCoverageMappingDecls.try_emplace(
D,
true);
7225 if (!CodeGenOpts.CoverageMapping)
7227 if (
const auto *Fn = dyn_cast<FunctionDecl>(
D)) {
7228 if (Fn->isTemplateInstantiation())
7231 DeferredEmptyCoverageMappingDecls.insert_or_assign(
D,
false);
7239 for (
const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
7242 const Decl *
D = Entry.first;
7244 case Decl::CXXConversion:
7245 case Decl::CXXMethod:
7246 case Decl::Function:
7247 case Decl::ObjCMethod: {
7254 case Decl::CXXConstructor: {
7261 case Decl::CXXDestructor: {
7278 if (llvm::Function *F =
getModule().getFunction(
"main")) {
7279 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
7281 auto *GA = llvm::GlobalAlias::create(
"__main_void", F);
7282 GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
7291 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
7292 return llvm::ConstantInt::get(i64, PtrInt);
7296 llvm::NamedMDNode *&GlobalMetadata,
7298 llvm::GlobalValue *Addr) {
7299 if (!GlobalMetadata)
7301 CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
7304 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
7307 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
7310bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
7311 llvm::GlobalValue *CppFunc) {
7319 if (Elem == CppFunc)
7325 for (llvm::User *User : Elem->users()) {
7329 if (
auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
7330 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
7333 for (llvm::User *CEUser : ConstExpr->users()) {
7334 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
7335 IFuncs.push_back(IFunc);
7340 CEs.push_back(ConstExpr);
7341 }
else if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
7342 IFuncs.push_back(IFunc);
7354 for (llvm::GlobalIFunc *IFunc : IFuncs)
7355 IFunc->setResolver(
nullptr);
7356 for (llvm::ConstantExpr *ConstExpr : CEs)
7357 ConstExpr->destroyConstant();
7361 Elem->eraseFromParent();
7363 for (llvm::GlobalIFunc *IFunc : IFuncs) {
7368 llvm::FunctionType::get(IFunc->getType(),
false);
7369 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
7370 CppFunc->getName(), ResolverTy, {},
false);
7371 IFunc->setResolver(Resolver);
7381void CodeGenModule::EmitStaticExternCAliases() {
7384 for (
auto &I : StaticExternCValues) {
7386 llvm::GlobalValue *Val = I.second;
7394 llvm::GlobalValue *ExistingElem =
7395 getModule().getNamedValue(Name->getName());
7399 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
7406 auto Res = Manglings.find(MangledName);
7407 if (Res == Manglings.end())
7409 Result = Res->getValue();
7420void CodeGenModule::EmitDeclMetadata() {
7421 llvm::NamedMDNode *GlobalMetadata =
nullptr;
7423 for (
auto &I : MangledDeclNames) {
7424 llvm::GlobalValue *Addr =
getModule().getNamedValue(I.second);
7434void CodeGenFunction::EmitDeclMetadata() {
7435 if (LocalDeclMap.empty())
return;
7440 unsigned DeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
7442 llvm::NamedMDNode *GlobalMetadata =
nullptr;
7444 for (
auto &I : LocalDeclMap) {
7445 const Decl *
D = I.first;
7446 llvm::Value *Addr = I.second.emitRawPointer(*
this);
7447 if (
auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
7449 Alloca->setMetadata(
7450 DeclPtrKind, llvm::MDNode::get(
7451 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
7452 }
else if (
auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
7459void CodeGenModule::EmitVersionIdentMetadata() {
7460 llvm::NamedMDNode *IdentMetadata =
7461 TheModule.getOrInsertNamedMetadata(
"llvm.ident");
7463 llvm::LLVMContext &Ctx = TheModule.getContext();
7465 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
7466 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
7469void CodeGenModule::EmitCommandLineMetadata() {
7470 llvm::NamedMDNode *CommandLineMetadata =
7471 TheModule.getOrInsertNamedMetadata(
"llvm.commandline");
7473 llvm::LLVMContext &Ctx = TheModule.getContext();
7475 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
7476 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
7479void CodeGenModule::EmitCoverageFile() {
7480 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu");
7484 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
7485 llvm::LLVMContext &Ctx = TheModule.getContext();
7486 auto *CoverageDataFile =
7488 auto *CoverageNotesFile =
7490 for (
int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
7491 llvm::MDNode *CU = CUNode->getOperand(i);
7492 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
7493 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
7514 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
7516 for (
auto RefExpr :
D->varlist()) {
7517 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
7519 VD->getAnyInitializer() &&
7520 !VD->getAnyInitializer()->isConstantInitializer(
getContext(),
7527 VD, Addr, RefExpr->getBeginLoc(), PerformInit))
7528 CXXGlobalInits.push_back(InitFunction);
7533CodeGenModule::CreateMetadataIdentifierImpl(
QualType T, MetadataTypeMap &Map,
7537 FnType->getReturnType(), FnType->getParamTypes(),
7538 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
7540 llvm::Metadata *&InternalId = Map[
T.getCanonicalType()];
7545 std::string OutName;
7546 llvm::raw_string_ostream Out(OutName);
7551 Out <<
".normalized";
7565 return CreateMetadataIdentifierImpl(
T, MetadataIdMap,
"");
7570 return CreateMetadataIdentifierImpl(
T, VirtualMetadataIdMap,
".virtual");
7590 for (
auto &Param : FnType->param_types())
7595 GeneralizedParams, FnType->getExtProtoInfo());
7602 llvm_unreachable(
"Encountered unknown FunctionType");
7607 GeneralizedMetadataIdMap,
".generalized");
7614 return ((LangOpts.
Sanitize.
has(SanitizerKind::CFIVCall) &&
7616 (LangOpts.
Sanitize.
has(SanitizerKind::CFINVCall) &&
7618 (LangOpts.
Sanitize.
has(SanitizerKind::CFIDerivedCast) &&
7620 (LangOpts.
Sanitize.
has(SanitizerKind::CFIUnrelatedCast) &&
7627 llvm::Metadata *MD =
7629 VTable->addTypeMetadata(Offset.getQuantity(), MD);
7631 if (CodeGenOpts.SanitizeCfiCrossDso)
7633 VTable->addTypeMetadata(Offset.getQuantity(),
7634 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
7637 llvm::Metadata *MD = llvm::MDString::get(
getLLVMContext(),
"all-vtables");
7638 VTable->addTypeMetadata(Offset.getQuantity(), MD);
7644 SanStats = std::make_unique<llvm::SanitizerStatReport>(&
getModule());
7654 auto *FTy = llvm::FunctionType::get(SamplerT, {
C->getType()},
false);
7669 bool forPointeeType) {
7680 if (
auto Align = TT->getDecl()->getMaxAlignment()) {
7710 if (
T.getQualifiers().hasUnaligned()) {
7712 }
else if (forPointeeType && !AlignForArray &&
7724 if (
unsigned MaxAlign =
getLangOpts().MaxTypeAlign) {
7737 if (NumAutoVarInit >= StopAfter) {
7740 if (!NumAutoVarInit) {
7743 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
7744 "number of times ftrivial-auto-var-init=%1 gets applied.");
7758 const Decl *
D)
const {
7762 OS << (isa<VarDecl>(
D) ?
".static." :
".intern.");
7764 OS << (isa<VarDecl>(
D) ?
"__static__" :
"__intern__");
7770 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
7774 llvm::MD5::MD5Result
Result;
7775 for (
const auto &Arg : PreprocessorOpts.
Macros)
7776 Hash.update(Arg.first);
7780 llvm::sys::fs::UniqueID ID;
7781 if (llvm::sys::fs::getUniqueID(PLoc.
getFilename(), ID)) {
7783 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
7784 if (
auto EC = llvm::sys::fs::getUniqueID(PLoc.
getFilename(), ID))
7785 SM.getDiagnostics().Report(diag::err_cannot_open_file)
7788 OS << llvm::format(
"%x", ID.getFile()) << llvm::format(
"%x", ID.getDevice())
7789 <<
"_" << llvm::utohexstr(
Result.low(),
true, 8);
7796 assert(DeferredDeclsToEmit.empty() &&
7797 "Should have emitted all decls deferred to emit.");
7798 assert(NewBuilder->DeferredDecls.empty() &&
7799 "Newly created module should not have deferred decls");
7800 NewBuilder->DeferredDecls = std::move(DeferredDecls);
7801 assert(EmittedDeferredDecls.empty() &&
7802 "Still have (unmerged) EmittedDeferredDecls deferred decls");
7804 assert(NewBuilder->DeferredVTables.empty() &&
7805 "Newly created module should not have deferred vtables");
7806 NewBuilder->DeferredVTables = std::move(DeferredVTables);
7808 assert(NewBuilder->MangledDeclNames.empty() &&
7809 "Newly created module should not have mangled decl names");
7810 assert(NewBuilder->Manglings.empty() &&
7811 "Newly created module should not have manglings");
7812 NewBuilder->Manglings = std::move(Manglings);
7814 NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
7816 NewBuilder->TBAA = std::move(TBAA);
7818 NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
Defines the clang::ASTContext interface.
ASTImporterLookupTable & LT
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines the Diagnostic-related interfaces.
Defines enum values for all the target-independent builtin functions.
static 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 void checkAliasForTocData(llvm::GlobalVariable *GVar, const CodeGenOptions &CodeGenOpts, DiagnosticsEngine &Diags, SourceLocation Location)
llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM, GlobalDecl GD)
static bool hasImplicitAttr(const ValueDecl *D)
static void emitUsed(CodeGenModule &CGM, StringRef Name, std::vector< llvm::WeakTrackingVH > &List)
static bool HasNonDllImportDtor(QualType T)
static llvm::Constant * GetPointerConstant(llvm::LLVMContext &Context, const void *Ptr)
Turns the given pointer into a constant.
static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S)
static unsigned TargetMVPriority(const TargetInfo &TI, const CodeGenFunction::MultiVersionResolverOption &RO)
static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO, llvm::Module &M)
static std::string getCPUSpecificMangling(const CodeGenModule &CGM, StringRef Name)
static const char AnnotationSection[]
static bool isUniqueInternalLinkageDecl(GlobalDecl GD, CodeGenModule &CGM)
static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty)
static bool allowKCFIIdentifier(StringRef Name)
static bool shouldAssumeDSOLocal(const CodeGenModule &CGM, llvm::GlobalValue *GV)
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 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 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 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)
void setLLVMVisibility(llvm::GlobalValue &GV, std::optional< llvm::GlobalValue::VisibilityTypes > V)
static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D)
static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD, const NamedDecl *ND, bool OmitMultiVersionMangling=false)
static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND)
static unsigned ArgInfoAddressSpace(LangAS AS)
static void replaceDeclarationWith(llvm::GlobalValue *Old, llvm::Constant *New)
static QualType GeneralizeType(ASTContext &Ctx, QualType Ty)
static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, llvm::Function *NewFn)
ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we implement a function with...
static bool isVarDeclStrongDefinition(const ASTContext &Context, CodeGenModule &CGM, const VarDecl *D, bool NoCommon)
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.
Defines the clang::FileManager interface and associated types.
llvm::DenseSet< const void * > Visited
llvm::MachO::Target Target
llvm::MachO::Record Record
Defines the clang::Module class, which describes a module in the source code.
static const RecordType * getRecordType(QualType QT)
Checks that the passed in QualType either is of RecordType or points to RecordType.
static const NamedDecl * getDefinition(const Decl *D)
Defines the SourceManager interface.
static CharUnits getTypeAllocSize(CodeGenModule &CGM, llvm::Type *type)
Defines version macros and version-related utility functions for Clang.
__device__ __2f16 float __ockl_bool s
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
SourceManager & getSourceManager()
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
@ Strong
Strong definition.
@ WeakUnknown
Weak for now, might become strong later in this TU.
const ProfileList & getProfileList() const
llvm::StringMap< SectionInfo > SectionInfos
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
QualType getRecordType(const RecordDecl *Decl) 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.
FullSourceLoc getFullLoc(SourceLocation Loc) const
const XRayFunctionFilter & getXRayFilter() const
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=RecordDecl::TagKind::Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
StringRef getCUIDHash() const
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
Builtin::Context & BuiltinInfo
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
SelectorTable & Selectors
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
llvm::SetVector< const ValueDecl * > CUDAExternalDeviceDeclODRUsedByHost
Keep track of CUDA/HIP external kernels or device variables ODR-used by host code.
QualType getCFConstantStringType() const
Return the C structure type used to represent constant CFStrings.
const NoSanitizeList & getNoSanitizeList() const
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
CanQualType UnsignedLongTy
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
const clang::PrintingPolicy & getPrintingPolicy() const
CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const
Return the alignment in characters that should be given to a global variable with type T.
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
QualType getObjCIdType() const
Represents the Objective-CC id type.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
unsigned getTypeAlignIfKnown(QualType T, bool NeedsPreferredAlignment=false) const
Return the alignment of a type, in bits, or 0 if the type is incomplete and we cannot determine the a...
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
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.
unsigned getTargetAddressSpace(LangAS AS) const
QualType getWideCharType() const
Return the type of wide characters.
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
Module * getCurrentNamedModule() const
Get module under construction, nullptr if this is not a C++20 module.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Attr - This represents one attribute.
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
bool isLibFunction(unsigned ID) const
Return true if this is a builtin for a libc/libm function, with a "__builtin_" prefix (e....
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Represents a base class of a C++ class.
Represents binding an expression to a temporary.
Represents a call to a C++ constructor.
Represents a C++ base or member initializer.
Expr * getInit() const
Get the initializer.
Represents a delete expression for memory deallocation and destructor calls, e.g.
Represents a C++ destructor within a class.
Represents a call to a member function that may be written either with member call syntax (e....
Represents a static or instance method of a struct/union/class.
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Represents a C++ struct/union/class.
bool hasMutableFields() const
Determine whether this class, or any of its class subobjects, contains a mutable field.
unsigned getNumBases() const
Retrieves the number of base classes of this class.
bool hasDefinition() const
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
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 RecordCommandLine
The string containing the commandline for the llvm.commandline metadata, if non-empty.
std::string FloatABI
The ABI to use for passing floating point arguments.
llvm::Reloc::Model RelocationModel
The name of the relocation model to use.
std::string CoverageNotesFile
The filename with path we use for coverage notes files.
std::string ProfileInstrumentUsePath
Name of the profile file to use as input for -fprofile-instr-use.
std::string MemoryProfileOutput
Name of the profile file to use as output for with -fmemory-profile.
std::vector< std::string > TocDataVarsUserSpecified
List of global variables explicitly specified by the user as toc-data.
std::string CoverageDataFile
The filename with path we use for coverage data files.
PointerAuthOptions PointerAuth
Configuration for pointer-signing.
llvm::DenormalMode FP32DenormalMode
The floating-point denormal mode to use, for float.
SanitizerSet SanitizeTrap
Set of sanitizer checks that trap rather than diagnose.
std::string ProfileRemappingFile
Name of the profile remapping file to apply to the profile data supplied by -fprofile-sample-use or -...
bool hasProfileClangUse() const
Check if Clang profile use is on.
std::string SymbolPartition
The name of the partition that symbols are assigned to, specified with -fsymbol-partition (see https:...
ABIInfo - Target specific hooks for defining how a type should be passed or returned from functions.
virtual void appendAttributeMangling(TargetAttr *Attr, raw_ostream &Out) const
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
virtual void handleVarRegistration(const VarDecl *VD, llvm::GlobalVariable &Var)=0
Check whether a variable is a device variable and register it if true.
virtual llvm::GlobalValue * getKernelHandle(llvm::Function *Stub, GlobalDecl GD)=0
Get kernel handle by stub function.
virtual void internalizeDeviceSideVar(const VarDecl *D, llvm::GlobalValue::LinkageTypes &Linkage)=0
Adjust linkage of shadow variables in host compilation.
Implements C++ ABI-specific code generation functions.
virtual void EmitCXXConstructors(const CXXConstructorDecl *D)=0
Emit constructor variants required by this ABI.
virtual llvm::Constant * getAddrOfRTTIDescriptor(QualType Ty)=0
virtual void EmitCXXDestructors(const CXXDestructorDecl *D)=0
Emit destructor variants required by this ABI.
virtual void setCXXDestructorDLLStorage(llvm::GlobalValue *GV, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
virtual llvm::GlobalValue::LinkageTypes getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
MangleContext & getMangleContext()
Gets the mangle context.
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
void 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 addBuffer(const HLSLBufferDecl *D)
llvm::Type * getSamplerType(const Type *T)
void emitDeferredTargetDecls() const
Emit deferred declare target variables marked for deferred emission.
virtual void emitDeclareTargetFunction(const FunctionDecl *FD, llvm::GlobalValue *GV)
Emit code for handling declare target functions in the runtime.
virtual ConstantAddress getAddrOfDeclareTargetVar(const VarDecl *VD)
Returns the address of the variable marked as declare target with link clause OR as declare target wi...
bool hasRequiresUnifiedSharedMemory() const
Return whether the unified_shared_memory has been specified.
virtual void emitDeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn)
Marks function Fn with properly mangled versions of vector functions.
virtual void registerTargetGlobalVariable(const VarDecl *VD, llvm::Constant *Addr)
Checks if the provided global decl GD is a declare target variable and registers it when emitting cod...
Class supports emissionof SIMD-only code.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, ObjCMethodDecl *MD, bool ctor)
void GenerateObjCMethod(const ObjCMethodDecl *OMD)
void EmitCfiCheckStub()
Emit a stub for the cross-DSO CFI check function.
void EmitCfiCheckFail()
Emit a cross-DSO CFI failure handling function.
bool isTrivialInitializer(const Expr *Init)
Determine whether the given initializer is trivial in the sense that it requires no code to be genera...
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.
void GenerateObjCGetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCGetter - Synthesize an Objective-C property getter function.
llvm::LLVMContext & getLLVMContext()
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
This class organizes the cross-function state that is used while generating LLVM code.
StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD)
ConstantAddress GetAddrOfMSGuidDecl(const MSGuidDecl *GD)
Get the address of a GUID.
void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const
Set visibility, dllimport/dllexport and dso_local.
void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD)
Create and attach type metadata for the given vtable.
void UpdateCompletedType(const TagDecl *TD)
llvm::MDNode * getTBAAAccessTagInfo(TBAAAccessInfo Info)
getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
llvm::GlobalVariable::ThreadLocalMode GetDefaultLLVMTLSModel() const
Get LLVM TLS mode from CodeGenOptions.
void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F, const CGFunctionInfo &FI)
Set the attributes on the LLVM function for the given decl and function info.
void setDSOLocal(llvm::GlobalValue *GV) const
llvm::MDNode * getTBAAStructInfo(QualType QTy)
CGHLSLRuntime & getHLSLRuntime()
Return a reference to the configured HLSL runtime.
llvm::Constant * EmitAnnotationArgs(const AnnotateAttr *Attr)
Emit additional args of the annotation.
llvm::Module & getModule() const
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
CGDebugInfo * getModuleDebugInfo()
bool NeedAllVtablesTypeId() const
Returns whether this module needs the "all-vtables" type identifier.
void addCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
CodeGenVTables & getVTables()
llvm::ConstantInt * CreateCrossDsoCfiTypeId(llvm::Metadata *MD)
Generate a cross-DSO type identifier for MD.
CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const
Return the store size, in character units, of the given LLVM type.
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
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
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.
llvm::GlobalValue::LinkageTypes getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage)
Returns LLVM linkage for a declarator.
TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, TBAAAccessInfo SrcInfo)
mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the purposes of memory transfer call...
const LangOptions & getLangOpts() const
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
llvm::Constant * EmitAnnotationLineNo(SourceLocation L)
Emit the annotation line number.
QualType getObjCFastEnumerationStateType()
Retrieve the record type that describes the state of an Objective-C fast enumeration loop (for....
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
CodeGenTypes & getTypes()
bool shouldMapVisibilityToDLLExport(const NamedDecl *D) const
CGOpenCLRuntime & getOpenCLRuntime()
Return a reference to the configured OpenCL runtime.
const std::string & getModuleNameHash() const
const TargetInfo & getTarget() const
bool shouldEmitRTTI(bool ForEH=false)
void EmitGlobal(GlobalDecl D)
Emit code for a single global function or var decl.
llvm::Metadata * CreateMetadataIdentifierForType(QualType T)
Create a metadata identifier for the given type.
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
void AppendLinkerOptions(StringRef Opts)
Appends Opts to the "llvm.linker.options" metadata value.
void EmitExternalDeclaration(const DeclaratorDecl *D)
void AddDependentLib(StringRef Lib)
Appends a dependent lib to the appropriate metadata value.
void Release()
Finalize LLVM code generation.
ProfileList::ExclusionType isFunctionBlockedByProfileList(llvm::Function *Fn, SourceLocation Loc) const
llvm::MDNode * getTBAABaseTypeInfo(QualType QTy)
getTBAABaseTypeInfo - Get metadata that describes the given base access type.
bool lookupRepresentativeDecl(StringRef MangledName, GlobalDecl &Result) const
void EmitOMPAllocateDecl(const OMPAllocateDecl *D)
Emit a code for the allocate directive.
void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const
Set the visibility for the given LLVM GlobalValue.
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD)
Returns LLVM linkage for a declarator.
bool HasHiddenLTOVisibility(const CXXRecordDecl *RD)
Returns whether the given record has hidden LTO visibility and therefore may participate in (single-m...
const llvm::DataLayout & getDataLayout() const
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can't be done.
TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType)
getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an access to a virtual table poi...
CGCXXABI & getCXXABI() const
ConstantAddress GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
llvm::Constant * GetFunctionStart(const ValueDecl *Decl)
static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V)
void EmitTentativeDefinition(const VarDecl *D)
void EmitDeferredUnusedCoverageMappings()
Emit all the deferred coverage mappings for the uninstrumented functions.
void addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, StringRef Category=StringRef()) const
Imbue XRay attributes to a function, applying the always/never attribute lists in the process.
llvm::Metadata * CreateMetadataIdentifierGeneralized(QualType T)
Create a metadata identifier for the generalization of the given type.
void EmitGlobalAnnotations()
Emit all the global annotations.
CharUnits getClassPointerAlignment(const CXXRecordDecl *CD)
Returns the assumed alignment of an opaque pointer to the given class.
const llvm::Triple & getTriple() const
SmallVector< const CXXRecordDecl *, 0 > getMostBaseClasses(const CXXRecordDecl *RD)
Return a vector of most-base classes for RD.
void AddDeferredUnusedCoverageMapping(Decl *D)
Stored a deferred empty coverage mapping for an unused and thus uninstrumented top level declaration.
void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV)
If the declaration has internal linkage but is inside an extern "C" linkage specification,...
void DecorateInstructionWithTBAA(llvm::Instruction *Inst, TBAAAccessInfo TBAAInfo)
DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD)
void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535, bool IsDtorAttrFunc=false)
AddGlobalDtor - Add a function to the list that will be called when the module is unloaded.
llvm::Constant * CreateRuntimeVariable(llvm::Type *Ty, StringRef Name)
Create a new runtime global variable with the specified type and name.
void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info, CGCalleeInfo CalleeInfo, llvm::AttributeList &Attrs, unsigned &CallingConv, bool AttrOnCallSite, bool IsThunk)
Get the LLVM attributes and calling convention to use for a particular function type.
llvm::Constant * GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, LangAS AddrSpace, const VarDecl *D, ForDefinition_t IsForDefinition=NotForDefinition)
GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, create and return an llvm...
TBAAAccessInfo getTBAAAccessInfo(QualType AccessType)
getTBAAAccessInfo - Get TBAA information that describes an access to an object of the given type.
void setFunctionLinkage(GlobalDecl GD, llvm::Function *F)
llvm::Constant * GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition=NotForDefinition)
ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal)
Return a pointer to a constant CFString object for the given string.
ProfileList::ExclusionType isFunctionBlockedFromProfileInstr(llvm::Function *Fn, SourceLocation Loc) const
void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV)
Add global annotations that are set on D, for the global GV.
void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const
Set the TLS mode for the given LLVM GlobalValue for the thread-local variable declaration D.
ConstantAddress GetAddrOfConstantStringFromLiteral(const StringLiteral *S, StringRef Name=".str")
Return a pointer to a constant array for the given string literal.
ASTContext & getContext() const
ConstantAddress GetAddrOfTemplateParamObject(const TemplateParamObjectDecl *TPO)
Get the address of a template parameter object.
void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D)
Emit a code for threadprivate directive.
ConstantAddress GetAddrOfUnnamedGlobalConstantDecl(const UnnamedGlobalConstantDecl *GCD)
Get the address of a UnnamedGlobalConstant.
TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, TBAAAccessInfo TargetInfo)
mergeTBAAInfoForCast - Get merged TBAA information for the purposes of type casts.
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
llvm::SanitizerStatReport & getSanStats()
llvm::Constant * EmitAnnotationString(StringRef Str)
Emit an annotation string.
void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare mapper construct.
bool supportsCOMDAT() const
void RefreshTypeCacheForClass(const CXXRecordDecl *Class)
llvm::MDNode * getTBAATypeInfo(QualType QTy)
getTBAATypeInfo - Get metadata used to describe accesses to objects of the given type.
void EmitOMPRequiresDecl(const OMPRequiresDecl *D)
Emit a code for requires directive.
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD)
Tell the consumer that this variable has been instantiated.
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
llvm::Constant * GetConstantArrayFromStringLiteral(const StringLiteral *E)
Return a constant array for the given string.
void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV)
Set attributes which are common to any form of a global definition (alias, Objective-C method,...
std::optional< CharUnits > getOMPAllocateAlignment(const VarDecl *VD)
Return the alignment specified in an allocate directive, if present.
llvm::GlobalVariable * CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, llvm::Align Alignment)
Will return a global variable of the given type.
CharUnits getNaturalPointeeTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, TBAAAccessInfo InfoB)
mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the purposes of conditional ope...
llvm::LLVMContext & getLLVMContext()
llvm::GlobalValue * GetGlobalValue(StringRef Ref)
void GenKernelArgMetadata(llvm::Function *FN, const FunctionDecl *FD=nullptr, CodeGenFunction *CGF=nullptr)
OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument information in the program executab...
void CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, llvm::Function *F)
Create and attach type metadata to the given function.
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.
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 addReplacement(StringRef Name, llvm::Constant *C)
llvm::ConstantInt * CreateKCFITypeId(QualType T)
Generate a KCFI type identifier for T.
llvm::Constant * getConstantSignedPointer(llvm::Constant *Pointer, const PointerAuthSchema &Schema, llvm::Constant *StorageAddress, GlobalDecl SchemaDecl, QualType SchemaType)
Sign a constant pointer using the given scheme, producing a constant with the same IR type.
void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535, unsigned LexOrder=~0U, llvm::Constant *AssociatedData=nullptr)
AddGlobalCtor - Add a function to the list that will be called before main() runs.
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
llvm::Metadata * CreateMetadataIdentifierForVirtualMemPtrType(QualType T)
Create a metadata identifier that is intended to be used to check virtual calls via a member function...
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys=std::nullopt)
ConstantAddress GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *)
Return a pointer to a constant array for the given ObjCEncodeExpr node.
const GlobalDecl getMangledNameDecl(StringRef)
void ClearUnusedCoverageMapping(const Decl *D)
Remove the deferred empty coverage mapping as this declaration is actually instrumented.
void EmitTopLevelDecl(Decl *D)
Emit code for a single top level declaration.
llvm::Constant * EmitAnnotationUnit(SourceLocation Loc)
Emit the annotation's translation unit.
ConstantAddress GetAddrOfConstantCString(const std::string &Str, const char *GlobalName=nullptr)
Returns a pointer to a character array containing the literal and a terminating '\0' character.
void printPostfixForExternalizedDecl(llvm::raw_ostream &OS, const Decl *D) const
Print the postfix for externalized static variable or kernels for single source offloading languages ...
void moveLazyEmissionStates(CodeGenModule *NewBuilder)
Move some lazily-emitted states to the NewBuilder.
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
void finalizeKCFITypes()
Emit KCFI type identifier constants and remove unused identifiers.
void setValueProfilingFlag(llvm::Module &M)
void setProfileVersion(llvm::Module &M)
void emitEmptyCounterMapping(const Decl *D, StringRef FuncName, llvm::GlobalValue::LinkageTypes Linkage)
Emit a coverage mapping range with a counter zero for an unused declaration.
CodeGenTBAA - This class organizes the cross-module state that is used while lowering AST types to LL...
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.
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.
void RefreshTypeCacheForClass(const CXXRecordDecl *RD)
Remove stale types from the type cache when an inheritance model gets assigned to a class.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
void UpdateCompletedType(const TagDecl *TD)
UpdateCompletedType - When we find the full definition for a TagDecl, replace the 'opaque' type we pr...
const CGFunctionInfo & arrangeGlobalDeclaration(GlobalDecl GD)
void GenerateClassData(const CXXRecordDecl *RD)
GenerateClassData - Generate all the class data required to be generated upon definition of a KeyFunc...
void EmitThunks(GlobalDecl GD)
EmitThunks - Emit the associated thunks for the given global decl.
A specialization of Address that requires the address to be an LLVM Constant.
static ConstantAddress invalid()
llvm::Constant * tryEmitForInitializer(const VarDecl &D)
Try to emit the initiaizer of the given declaration as an abstract constant.
void finalize(llvm::GlobalVariable *global)
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded.
The standard implementation of ConstantInitBuilder used in Clang.
Organizes the cross-function state that is used while generating code coverage mapping data.
FunctionArgList - Type for representing both the decl and type of parameters to a function.
bool hasDiagnostics()
Whether or not the stats we've gathered indicate any potential problems.
void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile)
Report potential problems we've found to Diags.
TargetCodeGenInfo - This class organizes various target-specific codegeneration issues,...
virtual void getDependentLibraryOption(llvm::StringRef Lib, llvm::SmallString< 24 > &Opt) const
Gets the linker options necessary to link a dependent library on this platform.
Address performAddrSpaceCast(CodeGen::CodeGenFunction &CGF, Address Addr, LangAS SrcAddr, LangAS DestAddr, llvm::Type *DestTy, bool IsNonNull=false) const
const T & getABIInfo() const
virtual LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, const VarDecl *D) const
Get target favored AST address space of a global variable for languages other than OpenCL and CUDA.
virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const
setTargetAttributes - Provides a convenient hook to handle extra target-specific attributes for the g...
virtual LangAS getASTAllocaAddressSpace() const
Get the AST address space for alloca.
virtual void emitTargetMetadata(CodeGen::CodeGenModule &CGM, const llvm::MapVector< GlobalDecl, StringRef > &MangledDeclNames) const
emitTargetMetadata - Provides a convenient hook to handle extra target-specific metadata for the give...
virtual void emitTargetGlobals(CodeGen::CodeGenModule &CGM) const
Provides a convenient hook to handle extra target-specific globals.
virtual void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, llvm::SmallString< 32 > &Opt) const
Gets the linker options necessary to detect object file mismatches on this platform.
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Represents the canonical version of C arrays with a specified constant size.
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Stores additional source code information like skipped ranges which is required by the coverage mappi...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
A reference to a declared variable, function, enum, etc.
Decl - This represents one declaration (or definition), e.g.
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
SourceLocation getEndLoc() const LLVM_READONLY
ASTContext & getASTContext() const LLVM_READONLY
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
const Attr * getDefiningAttr() const
Return this declaration's defining attribute if it has one.
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
SourceLocation getLocation() const
SourceLocation getBeginLoc() const LLVM_READONLY
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Represents a ValueDecl that came out of a declarator.
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
This represents one expression.
Represents a member of a struct/union/class.
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
StringRef getName() const
The name of this FileEntry.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Represents a function declaration or definition.
bool isTargetClonesMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target-clones functional...
bool isMultiVersion() const
True if this function is considered a multiversioned function.
const ParmVarDecl * getParamDecl(unsigned i) const
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
bool isImmediateFunction() const
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
bool isInlineBuiltinDeclaration() const
Determine if this function provides an inline implementation of a builtin.
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
FunctionDecl * getDefinition()
Get the definition for this declaration.
bool isTargetVersionMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target-version functiona...
bool isReplaceableGlobalAllocationFunction(std::optional< unsigned > *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
bool doesDeclarationForceExternallyVisibleDefinition() const
For a function declaration in C or C++, determine whether this declaration causes the definition to b...
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const override
Appends a human-readable name for this declaration into the given stream.
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Represents a prototype with parameter type info, e.g.
FunctionType - C99 6.7.5.3 - Function Declarators.
CallingConv getCallConv() const
GlobalDecl - represents a global declaration.
GlobalDecl getWithMultiVersionIndex(unsigned Index)
CXXCtorType getCtorType() const
GlobalDecl getWithKernelReferenceKind(KernelReferenceKind Kind)
GlobalDecl getCanonicalDecl() const
KernelReferenceKind getKernelReferenceKind() const
GlobalDecl getWithDecl(const Decl *D)
unsigned getMultiVersionIndex() const
CXXDtorType getDtorType() const
const Decl * getDecl() const
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
@ None
No signing for any function.
@ Swift5_0
Interoperability with the Swift 5.0 runtime.
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
VisibilityFromDLLStorageClassKinds
@ Keep
Keep the IR-gen assigned visibility.
@ Protected
Override the IR-gen assigned visibility with protected visibility.
@ Default
Override the IR-gen assigned visibility with default visibility.
@ Hidden
Override the IR-gen assigned visibility with hidden visibility.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
bool isSignReturnAddressWithAKey() const
Check if return address signing uses AKey.
clang::ObjCRuntime ObjCRuntime
CoreFoundationABI CFRuntime
SanitizerSet Sanitize
Set of enabled sanitizers.
bool hasSignReturnAddress() const
Check if return address signing is enabled.
std::map< std::string, std::string, std::greater< std::string > > MacroPrefixMap
A prefix map for FILE, BASE_FILE and __builtin_FILE().
LangStandard::Kind LangStd
The used language standard.
bool isSignReturnAddressScopeAll() const
Check if leaf functions are also signed.
std::string CUID
The user provided compilation unit ID, if non-empty.
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Visibility getVisibility() const
void setLinkage(Linkage L)
Linkage getLinkage() const
bool isVisibilityExplicit() const
Represents a linkage specification.
LinkageSpecLanguageIDs getLanguage() const
Return the language specified by this linkage specification.
Parts getParts() const
Get the decomposed parts of this declaration.
APValue & getAsAPValue() const
Get the value of this MSGuidDecl as an APValue.
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
void mangleBlock(const DeclContext *DC, const BlockDecl *BD, raw_ostream &Out)
void mangleCtorBlock(const CXXConstructorDecl *CD, CXXCtorType CT, const BlockDecl *BD, raw_ostream &Out)
void mangleGlobalBlock(const BlockDecl *BD, const NamedDecl *ID, raw_ostream &Out)
bool shouldMangleDeclName(const NamedDecl *D)
void mangleName(GlobalDecl GD, raw_ostream &)
virtual void mangleCanonicalTypeName(QualType T, raw_ostream &, bool NormalizeIntegers=false)=0
Generates a unique string for an externally visible type for use with TBAA or type uniquing.
virtual void mangleStringLiteral(const StringLiteral *SL, raw_ostream &)=0
ManglerKind getKind() const
virtual void needsUniqueInternalLinkageNames()
virtual void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber, raw_ostream &)=0
void mangleDtorBlock(const CXXDestructorDecl *CD, CXXDtorType DT, const BlockDecl *BD, raw_ostream &Out)
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Describes a module or submodule.
bool isInterfaceOrPartition() const
bool isNamedModuleUnit() const
Is this a C++20 named module unit.
Module * Parent
The parent of this module.
Module * getPrivateModuleFragment() const
Get the Private Module Fragment (sub-module) for this module, it there is one.
llvm::SmallSetVector< Module *, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Module * getGlobalModuleFragment() const
Get the Global Module Fragment (sub-module) for this module, it there is one.
llvm::iterator_range< submodule_iterator > submodules()
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used.
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
bool UseExportAsModuleLinkName
Autolinking uses the framework name for linking purposes when this is false and the export_as name ot...
This represents a decl that may have a name.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
LinkageInfo getLinkageAndVisibility() const
Determines the linkage and visibility of this entity.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Represent a C++ namespace.
This represents '#pragma omp threadprivate ...' directive.
ObjCEncodeExpr, used for @encode in Objective-C.
const ObjCInterfaceDecl * getClassInterface() const
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Represents an ObjC class declaration.
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
ObjCIvarDecl - Represents an ObjC instance variable.
ObjCIvarDecl * getNextIvar()
ObjCMethodDecl - Represents an instance or class method declaration.
static ObjCMethodDecl * Create(ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc, Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo, DeclContext *contextDecl, bool isInstance=true, bool isVariadic=false, bool isPropertyAccessor=false, bool isSynthesizedAccessorStub=false, bool isImplicitlyDeclared=false, bool isDefined=false, ObjCImplementationControl impControl=ObjCImplementationControl::None, bool HasRelatedResultType=false)
Represents one property declaration in an Objective-C interface.
ObjCMethodDecl * getGetterMethodDecl() const
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
The basic abstraction for the target Objective-C runtime.
bool hasUnwindExceptions() const
Does this runtime use zero-cost exceptions?
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
@ MacOSX
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
@ FragileMacOSX
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
@ GNUstep
'gnustep' is the modern non-fragile GNUstep runtime.
@ ObjFW
'objfw' is the Objective-C runtime included in ObjFW
@ iOS
'ios' is the Apple-provided NeXT-derived runtime on iOS or the iOS simulator; it is always non-fragil...
@ GCC
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI
@ WatchOS
'watchos' is a variant of iOS for Apple's watchOS.
Represents a parameter to a function.
ParsedAttr - Represents a syntactic attribute.
bool isAddressDiscriminated() const
uint16_t getConstantDiscrimination() const
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::optional< uint64_t > SourceDateEpoch
If set, the UNIX timestamp specified by SOURCE_DATE_EPOCH.
std::vector< std::pair< std::string, bool > > Macros
Represents an unpacked "presumed" location which can be presented to the user.
const char * getFilename() const
Return the presumed filename of this location.
unsigned getLine() const
Return the presumed line number of this location.
PrettyStackTraceDecl - If a crash occurs, indicate that it happened when doing something to a specifi...
std::optional< ExclusionType > isFunctionExcluded(StringRef FunctionName, CodeGenOptions::ProfileInstrKind Kind) const
std::optional< ExclusionType > isLocationExcluded(SourceLocation Loc, CodeGenOptions::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.
ExclusionType getDefault(CodeGenOptions::ProfileInstrKind Kind) const
std::optional< ExclusionType > isFileExcluded(StringRef FileName, CodeGenOptions::ProfileInstrKind Kind) const
A (possibly-)qualified type.
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
LangAS getAddressSpace() const
Return the address space of this type.
QualType getCanonicalType() const
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
QualType withCVRQualifiers(unsigned CVR) const
bool isConstQualified() const
Determine whether this type is const-qualified.
bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Represents a struct/union/class.
field_range fields() const
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Selector getSelector(unsigned NumArgs, const IdentifierInfo **IIV)
Can create any sort of selector.
Smart pointer class that efficiently represents Objective-C method names.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
Stmt - This represents one statement.
StringLiteral - This represents a string literal expression, e.g.
Represents the declaration of a struct/union/class/enum.
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Exposes information about the current target.
TargetOptions & getTargetOpts() const
Retrieve the target options.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
bool isReadOnlyFeature(StringRef Feature) const
Determine whether the given target feature is read only.
virtual unsigned multiVersionSortPriority(StringRef Name) const
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
virtual unsigned multiVersionFeatureCost() const
bool supportsIFunc() const
Identify whether this target supports IFuncs.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
std::string TuneCPU
If given, the name of the target CPU to tune code for.
std::string CPU
If given, the name of the target CPU to generate code for.
@ Hostcall
printf lowering scheme involving hostcalls, currently used by HIP programs by default
A template parameter object.
const APValue & getValue() const
A declaration that models statements at global scope.
The top declaration context.
static DeclContext * castToDeclContext(const TranslationUnitDecl *D)
const Type * getTypeForDecl() const
The base class of the type hierarchy.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
bool isPointerType() const
const T * castAs() const
Member-template castAs<specific type>.
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
bool isObjCObjectPointerType() const
Linkage getLinkage() const
Determine the linkage of this type.
const T * getAs() const
Member-template getAs<specific type>'.
bool isRecordType() const
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
const APValue & getValue() const
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Represents a variable declaration or definition.
TLSKind getTLSKind() const
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
bool hasFlexibleArrayInit(const ASTContext &Ctx) const
Whether this variable has a flexible array member initialized with one or more elements.
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
@ TLS_Dynamic
TLS with a dynamic initializer.
@ DeclarationOnly
This declaration is only a declaration.
@ Definition
This declaration is definitely a definition.
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Defines the clang::TargetInfo interface.
std::unique_ptr< TargetCodeGenInfo > createARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind Kind)
std::unique_ptr< TargetCodeGenInfo > createM68kTargetCodeGenInfo(CodeGenModule &CGM)
@ AttributedType
The l-value was considered opaque, so the alignment was determined from a type, but that type was an ...
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
std::unique_ptr< TargetCodeGenInfo > createBPFTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createMSP430TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel)
std::unique_ptr< TargetCodeGenInfo > createWebAssemblyTargetCodeGenInfo(CodeGenModule &CGM, WebAssemblyABIKind K)
std::unique_ptr< TargetCodeGenInfo > createPPC64_SVR4_TargetCodeGenInfo(CodeGenModule &CGM, PPC64_SVR4_ABIKind Kind, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createMIPSTargetCodeGenInfo(CodeGenModule &CGM, bool IsOS32)
std::unique_ptr< TargetCodeGenInfo > createHexagonTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createNVPTXTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createSystemZTargetCodeGenInfo(CodeGenModule &CGM, bool HasVector, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createWinX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters)
std::unique_ptr< TargetCodeGenInfo > createAIXTargetCodeGenInfo(CodeGenModule &CGM, bool Is64Bit)
std::unique_ptr< TargetCodeGenInfo > createAMDGPUTargetCodeGenInfo(CodeGenModule &CGM)
CGObjCRuntime * CreateMacObjCRuntime(CodeGenModule &CGM)
X86AVXABILevel
The AVX ABI level for X86 targets.
std::unique_ptr< TargetCodeGenInfo > createTCETargetCodeGenInfo(CodeGenModule &CGM)
CGObjCRuntime * CreateGNUObjCRuntime(CodeGenModule &CGM)
Creates an instance of an Objective-C runtime class.
std::unique_ptr< TargetCodeGenInfo > createWindowsARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind K)
std::unique_ptr< TargetCodeGenInfo > createAVRTargetCodeGenInfo(CodeGenModule &CGM, unsigned NPR, unsigned NRR)
std::unique_ptr< TargetCodeGenInfo > 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 > 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 > createPNaClTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createLanaiTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createPPC32TargetCodeGenInfo(CodeGenModule &CGM, bool SoftFloatABI)
CGCUDARuntime * CreateNVCUDARuntime(CodeGenModule &CGM)
Creates an instance of a CUDA runtime class.
std::unique_ptr< TargetCodeGenInfo > createLoongArchTargetCodeGenInfo(CodeGenModule &CGM, unsigned GRLen, unsigned FLen)
std::unique_ptr< TargetCodeGenInfo > createPPC64TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createWinX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel)
std::unique_ptr< TargetCodeGenInfo > createXCoreTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createCSKYTargetCodeGenInfo(CodeGenModule &CGM, unsigned FLen)
llvm::PointerUnion< const Decl *, const Expr * > DeclTy
The JSON file list parser is used to communicate input to InstallAPI.
CXXCtorType
C++ constructor types.
@ Ctor_Base
Base object ctor.
@ Ctor_Complete
Complete object ctor.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, DiagnosticsEngine &Diags)
GVALinkage
A more specific kind of linkage than enum Linkage.
@ GVA_AvailableExternally
std::string getClangVendor()
Retrieves the Clang vendor tag.
@ ICIS_NoInit
No in-class initializer.
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ Asm
Assembly: we accept this only so that we can preprocess it.
@ SD_Thread
Thread storage duration.
@ SD_Static
Static storage duration.
bool isLambdaCallOperator(const CXXMethodDecl *MD)
@ Result
The result type of a method or function.
StringRef languageToString(Language L)
@ Dtor_Base
Base object dtor.
@ Dtor_Complete
Complete object dtor.
LangAS
Defines the address space values used by the address space qualifier of QualType.
@ FirstTargetAddressSpace
const FunctionProtoType * T
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
@ 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
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
llvm::CallingConv::ID RuntimeCC
llvm::IntegerType * Int64Ty
llvm::PointerType * ConstGlobalsPtrTy
void* in the address space for constant globals
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::IntegerType * CharTy
char
LangAS ASTAllocaAddressSpace
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
unsigned char IntAlignInBytes
llvm::Type * HalfTy
half, bfloat, float, double
unsigned char SizeSizeInBytes
llvm::CallingConv::ID getRuntimeCC() const
llvm::IntegerType * SizeTy
llvm::PointerType * GlobalsInt8PtrTy
llvm::IntegerType * Int32Ty
llvm::IntegerType * IntPtrTy
llvm::IntegerType * IntTy
int
llvm::IntegerType * Int16Ty
unsigned char PointerAlignInBytes
llvm::PointerType * Int8PtrTy
CharUnits getPointerAlign() const
llvm::PointerType * AllocaInt8PtrTy
EvalResult is a struct with detailed info about an evaluated expression.
APValue Val
Val - This is the value the expression can be folded to.
bool hasSideEffects() const
static const LangStandard & getLangStandardForKind(Kind K)
Parts of a decomposed MSGuidDecl.
uint16_t Part2
...-89ab-...
uint32_t Part1
{01234567-...
uint16_t Part3
...-cdef-...
uint8_t Part4And5[8]
...-0123-456789abcdef}
A library or framework to link against when an entity from this module is used.
Contains information gathered from parsing the contents of TargetAttr.
PointerAuthSchema InitFiniPointers
The ABI for function addresses in .init_array and .fini_array.
Describes how types, statements, expressions, and declarations should be printed.
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.