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/Frontend/OpenMP/OMPIRBuilder.h"
57#include "llvm/IR/AttributeMask.h"
58#include "llvm/IR/CallingConv.h"
59#include "llvm/IR/DataLayout.h"
60#include "llvm/IR/Intrinsics.h"
61#include "llvm/IR/LLVMContext.h"
62#include "llvm/IR/Module.h"
63#include "llvm/IR/ProfileSummary.h"
64#include "llvm/ProfileData/InstrProfReader.h"
65#include "llvm/ProfileData/SampleProf.h"
66#include "llvm/Support/CRC.h"
67#include "llvm/Support/CodeGen.h"
68#include "llvm/Support/CommandLine.h"
69#include "llvm/Support/ConvertUTF.h"
70#include "llvm/Support/ErrorHandling.h"
71#include "llvm/Support/TimeProfiler.h"
72#include "llvm/Support/xxhash.h"
73#include "llvm/TargetParser/RISCVISAInfo.h"
74#include "llvm/TargetParser/Triple.h"
75#include "llvm/TargetParser/X86TargetParser.h"
79using namespace CodeGen;
82 "limited-coverage-experimental", llvm::cl::Hidden,
83 llvm::cl::desc(
"Emit limited coverage mapping information (experimental)"));
89 case TargetCXXABI::AppleARM64:
90 case TargetCXXABI::Fuchsia:
91 case TargetCXXABI::GenericAArch64:
92 case TargetCXXABI::GenericARM:
93 case TargetCXXABI::iOS:
94 case TargetCXXABI::WatchOS:
95 case TargetCXXABI::GenericMIPS:
96 case TargetCXXABI::GenericItanium:
97 case TargetCXXABI::WebAssembly:
98 case TargetCXXABI::XL:
100 case TargetCXXABI::Microsoft:
104 llvm_unreachable(
"invalid C++ ABI kind");
107static std::unique_ptr<TargetCodeGenInfo>
113 switch (Triple.getArch()) {
117 case llvm::Triple::le32:
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;
154 case llvm::Triple::wasm32:
155 case llvm::Triple::wasm64: {
157 if (
Target.getABI() ==
"experimental-mv")
158 Kind = WebAssemblyABIKind::ExperimentalMV;
162 case llvm::Triple::arm:
163 case llvm::Triple::armeb:
164 case llvm::Triple::thumb:
165 case llvm::Triple::thumbeb: {
166 if (Triple.getOS() == llvm::Triple::Win32)
170 StringRef ABIStr =
Target.getABI();
171 if (ABIStr ==
"apcs-gnu")
172 Kind = ARMABIKind::APCS;
173 else if (ABIStr ==
"aapcs16")
174 Kind = ARMABIKind::AAPCS16_VFP;
175 else if (CodeGenOpts.
FloatABI ==
"hard" ||
177 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
178 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
179 Triple.getEnvironment() == llvm::Triple::EABIHF)))
180 Kind = ARMABIKind::AAPCS_VFP;
185 case llvm::Triple::ppc: {
186 if (Triple.isOSAIX())
193 case llvm::Triple::ppcle: {
194 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
197 case llvm::Triple::ppc64:
198 if (Triple.isOSAIX())
201 if (Triple.isOSBinFormatELF()) {
203 if (
Target.getABI() ==
"elfv2")
204 Kind = PPC64_SVR4_ABIKind::ELFv2;
205 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
210 case llvm::Triple::ppc64le: {
211 assert(Triple.isOSBinFormatELF() &&
"PPC64 LE non-ELF not supported!");
213 if (
Target.getABI() ==
"elfv1")
214 Kind = PPC64_SVR4_ABIKind::ELFv1;
215 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
220 case llvm::Triple::nvptx:
221 case llvm::Triple::nvptx64:
224 case llvm::Triple::msp430:
227 case llvm::Triple::riscv32:
228 case llvm::Triple::riscv64: {
229 StringRef ABIStr =
Target.getABI();
230 unsigned XLen =
Target.getPointerWidth(LangAS::Default);
231 unsigned ABIFLen = 0;
232 if (ABIStr.ends_with(
"f"))
234 else if (ABIStr.ends_with(
"d"))
236 bool EABI = ABIStr.ends_with(
"e");
240 case llvm::Triple::systemz: {
241 bool SoftFloat = CodeGenOpts.
FloatABI ==
"soft";
242 bool HasVector = !SoftFloat &&
Target.getABI() ==
"vector";
246 case llvm::Triple::tce:
247 case llvm::Triple::tcele:
250 case llvm::Triple::x86: {
251 bool IsDarwinVectorABI = Triple.isOSDarwin();
252 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
254 if (Triple.getOS() == llvm::Triple::Win32) {
256 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
257 CodeGenOpts.NumRegisterParameters);
260 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
261 CodeGenOpts.NumRegisterParameters, CodeGenOpts.
FloatABI ==
"soft");
264 case llvm::Triple::x86_64: {
265 StringRef ABI =
Target.getABI();
266 X86AVXABILevel AVXLevel = (ABI ==
"avx512" ? X86AVXABILevel::AVX512
267 : ABI ==
"avx" ? X86AVXABILevel::AVX
268 : X86AVXABILevel::None);
270 switch (Triple.getOS()) {
271 case llvm::Triple::Win32:
277 case llvm::Triple::hexagon:
279 case llvm::Triple::lanai:
281 case llvm::Triple::r600:
283 case llvm::Triple::amdgcn:
285 case llvm::Triple::sparc:
287 case llvm::Triple::sparcv9:
289 case llvm::Triple::xcore:
291 case llvm::Triple::arc:
293 case llvm::Triple::spir:
294 case llvm::Triple::spir64:
296 case llvm::Triple::spirv32:
297 case llvm::Triple::spirv64:
299 case llvm::Triple::ve:
301 case llvm::Triple::csky: {
302 bool IsSoftFloat = !
Target.hasFeature(
"hard-float-abi");
304 Target.hasFeature(
"fpuv2_df") ||
Target.hasFeature(
"fpuv3_df");
309 case llvm::Triple::bpfeb:
310 case llvm::Triple::bpfel:
312 case llvm::Triple::loongarch32:
313 case llvm::Triple::loongarch64: {
314 StringRef ABIStr =
Target.getABI();
315 unsigned ABIFRLen = 0;
316 if (ABIStr.ends_with(
"f"))
318 else if (ABIStr.ends_with(
"d"))
321 CGM,
Target.getPointerWidth(LangAS::Default), ABIFRLen);
327 if (!TheTargetCodeGenInfo)
329 return *TheTargetCodeGenInfo;
339 : Context(
C), LangOpts(
C.getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
340 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
342 VMContext(M.getContext()), Types(*this), VTables(*this),
346 llvm::LLVMContext &LLVMContext = M.getContext();
347 VoidTy = llvm::Type::getVoidTy(LLVMContext);
348 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
349 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
350 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
351 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
352 HalfTy = llvm::Type::getHalfTy(LLVMContext);
353 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
354 FloatTy = llvm::Type::getFloatTy(LLVMContext);
355 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
361 C.toCharUnitsFromBits(
C.getTargetInfo().getMaxPointerWidth()).getQuantity();
363 C.toCharUnitsFromBits(
C.getTargetInfo().getIntAlign()).getQuantity();
365 llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getCharWidth());
366 IntTy = llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getIntWidth());
367 IntPtrTy = llvm::IntegerType::get(LLVMContext,
368 C.getTargetInfo().getMaxPointerWidth());
369 Int8PtrTy = llvm::PointerType::get(LLVMContext, 0);
370 const llvm::DataLayout &DL = M.getDataLayout();
372 llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
374 llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
391 createOpenCLRuntime();
393 createOpenMPRuntime();
400 if (LangOpts.
Sanitize.
has(SanitizerKind::Thread) ||
401 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
407 if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
412 Block.GlobalUniqueCount = 0;
414 if (
C.getLangOpts().ObjC)
418 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
425 PGOReader = std::move(ReaderOrErr.get());
430 if (CodeGenOpts.CoverageMapping)
434 if (CodeGenOpts.UniqueInternalLinkageNames &&
435 !
getModule().getSourceFileName().empty()) {
436 std::string Path =
getModule().getSourceFileName();
439 if (Path.rfind(Entry.first, 0) != std::string::npos) {
440 Path = Entry.second + Path.substr(Entry.first.size());
443 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path);
449void CodeGenModule::createObjCRuntime() {
466 llvm_unreachable(
"bad runtime kind");
469void CodeGenModule::createOpenCLRuntime() {
473void CodeGenModule::createOpenMPRuntime() {
477 case llvm::Triple::nvptx:
478 case llvm::Triple::nvptx64:
479 case llvm::Triple::amdgcn:
481 "OpenMP AMDGPU/NVPTX is only prepared to deal with device code.");
485 if (LangOpts.OpenMPSimd)
493void CodeGenModule::createCUDARuntime() {
497void CodeGenModule::createHLSLRuntime() {
502 Replacements[Name] =
C;
505void CodeGenModule::applyReplacements() {
506 for (
auto &I : Replacements) {
507 StringRef MangledName = I.first;
508 llvm::Constant *Replacement = I.second;
512 auto *OldF = cast<llvm::Function>(Entry);
513 auto *NewF = dyn_cast<llvm::Function>(Replacement);
515 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
516 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
518 auto *CE = cast<llvm::ConstantExpr>(Replacement);
519 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
520 CE->getOpcode() == llvm::Instruction::GetElementPtr);
521 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
526 OldF->replaceAllUsesWith(Replacement);
528 NewF->removeFromParent();
529 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
532 OldF->eraseFromParent();
537 GlobalValReplacements.push_back(std::make_pair(GV,
C));
540void CodeGenModule::applyGlobalValReplacements() {
541 for (
auto &I : GlobalValReplacements) {
542 llvm::GlobalValue *GV = I.first;
543 llvm::Constant *
C = I.second;
545 GV->replaceAllUsesWith(
C);
546 GV->eraseFromParent();
553 const llvm::Constant *
C;
554 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
555 C = GA->getAliasee();
556 else if (
auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
557 C = GI->getResolver();
561 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(
C->stripPointerCasts());
565 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
574 bool IsIFunc,
const llvm::GlobalValue *Alias,
const llvm::GlobalValue *&GV,
575 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
579 Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
583 if (GV->hasCommonLinkage()) {
585 if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
586 Diags.
Report(Location, diag::err_alias_to_common);
591 if (GV->isDeclaration()) {
592 Diags.
Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
593 Diags.
Report(Location, diag::note_alias_requires_mangled_name)
594 << IsIFunc << IsIFunc;
597 for (
const auto &[
Decl, Name] : MangledDeclNames) {
598 if (
const auto *ND = dyn_cast<NamedDecl>(
Decl.getDecl())) {
599 if (ND->getName() == GV->getName()) {
600 Diags.
Report(Location, diag::note_alias_mangled_name_alternative)
604 (Twine(IsIFunc ?
"ifunc" :
"alias") +
"(\"" + Name +
"\")")
614 const auto *F = dyn_cast<llvm::Function>(GV);
616 Diags.
Report(Location, diag::err_alias_to_undefined)
617 << IsIFunc << IsIFunc;
621 llvm::FunctionType *FTy = F->getFunctionType();
622 if (!FTy->getReturnType()->isPointerTy()) {
623 Diags.
Report(Location, diag::err_ifunc_resolver_return);
637 if (GVar->hasAttribute(
"toc-data")) {
638 auto GVId = GVar->getName();
641 Diags.
Report(Location, diag::warn_toc_unsupported_type)
642 << GVId <<
"the variable has an alias";
644 llvm::AttributeSet CurrAttributes = GVar->getAttributes();
645 llvm::AttributeSet NewAttributes =
646 CurrAttributes.removeAttribute(GVar->getContext(),
"toc-data");
647 GVar->setAttributes(NewAttributes);
651void CodeGenModule::checkAliases() {
658 const auto *D = cast<ValueDecl>(GD.getDecl());
661 bool IsIFunc = D->hasAttr<IFuncAttr>();
662 if (
const Attr *A = D->getDefiningAttr()) {
663 Location = A->getLocation();
664 Range = A->getRange();
666 llvm_unreachable(
"Not an alias or ifunc?");
670 const llvm::GlobalValue *GV =
nullptr;
672 MangledDeclNames, Range)) {
678 if (
const llvm::GlobalVariable *GVar =
679 dyn_cast<const llvm::GlobalVariable>(GV))
683 llvm::Constant *Aliasee =
684 IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver()
685 : cast<llvm::GlobalAlias>(Alias)->getAliasee();
687 llvm::GlobalValue *AliaseeGV;
688 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
689 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
691 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
693 if (
const SectionAttr *SA = D->getAttr<SectionAttr>()) {
694 StringRef AliasSection = SA->getName();
695 if (AliasSection != AliaseeGV->getSection())
696 Diags.
Report(SA->getLocation(), diag::warn_alias_with_section)
697 << AliasSection << IsIFunc << IsIFunc;
705 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
706 if (GA->isInterposable()) {
707 Diags.
Report(Location, diag::warn_alias_to_weak_alias)
708 << GV->getName() << GA->getName() << IsIFunc;
709 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
710 GA->getAliasee(), Alias->getType());
713 cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee);
715 cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee);
725 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
726 Alias->eraseFromParent();
731 DeferredDeclsToEmit.clear();
732 EmittedDeferredDecls.clear();
733 DeferredAnnotations.clear();
735 OpenMPRuntime->clear();
739 StringRef MainFile) {
742 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
743 if (MainFile.empty())
744 MainFile =
"<stdin>";
745 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
748 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
751 Diags.
Report(diag::warn_profile_data_missing) << Visited << Missing;
755static std::optional<llvm::GlobalValue::VisibilityTypes>
762 return llvm::GlobalValue::DefaultVisibility;
764 return llvm::GlobalValue::HiddenVisibility;
766 return llvm::GlobalValue::ProtectedVisibility;
768 llvm_unreachable(
"unknown option value!");
772 std::optional<llvm::GlobalValue::VisibilityTypes>
V) {
781 GV.setDSOLocal(
false);
782 GV.setVisibility(*
V);
787 if (!LO.VisibilityFromDLLStorageClass)
790 std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
793 std::optional<llvm::GlobalValue::VisibilityTypes>
794 NoDLLStorageClassVisibility =
797 std::optional<llvm::GlobalValue::VisibilityTypes>
798 ExternDeclDLLImportVisibility =
801 std::optional<llvm::GlobalValue::VisibilityTypes>
802 ExternDeclNoDLLStorageClassVisibility =
805 for (llvm::GlobalValue &GV : M.global_values()) {
806 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
809 if (GV.isDeclarationForLinker())
811 llvm::GlobalValue::DLLImportStorageClass
812 ? ExternDeclDLLImportVisibility
813 : ExternDeclNoDLLStorageClassVisibility);
816 llvm::GlobalValue::DLLExportStorageClass
817 ? DLLExportVisibility
818 : NoDLLStorageClassVisibility);
820 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
825 const llvm::Triple &Triple,
827 if (Triple.isAMDGPU() || Triple.isNVPTX())
829 return LangOpts.getStackProtector() == Mode;
835 EmitModuleInitializers(Primary);
837 DeferredDecls.insert(EmittedDeferredDecls.begin(),
838 EmittedDeferredDecls.end());
839 EmittedDeferredDecls.clear();
840 EmitVTablesOpportunistically();
841 applyGlobalValReplacements();
843 emitMultiVersionFunctions();
846 GlobalTopLevelStmtBlockInFlight.first) {
848 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->
getEndLoc());
849 GlobalTopLevelStmtBlockInFlight = {
nullptr,
nullptr};
855 EmitCXXModuleInitFunc(Primary);
857 EmitCXXGlobalInitFunc();
858 EmitCXXGlobalCleanUpFunc();
859 registerGlobalDtorsWithAtExit();
860 EmitCXXThreadLocalInitFunc();
862 if (llvm::Function *ObjCInitFunction =
ObjCRuntime->ModuleInitFunction())
865 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
869 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
870 OpenMPRuntime->clear();
874 PGOReader->getSummary(
false).getMD(VMContext),
875 llvm::ProfileSummary::PSK_Instr);
882 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
883 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
885 EmitStaticExternCAliases();
891 CoverageMapping->emit();
892 if (CodeGenOpts.SanitizeCfiCrossDso) {
898 emitAtAvailableLinkGuard();
905 if (
getTarget().getTargetOpts().CodeObjectVersion !=
906 llvm::CodeObjectVersionKind::COV_None) {
907 getModule().addModuleFlag(llvm::Module::Error,
908 "amdhsa_code_object_version",
909 getTarget().getTargetOpts().CodeObjectVersion);
914 auto *MDStr = llvm::MDString::get(
919 getModule().addModuleFlag(llvm::Module::Error,
"amdgpu_printf_kind",
932 if (
auto *FD = dyn_cast<FunctionDecl>(D))
936 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
940 llvm::ArrayType *ATy = llvm::ArrayType::get(
Int8PtrTy, UsedArray.size());
942 auto *GV =
new llvm::GlobalVariable(
943 getModule(), ATy,
false, llvm::GlobalValue::InternalLinkage,
944 llvm::ConstantArray::get(ATy, UsedArray),
"__clang_gpu_used_external");
947 if (LangOpts.HIP && !
getLangOpts().OffloadingNewDriver) {
950 auto *GV =
new llvm::GlobalVariable(
952 llvm::Constant::getNullValue(
Int8Ty),
960 if (CodeGenOpts.Autolink &&
961 (Context.
getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
962 EmitModuleLinkOptions();
977 if (!ELFDependentLibraries.empty() && !Context.
getLangOpts().CUDAIsDevice) {
978 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.dependent-libraries");
979 for (
auto *MD : ELFDependentLibraries)
985 getModule().addModuleFlag(llvm::Module::Error,
"NumRegisterParameters",
986 CodeGenOpts.NumRegisterParameters);
988 if (CodeGenOpts.DwarfVersion) {
989 getModule().addModuleFlag(llvm::Module::Max,
"Dwarf Version",
990 CodeGenOpts.DwarfVersion);
993 if (CodeGenOpts.Dwarf64)
994 getModule().addModuleFlag(llvm::Module::Max,
"DWARF64", 1);
998 getModule().setSemanticInterposition(
true);
1000 if (CodeGenOpts.EmitCodeView) {
1002 getModule().addModuleFlag(llvm::Module::Warning,
"CodeView", 1);
1004 if (CodeGenOpts.CodeViewGHash) {
1005 getModule().addModuleFlag(llvm::Module::Warning,
"CodeViewGHash", 1);
1007 if (CodeGenOpts.ControlFlowGuard) {
1009 getModule().addModuleFlag(llvm::Module::Warning,
"cfguard", 2);
1010 }
else if (CodeGenOpts.ControlFlowGuardNoChecks) {
1012 getModule().addModuleFlag(llvm::Module::Warning,
"cfguard", 1);
1014 if (CodeGenOpts.EHContGuard) {
1016 getModule().addModuleFlag(llvm::Module::Warning,
"ehcontguard", 1);
1020 getModule().addModuleFlag(llvm::Module::Warning,
"ms-kernel", 1);
1022 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
1027 getModule().addModuleFlag(llvm::Module::Error,
"StrictVTablePointers",1);
1029 llvm::Metadata *Ops[2] = {
1030 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
1031 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1032 llvm::Type::getInt32Ty(VMContext), 1))};
1034 getModule().addModuleFlag(llvm::Module::Require,
1035 "StrictVTablePointersRequirement",
1036 llvm::MDNode::get(VMContext, Ops));
1042 getModule().addModuleFlag(llvm::Module::Warning,
"Debug Info Version",
1043 llvm::DEBUG_METADATA_VERSION);
1048 uint64_t WCharWidth =
1050 getModule().addModuleFlag(llvm::Module::Error,
"wchar_size", WCharWidth);
1053 getModule().addModuleFlag(llvm::Module::Warning,
1054 "zos_product_major_version",
1055 uint32_t(CLANG_VERSION_MAJOR));
1056 getModule().addModuleFlag(llvm::Module::Warning,
1057 "zos_product_minor_version",
1058 uint32_t(CLANG_VERSION_MINOR));
1059 getModule().addModuleFlag(llvm::Module::Warning,
"zos_product_patchlevel",
1060 uint32_t(CLANG_VERSION_PATCHLEVEL));
1062 getModule().addModuleFlag(llvm::Module::Error,
"zos_product_id",
1063 llvm::MDString::get(VMContext, ProductId));
1068 getModule().addModuleFlag(llvm::Module::Error,
"zos_cu_language",
1069 llvm::MDString::get(VMContext, lang_str));
1073 : std::time(
nullptr);
1074 getModule().addModuleFlag(llvm::Module::Max,
"zos_translation_time",
1075 static_cast<uint64_t
>(TT));
1078 getModule().addModuleFlag(llvm::Module::Error,
"zos_le_char_mode",
1079 llvm::MDString::get(VMContext,
"ascii"));
1083 if (
T.isARM() ||
T.isThumb()) {
1085 uint64_t EnumWidth = Context.
getLangOpts().ShortEnums ? 1 : 4;
1086 getModule().addModuleFlag(llvm::Module::Error,
"min_enum_size", EnumWidth);
1090 StringRef ABIStr =
Target.getABI();
1091 llvm::LLVMContext &Ctx = TheModule.getContext();
1092 getModule().addModuleFlag(llvm::Module::Error,
"target-abi",
1093 llvm::MDString::get(Ctx, ABIStr));
1098 const std::vector<std::string> &Features =
1101 llvm::RISCVISAInfo::parseFeatures(
T.isRISCV64() ? 64 : 32, Features);
1102 if (!errorToBool(ParseResult.takeError()))
1104 llvm::Module::AppendUnique,
"riscv-isa",
1106 Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString())));
1109 if (CodeGenOpts.SanitizeCfiCrossDso) {
1111 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
1114 if (CodeGenOpts.WholeProgramVTables) {
1118 getModule().addModuleFlag(llvm::Module::Error,
"Virtual Function Elim",
1119 CodeGenOpts.VirtualFunctionElimination);
1122 if (LangOpts.
Sanitize.
has(SanitizerKind::CFIICall)) {
1123 getModule().addModuleFlag(llvm::Module::Override,
1124 "CFI Canonical Jump Tables",
1125 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1129 getModule().addModuleFlag(llvm::Module::Override,
"kcfi", 1);
1132 if (CodeGenOpts.PatchableFunctionEntryOffset)
1133 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-offset",
1134 CodeGenOpts.PatchableFunctionEntryOffset);
1137 if (CodeGenOpts.CFProtectionReturn &&
1140 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-return",
1144 if (CodeGenOpts.CFProtectionBranch &&
1147 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-branch",
1151 if (CodeGenOpts.FunctionReturnThunks)
1152 getModule().addModuleFlag(llvm::Module::Override,
"function_return_thunk_extern", 1);
1154 if (CodeGenOpts.IndirectBranchCSPrefix)
1155 getModule().addModuleFlag(llvm::Module::Override,
"indirect_branch_cs_prefix", 1);
1167 LangOpts.getSignReturnAddressScope() !=
1169 getModule().addModuleFlag(llvm::Module::Override,
1170 "sign-return-address-buildattr", 1);
1171 if (LangOpts.
Sanitize.
has(SanitizerKind::MemtagStack))
1172 getModule().addModuleFlag(llvm::Module::Override,
1173 "tag-stack-memory-buildattr", 1);
1175 if (
T.isARM() ||
T.isThumb() ||
T.isAArch64()) {
1176 if (LangOpts.BranchTargetEnforcement)
1177 getModule().addModuleFlag(llvm::Module::Min,
"branch-target-enforcement",
1179 if (LangOpts.BranchProtectionPAuthLR)
1180 getModule().addModuleFlag(llvm::Module::Min,
"branch-protection-pauth-lr",
1182 if (LangOpts.GuardedControlStack)
1183 getModule().addModuleFlag(llvm::Module::Min,
"guarded-control-stack", 1);
1185 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address", 1);
1187 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address-all",
1190 getModule().addModuleFlag(llvm::Module::Min,
1191 "sign-return-address-with-bkey", 1);
1194 if (CodeGenOpts.StackClashProtector)
1196 llvm::Module::Override,
"probe-stack",
1197 llvm::MDString::get(TheModule.getContext(),
"inline-asm"));
1199 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
1200 getModule().addModuleFlag(llvm::Module::Min,
"stack-probe-size",
1201 CodeGenOpts.StackProbeSize);
1204 llvm::LLVMContext &Ctx = TheModule.getContext();
1206 llvm::Module::Error,
"MemProfProfileFilename",
1210 if (LangOpts.CUDAIsDevice &&
getTriple().isNVPTX()) {
1214 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
1216 llvm::DenormalMode::IEEE);
1219 if (LangOpts.EHAsynch)
1220 getModule().addModuleFlag(llvm::Module::Warning,
"eh-asynch", 1);
1224 getModule().addModuleFlag(llvm::Module::Max,
"openmp", LangOpts.OpenMP);
1226 getModule().addModuleFlag(llvm::Module::Max,
"openmp-device",
1230 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())) {
1231 EmitOpenCLMetadata();
1239 llvm::Metadata *SPIRVerElts[] = {
1240 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1242 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1243 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
1244 llvm::NamedMDNode *SPIRVerMD =
1245 TheModule.getOrInsertNamedMetadata(
"opencl.spir.version");
1246 llvm::LLVMContext &Ctx = TheModule.getContext();
1247 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
1255 if (uint32_t PLevel = Context.
getLangOpts().PICLevel) {
1256 assert(PLevel < 3 &&
"Invalid PIC Level");
1257 getModule().setPICLevel(
static_cast<llvm::PICLevel::Level
>(PLevel));
1259 getModule().setPIELevel(
static_cast<llvm::PIELevel::Level
>(PLevel));
1263 unsigned CM = llvm::StringSwitch<unsigned>(
getCodeGenOpts().CodeModel)
1264 .Case(
"tiny", llvm::CodeModel::Tiny)
1265 .Case(
"small", llvm::CodeModel::Small)
1266 .Case(
"kernel", llvm::CodeModel::Kernel)
1267 .Case(
"medium", llvm::CodeModel::Medium)
1268 .Case(
"large", llvm::CodeModel::Large)
1271 llvm::CodeModel::Model codeModel =
static_cast<llvm::CodeModel::Model
>(CM);
1274 if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
1276 llvm::Triple::x86_64) {
1282 if (CodeGenOpts.NoPLT)
1285 CodeGenOpts.DirectAccessExternalData !=
1286 getModule().getDirectAccessExternalData()) {
1287 getModule().setDirectAccessExternalData(
1288 CodeGenOpts.DirectAccessExternalData);
1290 if (CodeGenOpts.UnwindTables)
1291 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1293 switch (CodeGenOpts.getFramePointer()) {
1298 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1301 getModule().setFramePointer(llvm::FramePointerKind::All);
1305 SimplifyPersonality();
1318 EmitVersionIdentMetadata();
1321 EmitCommandLineMetadata();
1329 getModule().setStackProtectorGuardSymbol(
1332 getModule().setStackProtectorGuardOffset(
1337 getModule().addModuleFlag(llvm::Module::Override,
"SkipRaxSetup", 1);
1339 getModule().addModuleFlag(llvm::Module::Override,
"RegCallv4", 1);
1341 if (
getContext().getTargetInfo().getMaxTLSAlign())
1342 getModule().addModuleFlag(llvm::Module::Error,
"MaxTLSAlign",
1343 getContext().getTargetInfo().getMaxTLSAlign());
1361void CodeGenModule::EmitOpenCLMetadata() {
1366 llvm::Metadata *OCLVerElts[] = {
1367 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1369 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1370 Int32Ty, (Version % 100) / 10))};
1371 llvm::NamedMDNode *OCLVerMD =
1372 TheModule.getOrInsertNamedMetadata(
"opencl.ocl.version");
1373 llvm::LLVMContext &Ctx = TheModule.getContext();
1374 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
1377void CodeGenModule::EmitBackendOptionsMetadata(
1380 getModule().addModuleFlag(llvm::Module::Min,
"SmallDataLimit",
1381 CodeGenOpts.SmallDataLimit);
1398 return TBAA->getTypeInfo(QTy);
1417 return TBAA->getAccessInfo(AccessType);
1424 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
1430 return TBAA->getTBAAStructInfo(QTy);
1436 return TBAA->getBaseTypeInfo(QTy);
1442 return TBAA->getAccessTagInfo(Info);
1449 return TBAA->mergeTBAAInfoForCast(SourceInfo,
TargetInfo);
1457 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
1465 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
1471 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
1476 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
1489 "cannot compile this %0 yet");
1490 std::string Msg =
Type;
1492 << Msg << S->getSourceRange();
1499 "cannot compile this %0 yet");
1500 std::string Msg =
Type;
1511 if (GV->hasLocalLinkage()) {
1512 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1526 Context.
getLangOpts().OpenMPIsTargetDevice && isa<VarDecl>(D) &&
1527 D->
hasAttr<OMPDeclareTargetDeclAttr>() &&
1528 D->
getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
1529 OMPDeclareTargetDeclAttr::DT_NoHost &&
1531 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1535 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
1539 if (GV->hasDLLExportStorageClass()) {
1542 diag::err_hidden_visibility_dllexport);
1545 diag::err_non_default_visibility_dllimport);
1551 !GV->isDeclarationForLinker())
1556 llvm::GlobalValue *GV) {
1557 if (GV->hasLocalLinkage())
1560 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
1564 if (GV->hasDLLImportStorageClass())
1567 const llvm::Triple &TT = CGM.
getTriple();
1569 if (TT.isWindowsGNUEnvironment()) {
1578 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
1587 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
1595 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
1599 if (!TT.isOSBinFormatELF())
1605 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1611 if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias()))
1613 return !(CGM.
getLangOpts().SemanticInterposition ||
1618 if (!GV->isDeclarationForLinker())
1624 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
1631 if (CGOpts.DirectAccessExternalData) {
1637 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1638 if (!Var->isThreadLocal())
1647 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
1663 const auto *D = dyn_cast<NamedDecl>(GD.
getDecl());
1665 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
1675 if (D->
hasAttr<DLLImportAttr>())
1676 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1677 else if ((D->
hasAttr<DLLExportAttr>() ||
1679 !GV->isDeclarationForLinker())
1680 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
1704 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
1705 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
1706 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
1707 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
1708 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
1711llvm::GlobalVariable::ThreadLocalMode
1713 switch (CodeGenOpts.getDefaultTLSModel()) {
1715 return llvm::GlobalVariable::GeneralDynamicTLSModel;
1717 return llvm::GlobalVariable::LocalDynamicTLSModel;
1719 return llvm::GlobalVariable::InitialExecTLSModel;
1721 return llvm::GlobalVariable::LocalExecTLSModel;
1723 llvm_unreachable(
"Invalid TLS model!");
1727 assert(D.
getTLSKind() &&
"setting TLS mode on non-TLS var!");
1729 llvm::GlobalValue::ThreadLocalMode TLM;
1733 if (
const TLSModelAttr *
Attr = D.
getAttr<TLSModelAttr>()) {
1737 GV->setThreadLocalMode(TLM);
1743 return (Twine(
'.') + Twine(
Target.CPUSpecificManglingCharacter(Name))).str();
1747 const CPUSpecificAttr *
Attr,
1769 bool OmitMultiVersionMangling =
false) {
1771 llvm::raw_svector_ostream Out(Buffer);
1780 assert(II &&
"Attempt to mangle unnamed decl.");
1781 const auto *FD = dyn_cast<FunctionDecl>(ND);
1786 Out <<
"__regcall4__" << II->
getName();
1788 Out <<
"__regcall3__" << II->
getName();
1789 }
else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
1791 Out <<
"__device_stub__" << II->
getName();
1807 "Hash computed when not explicitly requested");
1811 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
1812 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
1813 switch (FD->getMultiVersionKind()) {
1817 FD->getAttr<CPUSpecificAttr>(),
1821 auto *
Attr = FD->getAttr<TargetAttr>();
1823 Info.appendAttributeMangling(
Attr, Out);
1827 auto *
Attr = FD->getAttr<TargetVersionAttr>();
1829 Info.appendAttributeMangling(
Attr, Out);
1833 auto *
Attr = FD->getAttr<TargetClonesAttr>();
1840 llvm_unreachable(
"None multiversion type isn't valid here");
1850 return std::string(Out.str());
1853void CodeGenModule::UpdateMultiVersionNames(
GlobalDecl GD,
1855 StringRef &CurName) {
1862 std::string NonTargetName =
1870 "Other GD should now be a multiversioned function");
1880 if (OtherName != NonTargetName) {
1883 const auto ExistingRecord = Manglings.find(NonTargetName);
1884 if (ExistingRecord != std::end(Manglings))
1885 Manglings.remove(&(*ExistingRecord));
1886 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1891 CurName = OtherNameRef;
1893 Entry->setName(OtherName);
1903 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
1917 auto FoundName = MangledDeclNames.find(CanonicalGD);
1918 if (FoundName != MangledDeclNames.end())
1919 return FoundName->second;
1923 const auto *ND = cast<NamedDecl>(GD.
getDecl());
1935 assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
1946 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
1947 return MangledDeclNames[CanonicalGD] =
Result.first->first();
1956 llvm::raw_svector_ostream Out(Buffer);
1959 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.
getDecl()), Out);
1960 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(D))
1962 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(D))
1965 MangleCtx.
mangleBlock(cast<DeclContext>(D), BD, Out);
1967 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1968 return Result.first->first();
1972 auto it = MangledDeclNames.begin();
1973 while (it != MangledDeclNames.end()) {
1974 if (it->second == Name)
1989 llvm::Constant *AssociatedData) {
1997 bool IsDtorAttrFunc) {
1998 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2000 DtorsUsingAtExit[
Priority].push_back(Dtor);
2008void CodeGenModule::EmitCtorList(CtorList &Fns,
const char *GlobalName) {
2009 if (Fns.empty())
return;
2012 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(
VoidTy,
false);
2013 llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
2014 TheModule.getDataLayout().getProgramAddressSpace());
2017 llvm::StructType *CtorStructTy = llvm::StructType::get(
2022 auto ctors = builder.beginArray(CtorStructTy);
2023 for (
const auto &I : Fns) {
2024 auto ctor = ctors.beginStruct(CtorStructTy);
2025 ctor.addInt(
Int32Ty, I.Priority);
2026 ctor.add(I.Initializer);
2027 if (I.AssociatedData)
2028 ctor.add(I.AssociatedData);
2031 ctor.finishAndAddTo(ctors);
2037 llvm::GlobalValue::AppendingLinkage);
2041 list->setAlignment(std::nullopt);
2046llvm::GlobalValue::LinkageTypes
2048 const auto *D = cast<FunctionDecl>(GD.
getDecl());
2052 if (
const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
2059 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2060 if (!MDS)
return nullptr;
2062 return llvm::ConstantInt::get(
Int64Ty, llvm::MD5Hash(MDS->getString()));
2068 FnType->getReturnType(), FnType->getParamTypes(),
2069 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
2071 std::string OutName;
2072 llvm::raw_string_ostream Out(OutName);
2077 Out <<
".normalized";
2079 return llvm::ConstantInt::get(
Int32Ty,
2080 static_cast<uint32_t
>(llvm::xxHash64(OutName)));
2085 llvm::Function *F,
bool IsThunk) {
2087 llvm::AttributeList PAL;
2090 if (
CallingConv == llvm::CallingConv::X86_VectorCall &&
2094 Loc = D->getLocation();
2096 Error(Loc,
"__vectorcall calling convention is not currently supported");
2098 F->setAttributes(PAL);
2099 F->setCallingConv(
static_cast<llvm::CallingConv::ID
>(
CallingConv));
2103 std::string ReadOnlyQual(
"__read_only");
2104 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2105 if (ReadOnlyPos != std::string::npos)
2107 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2109 std::string WriteOnlyQual(
"__write_only");
2110 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2111 if (WriteOnlyPos != std::string::npos)
2112 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2114 std::string ReadWriteQual(
"__read_write");
2115 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2116 if (ReadWritePos != std::string::npos)
2117 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2150 assert(((FD && CGF) || (!FD && !CGF)) &&
2151 "Incorrect use - FD and CGF should either be both null or not!");
2177 for (
unsigned i = 0, e = FD->
getNumParams(); i != e; ++i) {
2180 argNames.push_back(llvm::MDString::get(VMContext, parm->
getName()));
2185 std::string typeQuals;
2189 const Decl *PDecl = parm;
2191 PDecl = TD->getDecl();
2192 const OpenCLAccessAttr *A = PDecl->
getAttr<OpenCLAccessAttr>();
2193 if (A && A->isWriteOnly())
2194 accessQuals.push_back(llvm::MDString::get(VMContext,
"write_only"));
2195 else if (A && A->isReadWrite())
2196 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_write"));
2198 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_only"));
2200 accessQuals.push_back(llvm::MDString::get(VMContext,
"none"));
2202 auto getTypeSpelling = [&](
QualType Ty) {
2203 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2205 if (Ty.isCanonical()) {
2206 StringRef typeNameRef = typeName;
2208 if (typeNameRef.consume_front(
"unsigned "))
2209 return std::string(
"u") + typeNameRef.str();
2210 if (typeNameRef.consume_front(
"signed "))
2211 return typeNameRef.str();
2221 addressQuals.push_back(
2222 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(
2226 std::string typeName = getTypeSpelling(pointeeTy) +
"*";
2227 std::string baseTypeName =
2229 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2230 argBaseTypeNames.push_back(
2231 llvm::MDString::get(VMContext, baseTypeName));
2235 typeQuals =
"restrict";
2238 typeQuals += typeQuals.empty() ?
"const" :
" const";
2240 typeQuals += typeQuals.empty() ?
"volatile" :
" volatile";
2242 uint32_t AddrSpc = 0;
2247 addressQuals.push_back(
2248 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(AddrSpc)));
2252 std::string typeName = getTypeSpelling(ty);
2264 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2265 argBaseTypeNames.push_back(
2266 llvm::MDString::get(VMContext, baseTypeName));
2271 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
2275 Fn->setMetadata(
"kernel_arg_addr_space",
2276 llvm::MDNode::get(VMContext, addressQuals));
2277 Fn->setMetadata(
"kernel_arg_access_qual",
2278 llvm::MDNode::get(VMContext, accessQuals));
2279 Fn->setMetadata(
"kernel_arg_type",
2280 llvm::MDNode::get(VMContext, argTypeNames));
2281 Fn->setMetadata(
"kernel_arg_base_type",
2282 llvm::MDNode::get(VMContext, argBaseTypeNames));
2283 Fn->setMetadata(
"kernel_arg_type_qual",
2284 llvm::MDNode::get(VMContext, argTypeQuals));
2288 Fn->setMetadata(
"kernel_arg_name",
2289 llvm::MDNode::get(VMContext, argNames));
2299 if (!LangOpts.Exceptions)
return false;
2302 if (LangOpts.CXXExceptions)
return true;
2305 if (LangOpts.ObjCExceptions) {
2322 !isa<CXXConstructorDecl, CXXDestructorDecl>(MD);
2327 llvm::SetVector<const CXXRecordDecl *> MostBases;
2329 std::function<void (
const CXXRecordDecl *)> CollectMostBases;
2332 MostBases.insert(RD);
2334 CollectMostBases(B.getType()->getAsCXXRecordDecl());
2336 CollectMostBases(RD);
2337 return MostBases.takeVector();
2341 llvm::Function *F) {
2342 llvm::AttrBuilder B(F->getContext());
2344 if ((!D || !D->
hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2345 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2347 if (CodeGenOpts.StackClashProtector)
2348 B.addAttribute(
"probe-stack",
"inline-asm");
2350 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
2351 B.addAttribute(
"stack-probe-size",
2352 std::to_string(CodeGenOpts.StackProbeSize));
2355 B.addAttribute(llvm::Attribute::NoUnwind);
2357 if (D && D->
hasAttr<NoStackProtectorAttr>())
2359 else if (D && D->
hasAttr<StrictGuardStackCheckAttr>() &&
2361 B.addAttribute(llvm::Attribute::StackProtectStrong);
2363 B.addAttribute(llvm::Attribute::StackProtect);
2365 B.addAttribute(llvm::Attribute::StackProtectStrong);
2367 B.addAttribute(llvm::Attribute::StackProtectReq);
2373 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2375 B.addAttribute(llvm::Attribute::NoInline);
2383 if (D->
hasAttr<ArmLocallyStreamingAttr>())
2384 B.addAttribute(
"aarch64_pstate_sm_body");
2387 if (
Attr->isNewZA())
2388 B.addAttribute(
"aarch64_new_za");
2389 if (
Attr->isNewZT0())
2390 B.addAttribute(
"aarch64_new_zt0");
2395 bool ShouldAddOptNone =
2396 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
2398 ShouldAddOptNone &= !D->
hasAttr<MinSizeAttr>();
2399 ShouldAddOptNone &= !D->
hasAttr<AlwaysInlineAttr>();
2402 if ((ShouldAddOptNone || D->
hasAttr<OptimizeNoneAttr>()) &&
2403 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2404 B.addAttribute(llvm::Attribute::OptimizeNone);
2407 B.addAttribute(llvm::Attribute::NoInline);
2412 B.addAttribute(llvm::Attribute::Naked);
2415 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
2416 F->removeFnAttr(llvm::Attribute::MinSize);
2417 }
else if (D->
hasAttr<NakedAttr>()) {
2419 B.addAttribute(llvm::Attribute::Naked);
2420 B.addAttribute(llvm::Attribute::NoInline);
2421 }
else if (D->
hasAttr<NoDuplicateAttr>()) {
2422 B.addAttribute(llvm::Attribute::NoDuplicate);
2423 }
else if (D->
hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2425 B.addAttribute(llvm::Attribute::NoInline);
2426 }
else if (D->
hasAttr<AlwaysInlineAttr>() &&
2427 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
2429 B.addAttribute(llvm::Attribute::AlwaysInline);
2433 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
2434 B.addAttribute(llvm::Attribute::NoInline);
2438 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
2441 auto CheckRedeclForInline = [](
const FunctionDecl *Redecl) {
2442 return Redecl->isInlineSpecified();
2444 if (any_of(FD->
redecls(), CheckRedeclForInline))
2449 return any_of(Pattern->
redecls(), CheckRedeclForInline);
2451 if (CheckForInline(FD)) {
2452 B.addAttribute(llvm::Attribute::InlineHint);
2453 }
else if (CodeGenOpts.getInlining() ==
2456 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2457 B.addAttribute(llvm::Attribute::NoInline);
2464 if (!D->
hasAttr<OptimizeNoneAttr>()) {
2466 if (!ShouldAddOptNone)
2467 B.addAttribute(llvm::Attribute::OptimizeForSize);
2468 B.addAttribute(llvm::Attribute::Cold);
2471 B.addAttribute(llvm::Attribute::Hot);
2472 if (D->
hasAttr<MinSizeAttr>())
2473 B.addAttribute(llvm::Attribute::MinSize);
2480 F->setAlignment(llvm::Align(alignment));
2482 if (!D->
hasAttr<AlignedAttr>())
2483 if (LangOpts.FunctionAlignment)
2484 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
2491 if (isa<CXXMethodDecl>(D) && F->getPointerAlignment(
getDataLayout()) < 2)
2492 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
2497 if (CodeGenOpts.SanitizeCfiCrossDso &&
2498 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2499 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
2510 auto *MD = dyn_cast<CXXMethodDecl>(D);
2513 llvm::Metadata *
Id =
2516 F->addTypeMetadata(0,
Id);
2523 if (isa_and_nonnull<NamedDecl>(D))
2526 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2528 if (D && D->
hasAttr<UsedAttr>())
2531 if (
const auto *VD = dyn_cast_if_present<VarDecl>(D);
2533 ((CodeGenOpts.KeepPersistentStorageVariables &&
2534 (VD->getStorageDuration() ==
SD_Static ||
2535 VD->getStorageDuration() ==
SD_Thread)) ||
2536 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
2537 VD->getType().isConstQualified())))
2541bool CodeGenModule::GetCPUAndFeaturesAttributes(
GlobalDecl GD,
2542 llvm::AttrBuilder &Attrs,
2543 bool SetTargetFeatures) {
2549 std::vector<std::string> Features;
2550 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.
getDecl());
2552 const auto *TD = FD ? FD->
getAttr<TargetAttr>() :
nullptr;
2553 const auto *TV = FD ? FD->
getAttr<TargetVersionAttr>() :
nullptr;
2554 assert((!TD || !TV) &&
"both target_version and target specified");
2555 const auto *SD = FD ? FD->
getAttr<CPUSpecificAttr>() :
nullptr;
2556 const auto *TC = FD ? FD->
getAttr<TargetClonesAttr>() :
nullptr;
2557 bool AddedAttr =
false;
2558 if (TD || TV || SD || TC) {
2559 llvm::StringMap<bool> FeatureMap;
2563 for (
const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
2564 Features.push_back((Entry.getValue() ?
"+" :
"-") + Entry.getKey().str());
2572 Target.parseTargetAttr(TD->getFeaturesStr());
2594 if (!TargetCPU.empty()) {
2595 Attrs.addAttribute(
"target-cpu", TargetCPU);
2598 if (!TuneCPU.empty()) {
2599 Attrs.addAttribute(
"tune-cpu", TuneCPU);
2602 if (!Features.empty() && SetTargetFeatures) {
2603 llvm::erase_if(Features, [&](
const std::string& F) {
2606 llvm::sort(Features);
2607 Attrs.addAttribute(
"target-features", llvm::join(Features,
","));
2614void CodeGenModule::setNonAliasAttributes(
GlobalDecl GD,
2615 llvm::GlobalObject *GO) {
2620 if (
auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
2623 if (
auto *SA = D->
getAttr<PragmaClangBSSSectionAttr>())
2624 GV->addAttribute(
"bss-section", SA->getName());
2625 if (
auto *SA = D->
getAttr<PragmaClangDataSectionAttr>())
2626 GV->addAttribute(
"data-section", SA->getName());
2627 if (
auto *SA = D->
getAttr<PragmaClangRodataSectionAttr>())
2628 GV->addAttribute(
"rodata-section", SA->getName());
2629 if (
auto *SA = D->
getAttr<PragmaClangRelroSectionAttr>())
2630 GV->addAttribute(
"relro-section", SA->getName());
2633 if (
auto *F = dyn_cast<llvm::Function>(GO)) {
2636 if (
auto *SA = D->
getAttr<PragmaClangTextSectionAttr>())
2637 if (!D->
getAttr<SectionAttr>())
2638 F->setSection(SA->getName());
2640 llvm::AttrBuilder Attrs(F->getContext());
2641 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
2645 llvm::AttributeMask RemoveAttrs;
2646 RemoveAttrs.addAttribute(
"target-cpu");
2647 RemoveAttrs.addAttribute(
"target-features");
2648 RemoveAttrs.addAttribute(
"tune-cpu");
2649 F->removeFnAttrs(RemoveAttrs);
2650 F->addFnAttrs(Attrs);
2654 if (
const auto *CSA = D->
getAttr<CodeSegAttr>())
2655 GO->setSection(CSA->getName());
2656 else if (
const auto *SA = D->
getAttr<SectionAttr>())
2657 GO->setSection(SA->getName());
2670 F->setLinkage(llvm::Function::InternalLinkage);
2672 setNonAliasAttributes(GD, F);
2683 GV->
setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2687 llvm::Function *F) {
2689 if (!LangOpts.
Sanitize.
has(SanitizerKind::CFIICall))
2694 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2698 F->addTypeMetadata(0, MD);
2702 if (CodeGenOpts.SanitizeCfiCrossDso)
2704 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
2708 llvm::LLVMContext &Ctx = F->getContext();
2709 llvm::MDBuilder MDB(Ctx);
2710 F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
2719 return llvm::all_of(Name, [](
const char &
C) {
2720 return llvm::isAlnum(
C) ||
C ==
'_' ||
C ==
'.';
2726 for (
auto &F : M.functions()) {
2728 bool AddressTaken = F.hasAddressTaken();
2729 if (!AddressTaken && F.hasLocalLinkage())
2730 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
2735 if (!AddressTaken || !F.isDeclaration())
2738 const llvm::ConstantInt *
Type;
2739 if (
const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
2740 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
2744 StringRef Name = F.getName();
2748 std::string
Asm = (
".weak __kcfi_typeid_" + Name +
"\n.set __kcfi_typeid_" +
2749 Name +
", " + Twine(
Type->getZExtValue()) +
"\n")
2751 M.appendModuleInlineAsm(
Asm);
2755void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
2756 bool IsIncompleteFunction,
2759 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
2762 F->setAttributes(llvm::Intrinsic::getAttributes(
getLLVMContext(), IID));
2766 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
2768 if (!IsIncompleteFunction)
2775 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
2777 assert(!F->arg_empty() &&
2778 F->arg_begin()->getType()
2779 ->canLosslesslyBitCastTo(F->getReturnType()) &&
2780 "unexpected this return");
2781 F->addParamAttr(0, llvm::Attribute::Returned);
2791 if (!IsIncompleteFunction && F->isDeclaration())
2794 if (
const auto *CSA = FD->
getAttr<CodeSegAttr>())
2795 F->setSection(CSA->getName());
2796 else if (
const auto *SA = FD->
getAttr<SectionAttr>())
2797 F->setSection(SA->getName());
2799 if (
const auto *EA = FD->
getAttr<ErrorAttr>()) {
2801 F->addFnAttr(
"dontcall-error", EA->getUserDiagnostic());
2802 else if (EA->isWarning())
2803 F->addFnAttr(
"dontcall-warn", EA->getUserDiagnostic());
2809 bool HasBody = FD->
hasBody(FDBody);
2811 assert(HasBody &&
"Inline builtin declarations should always have an "
2813 if (shouldEmitFunction(FDBody))
2814 F->addFnAttr(llvm::Attribute::NoBuiltin);
2820 F->addFnAttr(llvm::Attribute::NoBuiltin);
2823 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
2824 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2825 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
2826 if (MD->isVirtual())
2827 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2833 if (!CodeGenOpts.SanitizeCfiCrossDso ||
2834 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
2843 if (CodeGenOpts.InlineMaxStackSize !=
UINT_MAX)
2844 F->addFnAttr(
"inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
2846 if (
const auto *CB = FD->
getAttr<CallbackAttr>()) {
2850 llvm::LLVMContext &Ctx = F->getContext();
2851 llvm::MDBuilder MDB(Ctx);
2855 int CalleeIdx = *CB->encoding_begin();
2856 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
2857 F->addMetadata(llvm::LLVMContext::MD_callback,
2858 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
2859 CalleeIdx, PayloadIndices,
2865 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2866 "Only globals with definition can force usage.");
2867 LLVMUsed.emplace_back(GV);
2871 assert(!GV->isDeclaration() &&
2872 "Only globals with definition can force usage.");
2873 LLVMCompilerUsed.emplace_back(GV);
2877 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2878 "Only globals with definition can force usage.");
2880 LLVMCompilerUsed.emplace_back(GV);
2882 LLVMUsed.emplace_back(GV);
2886 std::vector<llvm::WeakTrackingVH> &List) {
2893 UsedArray.resize(List.size());
2894 for (
unsigned i = 0, e = List.size(); i != e; ++i) {
2896 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
2897 cast<llvm::Constant>(&*List[i]), CGM.
Int8PtrTy);
2900 if (UsedArray.empty())
2902 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
2904 auto *GV =
new llvm::GlobalVariable(
2905 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
2906 llvm::ConstantArray::get(ATy, UsedArray), Name);
2908 GV->setSection(
"llvm.metadata");
2911void CodeGenModule::emitLLVMUsed() {
2912 emitUsed(*
this,
"llvm.used", LLVMUsed);
2913 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
2918 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
2927 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
2933 ELFDependentLibraries.push_back(
2934 llvm::MDNode::get(
C, llvm::MDString::get(
C, Lib)));
2941 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
C, MDOpts));
2956 if (
Visited.insert(Import).second)
2973 if (LL.IsFramework) {
2974 llvm::Metadata *Args[2] = {llvm::MDString::get(Context,
"-framework"),
2975 llvm::MDString::get(Context, LL.Library)};
2977 Metadata.push_back(llvm::MDNode::get(Context, Args));
2983 llvm::Metadata *Args[2] = {
2984 llvm::MDString::get(Context,
"lib"),
2985 llvm::MDString::get(Context, LL.Library),
2987 Metadata.push_back(llvm::MDNode::get(Context, Args));
2991 auto *OptString = llvm::MDString::get(Context, Opt);
2992 Metadata.push_back(llvm::MDNode::get(Context, OptString));
2997void CodeGenModule::EmitModuleInitializers(
clang::Module *Primary) {
2999 "We should only emit module initializers for named modules.");
3005 if (isa<ImportDecl>(D))
3007 assert(isa<VarDecl>(D) &&
"GMF initializer decl is not a var?");
3014 if (isa<ImportDecl>(D))
3022 if (isa<ImportDecl>(D))
3024 assert(isa<VarDecl>(D) &&
"PMF initializer decl is not a var?");
3030void CodeGenModule::EmitModuleLinkOptions() {
3034 llvm::SetVector<clang::Module *> LinkModules;
3039 for (
Module *M : ImportedModules) {
3042 if (M->getTopLevelModuleName() ==
getLangOpts().CurrentModule &&
3051 while (!Stack.empty()) {
3054 bool AnyChildren =
false;
3064 Stack.push_back(
SM);
3072 LinkModules.insert(Mod);
3081 for (
Module *M : LinkModules)
3084 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
3085 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
3088 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.linker.options");
3089 for (
auto *MD : LinkerOptionsMetadata)
3090 NMD->addOperand(MD);
3093void CodeGenModule::EmitDeferred() {
3102 if (!DeferredVTables.empty()) {
3103 EmitDeferredVTables();
3108 assert(DeferredVTables.empty());
3115 llvm::append_range(DeferredDeclsToEmit,
3119 if (DeferredDeclsToEmit.empty())
3124 std::vector<GlobalDecl> CurDeclsToEmit;
3125 CurDeclsToEmit.swap(DeferredDeclsToEmit);
3132 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
3150 if (!GV->isDeclaration())
3154 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
3158 EmitGlobalDefinition(D, GV);
3163 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
3165 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
3170void CodeGenModule::EmitVTablesOpportunistically() {
3176 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
3177 &&
"Only emit opportunistic vtables with optimizations");
3181 "This queue should only contain external vtables");
3182 if (
getCXXABI().canSpeculativelyEmitVTable(RD))
3185 OpportunisticVTables.clear();
3189 for (
const auto& [MangledName, VD] : DeferredAnnotations) {
3194 DeferredAnnotations.clear();
3196 if (Annotations.empty())
3200 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
3201 Annotations[0]->getType(), Annotations.size()), Annotations);
3202 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
3203 llvm::GlobalValue::AppendingLinkage,
3204 Array,
"llvm.global.annotations");
3209 llvm::Constant *&AStr = AnnotationStrings[Str];
3214 llvm::Constant *
s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
3215 auto *gv =
new llvm::GlobalVariable(
3216 getModule(),
s->getType(),
true, llvm::GlobalValue::PrivateLinkage,
s,
3217 ".str",
nullptr, llvm::GlobalValue::NotThreadLocal,
3220 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3237 SM.getExpansionLineNumber(L);
3238 return llvm::ConstantInt::get(
Int32Ty, LineNo);
3246 llvm::FoldingSetNodeID ID;
3247 for (
Expr *E : Exprs) {
3248 ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult());
3250 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
3255 LLVMArgs.reserve(Exprs.size());
3257 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](
const Expr *E) {
3258 const auto *CE = cast<clang::ConstantExpr>(E);
3259 return ConstEmiter.
emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
3262 auto *
Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
3263 auto *GV =
new llvm::GlobalVariable(
getModule(),
Struct->getType(),
true,
3264 llvm::GlobalValue::PrivateLinkage,
Struct,
3267 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3274 const AnnotateAttr *AA,
3282 llvm::Constant *GVInGlobalsAS = GV;
3283 if (GV->getAddressSpace() !=
3285 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
3287 llvm::PointerType::get(
3288 GV->getContext(),
getDataLayout().getDefaultGlobalsAddressSpace()));
3292 llvm::Constant *Fields[] = {
3293 GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
3295 return llvm::ConstantStruct::getAnon(Fields);
3299 llvm::GlobalValue *GV) {
3300 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
3310 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
3315 if (NoSanitizeL.containsMainFile(Kind, MainFile.
getName()))
3320 return NoSanitizeL.containsLocation(Kind, Loc);
3323 return NoSanitizeL.containsFile(Kind, MainFile.
getName());
3327 llvm::GlobalVariable *GV,
3331 if (NoSanitizeL.containsGlobal(Kind, GV->getName(),
Category))
3334 if (NoSanitizeL.containsMainFile(
3335 Kind,
SM.getFileEntryRefForID(
SM.getMainFileID())->getName(),
3338 if (NoSanitizeL.containsLocation(Kind, Loc,
Category))
3345 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
3346 Ty = AT->getElementType();
3351 if (NoSanitizeL.containsType(Kind, TypeStr,
Category))
3362 auto Attr = ImbueAttr::NONE;
3365 if (
Attr == ImbueAttr::NONE)
3366 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
3368 case ImbueAttr::NONE:
3370 case ImbueAttr::ALWAYS:
3371 Fn->addFnAttr(
"function-instrument",
"xray-always");
3373 case ImbueAttr::ALWAYS_ARG1:
3374 Fn->addFnAttr(
"function-instrument",
"xray-always");
3375 Fn->addFnAttr(
"xray-log-args",
"1");
3377 case ImbueAttr::NEVER:
3378 Fn->addFnAttr(
"function-instrument",
"xray-never");
3402 if (
auto MainFile =
SM.getFileEntryRefForID(
SM.getMainFileID()))
3416 if (NumGroups > 1) {
3417 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
3426 if (LangOpts.EmitAllDecls)
3429 const auto *VD = dyn_cast<VarDecl>(
Global);
3431 ((CodeGenOpts.KeepPersistentStorageVariables &&
3432 (VD->getStorageDuration() ==
SD_Static ||
3433 VD->getStorageDuration() ==
SD_Thread)) ||
3434 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
3435 VD->getType().isConstQualified())))
3448 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
3449 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
3450 OMPDeclareTargetDeclAttr::getActiveAttr(
Global);
3451 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (
unsigned)-1)
3455 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
3464 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
3470 if (CXX20ModuleInits && VD->getOwningModule() &&
3471 !VD->getOwningModule()->isModuleMapModule()) {
3480 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
3483 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
Global))
3496 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
3500 llvm::Constant *
Init;
3503 if (!
V.isAbsent()) {
3514 llvm::Constant *Fields[4] = {
3518 llvm::ConstantDataArray::getRaw(
3519 StringRef(
reinterpret_cast<char *
>(Parts.
Part4And5), 8), 8,
3521 Init = llvm::ConstantStruct::getAnon(Fields);
3524 auto *GV =
new llvm::GlobalVariable(
3526 true, llvm::GlobalValue::LinkOnceODRLinkage,
Init, Name);
3528 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3531 if (!
V.isAbsent()) {
3544 llvm::GlobalVariable **Entry =
nullptr;
3545 Entry = &UnnamedGlobalConstantDeclMap[GCD];
3550 llvm::Constant *
Init;
3554 assert(!
V.isAbsent());
3558 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
3560 llvm::GlobalValue::PrivateLinkage,
Init,
3562 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3576 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
3580 llvm::Constant *
Init =
Emitter.emitForInitializer(
3588 llvm::GlobalValue::LinkageTypes
Linkage =
3590 ? llvm::GlobalValue::LinkOnceODRLinkage
3591 : llvm::GlobalValue::InternalLinkage;
3592 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
3596 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3603 const AliasAttr *AA = VD->
getAttr<AliasAttr>();
3604 assert(AA &&
"No alias?");
3614 llvm::Constant *Aliasee;
3615 if (isa<llvm::FunctionType>(DeclTy))
3616 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
3623 auto *F = cast<llvm::GlobalValue>(Aliasee);
3624 F->setLinkage(llvm::Function::ExternalWeakLinkage);
3625 WeakRefReferences.insert(F);
3633 if (
auto *A = D->
getAttr<AttrT>())
3634 return A->isImplicit();
3642 if (
Global->hasAttr<WeakRefAttr>())
3647 if (
Global->hasAttr<AliasAttr>())
3648 return EmitAliasDefinition(GD);
3651 if (
Global->hasAttr<IFuncAttr>())
3652 return emitIFuncDefinition(GD);
3655 if (
Global->hasAttr<CPUDispatchAttr>())
3656 return emitCPUDispatchDefinition(GD);
3661 if (LangOpts.CUDA) {
3662 if (LangOpts.CUDAIsDevice) {
3663 const auto *FD = dyn_cast<FunctionDecl>(
Global);
3664 if ((!
Global->hasAttr<CUDADeviceAttr>() ||
3665 (LangOpts.OffloadImplicitHostDeviceTemplates && FD &&
3666 hasImplicitAttr<CUDAHostAttr>(FD) &&
3667 hasImplicitAttr<CUDADeviceAttr>(FD) && !FD->
isConstexpr() &&
3669 !
getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
3670 !
Global->hasAttr<CUDAGlobalAttr>() &&
3671 !
Global->hasAttr<CUDAConstantAttr>() &&
3672 !
Global->hasAttr<CUDASharedAttr>() &&
3673 !
Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
3674 !
Global->getType()->isCUDADeviceBuiltinTextureType() &&
3675 !(LangOpts.HIPStdPar && isa<FunctionDecl>(
Global) &&
3676 !
Global->hasAttr<CUDAHostAttr>()))
3685 if (isa<FunctionDecl>(
Global) && !
Global->hasAttr<CUDAHostAttr>() &&
3686 Global->hasAttr<CUDADeviceAttr>())
3689 assert((isa<FunctionDecl>(
Global) || isa<VarDecl>(
Global)) &&
3690 "Expected Variable or Function");
3694 if (LangOpts.OpenMP) {
3696 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
3698 if (
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(
Global)) {
3699 if (MustBeEmitted(
Global))
3703 if (
auto *DMD = dyn_cast<OMPDeclareMapperDecl>(
Global)) {
3704 if (MustBeEmitted(
Global))
3711 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
3714 if (FD->
hasAttr<AnnotateAttr>()) {
3717 DeferredAnnotations[MangledName] = FD;
3733 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
3738 const auto *VD = cast<VarDecl>(
Global);
3739 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
3742 if (LangOpts.OpenMP) {
3744 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3745 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
3749 if (VD->hasExternalStorage() &&
3750 Res != OMPDeclareTargetDeclAttr::MT_Link)
3753 bool UnifiedMemoryEnabled =
3755 if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3756 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3757 !UnifiedMemoryEnabled) {
3760 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3761 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3762 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3763 UnifiedMemoryEnabled)) &&
3764 "Link clause or to clause with unified memory expected.");
3783 if (MustBeEmitted(
Global) && MayBeEmittedEagerly(
Global)) {
3785 EmitGlobalDefinition(GD);
3786 addEmittedDeferredDecl(GD);
3793 cast<VarDecl>(
Global)->hasInit()) {
3794 DelayedCXXInitPosition[
Global] = CXXGlobalInits.size();
3795 CXXGlobalInits.push_back(
nullptr);
3801 addDeferredDeclToEmit(GD);
3802 }
else if (MustBeEmitted(
Global)) {
3804 assert(!MayBeEmittedEagerly(
Global));
3805 addDeferredDeclToEmit(GD);
3810 DeferredDecls[MangledName] = GD;
3817 if (
CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
3818 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
3825 struct FunctionIsDirectlyRecursive
3827 const StringRef Name;
3832 bool VisitCallExpr(
const CallExpr *E) {
3837 if (
Attr && Name ==
Attr->getLabel())
3842 StringRef BuiltinName = BI.
getName(BuiltinID);
3843 if (BuiltinName.starts_with(
"__builtin_") &&
3844 Name == BuiltinName.slice(strlen(
"__builtin_"), StringRef::npos)) {
3850 bool VisitStmt(
const Stmt *S) {
3851 for (
const Stmt *Child : S->children())
3852 if (Child && this->Visit(Child))
3859 struct DLLImportFunctionVisitor
3861 bool SafeToInline =
true;
3863 bool shouldVisitImplicitCode()
const {
return true; }
3865 bool VisitVarDecl(
VarDecl *VD) {
3868 SafeToInline =
false;
3869 return SafeToInline;
3876 return SafeToInline;
3881 SafeToInline = D->
hasAttr<DLLImportAttr>();
3882 return SafeToInline;
3887 if (isa<FunctionDecl>(VD))
3888 SafeToInline = VD->
hasAttr<DLLImportAttr>();
3889 else if (
VarDecl *
V = dyn_cast<VarDecl>(VD))
3890 SafeToInline = !
V->hasGlobalStorage() ||
V->hasAttr<DLLImportAttr>();
3891 return SafeToInline;
3896 return SafeToInline;
3903 SafeToInline =
true;
3905 SafeToInline = M->
hasAttr<DLLImportAttr>();
3907 return SafeToInline;
3912 return SafeToInline;
3917 return SafeToInline;
3926CodeGenModule::isTriviallyRecursive(
const FunctionDecl *FD) {
3928 if (
getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
3933 Name =
Attr->getLabel();
3938 FunctionIsDirectlyRecursive Walker(Name, Context.
BuiltinInfo);
3940 return Body ? Walker.Visit(Body) :
false;
3943bool CodeGenModule::shouldEmitFunction(
GlobalDecl GD) {
3947 const auto *F = cast<FunctionDecl>(GD.
getDecl());
3948 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
3953 if (
const Module *M = F->getOwningModule();
3954 M && M->getTopLevelModule()->isNamedModule() &&
3955 getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
3965 if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
3970 if (F->hasAttr<NoInlineAttr>())
3973 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
3975 DLLImportFunctionVisitor Visitor;
3976 Visitor.TraverseFunctionDecl(
const_cast<FunctionDecl*
>(F));
3977 if (!Visitor.SafeToInline)
3983 for (
const Decl *
Member : Dtor->getParent()->decls())
3984 if (isa<FieldDecl>(
Member))
3995 if (F->isInlineBuiltinDeclaration())
4003 return !isTriviallyRecursive(F);
4006bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
4007 return CodeGenOpts.OptimizationLevel > 0;
4010void CodeGenModule::EmitMultiVersionFunctionDefinition(
GlobalDecl GD,
4011 llvm::GlobalValue *GV) {
4012 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4015 auto *Spec = FD->
getAttr<CPUSpecificAttr>();
4016 for (
unsigned I = 0; I < Spec->cpus_size(); ++I)
4018 }
else if (
auto *TC = FD->
getAttr<TargetClonesAttr>()) {
4019 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I)
4022 TC->isFirstOfVersion(I))
4025 GetOrCreateMultiVersionResolver(GD);
4027 EmitGlobalFunctionDefinition(GD, GV);
4032 AddDeferredMultiVersionResolverToEmit(GD);
4035void CodeGenModule::EmitGlobalDefinition(
GlobalDecl GD, llvm::GlobalValue *GV) {
4036 const auto *D = cast<ValueDecl>(GD.
getDecl());
4040 "Generating code for declaration");
4042 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
4045 if (!shouldEmitFunction(GD))
4048 llvm::TimeTraceScope TimeScope(
"CodeGen Function", [&]() {
4050 llvm::raw_string_ostream OS(Name);
4056 if (
const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
4059 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
4060 ABI->emitCXXStructor(GD);
4062 EmitMultiVersionFunctionDefinition(GD, GV);
4064 EmitGlobalFunctionDefinition(GD, GV);
4066 if (Method->isVirtual())
4073 return EmitMultiVersionFunctionDefinition(GD, GV);
4074 return EmitGlobalFunctionDefinition(GD, GV);
4077 if (
const auto *VD = dyn_cast<VarDecl>(D))
4078 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
4080 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
4084 llvm::Function *NewFn);
4088 const CodeGenFunction::MultiVersionResolverOption &RO) {
4090 unsigned NumFeatures = 0;
4091 for (StringRef Feat : RO.Conditions.Features) {
4096 if (!RO.Conditions.Architecture.empty())
4114 return llvm::GlobalValue::InternalLinkage;
4115 return llvm::GlobalValue::WeakODRLinkage;
4129 NewDecl->
addAttr(TargetVersionAttr::CreateImplicit(
4135void CodeGenModule::emitMultiVersionFunctions() {
4136 std::vector<GlobalDecl> MVFuncsToEmit;
4137 MultiVersionFuncs.swap(MVFuncsToEmit);
4139 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4140 assert(FD &&
"Expected a FunctionDecl");
4147 if (
Decl->isDefined()) {
4148 EmitGlobalFunctionDefinition(CurGD,
nullptr);
4156 assert(
Func &&
"This should have just been created");
4158 return cast<llvm::Function>(
Func);
4162 bool ShouldEmitResolver =
4170 if (
const auto *TA = CurFD->
getAttr<TargetAttr>()) {
4171 TA->getAddedFeatures(Feats);
4172 llvm::Function *Func = createFunction(CurFD);
4173 Options.emplace_back(Func, TA->getArchitecture(), Feats);
4174 }
else if (
const auto *TVA = CurFD->
getAttr<TargetVersionAttr>()) {
4175 bool HasDefaultDef = TVA->isDefaultVersion() &&
4176 CurFD->doesThisDeclarationHaveABody();
4177 HasDefaultDecl |= TVA->isDefaultVersion();
4178 ShouldEmitResolver |= (CurFD->isUsed() || HasDefaultDef);
4179 TVA->getFeatures(Feats);
4180 llvm::Function *Func = createFunction(CurFD);
4181 Options.emplace_back(Func,
"", Feats);
4182 }
else if (
const auto *TC = CurFD->
getAttr<TargetClonesAttr>()) {
4183 ShouldEmitResolver |= CurFD->doesThisDeclarationHaveABody();
4184 for (unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
4185 if (!TC->isFirstOfVersion(I))
4188 llvm::Function *Func = createFunction(CurFD, I);
4189 StringRef Architecture;
4191 if (getTarget().getTriple().isAArch64())
4192 TC->getFeatures(Feats, I);
4194 StringRef Version = TC->getFeatureStr(I);
4195 if (Version.starts_with(
"arch="))
4196 Architecture = Version.drop_front(sizeof(
"arch=") - 1);
4197 else if (Version !=
"default")
4198 Feats.push_back(Version);
4200 Options.emplace_back(Func, Architecture, Feats);
4203 llvm_unreachable(
"unexpected MultiVersionKind");
4206 if (!ShouldEmitResolver)
4209 if (!HasDefaultDecl) {
4211 llvm::Function *
Func = createFunction(NewFD);
4213 Options.emplace_back(
Func,
"", Feats);
4216 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
4217 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
4218 ResolverConstant = IFunc->getResolver();
4222 *
this, GD, FD,
true);
4229 auto *Alias = llvm::GlobalAlias::create(
4231 MangledName +
".ifunc", IFunc, &
getModule());
4236 llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant);
4241 ResolverFunc->setComdat(
4242 getModule().getOrInsertComdat(ResolverFunc->getName()));
4246 Options, [&TI](
const CodeGenFunction::MultiVersionResolverOption &LHS,
4247 const CodeGenFunction::MultiVersionResolverOption &RHS) {
4251 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4257 if (!MVFuncsToEmit.empty())
4262 if (!MultiVersionFuncs.empty())
4263 emitMultiVersionFunctions();
4266void CodeGenModule::emitCPUDispatchDefinition(
GlobalDecl GD) {
4267 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4268 assert(FD &&
"Not a FunctionDecl?");
4270 const auto *DD = FD->
getAttr<CPUDispatchAttr>();
4271 assert(DD &&
"Not a cpu_dispatch Function?");
4277 UpdateMultiVersionNames(GD, FD, ResolverName);
4279 llvm::Type *ResolverType;
4282 ResolverType = llvm::FunctionType::get(
4283 llvm::PointerType::get(DeclTy,
4292 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
4293 ResolverName, ResolverType, ResolverGD,
false));
4296 ResolverFunc->setComdat(
4297 getModule().getOrInsertComdat(ResolverFunc->getName()));
4310 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
4313 EmitGlobalFunctionDefinition(ExistingDecl,
nullptr);
4319 Func = GetOrCreateLLVMFunction(
4320 MangledName, DeclTy, ExistingDecl,
4327 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
4328 llvm::transform(Features, Features.begin(),
4329 [](StringRef Str) { return Str.substr(1); });
4330 llvm::erase_if(Features, [&
Target](StringRef Feat) {
4331 return !
Target.validateCpuSupports(Feat);
4333 Options.emplace_back(cast<llvm::Function>(
Func), StringRef{}, Features);
4338 Options, [](
const CodeGenFunction::MultiVersionResolverOption &LHS,
4339 const CodeGenFunction::MultiVersionResolverOption &RHS) {
4340 return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) >
4341 llvm::X86::getCpuSupportsMask(RHS.Conditions.Features);
4348 while (Options.size() > 1 &&
4349 llvm::all_of(llvm::X86::getCpuSupportsMask(
4350 (Options.end() - 2)->Conditions.Features),
4351 [](
auto X) { return X == 0; })) {
4352 StringRef LHSName = (Options.end() - 2)->
Function->getName();
4353 StringRef RHSName = (Options.end() - 1)->
Function->getName();
4354 if (LHSName.compare(RHSName) < 0)
4355 Options.erase(Options.end() - 2);
4357 Options.erase(Options.end() - 1);
4361 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4365 auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD));
4369 if (!isa<llvm::GlobalIFunc>(IFunc)) {
4370 assert(cast<llvm::Function>(IFunc)->isDeclaration());
4371 auto *GI = llvm::GlobalIFunc::create(DeclTy, 0,
Linkage,
"", ResolverFunc,
4373 GI->takeName(IFunc);
4374 IFunc->replaceAllUsesWith(GI);
4375 IFunc->eraseFromParent();
4380 *
this, GD, FD,
true);
4383 auto *GA = llvm::GlobalAlias::create(DeclTy, 0,
Linkage, AliasName, IFunc,
4391void CodeGenModule::AddDeferredMultiVersionResolverToEmit(
GlobalDecl GD) {
4392 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4393 assert(FD &&
"Not a FunctionDecl?");
4396 std::string MangledName =
4398 if (!DeferredResolversToEmit.insert(MangledName).second)
4401 MultiVersionFuncs.push_back(GD);
4406llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
GlobalDecl GD) {
4407 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4408 assert(FD &&
"Not a FunctionDecl?");
4410 std::string MangledName =
4415 std::string ResolverName = MangledName;
4419 llvm_unreachable(
"unexpected MultiVersionKind::None for resolver");
4423 ResolverName +=
".ifunc";
4430 ResolverName +=
".resolver";
4434 if (llvm::GlobalValue *ResolverGV =
GetGlobalValue(ResolverName))
4443 AddDeferredMultiVersionResolverToEmit(GD);
4448 llvm::Type *ResolverType = llvm::FunctionType::get(
4449 llvm::PointerType::get(DeclTy,
4452 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4453 MangledName +
".resolver", ResolverType,
GlobalDecl{},
4455 llvm::GlobalIFunc *GIF =
4458 GIF->setName(ResolverName);
4464 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4466 assert(isa<llvm::GlobalValue>(Resolver) &&
4467 "Resolver should be created for the first time");
4479llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
4480 StringRef MangledName, llvm::Type *Ty,
GlobalDecl GD,
bool ForVTable,
4481 bool DontDefer,
bool IsThunk, llvm::AttributeList ExtraAttrs,
4487 if (
const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
4489 if (
getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
4490 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->
isDefined() &&
4491 !DontDefer && !IsForDefinition) {
4494 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
4496 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
4505 UpdateMultiVersionNames(GD, FD, MangledName);
4508 AddDeferredMultiVersionResolverToEmit(GD);
4509 else if (!IsForDefinition)
4510 return GetOrCreateMultiVersionResolver(GD);
4517 if (WeakRefReferences.erase(Entry)) {
4518 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
4519 if (FD && !FD->
hasAttr<WeakAttr>())
4520 Entry->setLinkage(llvm::Function::ExternalLinkage);
4524 if (D && !D->
hasAttr<DLLImportAttr>() && !D->
hasAttr<DLLExportAttr>() &&
4526 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4532 if (IsForDefinition && !Entry->isDeclaration()) {
4539 DiagnosedConflictingDefinitions.insert(GD).second) {
4543 diag::note_previous_definition);
4547 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
4548 (Entry->getValueType() == Ty)) {
4555 if (!IsForDefinition)
4562 bool IsIncompleteFunction =
false;
4564 llvm::FunctionType *FTy;
4565 if (isa<llvm::FunctionType>(Ty)) {
4566 FTy = cast<llvm::FunctionType>(Ty);
4568 FTy = llvm::FunctionType::get(
VoidTy,
false);
4569 IsIncompleteFunction =
true;
4573 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
4574 Entry ? StringRef() : MangledName, &
getModule());
4578 if (D && D->
hasAttr<AnnotateAttr>())
4579 DeferredAnnotations[MangledName] = cast<ValueDecl>(D);
4596 if (!Entry->use_empty()) {
4598 Entry->removeDeadConstantUsers();
4604 assert(F->getName() == MangledName &&
"name was uniqued!");
4606 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
4607 if (ExtraAttrs.hasFnAttrs()) {
4608 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
4616 if (isa_and_nonnull<CXXDestructorDecl>(D) &&
4617 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
4619 addDeferredDeclToEmit(GD);
4624 auto DDI = DeferredDecls.find(MangledName);
4625 if (DDI != DeferredDecls.end()) {
4629 addDeferredDeclToEmit(DDI->second);
4630 DeferredDecls.erase(DDI);
4645 for (
const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
4658 if (!IsIncompleteFunction) {
4659 assert(F->getFunctionType() == Ty);
4675 const auto *FD = cast<FunctionDecl>(GD.
getDecl());
4682 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(GD.
getDecl())) {
4685 DD->getParent()->getNumVBases() == 0)
4690 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
4691 false, llvm::AttributeList(),
4694 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
4695 cast<FunctionDecl>(GD.
getDecl())->hasAttr<CUDAGlobalAttr>()) {
4697 cast<llvm::Function>(F->stripPointerCasts()), GD);
4698 if (IsForDefinition)
4706 llvm::GlobalValue *F =
4709 return llvm::NoCFIValue::get(F);
4719 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
4722 if (!
C.getLangOpts().CPlusPlus)
4727 (Name ==
"_ZSt9terminatev" || Name ==
"?terminate@@YAXXZ")
4728 ?
C.Idents.get(
"terminate")
4729 :
C.Idents.get(Name);
4731 for (
const auto &N : {
"__cxxabiv1",
"std"}) {
4735 if (
auto *LSD = dyn_cast<LinkageSpecDecl>(
Result))
4736 for (
const auto *
Result : LSD->lookup(&NS))
4737 if ((ND = dyn_cast<NamespaceDecl>(
Result)))
4742 if (
const auto *FD = dyn_cast<FunctionDecl>(
Result))
4754 llvm::AttributeList ExtraAttrs,
bool Local,
4755 bool AssumeConvergent) {
4756 if (AssumeConvergent) {
4758 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
4762 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
4766 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
4775 if (!Local &&
getTriple().isWindowsItaniumEnvironment() &&
4778 if (!FD || FD->
hasAttr<DLLImportAttr>()) {
4779 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4780 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
4809 if (WeakRefReferences.erase(Entry)) {
4810 if (D && !D->
hasAttr<WeakAttr>())
4811 Entry->setLinkage(llvm::Function::ExternalLinkage);
4815 if (D && !D->
hasAttr<DLLImportAttr>() && !D->
hasAttr<DLLExportAttr>() &&
4817 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4819 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
4822 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
4827 if (IsForDefinition && !Entry->isDeclaration()) {
4835 (OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
4837 DiagnosedConflictingDefinitions.insert(D).second) {
4841 diag::note_previous_definition);
4846 if (Entry->getType()->getAddressSpace() != TargetAS)
4847 return llvm::ConstantExpr::getAddrSpaceCast(
4848 Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
4852 if (!IsForDefinition)
4858 auto *GV =
new llvm::GlobalVariable(
4859 getModule(), Ty,
false, llvm::GlobalValue::ExternalLinkage,
nullptr,
4860 MangledName,
nullptr, llvm::GlobalVariable::NotThreadLocal,
4861 getContext().getTargetAddressSpace(DAddrSpace));
4866 GV->takeName(Entry);
4868 if (!Entry->use_empty()) {
4869 Entry->replaceAllUsesWith(GV);
4872 Entry->eraseFromParent();
4878 auto DDI = DeferredDecls.find(MangledName);
4879 if (DDI != DeferredDecls.end()) {
4882 addDeferredDeclToEmit(DDI->second);
4883 DeferredDecls.erase(DDI);
4888 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
4895 GV->setAlignment(
getContext().getDeclAlign(D).getAsAlign());
4901 CXXThreadLocals.push_back(D);
4909 if (
getContext().isMSStaticDataMemberInlineDefinition(D)) {
4910 EmitGlobalVarDefinition(D);
4915 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>())
4916 GV->setSection(SA->getName());
4920 if (
getTriple().getArch() == llvm::Triple::xcore &&
4924 GV->setSection(
".cp.rodata");
4927 if (
const auto *CMA = D->
getAttr<CodeModelAttr>())
4928 GV->setCodeModel(CMA->getModel());
4933 if (Context.
getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
4939 if (!HasMutableFields) {
4946 auto *InitType =
Init->getType();
4947 if (GV->getValueType() != InitType) {
4952 GV->setName(StringRef());
4955 auto *NewGV = cast<llvm::GlobalVariable>(
4957 ->stripPointerCasts());
4960 GV->eraseFromParent();
4963 GV->setInitializer(
Init);
4964 GV->setConstant(
true);
4965 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
4985 SanitizerMD->reportGlobal(GV, *D);
4990 assert(
getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
4991 if (DAddrSpace != ExpectedAS) {
4993 *
this, GV, DAddrSpace, ExpectedAS,
5004 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
5006 false, IsForDefinition);
5008 if (isa<CXXMethodDecl>(D)) {
5016 if (isa<FunctionDecl>(D)) {
5027 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes
Linkage,
5028 llvm::Align Alignment) {
5029 llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
5030 llvm::GlobalVariable *OldGV =
nullptr;
5034 if (GV->getValueType() == Ty)
5039 assert(GV->isDeclaration() &&
"Declaration has wrong type!");
5044 GV =
new llvm::GlobalVariable(
getModule(), Ty,
true,
5049 GV->takeName(OldGV);
5051 if (!OldGV->use_empty()) {
5052 OldGV->replaceAllUsesWith(GV);
5055 OldGV->eraseFromParent();
5059 !GV->hasAvailableExternallyLinkage())
5060 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5062 GV->setAlignment(Alignment);
5094 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
5099 assert(!D->
getInit() &&
"Cannot emit definite definitions here!");
5107 if (GV && !GV->isDeclaration())
5112 if (!MustBeEmitted(D) && !GV) {
5113 DeferredDecls[MangledName] = D;
5118 EmitGlobalVarDefinition(D);
5122 EmitExternalVarDeclaration(D);
5131 if (LangOpts.OpenCL) {
5142 if (LangOpts.SYCLIsDevice &&
5146 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
5148 if (D->
hasAttr<CUDAConstantAttr>())
5150 if (D->
hasAttr<CUDASharedAttr>())
5152 if (D->
hasAttr<CUDADeviceAttr>())
5160 if (LangOpts.OpenMP) {
5162 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
5170 if (LangOpts.OpenCL)
5172 if (LangOpts.SYCLIsDevice)
5174 if (LangOpts.HIP && LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())
5182 if (
auto AS =
getTarget().getConstantAddressSpace())
5195static llvm::Constant *
5197 llvm::GlobalVariable *GV) {
5198 llvm::Constant *Cast = GV;
5204 llvm::PointerType::get(
5211template<
typename SomeDecl>
5213 llvm::GlobalValue *GV) {
5219 if (!D->template hasAttr<UsedAttr>())
5228 const SomeDecl *
First = D->getFirstDecl();
5229 if (
First->getDeclContext()->isRecord() || !
First->isInExternCContext())
5235 std::pair<StaticExternCMap::iterator, bool> R =
5236 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
5241 R.first->second =
nullptr;
5248 if (D.
hasAttr<SelectAnyAttr>())
5252 if (
auto *VD = dyn_cast<VarDecl>(&D))
5266 llvm_unreachable(
"No such linkage");
5274 llvm::GlobalObject &GO) {
5277 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
5281void CodeGenModule::EmitGlobalVarDefinition(
const VarDecl *D,
5291 if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
5292 OpenMPRuntime->emitTargetGlobalVariable(D))
5295 llvm::TrackingVH<llvm::Constant>
Init;
5296 bool NeedsGlobalCtor =
false;
5300 bool IsDefinitionAvailableExternally =
5302 bool NeedsGlobalDtor =
5303 !IsDefinitionAvailableExternally &&
5309 std::optional<ConstantEmitter> emitter;
5314 bool IsCUDASharedVar =
5319 bool IsCUDAShadowVar =
5321 (D->
hasAttr<CUDAConstantAttr>() || D->
hasAttr<CUDADeviceAttr>() ||
5322 D->
hasAttr<CUDASharedAttr>());
5323 bool IsCUDADeviceShadowVar =
5328 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
5329 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
5330 else if (D->
hasAttr<LoaderUninitializedAttr>())
5331 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
5332 else if (!InitExpr) {
5346 emitter.emplace(*
this);
5347 llvm::Constant *
Initializer = emitter->tryEmitForInitializer(*InitDecl);
5358 if (!IsDefinitionAvailableExternally)
5359 NeedsGlobalCtor =
true;
5370 DelayedCXXInitPosition.erase(D);
5377 assert(VarSize == CstSize &&
"Emitted constant has unexpected size");
5382 llvm::Type* InitType =
Init->getType();
5383 llvm::Constant *Entry =
5387 Entry = Entry->stripPointerCasts();
5390 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
5401 if (!GV || GV->getValueType() != InitType ||
5402 GV->getType()->getAddressSpace() !=
5406 Entry->setName(StringRef());
5409 GV = cast<llvm::GlobalVariable>(
5411 ->stripPointerCasts());
5414 llvm::Constant *NewPtrForOldDecl =
5415 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5417 Entry->replaceAllUsesWith(NewPtrForOldDecl);
5420 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
5425 if (D->
hasAttr<AnnotateAttr>())
5438 if (LangOpts.CUDA) {
5439 if (LangOpts.CUDAIsDevice) {
5440 if (
Linkage != llvm::GlobalValue::InternalLinkage &&
5441 (D->
hasAttr<CUDADeviceAttr>() || D->
hasAttr<CUDAConstantAttr>() ||
5444 GV->setExternallyInitialized(
true);
5451 GV->setInitializer(
Init);
5453 emitter->finalize(GV);
5456 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
5460 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>()) {
5463 GV->setConstant(
true);
5468 if (std::optional<CharUnits> AlignValFromAllocate =
5470 AlignVal = *AlignValFromAllocate;
5488 Linkage == llvm::GlobalValue::ExternalLinkage &&
5491 Linkage = llvm::GlobalValue::InternalLinkage;
5494 if (D->
hasAttr<DLLImportAttr>())
5495 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
5496 else if (D->
hasAttr<DLLExportAttr>())
5497 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
5499 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
5501 if (
Linkage == llvm::GlobalVariable::CommonLinkage) {
5503 GV->setConstant(
false);
5508 if (!GV->getInitializer()->isNullValue())
5509 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
5512 setNonAliasAttributes(D, GV);
5514 if (D->
getTLSKind() && !GV->isThreadLocal()) {
5516 CXXThreadLocals.push_back(D);
5523 if (NeedsGlobalCtor || NeedsGlobalDtor)
5524 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
5526 SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
5531 DI->EmitGlobalVariable(GV, D);
5534void CodeGenModule::EmitExternalVarDeclaration(
const VarDecl *D) {
5539 llvm::Constant *GV =
5541 DI->EmitExternalVariable(
5542 cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
5551 if ((NoCommon || D->
hasAttr<NoCommonAttr>()) && !D->
hasAttr<CommonAttr>())
5562 if (D->
hasAttr<SectionAttr>())
5568 if (D->
hasAttr<PragmaClangBSSSectionAttr>() ||
5569 D->
hasAttr<PragmaClangDataSectionAttr>() ||
5570 D->
hasAttr<PragmaClangRelroSectionAttr>() ||
5571 D->
hasAttr<PragmaClangRodataSectionAttr>())
5579 if (D->
hasAttr<WeakImportAttr>())
5589 if (D->
hasAttr<AlignedAttr>())
5598 if (FD->isBitField())
5600 if (FD->
hasAttr<AlignedAttr>())
5622llvm::GlobalValue::LinkageTypes
5626 return llvm::Function::InternalLinkage;
5629 return llvm::GlobalVariable::WeakAnyLinkage;
5633 return llvm::GlobalVariable::LinkOnceAnyLinkage;
5638 return llvm::GlobalValue::AvailableExternallyLinkage;
5652 return !Context.
getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
5653 : llvm::Function::InternalLinkage;
5667 return llvm::Function::ExternalLinkage;
5670 return D->
hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
5671 : llvm::Function::InternalLinkage;
5672 return llvm::Function::WeakODRLinkage;
5677 if (!
getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
5679 CodeGenOpts.NoCommon))
5680 return llvm::GlobalVariable::CommonLinkage;
5686 if (D->
hasAttr<SelectAnyAttr>())
5687 return llvm::GlobalVariable::WeakODRLinkage;
5691 return llvm::GlobalVariable::ExternalLinkage;
5694llvm::GlobalValue::LinkageTypes
5703 llvm::Function *newFn) {
5705 if (old->use_empty())
return;
5707 llvm::Type *newRetTy = newFn->getReturnType();
5710 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
5712 llvm::Value::use_iterator use = ui++;
5713 llvm::User *user = use->getUser();
5717 if (
auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
5718 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
5724 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
5725 if (!callSite)
continue;
5726 if (!callSite->isCallee(&*use))
5731 if (callSite->getType() != newRetTy && !callSite->use_empty())
5736 llvm::AttributeList oldAttrs = callSite->getAttributes();
5739 unsigned newNumArgs = newFn->arg_size();
5740 if (callSite->arg_size() < newNumArgs)
5746 bool dontTransform =
false;
5747 for (llvm::Argument &A : newFn->args()) {
5748 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
5749 dontTransform =
true;
5754 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
5762 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
5766 callSite->getOperandBundlesAsDefs(newBundles);
5768 llvm::CallBase *newCall;
5769 if (isa<llvm::CallInst>(callSite)) {
5771 llvm::CallInst::Create(newFn, newArgs, newBundles,
"", callSite);
5773 auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
5774 newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
5775 oldInvoke->getUnwindDest(), newArgs,
5776 newBundles,
"", callSite);
5780 if (!newCall->getType()->isVoidTy())
5781 newCall->takeName(callSite);
5782 newCall->setAttributes(
5783 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
5784 oldAttrs.getRetAttrs(), newArgAttrs));
5785 newCall->setCallingConv(callSite->getCallingConv());
5788 if (!callSite->use_empty())
5789 callSite->replaceAllUsesWith(newCall);
5792 if (callSite->getDebugLoc())
5793 newCall->setDebugLoc(callSite->getDebugLoc());
5795 callSite->eraseFromParent();
5809 llvm::Function *NewFn) {
5811 if (!isa<llvm::Function>(Old))
return;
5830void CodeGenModule::EmitGlobalFunctionDefinition(
GlobalDecl GD,
5831 llvm::GlobalValue *GV) {
5832 const auto *D = cast<FunctionDecl>(GD.
getDecl());
5839 if (!GV || (GV->getValueType() != Ty))
5845 if (!GV->isDeclaration())
5852 auto *Fn = cast<llvm::Function>(GV);
5864 setNonAliasAttributes(GD, Fn);
5867 if (
const ConstructorAttr *CA = D->
getAttr<ConstructorAttr>())
5869 if (
const DestructorAttr *DA = D->
getAttr<DestructorAttr>())
5875void CodeGenModule::EmitAliasDefinition(
GlobalDecl GD) {
5876 const auto *D = cast<ValueDecl>(GD.
getDecl());
5877 const AliasAttr *AA = D->
getAttr<AliasAttr>();
5878 assert(AA &&
"Not an alias?");
5882 if (AA->getAliasee() == MangledName) {
5883 Diags.
Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
5890 if (Entry && !Entry->isDeclaration())
5893 Aliases.push_back(GD);
5899 llvm::Constant *Aliasee;
5900 llvm::GlobalValue::LinkageTypes
LT;
5901 if (isa<llvm::FunctionType>(DeclTy)) {
5902 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
5908 if (
const auto *VD = dyn_cast<VarDecl>(GD.
getDecl()))
5915 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
5917 llvm::GlobalAlias::create(DeclTy, AS,
LT,
"", Aliasee, &
getModule());
5920 if (GA->getAliasee() == Entry) {
5921 Diags.
Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
5925 assert(Entry->isDeclaration());
5934 GA->takeName(Entry);
5936 Entry->replaceAllUsesWith(GA);
5937 Entry->eraseFromParent();
5939 GA->setName(MangledName);
5947 GA->setLinkage(llvm::Function::WeakAnyLinkage);
5950 if (
const auto *VD = dyn_cast<VarDecl>(D))
5951 if (VD->getTLSKind())
5957 if (isa<VarDecl>(D))
5959 DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD);
5962void CodeGenModule::emitIFuncDefinition(
GlobalDecl GD) {
5963 const auto *D = cast<ValueDecl>(GD.
getDecl());
5964 const IFuncAttr *IFA = D->
getAttr<IFuncAttr>();
5965 assert(IFA &&
"Not an ifunc?");
5969 if (IFA->getResolver() == MangledName) {
5970 Diags.
Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
5976 if (Entry && !Entry->isDeclaration()) {
5979 DiagnosedConflictingDefinitions.insert(GD).second) {
5983 diag::note_previous_definition);
5988 Aliases.push_back(GD);
5991 llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy);
5992 llvm::Constant *Resolver =
5993 GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {},
5995 llvm::GlobalIFunc *GIF =
5996 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
5999 if (GIF->getResolver() == Entry) {
6000 Diags.
Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6003 assert(Entry->isDeclaration());
6012 GIF->takeName(Entry);
6014 Entry->replaceAllUsesWith(GIF);
6015 Entry->eraseFromParent();
6017 GIF->setName(MangledName);
6018 if (
auto *F = dyn_cast<llvm::Function>(Resolver)) {
6019 F->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
6026 return llvm::Intrinsic::getDeclaration(&
getModule(), (llvm::Intrinsic::ID)IID,
6030static llvm::StringMapEntry<llvm::GlobalVariable *> &
6033 bool &IsUTF16,
unsigned &StringLength) {
6034 StringRef String = Literal->getString();
6035 unsigned NumBytes = String.size();
6038 if (!Literal->containsNonAsciiOrNull()) {
6039 StringLength = NumBytes;
6040 return *Map.insert(std::make_pair(String,
nullptr)).first;
6047 const llvm::UTF8 *FromPtr = (
const llvm::UTF8 *)String.data();
6048 llvm::UTF16 *ToPtr = &ToBuf[0];
6050 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6051 ToPtr + NumBytes, llvm::strictConversion);
6054 StringLength = ToPtr - &ToBuf[0];
6058 return *Map.insert(std::make_pair(
6059 StringRef(
reinterpret_cast<const char *
>(ToBuf.data()),
6060 (StringLength + 1) * 2),
6066 unsigned StringLength = 0;
6067 bool isUTF16 =
false;
6068 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
6073 if (
auto *
C = Entry.second)
6077 llvm::Constant *Zero = llvm::Constant::getNullValue(
Int32Ty);
6078 llvm::Constant *Zeros[] = { Zero, Zero };
6081 const llvm::Triple &Triple =
getTriple();
6084 const bool IsSwiftABI =
6085 static_cast<unsigned>(CFRuntime) >=
6090 if (!CFConstantStringClassRef) {
6091 const char *CFConstantStringClassName =
"__CFConstantStringClassReference";
6093 Ty = llvm::ArrayType::get(Ty, 0);
6095 switch (CFRuntime) {
6099 CFConstantStringClassName =
6100 Triple.isOSDarwin() ?
"$s15SwiftFoundation19_NSCFConstantStringCN"
6101 :
"$s10Foundation19_NSCFConstantStringCN";
6105 CFConstantStringClassName =
6106 Triple.isOSDarwin() ?
"$S15SwiftFoundation19_NSCFConstantStringCN"
6107 :
"$S10Foundation19_NSCFConstantStringCN";
6111 CFConstantStringClassName =
6112 Triple.isOSDarwin() ?
"__T015SwiftFoundation19_NSCFConstantStringCN"
6113 :
"__T010Foundation19_NSCFConstantStringCN";
6120 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
6121 llvm::GlobalValue *GV =
nullptr;
6123 if ((GV = dyn_cast<llvm::GlobalValue>(
C))) {
6130 if ((VD = dyn_cast<VarDecl>(
Result)))
6133 if (Triple.isOSBinFormatELF()) {
6135 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6137 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6138 if (!VD || !VD->
hasAttr<DLLExportAttr>())
6139 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
6141 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
6149 CFConstantStringClassRef =
6150 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(
C, Ty)
6151 : llvm::ConstantExpr::getGetElementPtr(Ty,
C, Zeros);
6156 auto *STy = cast<llvm::StructType>(
getTypes().ConvertType(CFTy));
6159 auto Fields = Builder.beginStruct(STy);
6162 Fields.add(cast<llvm::Constant>(CFConstantStringClassRef));
6166 Fields.addInt(
IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
6167 Fields.addInt(
Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
6169 Fields.addInt(
IntTy, isUTF16 ? 0x07d0 : 0x07C8);
6173 llvm::Constant *
C =
nullptr;
6176 reinterpret_cast<uint16_t *
>(
const_cast<char *
>(Entry.first().data())),
6177 Entry.first().size() / 2);
6178 C = llvm::ConstantDataArray::get(VMContext, Arr);
6180 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
6186 new llvm::GlobalVariable(
getModule(),
C->getType(),
true,
6187 llvm::GlobalValue::PrivateLinkage,
C,
".str");
6188 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6198 if (Triple.isOSBinFormatMachO())
6199 GV->setSection(isUTF16 ?
"__TEXT,__ustring"
6200 :
"__TEXT,__cstring,cstring_literals");
6203 else if (Triple.isOSBinFormatELF())
6204 GV->setSection(
".rodata");
6207 llvm::Constant *Str =
6208 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
6213 llvm::IntegerType *LengthTy =
6223 Fields.addInt(LengthTy, StringLength);
6231 GV = Fields.finishAndCreateGlobal(
"_unnamed_cfstring_", Alignment,
6233 llvm::GlobalVariable::PrivateLinkage);
6234 GV->addAttribute(
"objc_arc_inert");
6235 switch (Triple.getObjectFormat()) {
6236 case llvm::Triple::UnknownObjectFormat:
6237 llvm_unreachable(
"unknown file format");
6238 case llvm::Triple::DXContainer:
6239 case llvm::Triple::GOFF:
6240 case llvm::Triple::SPIRV:
6241 case llvm::Triple::XCOFF:
6242 llvm_unreachable(
"unimplemented");
6243 case llvm::Triple::COFF:
6244 case llvm::Triple::ELF:
6245 case llvm::Triple::Wasm:
6246 GV->setSection(
"cfstring");
6248 case llvm::Triple::MachO:
6249 GV->setSection(
"__DATA,__cfstring");
6258 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
6262 if (ObjCFastEnumerationStateType.
isNull()) {
6272 for (
size_t i = 0; i < 4; ++i) {
6277 FieldTypes[i],
nullptr,
6289 return ObjCFastEnumerationStateType;
6303 assert(CAT &&
"String literal not of constant array type!");
6305 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
6308 auto *AType = cast<llvm::ArrayType>(
getTypes().ConvertType(E->
getType()));
6309 llvm::Type *ElemTy = AType->getElementType();
6310 unsigned NumElements = AType->getNumElements();
6313 if (ElemTy->getPrimitiveSizeInBits() == 16) {
6315 Elements.reserve(NumElements);
6317 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
6319 Elements.resize(NumElements);
6320 return llvm::ConstantDataArray::get(VMContext, Elements);
6323 assert(ElemTy->getPrimitiveSizeInBits() == 32);
6325 Elements.reserve(NumElements);
6327 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
6329 Elements.resize(NumElements);
6330 return llvm::ConstantDataArray::get(VMContext, Elements);
6333static llvm::GlobalVariable *
6342 auto *GV =
new llvm::GlobalVariable(
6343 M,
C->getType(), !CGM.
getLangOpts().WritableStrings,
LT,
C, GlobalName,
6344 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
6346 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6347 if (GV->isWeakForLinker()) {
6348 assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
6349 GV->setComdat(M.getOrInsertComdat(GV->getName()));
6365 llvm::GlobalVariable **Entry =
nullptr;
6366 if (!LangOpts.WritableStrings) {
6367 Entry = &ConstantStringMap[
C];
6368 if (
auto GV = *Entry) {
6369 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
6372 GV->getValueType(), Alignment);
6377 StringRef GlobalVariableName;
6378 llvm::GlobalValue::LinkageTypes
LT;
6383 if (
getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
6384 !LangOpts.WritableStrings) {
6385 llvm::raw_svector_ostream Out(MangledNameBuffer);
6387 LT = llvm::GlobalValue::LinkOnceODRLinkage;
6388 GlobalVariableName = MangledNameBuffer;
6390 LT = llvm::GlobalValue::PrivateLinkage;
6391 GlobalVariableName = Name;
6403 SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0),
"<string literal>");
6406 GV->getValueType(), Alignment);
6423 const std::string &Str,
const char *GlobalName) {
6424 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
6429 llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
6432 llvm::GlobalVariable **Entry =
nullptr;
6433 if (!LangOpts.WritableStrings) {
6434 Entry = &ConstantStringMap[
C];
6435 if (
auto GV = *Entry) {
6436 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
6439 GV->getValueType(), Alignment);
6445 GlobalName =
".str";
6448 GlobalName, Alignment);
6453 GV->getValueType(), Alignment);
6466 MaterializedType = E->
getType();
6470 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E,
nullptr});
6471 if (!InsertResult.second) {
6474 if (!InsertResult.first->second) {
6479 InsertResult.first->second =
new llvm::GlobalVariable(
6480 getModule(),
Type,
false, llvm::GlobalVariable::InternalLinkage,
6484 llvm::cast<llvm::GlobalVariable>(
6485 InsertResult.first->second->stripPointerCasts())
6494 llvm::raw_svector_ostream Out(Name);
6516 std::optional<ConstantEmitter> emitter;
6517 llvm::Constant *InitialValue =
nullptr;
6518 bool Constant =
false;
6522 emitter.emplace(*
this);
6523 InitialValue = emitter->emitForInitializer(*
Value, AddrSpace,
6528 Type = InitialValue->getType();
6537 if (
Linkage == llvm::GlobalVariable::ExternalLinkage) {
6539 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
6543 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
6547 Linkage = llvm::GlobalVariable::InternalLinkage;
6551 auto *GV =
new llvm::GlobalVariable(
6553 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
6554 if (emitter) emitter->finalize(GV);
6556 if (!llvm::GlobalValue::isLocalLinkage(
Linkage)) {
6558 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
6560 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6564 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
6565 if (VD->getTLSKind())
6567 llvm::Constant *CV = GV;
6571 llvm::PointerType::get(
6577 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
6579 Entry->replaceAllUsesWith(CV);
6580 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
6589void CodeGenModule::EmitObjCPropertyImplementations(
const
6602 if (!Getter || Getter->isSynthesizedAccessorStub())
6605 auto *Setter = PID->getSetterMethodDecl();
6606 if (!PD->
isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
6617 if (ivar->getType().isDestructedType())
6666 getContext().getObjCIdType(),
nullptr, D,
true,
6684 EmitDeclContext(LSD);
6689 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
6692 std::unique_ptr<CodeGenFunction> &CurCGF =
6693 GlobalTopLevelStmtBlockInFlight.first;
6697 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
6705 std::string Name =
"__stmts__" + llvm::utostr(CXXGlobalInits.size());
6711 llvm::Function *Fn = llvm::Function::Create(
6712 FnTy, llvm::GlobalValue::InternalLinkage, Name, &
getModule());
6715 GlobalTopLevelStmtBlockInFlight.second = D;
6716 CurCGF->StartFunction(
GlobalDecl(), RetTy, Fn, FnInfo, Args,
6718 CXXGlobalInits.push_back(Fn);
6721 CurCGF->EmitStmt(D->
getStmt());
6724void CodeGenModule::EmitDeclContext(
const DeclContext *DC) {
6725 for (
auto *I : DC->
decls()) {
6731 if (
auto *OID = dyn_cast<ObjCImplDecl>(I)) {
6732 for (
auto *M : OID->methods())
6751 case Decl::CXXConversion:
6752 case Decl::CXXMethod:
6753 case Decl::Function:
6760 case Decl::CXXDeductionGuide:
6765 case Decl::Decomposition:
6766 case Decl::VarTemplateSpecialization:
6768 if (
auto *DD = dyn_cast<DecompositionDecl>(D))
6769 for (
auto *B : DD->bindings())
6770 if (
auto *HD = B->getHoldingVar())
6776 case Decl::IndirectField:
6780 case Decl::Namespace:
6781 EmitDeclContext(cast<NamespaceDecl>(D));
6783 case Decl::ClassTemplateSpecialization: {
6784 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
6786 if (Spec->getSpecializationKind() ==
6788 Spec->hasDefinition())
6789 DI->completeTemplateDefinition(*Spec);
6791 case Decl::CXXRecord: {
6798 DI->completeUnusedClass(*CRD);
6801 for (
auto *I : CRD->
decls())
6802 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
6807 case Decl::UsingShadow:
6808 case Decl::ClassTemplate:
6809 case Decl::VarTemplate:
6811 case Decl::VarTemplatePartialSpecialization:
6812 case Decl::FunctionTemplate:
6813 case Decl::TypeAliasTemplate:
6820 DI->EmitUsingDecl(cast<UsingDecl>(*D));
6822 case Decl::UsingEnum:
6824 DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D));
6826 case Decl::NamespaceAlias:
6828 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
6830 case Decl::UsingDirective:
6832 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
6834 case Decl::CXXConstructor:
6837 case Decl::CXXDestructor:
6841 case Decl::StaticAssert:
6848 case Decl::ObjCInterface:
6849 case Decl::ObjCCategory:
6852 case Decl::ObjCProtocol: {
6853 auto *Proto = cast<ObjCProtocolDecl>(D);
6854 if (Proto->isThisDeclarationADefinition())
6859 case Decl::ObjCCategoryImpl:
6862 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
6865 case Decl::ObjCImplementation: {
6866 auto *OMD = cast<ObjCImplementationDecl>(D);
6867 EmitObjCPropertyImplementations(OMD);
6868 EmitObjCIvarInitializations(OMD);
6873 DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
6874 OMD->getClassInterface()), OMD->getLocation());
6877 case Decl::ObjCMethod: {
6878 auto *OMD = cast<ObjCMethodDecl>(D);
6884 case Decl::ObjCCompatibleAlias:
6885 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
6888 case Decl::PragmaComment: {
6889 const auto *PCD = cast<PragmaCommentDecl>(D);
6890 switch (PCD->getCommentKind()) {
6892 llvm_unreachable(
"unexpected pragma comment kind");
6907 case Decl::PragmaDetectMismatch: {
6908 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
6913 case Decl::LinkageSpec:
6914 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
6917 case Decl::FileScopeAsm: {
6919 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
6922 if (LangOpts.OpenMPIsTargetDevice)
6925 if (LangOpts.SYCLIsDevice)
6927 auto *AD = cast<FileScopeAsmDecl>(D);
6928 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
6932 case Decl::TopLevelStmt:
6933 EmitTopLevelStmt(cast<TopLevelStmtDecl>(D));
6936 case Decl::Import: {
6937 auto *Import = cast<ImportDecl>(D);
6940 if (!ImportedModules.insert(Import->getImportedModule()))
6944 if (!Import->getImportedOwningModule()) {
6946 DI->EmitImportDecl(*Import);
6952 if (CXX20ModuleInits && Import->getImportedOwningModule() &&
6953 !Import->getImportedOwningModule()->isModuleMapModule())
6962 Visited.insert(Import->getImportedModule());
6963 Stack.push_back(Import->getImportedModule());
6965 while (!Stack.empty()) {
6967 if (!EmittedModuleInitializers.insert(Mod).second)
6977 if (Submodule->IsExplicit)
6980 if (
Visited.insert(Submodule).second)
6981 Stack.push_back(Submodule);
6988 EmitDeclContext(cast<ExportDecl>(D));
6991 case Decl::OMPThreadPrivate:
6995 case Decl::OMPAllocate:
6999 case Decl::OMPDeclareReduction:
7003 case Decl::OMPDeclareMapper:
7007 case Decl::OMPRequires:
7012 case Decl::TypeAlias:
7014 DI->EmitAndRetainType(
7015 getContext().getTypedefType(cast<TypedefNameDecl>(D)));
7027 DI->EmitAndRetainType(
getContext().getEnumType(cast<EnumDecl>(D)));
7030 case Decl::HLSLBuffer:
7038 assert(isa<TypeDecl>(D) &&
"Unsupported decl kind");
7045 if (!CodeGenOpts.CoverageMapping)
7048 case Decl::CXXConversion:
7049 case Decl::CXXMethod:
7050 case Decl::Function:
7051 case Decl::ObjCMethod:
7052 case Decl::CXXConstructor:
7053 case Decl::CXXDestructor: {
7054 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
7059 DeferredEmptyCoverageMappingDecls.try_emplace(D,
true);
7069 if (!CodeGenOpts.CoverageMapping)
7071 if (
const auto *Fn = dyn_cast<FunctionDecl>(D)) {
7072 if (Fn->isTemplateInstantiation())
7075 DeferredEmptyCoverageMappingDecls.insert_or_assign(D,
false);
7083 for (
const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
7086 const Decl *D = Entry.first;
7088 case Decl::CXXConversion:
7089 case Decl::CXXMethod:
7090 case Decl::Function:
7091 case Decl::ObjCMethod: {
7098 case Decl::CXXConstructor: {
7105 case Decl::CXXDestructor: {
7122 if (llvm::Function *F =
getModule().getFunction(
"main")) {
7123 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
7125 auto *GA = llvm::GlobalAlias::create(
"__main_void", F);
7126 GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
7135 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
7136 return llvm::ConstantInt::get(i64, PtrInt);
7140 llvm::NamedMDNode *&GlobalMetadata,
7142 llvm::GlobalValue *Addr) {
7143 if (!GlobalMetadata)
7145 CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
7148 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
7151 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
7154bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
7155 llvm::GlobalValue *CppFunc) {
7163 if (Elem == CppFunc)
7169 for (llvm::User *User : Elem->users()) {
7173 if (
auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
7174 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
7177 for (llvm::User *CEUser : ConstExpr->users()) {
7178 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
7179 IFuncs.push_back(IFunc);
7184 CEs.push_back(ConstExpr);
7185 }
else if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
7186 IFuncs.push_back(IFunc);
7198 for (llvm::GlobalIFunc *IFunc : IFuncs)
7199 IFunc->setResolver(
nullptr);
7200 for (llvm::ConstantExpr *ConstExpr : CEs)
7201 ConstExpr->destroyConstant();
7205 Elem->eraseFromParent();
7207 for (llvm::GlobalIFunc *IFunc : IFuncs) {
7212 llvm::FunctionType::get(IFunc->getType(),
false);
7213 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
7214 CppFunc->getName(), ResolverTy, {},
false);
7215 IFunc->setResolver(Resolver);
7225void CodeGenModule::EmitStaticExternCAliases() {
7228 for (
auto &I : StaticExternCValues) {
7230 llvm::GlobalValue *Val = I.second;
7238 llvm::GlobalValue *ExistingElem =
7239 getModule().getNamedValue(Name->getName());
7243 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
7250 auto Res = Manglings.find(MangledName);
7251 if (Res == Manglings.end())
7253 Result = Res->getValue();
7264void CodeGenModule::EmitDeclMetadata() {
7265 llvm::NamedMDNode *GlobalMetadata =
nullptr;
7267 for (
auto &I : MangledDeclNames) {
7268 llvm::GlobalValue *Addr =
getModule().getNamedValue(I.second);
7278void CodeGenFunction::EmitDeclMetadata() {
7279 if (LocalDeclMap.empty())
return;
7284 unsigned DeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
7286 llvm::NamedMDNode *GlobalMetadata =
nullptr;
7288 for (
auto &I : LocalDeclMap) {
7289 const Decl *D = I.first;
7290 llvm::Value *Addr = I.second.emitRawPointer(*
this);
7291 if (
auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
7293 Alloca->setMetadata(
7294 DeclPtrKind, llvm::MDNode::get(
7295 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
7296 }
else if (
auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
7303void CodeGenModule::EmitVersionIdentMetadata() {
7304 llvm::NamedMDNode *IdentMetadata =
7305 TheModule.getOrInsertNamedMetadata(
"llvm.ident");
7307 llvm::LLVMContext &Ctx = TheModule.getContext();
7309 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
7310 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
7313void CodeGenModule::EmitCommandLineMetadata() {
7314 llvm::NamedMDNode *CommandLineMetadata =
7315 TheModule.getOrInsertNamedMetadata(
"llvm.commandline");
7317 llvm::LLVMContext &Ctx = TheModule.getContext();
7319 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
7320 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
7323void CodeGenModule::EmitCoverageFile() {
7324 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu");
7328 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
7329 llvm::LLVMContext &Ctx = TheModule.getContext();
7330 auto *CoverageDataFile =
7332 auto *CoverageNotesFile =
7334 for (
int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
7335 llvm::MDNode *CU = CUNode->getOperand(i);
7336 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
7337 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
7358 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
7360 for (
auto RefExpr : D->
varlists()) {
7361 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
7363 VD->getAnyInitializer() &&
7364 !VD->getAnyInitializer()->isConstantInitializer(
getContext(),
7371 VD, Addr, RefExpr->getBeginLoc(), PerformInit))
7372 CXXGlobalInits.push_back(InitFunction);
7377CodeGenModule::CreateMetadataIdentifierImpl(
QualType T, MetadataTypeMap &Map,
7381 FnType->getReturnType(), FnType->getParamTypes(),
7382 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
7384 llvm::Metadata *&InternalId = Map[
T.getCanonicalType()];
7389 std::string OutName;
7390 llvm::raw_string_ostream Out(OutName);
7395 Out <<
".normalized";
7409 return CreateMetadataIdentifierImpl(
T, MetadataIdMap,
"");
7414 return CreateMetadataIdentifierImpl(
T, VirtualMetadataIdMap,
".virtual");
7434 for (
auto &Param : FnType->param_types())
7439 GeneralizedParams, FnType->getExtProtoInfo());
7446 llvm_unreachable(
"Encountered unknown FunctionType");
7451 GeneralizedMetadataIdMap,
".generalized");
7458 return ((LangOpts.
Sanitize.
has(SanitizerKind::CFIVCall) &&
7460 (LangOpts.
Sanitize.
has(SanitizerKind::CFINVCall) &&
7462 (LangOpts.
Sanitize.
has(SanitizerKind::CFIDerivedCast) &&
7464 (LangOpts.
Sanitize.
has(SanitizerKind::CFIUnrelatedCast) &&
7471 llvm::Metadata *MD =
7473 VTable->addTypeMetadata(Offset.getQuantity(), MD);
7475 if (CodeGenOpts.SanitizeCfiCrossDso)
7477 VTable->addTypeMetadata(Offset.getQuantity(),
7478 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
7481 llvm::Metadata *MD = llvm::MDString::get(
getLLVMContext(),
"all-vtables");
7482 VTable->addTypeMetadata(Offset.getQuantity(), MD);
7488 SanStats = std::make_unique<llvm::SanitizerStatReport>(&
getModule());
7498 auto *FTy = llvm::FunctionType::get(SamplerT, {
C->getType()},
false);
7513 bool forPointeeType) {
7524 if (
auto Align = TT->getDecl()->getMaxAlignment()) {
7554 if (
T.getQualifiers().hasUnaligned()) {
7556 }
else if (forPointeeType && !AlignForArray &&
7568 if (
unsigned MaxAlign =
getLangOpts().MaxTypeAlign) {
7581 if (NumAutoVarInit >= StopAfter) {
7584 if (!NumAutoVarInit) {
7587 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
7588 "number of times ftrivial-auto-var-init=%1 gets applied.");
7602 const Decl *D)
const {
7606 OS << (isa<VarDecl>(D) ?
".static." :
".intern.");
7608 OS << (isa<VarDecl>(D) ?
"__static__" :
"__intern__");
7614 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
7618 llvm::MD5::MD5Result
Result;
7619 for (
const auto &Arg : PreprocessorOpts.
Macros)
7620 Hash.update(Arg.first);
7624 llvm::sys::fs::UniqueID ID;
7625 if (llvm::sys::fs::getUniqueID(PLoc.
getFilename(), ID)) {
7627 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
7628 if (
auto EC = llvm::sys::fs::getUniqueID(PLoc.
getFilename(), ID))
7629 SM.getDiagnostics().Report(diag::err_cannot_open_file)
7632 OS << llvm::format(
"%x", ID.getFile()) << llvm::format(
"%x", ID.getDevice())
7633 <<
"_" << llvm::utohexstr(
Result.low(),
true, 8);
7640 assert(DeferredDeclsToEmit.empty() &&
7641 "Should have emitted all decls deferred to emit.");
7642 assert(NewBuilder->DeferredDecls.empty() &&
7643 "Newly created module should not have deferred decls");
7644 NewBuilder->DeferredDecls = std::move(DeferredDecls);
7645 assert(EmittedDeferredDecls.empty() &&
7646 "Still have (unmerged) EmittedDeferredDecls deferred decls");
7648 assert(NewBuilder->DeferredVTables.empty() &&
7649 "Newly created module should not have deferred vtables");
7650 NewBuilder->DeferredVTables = std::move(DeferredVTables);
7652 assert(NewBuilder->MangledDeclNames.empty() &&
7653 "Newly created module should not have mangled decl names");
7654 assert(NewBuilder->Manglings.empty() &&
7655 "Newly created module should not have manglings");
7656 NewBuilder->Manglings = std::move(Manglings);
7658 NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
7660 NewBuilder->TBAA = std::move(TBAA);
7662 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 FunctionDecl * createDefaultTargetVersionFrom(const FunctionDecl *FD)
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 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.
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.
llvm::DenseSet< const ValueDecl * > CUDAExternalDeviceDeclODRUsedByHost
Keep track of CUDA/HIP external kernels or device variables ODR-used by host code.
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.
CXXTemporary * getTemporary()
Represents a call to a C++ constructor.
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Represents a C++ base or member initializer.
Expr * getInit() const
Get the initializer.
Represents a delete expression for memory deallocation and destructor calls, e.g.
FunctionDecl * getOperatorDelete() const
Represents a C++ destructor within a class.
Represents a call to a member function that may be written either with member call syntax (e....
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Represents a static or instance method of a struct/union/class.
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
FunctionDecl * getOperatorNew() const
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
const CXXDestructorDecl * getDestructor() const
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
CharUnits - This is an opaque type for sizes expressed in character units.
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
static CharUnits One()
One - Construct a CharUnits quantity of one.
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::string 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.
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 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.
void EmitExternalDeclaration(const VarDecl *D)
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.
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.
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)
llvm::Type * ConvertTypeForMem(QualType T, bool ForBitField=false)
ConvertTypeForMem - Convert type T into a llvm::Type.
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.
void addDecl(Decl *D)
Add the declaration D into this context.
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
A reference to a declared variable, function, enum, etc.
Decl - This represents one declaration (or definition), e.g.
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.
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
SourceLocation getLocation() const
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
SourceLocation getBeginLoc() const LLVM_READONLY
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
The name of a declaration.
Represents a ValueDecl that came out of a declarator.
SourceLocation getBeginLoc() const LLVM_READONLY
TypeSourceInfo * getTypeSourceInfo() const
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...
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
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.
StorageClass getStorageClass() const
Returns the storage class as written in the source.
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...
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, Expr *TrailingRequiresClause=nullptr)
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
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.
DeclarationNameInfo getNameInfo() const
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.
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
unsigned getManglingNumber() const
Describes a module or submodule.
bool isInterfaceOrPartition() const
bool isNamedModuleUnit() const
Is this a C++20 named module unit.
Module * Parent
The parent of this module.
Module * getPrivateModuleFragment() const
Get the Private Module Fragment (sub-module) for this module, it there is one.
llvm::SmallSetVector< Module *, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Module * getGlobalModuleFragment() const
Get the Global Module Fragment (sub-module) for this module, it there is one.
llvm::iterator_range< submodule_iterator > submodules()
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used.
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
bool UseExportAsModuleLinkName
Autolinking uses the framework name for linking purposes when this is false and the export_as name ot...
This represents a decl that may have a name.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
LinkageInfo getLinkageAndVisibility() const
Determines the linkage and visibility of this entity.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
bool isExternallyVisible() const
Represent a C++ namespace.
This represents '#pragma omp threadprivate ...' directive.
ObjCEncodeExpr, used for @encode in Objective-C.
QualType getEncodedType() const
propimpl_range property_impls() const
const ObjCInterfaceDecl * getClassInterface() const
void addInstanceMethod(ObjCMethodDecl *method)
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
init_iterator init_end()
init_end() - Retrieve an iterator past the last initializer.
init_iterator init_begin()
init_begin() - Retrieve an iterator to the first initializer.
unsigned getNumIvarInitializers() const
getNumArgs - Number of ivars which must be initialized.
void setHasDestructors(bool val)
void setHasNonZeroConstructors(bool val)
Represents an ObjC class declaration.
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
ObjCIvarDecl - Represents an ObjC instance variable.
ObjCIvarDecl * getNextIvar()
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.
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.
bool isConstant(const ASTContext &Ctx) const
QualType getCanonicalType() const
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
QualType withCVRQualifiers(unsigned CVR) const
bool isConstQualified() const
Determine whether this type is const-qualified.
bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Represents a struct/union/class.
field_range fields() const
virtual void completeDefinition()
Note that the definition of this type is now complete.
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.
unsigned getLength() const
uint32_t getCodeUnit(size_t i) const
StringRef getString() const
unsigned getCharByteWidth() const
Represents the declaration of a struct/union/class/enum.
void startDefinition()
Starts the definition of this tag declaration.
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
A container of type source information.
QualType getType() const
Return the type wrapped by this type source info.
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 isReferenceType() const
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
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.
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
bool hasFlexibleArrayInit(const ASTContext &Ctx) const
Whether this variable has a flexible array member initialized with one or more elements.
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
const Expr * getInit() const
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
@ TLS_Dynamic
TLS with a dynamic initializer.
@ DeclarationOnly
This declaration is only a declaration.
@ Definition
This declaration is definitely a definition.
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Defines the clang::TargetInfo interface.
std::unique_ptr< TargetCodeGenInfo > createARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind Kind)
std::unique_ptr< TargetCodeGenInfo > createM68kTargetCodeGenInfo(CodeGenModule &CGM)
@ AttributedType
The l-value was considered opaque, so the alignment was determined from a type, but that type was an ...
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
std::unique_ptr< TargetCodeGenInfo > createBPFTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createMSP430TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel)
std::unique_ptr< TargetCodeGenInfo > createWebAssemblyTargetCodeGenInfo(CodeGenModule &CGM, WebAssemblyABIKind K)
std::unique_ptr< TargetCodeGenInfo > createPPC64_SVR4_TargetCodeGenInfo(CodeGenModule &CGM, PPC64_SVR4_ABIKind Kind, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createMIPSTargetCodeGenInfo(CodeGenModule &CGM, bool IsOS32)
std::unique_ptr< TargetCodeGenInfo > createHexagonTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createNVPTXTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createSystemZTargetCodeGenInfo(CodeGenModule &CGM, bool HasVector, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createWinX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters)
std::unique_ptr< TargetCodeGenInfo > createAIXTargetCodeGenInfo(CodeGenModule &CGM, bool Is64Bit)
std::unique_ptr< TargetCodeGenInfo > createAMDGPUTargetCodeGenInfo(CodeGenModule &CGM)
CGObjCRuntime * CreateMacObjCRuntime(CodeGenModule &CGM)
X86AVXABILevel
The AVX ABI level for X86 targets.
std::unique_ptr< TargetCodeGenInfo > createTCETargetCodeGenInfo(CodeGenModule &CGM)
CGObjCRuntime * CreateGNUObjCRuntime(CodeGenModule &CGM)
Creates an instance of an Objective-C runtime class.
std::unique_ptr< TargetCodeGenInfo > createWindowsARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind K)
std::unique_ptr< TargetCodeGenInfo > createAVRTargetCodeGenInfo(CodeGenModule &CGM, unsigned NPR, unsigned NRR)
std::unique_ptr< TargetCodeGenInfo > 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)
StorageClass
Storage classes.
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.
__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::PointerType * VoidPtrTy
llvm::IntegerType * Int64Ty
llvm::PointerType * ConstGlobalsPtrTy
void* in the address space for constant globals
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::IntegerType * CharTy
char
LangAS ASTAllocaAddressSpace
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
unsigned char IntAlignInBytes
llvm::Type * HalfTy
half, bfloat, float, double
unsigned char SizeSizeInBytes
llvm::CallingConv::ID getRuntimeCC() const
llvm::IntegerType * SizeTy
llvm::PointerType * GlobalsInt8PtrTy
llvm::IntegerType * Int32Ty
llvm::IntegerType * IntPtrTy
llvm::IntegerType * IntTy
int
llvm::IntegerType * Int16Ty
unsigned char PointerAlignInBytes
llvm::PointerType * Int8PtrTy
CharUnits getPointerAlign() const
llvm::PointerType * AllocaInt8PtrTy
DeclarationName getName() const
getName - Returns the embedded declaration name.
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.
Describes how types, statements, expressions, and declarations should be printed.
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.