50#include "llvm/ADT/STLExtras.h"
51#include "llvm/ADT/StringExtras.h"
52#include "llvm/ADT/StringSwitch.h"
53#include "llvm/Analysis/TargetLibraryInfo.h"
54#include "llvm/BinaryFormat/ELF.h"
55#include "llvm/IR/AttributeMask.h"
56#include "llvm/IR/CallingConv.h"
57#include "llvm/IR/DataLayout.h"
58#include "llvm/IR/Intrinsics.h"
59#include "llvm/IR/LLVMContext.h"
60#include "llvm/IR/Module.h"
61#include "llvm/IR/ProfileSummary.h"
62#include "llvm/ProfileData/InstrProfReader.h"
63#include "llvm/ProfileData/SampleProf.h"
64#include "llvm/Support/CRC.h"
65#include "llvm/Support/CodeGen.h"
66#include "llvm/Support/CommandLine.h"
67#include "llvm/Support/ConvertUTF.h"
68#include "llvm/Support/ErrorHandling.h"
69#include "llvm/Support/Hash.h"
70#include "llvm/Support/TimeProfiler.h"
71#include "llvm/TargetParser/AArch64TargetParser.h"
72#include "llvm/TargetParser/RISCVISAInfo.h"
73#include "llvm/TargetParser/Triple.h"
74#include "llvm/TargetParser/X86TargetParser.h"
75#include "llvm/Transforms/Instrumentation/KCFI.h"
76#include "llvm/Transforms/Utils/BuildLibCalls.h"
84 "limited-coverage-experimental", llvm::cl::Hidden,
85 llvm::cl::desc(
"Emit limited coverage mapping information (experimental)"));
92 case TargetCXXABI::AppleARM64:
93 case TargetCXXABI::Fuchsia:
94 case TargetCXXABI::GenericAArch64:
95 case TargetCXXABI::GenericARM:
96 case TargetCXXABI::iOS:
97 case TargetCXXABI::WatchOS:
98 case TargetCXXABI::GenericMIPS:
99 case TargetCXXABI::GenericItanium:
100 case TargetCXXABI::WebAssembly:
101 case TargetCXXABI::XL:
103 case TargetCXXABI::Microsoft:
107 llvm_unreachable(
"invalid C++ ABI kind");
110static std::unique_ptr<TargetCodeGenInfo>
113 const llvm::Triple &Triple =
Target.getTriple();
116 switch (Triple.getArch()) {
120 case llvm::Triple::m68k:
122 case llvm::Triple::mips:
123 case llvm::Triple::mipsel:
124 if (Triple.getOS() == llvm::Triple::Win32)
128 case llvm::Triple::mips64:
129 case llvm::Triple::mips64el:
132 case llvm::Triple::avr: {
136 unsigned NPR =
Target.getABI() ==
"avrtiny" ? 6 : 18;
137 unsigned NRR =
Target.getABI() ==
"avrtiny" ? 4 : 8;
141 case llvm::Triple::aarch64:
142 case llvm::Triple::aarch64_32:
143 case llvm::Triple::aarch64_be: {
145 if (
Target.getABI() ==
"darwinpcs")
146 Kind = AArch64ABIKind::DarwinPCS;
147 else if (Triple.isOSWindows())
149 else if (
Target.getABI() ==
"aapcs-soft")
150 Kind = AArch64ABIKind::AAPCSSoft;
155 case llvm::Triple::wasm32:
156 case llvm::Triple::wasm64: {
158 if (
Target.getABI() ==
"experimental-mv")
159 Kind = WebAssemblyABIKind::ExperimentalMV;
163 case llvm::Triple::arm:
164 case llvm::Triple::armeb:
165 case llvm::Triple::thumb:
166 case llvm::Triple::thumbeb: {
167 if (Triple.getOS() == llvm::Triple::Win32)
171 StringRef ABIStr =
Target.getABI();
172 if (ABIStr ==
"apcs-gnu")
173 Kind = ARMABIKind::APCS;
174 else if (ABIStr ==
"aapcs16")
175 Kind = ARMABIKind::AAPCS16_VFP;
176 else if (CodeGenOpts.
FloatABI ==
"hard" ||
177 (CodeGenOpts.
FloatABI !=
"soft" && Triple.isHardFloatABI()))
178 Kind = ARMABIKind::AAPCS_VFP;
183 case llvm::Triple::ppc: {
184 if (Triple.isOSAIX())
191 case llvm::Triple::ppcle: {
196 case llvm::Triple::ppc64:
197 if (Triple.isOSAIX())
200 if (Triple.isOSBinFormatELF()) {
202 if (
Target.getABI() ==
"elfv2")
203 Kind = PPC64_SVR4_ABIKind::ELFv2;
204 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
209 case llvm::Triple::ppc64le: {
210 assert(Triple.isOSBinFormatELF() &&
"PPC64 LE non-ELF not supported!");
212 if (
Target.getABI() ==
"elfv1")
213 Kind = PPC64_SVR4_ABIKind::ELFv1;
214 bool IsSoftFloat = CodeGenOpts.
FloatABI ==
"soft";
219 case llvm::Triple::nvptx:
220 case llvm::Triple::nvptx64:
223 case llvm::Triple::msp430:
226 case llvm::Triple::riscv32:
227 case llvm::Triple::riscv64: {
228 StringRef ABIStr =
Target.getABI();
230 unsigned ABIFLen = 0;
231 if (ABIStr.ends_with(
"f"))
233 else if (ABIStr.ends_with(
"d"))
235 bool EABI = ABIStr.ends_with(
"e");
239 case llvm::Triple::systemz: {
240 bool SoftFloat = CodeGenOpts.
FloatABI ==
"soft";
241 bool HasVector = !SoftFloat &&
Target.getABI() ==
"vector";
245 case llvm::Triple::tce:
246 case llvm::Triple::tcele:
249 case llvm::Triple::x86: {
250 bool IsDarwinVectorABI = Triple.isOSDarwin();
251 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
253 if (Triple.getOS() == llvm::Triple::Win32) {
255 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
256 CodeGenOpts.NumRegisterParameters);
259 CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
260 CodeGenOpts.NumRegisterParameters, CodeGenOpts.
FloatABI ==
"soft");
263 case llvm::Triple::x86_64: {
264 StringRef ABI =
Target.getABI();
265 X86AVXABILevel AVXLevel = (ABI ==
"avx512" ? X86AVXABILevel::AVX512
266 : ABI ==
"avx" ? X86AVXABILevel::AVX
267 : X86AVXABILevel::None);
269 switch (Triple.getOS()) {
270 case llvm::Triple::UEFI:
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:
298 case llvm::Triple::spirv:
300 case llvm::Triple::dxil:
302 case llvm::Triple::ve:
304 case llvm::Triple::csky: {
305 bool IsSoftFloat = !
Target.hasFeature(
"hard-float-abi");
307 Target.hasFeature(
"fpuv2_df") ||
Target.hasFeature(
"fpuv3_df");
312 case llvm::Triple::bpfeb:
313 case llvm::Triple::bpfel:
315 case llvm::Triple::loongarch32:
316 case llvm::Triple::loongarch64: {
317 StringRef ABIStr =
Target.getABI();
318 unsigned ABIFRLen = 0;
319 if (ABIStr.ends_with(
"f"))
321 else if (ABIStr.ends_with(
"d"))
330 if (!TheTargetCodeGenInfo)
332 return *TheTargetCodeGenInfo;
336 llvm::LLVMContext &Context,
340 if (Opts.AlignDouble || Opts.OpenCL || Opts.HLSL)
343 llvm::Triple Triple =
Target.getTriple();
344 llvm::DataLayout DL(
Target.getDataLayoutString());
345 auto Check = [&](
const char *Name, llvm::Type *Ty,
unsigned Alignment) {
346 llvm::Align DLAlign = DL.getABITypeAlign(Ty);
347 llvm::Align ClangAlign(Alignment / 8);
348 if (DLAlign != ClangAlign) {
349 llvm::errs() <<
"For target " << Triple.str() <<
" type " << Name
350 <<
" mapping to " << *Ty <<
" has data layout alignment "
351 << DLAlign.value() <<
" while clang specifies "
352 << ClangAlign.value() <<
"\n";
357 Check(
"bool", llvm::Type::getIntNTy(Context,
Target.BoolWidth),
359 Check(
"short", llvm::Type::getIntNTy(Context,
Target.ShortWidth),
361 Check(
"int", llvm::Type::getIntNTy(Context,
Target.IntWidth),
363 Check(
"long", llvm::Type::getIntNTy(Context,
Target.LongWidth),
366 if (Triple.getArch() != llvm::Triple::m68k)
367 Check(
"long long", llvm::Type::getIntNTy(Context,
Target.LongLongWidth),
370 if (
Target.hasInt128Type() && !
Target.getTargetOpts().ForceEnableInt128 &&
371 !Triple.isAMDGPU() && !Triple.isSPIRV() &&
372 Triple.getArch() != llvm::Triple::ve)
373 Check(
"__int128", llvm::Type::getIntNTy(Context, 128),
Target.Int128Align);
375 if (
Target.hasFloat16Type())
376 Check(
"half", llvm::Type::getFloatingPointTy(Context, *
Target.HalfFormat),
378 if (
Target.hasBFloat16Type())
379 Check(
"bfloat", llvm::Type::getBFloatTy(Context),
Target.BFloat16Align);
380 Check(
"float", llvm::Type::getFloatingPointTy(Context, *
Target.FloatFormat),
382 Check(
"double", llvm::Type::getFloatingPointTy(Context, *
Target.DoubleFormat),
385 llvm::Type::getFloatingPointTy(Context, *
Target.LongDoubleFormat),
387 if (
Target.hasFloat128Type())
388 Check(
"__float128", llvm::Type::getFP128Ty(Context),
Target.Float128Align);
389 if (
Target.hasIbm128Type())
390 Check(
"__ibm128", llvm::Type::getPPC_FP128Ty(Context),
Target.Ibm128Align);
392 Check(
"void*", llvm::PointerType::getUnqual(Context),
Target.PointerAlign);
403 : Context(
C), LangOpts(
C.
getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
404 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
406 VMContext(M.
getContext()), VTables(*this), StackHandler(diags),
412 llvm::LLVMContext &LLVMContext = M.getContext();
413 VoidTy = llvm::Type::getVoidTy(LLVMContext);
414 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
415 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
416 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
417 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
418 HalfTy = llvm::Type::getHalfTy(LLVMContext);
419 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
420 FloatTy = llvm::Type::getFloatTy(LLVMContext);
421 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
427 C.toCharUnitsFromBits(
C.getTargetInfo().getMaxPointerWidth()).getQuantity();
429 C.toCharUnitsFromBits(
C.getTargetInfo().getIntAlign()).getQuantity();
431 llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getCharWidth());
432 IntTy = llvm::IntegerType::get(LLVMContext,
C.getTargetInfo().getIntWidth());
433 IntPtrTy = llvm::IntegerType::get(LLVMContext,
434 C.getTargetInfo().getMaxPointerWidth());
435 Int8PtrTy = llvm::PointerType::get(LLVMContext,
437 const llvm::DataLayout &DL = M.getDataLayout();
439 llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
441 llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
458 createOpenCLRuntime();
460 createOpenMPRuntime();
467 if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Thread | SanitizerKind::Type) ||
468 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
474 if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
475 CodeGenOpts.CoverageNotesFile.size() ||
476 CodeGenOpts.CoverageDataFile.size())
484 Block.GlobalUniqueCount = 0;
486 if (
C.getLangOpts().ObjC)
489 if (CodeGenOpts.hasProfileClangUse()) {
490 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
491 CodeGenOpts.ProfileInstrumentUsePath, *FS,
492 CodeGenOpts.ProfileRemappingFile);
493 if (
auto E = ReaderOrErr.takeError()) {
494 llvm::handleAllErrors(std::move(E), [&](
const llvm::ErrorInfoBase &EI) {
495 Diags.Report(diag::err_reading_profile)
496 << CodeGenOpts.ProfileInstrumentUsePath << EI.message();
500 PGOReader = std::move(ReaderOrErr.get());
505 if (CodeGenOpts.CoverageMapping)
509 if (CodeGenOpts.UniqueInternalLinkageNames &&
510 !
getModule().getSourceFileName().empty()) {
511 std::string Path =
getModule().getSourceFileName();
513 for (
const auto &Entry : LangOpts.MacroPrefixMap)
514 if (Path.rfind(Entry.first, 0) != std::string::npos) {
515 Path = Entry.second + Path.substr(Entry.first.size());
518 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path);
522 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
523 getModule().addModuleFlag(llvm::Module::Error,
"NumRegisterParameters",
524 CodeGenOpts.NumRegisterParameters);
533 const llvm::MemoryBuffer &FileBuffer = **BufOrErr;
534 for (llvm::line_iterator I(FileBuffer.getMemBufferRef(),
true), E;
536 this->MSHotPatchFunctions.push_back(std::string{*I});
538 auto &DE = Context.getDiagnostics();
539 DE.Report(diag::err_open_hotpatch_file_failed)
541 << BufOrErr.getError().message();
546 this->MSHotPatchFunctions.push_back(FuncName);
548 llvm::sort(this->MSHotPatchFunctions);
551 if (!Context.getAuxTargetInfo())
557void CodeGenModule::createObjCRuntime() {
574 llvm_unreachable(
"bad runtime kind");
577void CodeGenModule::createOpenCLRuntime() {
581void CodeGenModule::createOpenMPRuntime() {
582 if (!LangOpts.OMPHostIRFile.empty() && !FS->exists(LangOpts.OMPHostIRFile))
583 Diags.Report(diag::err_omp_host_ir_file_not_found)
584 << LangOpts.OMPHostIRFile;
589 case llvm::Triple::nvptx:
590 case llvm::Triple::nvptx64:
591 case llvm::Triple::amdgcn:
592 case llvm::Triple::spirv64:
595 "OpenMP AMDGPU/NVPTX/SPIRV is only prepared to deal with device code.");
596 OpenMPRuntime.reset(
new CGOpenMPRuntimeGPU(*
this));
599 if (LangOpts.OpenMPSimd)
600 OpenMPRuntime.reset(
new CGOpenMPSIMDRuntime(*
this));
602 OpenMPRuntime.reset(
new CGOpenMPRuntime(*
this));
607void CodeGenModule::createCUDARuntime() {
611void CodeGenModule::createHLSLRuntime() {
612 HLSLRuntime.reset(
new CGHLSLRuntime(*
this));
616 Replacements[Name] =
C;
619void CodeGenModule::applyReplacements() {
620 for (
auto &I : Replacements) {
621 StringRef MangledName = I.first;
622 llvm::Constant *Replacement = I.second;
627 auto *NewF = dyn_cast<llvm::Function>(Replacement);
629 if (
auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
630 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
633 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
634 CE->getOpcode() == llvm::Instruction::GetElementPtr);
635 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
640 OldF->replaceAllUsesWith(Replacement);
642 NewF->removeFromParent();
643 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
646 OldF->eraseFromParent();
651 GlobalValReplacements.push_back(std::make_pair(GV,
C));
654void CodeGenModule::applyGlobalValReplacements() {
655 for (
auto &I : GlobalValReplacements) {
656 llvm::GlobalValue *GV = I.first;
657 llvm::Constant *
C = I.second;
659 GV->replaceAllUsesWith(
C);
660 GV->eraseFromParent();
667 const llvm::Constant *
C;
668 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
669 C = GA->getAliasee();
670 else if (
auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
671 C = GI->getResolver();
675 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(
C->stripPointerCasts());
679 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
688 bool IsIFunc,
const llvm::GlobalValue *Alias,
const llvm::GlobalValue *&GV,
689 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
693 Diags.
Report(Location, diag::err_cyclic_alias) << IsIFunc;
697 if (GV->hasCommonLinkage()) {
698 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
699 if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
700 Diags.
Report(Location, diag::err_alias_to_common);
705 if (GV->isDeclaration()) {
706 Diags.
Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
707 Diags.
Report(Location, diag::note_alias_requires_mangled_name)
708 << IsIFunc << IsIFunc;
711 for (
const auto &[
Decl, Name] : MangledDeclNames) {
712 if (
const auto *ND = dyn_cast<NamedDecl>(
Decl.getDecl())) {
714 if (II && II->
getName() == GV->getName()) {
715 Diags.
Report(Location, diag::note_alias_mangled_name_alternative)
719 (Twine(IsIFunc ?
"ifunc" :
"alias") +
"(\"" + Name +
"\")")
729 const auto *F = dyn_cast<llvm::Function>(GV);
731 Diags.
Report(Location, diag::err_alias_to_undefined)
732 << IsIFunc << IsIFunc;
736 llvm::FunctionType *FTy = F->getFunctionType();
737 if (!FTy->getReturnType()->isPointerTy()) {
738 Diags.
Report(Location, diag::err_ifunc_resolver_return);
752 if (GVar->hasAttribute(
"toc-data")) {
753 auto GVId = GVar->getName();
756 Diags.
Report(Location, diag::warn_toc_unsupported_type)
757 << GVId <<
"the variable has an alias";
759 llvm::AttributeSet CurrAttributes = GVar->getAttributes();
760 llvm::AttributeSet NewAttributes =
761 CurrAttributes.removeAttribute(GVar->getContext(),
"toc-data");
762 GVar->setAttributes(NewAttributes);
766void CodeGenModule::checkAliases() {
771 DiagnosticsEngine &Diags =
getDiags();
772 for (
const GlobalDecl &GD : Aliases) {
774 SourceLocation Location;
776 bool IsIFunc = D->hasAttr<IFuncAttr>();
777 if (
const Attr *A = D->getDefiningAttr()) {
778 Location = A->getLocation();
779 Range = A->getRange();
781 llvm_unreachable(
"Not an alias or ifunc?");
785 const llvm::GlobalValue *GV =
nullptr;
787 MangledDeclNames, Range)) {
793 if (
const llvm::GlobalVariable *GVar =
794 dyn_cast<const llvm::GlobalVariable>(GV))
798 llvm::Constant *Aliasee =
802 llvm::GlobalValue *AliaseeGV;
803 if (
auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
808 if (
const SectionAttr *SA = D->getAttr<SectionAttr>()) {
809 StringRef AliasSection = SA->getName();
810 if (AliasSection != AliaseeGV->getSection())
811 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
812 << AliasSection << IsIFunc << IsIFunc;
820 if (
auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
821 if (GA->isInterposable()) {
822 Diags.Report(Location, diag::warn_alias_to_weak_alias)
823 << GV->getName() << GA->getName() << IsIFunc;
824 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
825 GA->getAliasee(), Alias->getType());
837 llvm::Attribute::DisableSanitizerInstrumentation);
842 for (
const GlobalDecl &GD : Aliases) {
845 Alias->replaceAllUsesWith(llvm::PoisonValue::get(Alias->getType()));
846 Alias->eraseFromParent();
851 DeferredDeclsToEmit.clear();
852 EmittedDeferredDecls.clear();
853 DeferredAnnotations.clear();
855 OpenMPRuntime->clear();
859 StringRef MainFile) {
862 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
863 if (MainFile.empty())
864 MainFile =
"<stdin>";
865 Diags.
Report(diag::warn_profile_data_unprofiled) << MainFile;
868 Diags.
Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
871 Diags.
Report(diag::warn_profile_data_missing) << Visited << Missing;
875static std::optional<llvm::GlobalValue::VisibilityTypes>
882 return llvm::GlobalValue::DefaultVisibility;
884 return llvm::GlobalValue::HiddenVisibility;
886 return llvm::GlobalValue::ProtectedVisibility;
888 llvm_unreachable(
"unknown option value!");
893 std::optional<llvm::GlobalValue::VisibilityTypes>
V) {
902 GV.setDSOLocal(
false);
903 GV.setVisibility(*
V);
908 if (!LO.VisibilityFromDLLStorageClass)
911 std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
914 std::optional<llvm::GlobalValue::VisibilityTypes>
915 NoDLLStorageClassVisibility =
918 std::optional<llvm::GlobalValue::VisibilityTypes>
919 ExternDeclDLLImportVisibility =
922 std::optional<llvm::GlobalValue::VisibilityTypes>
923 ExternDeclNoDLLStorageClassVisibility =
926 for (llvm::GlobalValue &GV : M.global_values()) {
927 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
930 if (GV.isDeclarationForLinker())
932 llvm::GlobalValue::DLLImportStorageClass
933 ? ExternDeclDLLImportVisibility
934 : ExternDeclNoDLLStorageClassVisibility);
937 llvm::GlobalValue::DLLExportStorageClass
938 ? DLLExportVisibility
939 : NoDLLStorageClassVisibility);
941 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
946 const llvm::Triple &Triple,
950 return LangOpts.getStackProtector() == Mode;
953std::optional<llvm::Attribute::AttrKind>
955 if (D && D->
hasAttr<NoStackProtectorAttr>())
957 else if (D && D->
hasAttr<StrictGuardStackCheckAttr>() &&
959 return llvm::Attribute::StackProtectStrong;
961 return llvm::Attribute::StackProtect;
963 return llvm::Attribute::StackProtectStrong;
965 return llvm::Attribute::StackProtectReq;
972 EmitModuleInitializers(Primary);
974 DeferredDecls.insert_range(EmittedDeferredDecls);
975 EmittedDeferredDecls.clear();
976 EmitVTablesOpportunistically();
977 applyGlobalValReplacements();
979 emitMultiVersionFunctions();
981 if (Context.getLangOpts().IncrementalExtensions &&
982 GlobalTopLevelStmtBlockInFlight.first) {
984 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->
getEndLoc());
985 GlobalTopLevelStmtBlockInFlight = {
nullptr,
nullptr};
991 EmitCXXModuleInitFunc(Primary);
993 EmitCXXGlobalInitFunc();
994 EmitCXXGlobalCleanUpFunc();
995 registerGlobalDtorsWithAtExit();
996 EmitCXXThreadLocalInitFunc();
998 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
1000 if (Context.getLangOpts().CUDA && CUDARuntime) {
1001 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
1004 if (OpenMPRuntime) {
1005 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
1006 OpenMPRuntime->clear();
1010 PGOReader->getSummary(
false).getMD(VMContext),
1011 llvm::ProfileSummary::PSK_Instr);
1012 if (PGOStats.hasDiagnostics())
1018 EmitCtorList(GlobalCtors,
"llvm.global_ctors");
1019 EmitCtorList(GlobalDtors,
"llvm.global_dtors");
1021 EmitStaticExternCAliases();
1026 if (CoverageMapping)
1027 CoverageMapping->emit();
1028 if (CodeGenOpts.SanitizeCfiCrossDso) {
1032 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
1034 emitAtAvailableLinkGuard();
1035 if (Context.getTargetInfo().getTriple().isWasm())
1042 if (
getTarget().getTargetOpts().CodeObjectVersion !=
1043 llvm::CodeObjectVersionKind::COV_None) {
1044 getModule().addModuleFlag(llvm::Module::Error,
1045 "amdhsa_code_object_version",
1046 getTarget().getTargetOpts().CodeObjectVersion);
1051 auto *MDStr = llvm::MDString::get(
1056 getModule().addModuleFlag(llvm::Module::Error,
"amdgpu_printf_kind",
1065 if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) {
1067 for (
auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) {
1069 if (
auto *FD = dyn_cast<FunctionDecl>(D))
1073 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1077 llvm::ArrayType *ATy = llvm::ArrayType::get(
Int8PtrTy, UsedArray.size());
1079 auto *GV =
new llvm::GlobalVariable(
1080 getModule(), ATy,
false, llvm::GlobalValue::InternalLinkage,
1081 llvm::ConstantArray::get(ATy, UsedArray),
"__clang_gpu_used_external");
1087 auto *GV =
new llvm::GlobalVariable(
1089 llvm::Constant::getNullValue(
Int8Ty),
1098 if (CodeGenOpts.Autolink &&
1099 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
1100 EmitModuleLinkOptions();
1115 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
1116 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.dependent-libraries");
1117 for (
auto *MD : ELFDependentLibraries)
1118 NMD->addOperand(MD);
1121 if (CodeGenOpts.DwarfVersion) {
1122 getModule().addModuleFlag(llvm::Module::Max,
"Dwarf Version",
1123 CodeGenOpts.DwarfVersion);
1126 if (CodeGenOpts.Dwarf64)
1127 getModule().addModuleFlag(llvm::Module::Max,
"DWARF64", 1);
1129 if (Context.getLangOpts().SemanticInterposition)
1131 getModule().setSemanticInterposition(
true);
1133 if (CodeGenOpts.EmitCodeView) {
1135 getModule().addModuleFlag(llvm::Module::Warning,
"CodeView", 1);
1137 if (CodeGenOpts.CodeViewGHash) {
1138 getModule().addModuleFlag(llvm::Module::Warning,
"CodeViewGHash", 1);
1140 if (CodeGenOpts.ControlFlowGuard) {
1143 llvm::Module::Warning,
"cfguard",
1144 static_cast<unsigned>(llvm::ControlFlowGuardMode::Enabled));
1145 }
else if (CodeGenOpts.ControlFlowGuardNoChecks) {
1148 llvm::Module::Warning,
"cfguard",
1149 static_cast<unsigned>(llvm::ControlFlowGuardMode::TableOnly));
1151 if (CodeGenOpts.EHContGuard) {
1153 getModule().addModuleFlag(llvm::Module::Warning,
"ehcontguard", 1);
1155 if (Context.getLangOpts().Kernel) {
1157 getModule().addModuleFlag(llvm::Module::Warning,
"ms-kernel", 1);
1159 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
1164 getModule().addModuleFlag(llvm::Module::Error,
"StrictVTablePointers",1);
1166 llvm::Metadata *Ops[2] = {
1167 llvm::MDString::get(VMContext,
"StrictVTablePointers"),
1168 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1169 llvm::Type::getInt32Ty(VMContext), 1))};
1171 getModule().addModuleFlag(llvm::Module::Require,
1172 "StrictVTablePointersRequirement",
1173 llvm::MDNode::get(VMContext, Ops));
1179 getModule().addModuleFlag(llvm::Module::Warning,
"Debug Info Version",
1180 llvm::DEBUG_METADATA_VERSION);
1185 uint64_t WCharWidth =
1186 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
1187 getModule().addModuleFlag(llvm::Module::Error,
"wchar_size", WCharWidth);
1190 getModule().addModuleFlag(llvm::Module::Warning,
1191 "zos_product_major_version",
1192 uint32_t(CLANG_VERSION_MAJOR));
1193 getModule().addModuleFlag(llvm::Module::Warning,
1194 "zos_product_minor_version",
1195 uint32_t(CLANG_VERSION_MINOR));
1196 getModule().addModuleFlag(llvm::Module::Warning,
"zos_product_patchlevel",
1197 uint32_t(CLANG_VERSION_PATCHLEVEL));
1199 getModule().addModuleFlag(llvm::Module::Error,
"zos_product_id",
1200 llvm::MDString::get(VMContext, ProductId));
1205 getModule().addModuleFlag(llvm::Module::Error,
"zos_cu_language",
1206 llvm::MDString::get(VMContext, lang_str));
1208 time_t TT = PreprocessorOpts.SourceDateEpoch
1209 ? *PreprocessorOpts.SourceDateEpoch
1210 : std::time(
nullptr);
1211 getModule().addModuleFlag(llvm::Module::Max,
"zos_translation_time",
1212 static_cast<uint64_t
>(TT));
1215 getModule().addModuleFlag(llvm::Module::Error,
"zos_le_char_mode",
1216 llvm::MDString::get(VMContext,
"ascii"));
1219 llvm::Triple
T = Context.getTargetInfo().getTriple();
1220 if (
T.isARM() ||
T.isThumb()) {
1222 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
1223 getModule().addModuleFlag(llvm::Module::Error,
"min_enum_size", EnumWidth);
1227 StringRef ABIStr = Target.getABI();
1228 llvm::LLVMContext &Ctx = TheModule.getContext();
1229 getModule().addModuleFlag(llvm::Module::Error,
"target-abi",
1230 llvm::MDString::get(Ctx, ABIStr));
1235 const std::vector<std::string> &Features =
1238 llvm::RISCVISAInfo::parseFeatures(
T.isRISCV64() ? 64 : 32, Features);
1239 if (!errorToBool(ParseResult.takeError()))
1241 llvm::Module::AppendUnique,
"riscv-isa",
1243 Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString())));
1246 if (CodeGenOpts.SanitizeCfiCrossDso) {
1248 getModule().addModuleFlag(llvm::Module::Override,
"Cross-DSO CFI", 1);
1251 if (CodeGenOpts.WholeProgramVTables) {
1255 getModule().addModuleFlag(llvm::Module::Error,
"Virtual Function Elim",
1256 CodeGenOpts.VirtualFunctionElimination);
1259 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
1260 getModule().addModuleFlag(llvm::Module::Override,
1261 "CFI Canonical Jump Tables",
1262 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1265 if (CodeGenOpts.SanitizeCfiICallNormalizeIntegers) {
1266 getModule().addModuleFlag(llvm::Module::Override,
"cfi-normalize-integers",
1270 if (!CodeGenOpts.UniqueSourceFileIdentifier.empty()) {
1272 llvm::Module::Append,
"Unique Source File Identifier",
1274 TheModule.getContext(),
1275 llvm::MDString::get(TheModule.getContext(),
1276 CodeGenOpts.UniqueSourceFileIdentifier)));
1279 if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) {
1280 getModule().addModuleFlag(llvm::Module::Override,
"kcfi", 1);
1283 if (CodeGenOpts.PatchableFunctionEntryOffset)
1284 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-offset",
1285 CodeGenOpts.PatchableFunctionEntryOffset);
1286 if (CodeGenOpts.SanitizeKcfiArity)
1287 getModule().addModuleFlag(llvm::Module::Override,
"kcfi-arity", 1);
1290 llvm::Module::Override,
"kcfi-hash",
1291 llvm::MDString::get(
1293 llvm::stringifyKCFIHashAlgorithm(CodeGenOpts.SanitizeKcfiHash)));
1296 if (CodeGenOpts.CFProtectionReturn &&
1297 Target.checkCFProtectionReturnSupported(
getDiags())) {
1299 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-return",
1303 if (CodeGenOpts.CFProtectionBranch &&
1304 Target.checkCFProtectionBranchSupported(
getDiags())) {
1306 getModule().addModuleFlag(llvm::Module::Min,
"cf-protection-branch",
1309 auto Scheme = CodeGenOpts.getCFBranchLabelScheme();
1310 if (Target.checkCFBranchLabelSchemeSupported(Scheme,
getDiags())) {
1312 Scheme = Target.getDefaultCFBranchLabelScheme();
1314 llvm::Module::Error,
"cf-branch-label-scheme",
1320 if (CodeGenOpts.FunctionReturnThunks)
1321 getModule().addModuleFlag(llvm::Module::Override,
"function_return_thunk_extern", 1);
1323 if (CodeGenOpts.IndirectBranchCSPrefix)
1324 getModule().addModuleFlag(llvm::Module::Override,
"indirect_branch_cs_prefix", 1);
1335 if (Context.getTargetInfo().hasFeature(
"ptrauth") &&
1336 LangOpts.getSignReturnAddressScope() !=
1338 getModule().addModuleFlag(llvm::Module::Override,
1339 "sign-return-address-buildattr", 1);
1340 if (LangOpts.Sanitize.has(SanitizerKind::MemtagStack))
1341 getModule().addModuleFlag(llvm::Module::Override,
1342 "tag-stack-memory-buildattr", 1);
1344 if (
T.isARM() ||
T.isThumb() ||
T.isAArch64()) {
1352 if (LangOpts.BranchTargetEnforcement)
1353 getModule().addModuleFlag(llvm::Module::Min,
"branch-target-enforcement",
1355 if (LangOpts.BranchProtectionPAuthLR)
1356 getModule().addModuleFlag(llvm::Module::Min,
"branch-protection-pauth-lr",
1358 if (LangOpts.GuardedControlStack)
1359 getModule().addModuleFlag(llvm::Module::Min,
"guarded-control-stack", 2);
1360 if (LangOpts.hasSignReturnAddress())
1361 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address", 2);
1362 if (LangOpts.isSignReturnAddressScopeAll())
1363 getModule().addModuleFlag(llvm::Module::Min,
"sign-return-address-all",
1365 if (!LangOpts.isSignReturnAddressWithAKey())
1366 getModule().addModuleFlag(llvm::Module::Min,
1367 "sign-return-address-with-bkey", 2);
1369 if (LangOpts.PointerAuthELFGOT)
1370 getModule().addModuleFlag(llvm::Module::Min,
"ptrauth-elf-got", 1);
1373 if (LangOpts.PointerAuthCalls)
1374 getModule().addModuleFlag(llvm::Module::Min,
"ptrauth-sign-personality",
1377 using namespace llvm::ELF;
1378 uint64_t PAuthABIVersion =
1379 (LangOpts.PointerAuthIntrinsics
1380 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS) |
1381 (LangOpts.PointerAuthCalls
1382 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS) |
1383 (LangOpts.PointerAuthReturns
1384 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS) |
1385 (LangOpts.PointerAuthAuthTraps
1386 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS) |
1387 (LangOpts.PointerAuthVTPtrAddressDiscrimination
1388 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR) |
1389 (LangOpts.PointerAuthVTPtrTypeDiscrimination
1390 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR) |
1391 (LangOpts.PointerAuthInitFini
1392 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI) |
1393 (LangOpts.PointerAuthInitFiniAddressDiscrimination
1394 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC) |
1395 (LangOpts.PointerAuthELFGOT
1396 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT) |
1397 (LangOpts.PointerAuthIndirectGotos
1398 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS) |
1399 (LangOpts.PointerAuthTypeInfoVTPtrDiscrimination
1400 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR) |
1401 (LangOpts.PointerAuthFunctionTypeDiscrimination
1402 << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR);
1403 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR ==
1404 AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
1405 "Update when new enum items are defined");
1406 if (PAuthABIVersion != 0) {
1407 getModule().addModuleFlag(llvm::Module::Error,
1408 "aarch64-elf-pauthabi-platform",
1409 AARCH64_PAUTH_PLATFORM_LLVM_LINUX);
1410 getModule().addModuleFlag(llvm::Module::Error,
1411 "aarch64-elf-pauthabi-version",
1417 if (CodeGenOpts.StackClashProtector)
1419 llvm::Module::Override,
"probe-stack",
1420 llvm::MDString::get(TheModule.getContext(),
"inline-asm"));
1422 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
1423 getModule().addModuleFlag(llvm::Module::Min,
"stack-probe-size",
1424 CodeGenOpts.StackProbeSize);
1426 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1427 llvm::LLVMContext &Ctx = TheModule.getContext();
1429 llvm::Module::Error,
"MemProfProfileFilename",
1430 llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
1433 if (LangOpts.CUDAIsDevice &&
getTriple().isNVPTX()) {
1437 getModule().addModuleFlag(llvm::Module::Override,
"nvvm-reflect-ftz",
1438 CodeGenOpts.FP32DenormalMode.Output !=
1439 llvm::DenormalMode::IEEE);
1442 if (LangOpts.EHAsynch)
1443 getModule().addModuleFlag(llvm::Module::Warning,
"eh-asynch", 1);
1446 if (CodeGenOpts.ImportCallOptimization)
1447 getModule().addModuleFlag(llvm::Module::Warning,
"import-call-optimization",
1451 if (CodeGenOpts.getWinX64EHUnwindV2() != llvm::WinX64EHUnwindV2Mode::Disabled)
1453 llvm::Module::Warning,
"winx64-eh-unwindv2",
1454 static_cast<unsigned>(CodeGenOpts.getWinX64EHUnwindV2()));
1458 getModule().addModuleFlag(llvm::Module::Max,
"openmp", LangOpts.OpenMP);
1460 getModule().addModuleFlag(llvm::Module::Max,
"openmp-device",
1464 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())) {
1465 EmitOpenCLMetadata();
1472 auto Version = LangOpts.getOpenCLCompatibleVersion();
1473 llvm::Metadata *SPIRVerElts[] = {
1474 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1476 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1477 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
1478 llvm::NamedMDNode *SPIRVerMD =
1479 TheModule.getOrInsertNamedMetadata(
"opencl.spir.version");
1480 llvm::LLVMContext &Ctx = TheModule.getContext();
1481 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
1489 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
1490 assert(PLevel < 3 &&
"Invalid PIC Level");
1491 getModule().setPICLevel(
static_cast<llvm::PICLevel::Level
>(PLevel));
1492 if (Context.getLangOpts().PIE)
1493 getModule().setPIELevel(
static_cast<llvm::PIELevel::Level
>(PLevel));
1497 unsigned CM = llvm::StringSwitch<unsigned>(
getCodeGenOpts().CodeModel)
1498 .Case(
"tiny", llvm::CodeModel::Tiny)
1499 .Case(
"small", llvm::CodeModel::Small)
1500 .Case(
"kernel", llvm::CodeModel::Kernel)
1501 .Case(
"medium", llvm::CodeModel::Medium)
1502 .Case(
"large", llvm::CodeModel::Large)
1505 llvm::CodeModel::Model codeModel =
static_cast<llvm::CodeModel::Model
>(CM);
1508 if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
1509 Context.getTargetInfo().getTriple().getArch() ==
1510 llvm::Triple::x86_64) {
1516 if (CodeGenOpts.NoPLT)
1519 CodeGenOpts.DirectAccessExternalData !=
1520 getModule().getDirectAccessExternalData()) {
1521 getModule().setDirectAccessExternalData(
1522 CodeGenOpts.DirectAccessExternalData);
1524 if (CodeGenOpts.UnwindTables)
1525 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1527 switch (CodeGenOpts.getFramePointer()) {
1532 getModule().setFramePointer(llvm::FramePointerKind::Reserved);
1535 getModule().setFramePointer(llvm::FramePointerKind::NonLeafNoReserve);
1538 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1541 getModule().setFramePointer(llvm::FramePointerKind::All);
1545 SimplifyPersonality();
1558 EmitVersionIdentMetadata();
1561 EmitCommandLineMetadata();
1569 getModule().setStackProtectorGuardSymbol(
1572 getModule().setStackProtectorGuardOffset(
1577 getModule().addModuleFlag(llvm::Module::Override,
"SkipRaxSetup", 1);
1579 getModule().addModuleFlag(llvm::Module::Override,
"RegCallv4", 1);
1581 if (
getContext().getTargetInfo().getMaxTLSAlign())
1582 getModule().addModuleFlag(llvm::Module::Error,
"MaxTLSAlign",
1583 getContext().getTargetInfo().getMaxTLSAlign());
1601 if (!MustTailCallUndefinedGlobals.empty()) {
1603 for (
auto &I : MustTailCallUndefinedGlobals) {
1604 if (!I.first->isDefined())
1605 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1609 if (!Entry || Entry->isWeakForLinker() ||
1610 Entry->isDeclarationForLinker())
1611 getDiags().
Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1615 for (
auto &I : MustTailCallUndefinedGlobals) {
1624 if (Entry->isDeclarationForLinker()) {
1627 Entry->hasHiddenVisibility() || Entry->hasProtectedVisibility();
1629 CalleeIsLocal = Entry->isDSOLocal();
1633 getDiags().
Report(I.second, diag::err_mips_impossible_musttail) << 1;
1644 auto *ErrnoTBAAMD = TheModule.getOrInsertNamedMetadata(
ErrnoTBAAMDName);
1645 ErrnoTBAAMD->addOperand(IntegerNode);
1650void CodeGenModule::EmitOpenCLMetadata() {
1656 auto EmitVersion = [
this](StringRef MDName,
int Version) {
1657 llvm::Metadata *OCLVerElts[] = {
1658 llvm::ConstantAsMetadata::get(
1659 llvm::ConstantInt::get(
Int32Ty, Version / 100)),
1660 llvm::ConstantAsMetadata::get(
1661 llvm::ConstantInt::get(
Int32Ty, (Version % 100) / 10))};
1662 llvm::NamedMDNode *OCLVerMD = TheModule.getOrInsertNamedMetadata(MDName);
1663 llvm::LLVMContext &Ctx = TheModule.getContext();
1664 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
1667 EmitVersion(
"opencl.ocl.version", CLVersion);
1668 if (LangOpts.OpenCLCPlusPlus) {
1670 EmitVersion(
"opencl.cxx.version", LangOpts.OpenCLCPlusPlusVersion);
1674void CodeGenModule::EmitBackendOptionsMetadata(
1675 const CodeGenOptions &CodeGenOpts) {
1677 getModule().addModuleFlag(llvm::Module::Min,
"SmallDataLimit",
1678 CodeGenOpts.SmallDataLimit);
1682 if (LangOpts.AllocTokenMode) {
1683 StringRef S = llvm::getAllocTokenModeAsString(*LangOpts.AllocTokenMode);
1684 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-mode",
1685 llvm::MDString::get(VMContext, S));
1687 if (LangOpts.AllocTokenMax)
1689 llvm::Module::Error,
"alloc-token-max",
1690 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1691 *LangOpts.AllocTokenMax));
1692 if (CodeGenOpts.SanitizeAllocTokenFastABI)
1693 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-fast-abi", 1);
1694 if (CodeGenOpts.SanitizeAllocTokenExtended)
1695 getModule().addModuleFlag(llvm::Module::Error,
"alloc-token-extended", 1);
1711 return TBAA->getTypeInfo(QTy);
1730 return TBAA->getAccessInfo(AccessType);
1737 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
1743 return TBAA->getTBAAStructInfo(QTy);
1749 return TBAA->getBaseTypeInfo(QTy);
1755 return TBAA->getAccessTagInfo(Info);
1762 return TBAA->mergeTBAAInfoForCast(SourceInfo,
TargetInfo);
1770 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
1778 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
1784 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
1789 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
1801 std::string Msg =
Type;
1803 diag::err_codegen_unsupported)
1809 diag::err_codegen_unsupported)
1816 std::string Msg =
Type;
1818 diag::err_codegen_unsupported)
1823 llvm::function_ref<
void()> Fn) {
1824 StackHandler.runWithSufficientStackSpace(Loc, Fn);
1834 if (GV->hasLocalLinkage()) {
1835 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1848 if (Context.getLangOpts().OpenMP &&
1849 Context.getLangOpts().OpenMPIsTargetDevice &&
isa<VarDecl>(D) &&
1850 D->
hasAttr<OMPDeclareTargetDeclAttr>() &&
1851 D->
getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
1852 OMPDeclareTargetDeclAttr::DT_NoHost &&
1854 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1859 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1863 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
1867 if (GV->hasDLLExportStorageClass()) {
1870 diag::err_hidden_visibility_dllexport);
1873 diag::err_non_default_visibility_dllimport);
1879 !GV->isDeclarationForLinker())
1884 llvm::GlobalValue *GV) {
1885 if (GV->hasLocalLinkage())
1888 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
1892 if (GV->hasDLLImportStorageClass())
1895 const llvm::Triple &TT = CGM.
getTriple();
1897 if (TT.isOSCygMing()) {
1915 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
1923 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
1927 if (!TT.isOSBinFormatELF())
1933 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1941 return !(CGM.
getLangOpts().SemanticInterposition ||
1946 if (!GV->isDeclarationForLinker())
1952 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
1959 if (CGOpts.DirectAccessExternalData) {
1965 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1966 if (!Var->isThreadLocal())
1991 const auto *D = dyn_cast<NamedDecl>(GD.
getDecl());
1993 if (
const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
2003 if (D->
hasAttr<DLLImportAttr>())
2004 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2005 else if ((D->
hasAttr<DLLExportAttr>() ||
2007 !GV->isDeclarationForLinker())
2008 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2028 GV->setPartition(CodeGenOpts.SymbolPartition);
2032 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
2033 .Case(
"global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
2034 .Case(
"local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
2035 .Case(
"initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
2036 .Case(
"local-exec", llvm::GlobalVariable::LocalExecTLSModel);
2039llvm::GlobalVariable::ThreadLocalMode
2041 switch (CodeGenOpts.getDefaultTLSModel()) {
2043 return llvm::GlobalVariable::GeneralDynamicTLSModel;
2045 return llvm::GlobalVariable::LocalDynamicTLSModel;
2047 return llvm::GlobalVariable::InitialExecTLSModel;
2049 return llvm::GlobalVariable::LocalExecTLSModel;
2051 llvm_unreachable(
"Invalid TLS model!");
2055 assert(D.
getTLSKind() &&
"setting TLS mode on non-TLS var!");
2057 llvm::GlobalValue::ThreadLocalMode TLM;
2061 if (
const TLSModelAttr *
Attr = D.
getAttr<TLSModelAttr>()) {
2065 GV->setThreadLocalMode(TLM);
2071 return (Twine(
'.') + Twine(
Target.CPUSpecificManglingCharacter(Name))).str();
2075 const CPUSpecificAttr *
Attr,
2097 bool OmitMultiVersionMangling =
false) {
2099 llvm::raw_svector_ostream Out(Buffer);
2108 assert(II &&
"Attempt to mangle unnamed decl.");
2109 const auto *FD = dyn_cast<FunctionDecl>(ND);
2114 Out <<
"__regcall4__" << II->
getName();
2116 Out <<
"__regcall3__" << II->
getName();
2117 }
else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
2119 Out <<
"__device_stub__" << II->
getName();
2121 DeviceKernelAttr::isOpenCLSpelling(
2122 FD->getAttr<DeviceKernelAttr>()) &&
2124 Out <<
"__clang_ocl_kern_imp_" << II->
getName();
2140 "Hash computed when not explicitly requested");
2144 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
2145 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
2146 switch (FD->getMultiVersionKind()) {
2150 FD->getAttr<CPUSpecificAttr>(),
2154 auto *
Attr = FD->getAttr<TargetAttr>();
2155 assert(
Attr &&
"Expected TargetAttr to be present "
2156 "for attribute mangling");
2162 auto *
Attr = FD->getAttr<TargetVersionAttr>();
2163 assert(
Attr &&
"Expected TargetVersionAttr to be present "
2164 "for attribute mangling");
2170 auto *
Attr = FD->getAttr<TargetClonesAttr>();
2171 assert(
Attr &&
"Expected TargetClonesAttr to be present "
2172 "for attribute mangling");
2179 llvm_unreachable(
"None multiversion type isn't valid here");
2189 return std::string(Out.str());
2192void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
2193 const FunctionDecl *FD,
2194 StringRef &CurName) {
2201 std::string NonTargetName =
2209 "Other GD should now be a multiversioned function");
2219 if (OtherName != NonTargetName) {
2222 const auto ExistingRecord = Manglings.find(NonTargetName);
2223 if (ExistingRecord != std::end(Manglings))
2224 Manglings.remove(&(*ExistingRecord));
2225 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
2230 CurName = OtherNameRef;
2232 Entry->setName(OtherName);
2242 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.
getDecl())) {
2256 auto FoundName = MangledDeclNames.find(CanonicalGD);
2257 if (FoundName != MangledDeclNames.end())
2258 return FoundName->second;
2295 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
2296 return MangledDeclNames[CanonicalGD] =
Result.first->first();
2305 llvm::raw_svector_ostream Out(Buffer);
2308 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
2309 else if (
const auto *CD = dyn_cast<CXXConstructorDecl>(D))
2311 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(D))
2316 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
2317 return Result.first->first();
2321 auto it = MangledDeclNames.begin();
2322 while (it != MangledDeclNames.end()) {
2323 if (it->second == Name)
2338 llvm::Constant *AssociatedData) {
2340 GlobalCtors.push_back(
Structor(Priority, LexOrder, Ctor, AssociatedData));
2346 bool IsDtorAttrFunc) {
2347 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2349 DtorsUsingAtExit[Priority].push_back(Dtor);
2354 GlobalDtors.push_back(
Structor(Priority, ~0
U, Dtor,
nullptr));
2357void CodeGenModule::EmitCtorList(CtorList &Fns,
const char *GlobalName) {
2358 if (Fns.empty())
return;
2364 llvm::PointerType *PtrTy = llvm::PointerType::get(
2365 getLLVMContext(), TheModule.getDataLayout().getProgramAddressSpace());
2368 llvm::StructType *CtorStructTy = llvm::StructType::get(
Int32Ty, PtrTy, PtrTy);
2372 auto Ctors = Builder.beginArray(CtorStructTy);
2373 for (
const auto &I : Fns) {
2374 auto Ctor = Ctors.beginStruct(CtorStructTy);
2375 Ctor.addInt(
Int32Ty, I.Priority);
2376 if (InitFiniAuthSchema) {
2377 llvm::Constant *StorageAddress =
2379 ? llvm::ConstantExpr::getIntToPtr(
2380 llvm::ConstantInt::get(
2382 llvm::ConstantPtrAuth::AddrDiscriminator_CtorsDtors),
2386 I.Initializer, InitFiniAuthSchema.
getKey(), StorageAddress,
2387 llvm::ConstantInt::get(
2389 Ctor.add(SignedCtorPtr);
2391 Ctor.add(I.Initializer);
2393 if (I.AssociatedData)
2394 Ctor.add(I.AssociatedData);
2396 Ctor.addNullPointer(PtrTy);
2397 Ctor.finishAndAddTo(Ctors);
2400 auto List = Ctors.finishAndCreateGlobal(GlobalName,
getPointerAlign(),
2402 llvm::GlobalValue::AppendingLinkage);
2406 List->setAlignment(std::nullopt);
2411llvm::GlobalValue::LinkageTypes
2417 if (
const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
2424 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2425 if (!MDS)
return nullptr;
2427 return llvm::ConstantInt::get(
Int64Ty, llvm::MD5Hash(MDS->getString()));
2434 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2435 if (!UD->
hasAttr<TransparentUnionAttr>())
2437 if (!UD->
fields().empty())
2438 return UD->
fields().begin()->getType();
2447 bool GeneralizePointers) {
2460 bool GeneralizePointers) {
2463 for (
auto &Param : FnType->param_types())
2464 GeneralizedParams.push_back(
2468 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers),
2469 GeneralizedParams, FnType->getExtProtoInfo());
2474 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers));
2476 llvm_unreachable(
"Encountered unknown FunctionType");
2484 FnType->getReturnType(), FnType->getParamTypes(),
2485 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
2487 std::string OutName;
2488 llvm::raw_string_ostream Out(OutName);
2496 Out <<
".normalized";
2498 Out <<
".generalized";
2500 return llvm::ConstantInt::get(
2506 llvm::Function *F,
bool IsThunk) {
2508 llvm::AttributeList PAL;
2511 if (
CallingConv == llvm::CallingConv::X86_VectorCall &&
2515 Loc = D->getLocation();
2517 Error(Loc,
"__vectorcall calling convention is not currently supported");
2519 F->setAttributes(PAL);
2520 F->setCallingConv(
static_cast<llvm::CallingConv::ID
>(
CallingConv));
2524 std::string ReadOnlyQual(
"__read_only");
2525 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2526 if (ReadOnlyPos != std::string::npos)
2528 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2530 std::string WriteOnlyQual(
"__write_only");
2531 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2532 if (WriteOnlyPos != std::string::npos)
2533 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2535 std::string ReadWriteQual(
"__read_write");
2536 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2537 if (ReadWritePos != std::string::npos)
2538 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2571 assert(((FD && CGF) || (!FD && !CGF)) &&
2572 "Incorrect use - FD and CGF should either be both null or not!");
2598 for (
unsigned i = 0, e = FD->
getNumParams(); i != e; ++i) {
2601 argNames.push_back(llvm::MDString::get(VMContext, parm->
getName()));
2606 std::string typeQuals;
2610 const Decl *PDecl = parm;
2612 PDecl = TD->getDecl();
2613 const OpenCLAccessAttr *A = PDecl->
getAttr<OpenCLAccessAttr>();
2614 if (A && A->isWriteOnly())
2615 accessQuals.push_back(llvm::MDString::get(VMContext,
"write_only"));
2616 else if (A && A->isReadWrite())
2617 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_write"));
2619 accessQuals.push_back(llvm::MDString::get(VMContext,
"read_only"));
2621 accessQuals.push_back(llvm::MDString::get(VMContext,
"none"));
2623 auto getTypeSpelling = [&](
QualType Ty) {
2624 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2626 if (Ty.isCanonical()) {
2627 StringRef typeNameRef = typeName;
2629 if (typeNameRef.consume_front(
"unsigned "))
2630 return std::string(
"u") + typeNameRef.str();
2631 if (typeNameRef.consume_front(
"signed "))
2632 return typeNameRef.str();
2642 addressQuals.push_back(
2643 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(
2647 std::string typeName = getTypeSpelling(pointeeTy) +
"*";
2648 std::string baseTypeName =
2650 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2651 argBaseTypeNames.push_back(
2652 llvm::MDString::get(VMContext, baseTypeName));
2656 typeQuals =
"restrict";
2659 typeQuals += typeQuals.empty() ?
"const" :
" const";
2661 typeQuals += typeQuals.empty() ?
"volatile" :
" volatile";
2663 uint32_t AddrSpc = 0;
2668 addressQuals.push_back(
2669 llvm::ConstantAsMetadata::get(CGF->
Builder.getInt32(AddrSpc)));
2673 std::string typeName = getTypeSpelling(ty);
2685 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2686 argBaseTypeNames.push_back(
2687 llvm::MDString::get(VMContext, baseTypeName));
2692 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
2696 Fn->setMetadata(
"kernel_arg_addr_space",
2697 llvm::MDNode::get(VMContext, addressQuals));
2698 Fn->setMetadata(
"kernel_arg_access_qual",
2699 llvm::MDNode::get(VMContext, accessQuals));
2700 Fn->setMetadata(
"kernel_arg_type",
2701 llvm::MDNode::get(VMContext, argTypeNames));
2702 Fn->setMetadata(
"kernel_arg_base_type",
2703 llvm::MDNode::get(VMContext, argBaseTypeNames));
2704 Fn->setMetadata(
"kernel_arg_type_qual",
2705 llvm::MDNode::get(VMContext, argTypeQuals));
2709 Fn->setMetadata(
"kernel_arg_name",
2710 llvm::MDNode::get(VMContext, argNames));
2720 if (!LangOpts.Exceptions)
return false;
2723 if (LangOpts.CXXExceptions)
return true;
2726 if (LangOpts.ObjCExceptions) {
2746SmallVector<const CXXRecordDecl *, 0>
2748 llvm::SetVector<const CXXRecordDecl *> MostBases;
2753 MostBases.insert(RD);
2755 CollectMostBases(B.getType()->getAsCXXRecordDecl());
2757 CollectMostBases(RD);
2758 return MostBases.takeVector();
2762 llvm::Function *F) {
2763 llvm::AttrBuilder B(F->getContext());
2765 if ((!D || !D->
hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2766 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2768 if (CodeGenOpts.StackClashProtector)
2769 B.addAttribute(
"probe-stack",
"inline-asm");
2771 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
2772 B.addAttribute(
"stack-probe-size",
2773 std::to_string(CodeGenOpts.StackProbeSize));
2776 B.addAttribute(llvm::Attribute::NoUnwind);
2778 if (std::optional<llvm::Attribute::AttrKind>
Attr =
2780 B.addAttribute(*
Attr);
2785 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline))
2786 B.addAttribute(llvm::Attribute::AlwaysInline);
2790 else if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2792 B.addAttribute(llvm::Attribute::NoInline);
2800 if (D->
hasAttr<ArmLocallyStreamingAttr>())
2801 B.addAttribute(
"aarch64_pstate_sm_body");
2804 if (
Attr->isNewZA())
2805 B.addAttribute(
"aarch64_new_za");
2806 if (
Attr->isNewZT0())
2807 B.addAttribute(
"aarch64_new_zt0");
2812 bool ShouldAddOptNone =
2813 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
2815 ShouldAddOptNone &= !D->
hasAttr<MinSizeAttr>();
2816 ShouldAddOptNone &= !D->
hasAttr<AlwaysInlineAttr>();
2819 if (
getLangOpts().
HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline) &&
2820 !D->
hasAttr<NoInlineAttr>()) {
2821 B.addAttribute(llvm::Attribute::AlwaysInline);
2822 }
else if ((ShouldAddOptNone || D->
hasAttr<OptimizeNoneAttr>()) &&
2823 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2825 B.addAttribute(llvm::Attribute::OptimizeNone);
2828 B.addAttribute(llvm::Attribute::NoInline);
2833 B.addAttribute(llvm::Attribute::Naked);
2836 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
2837 F->removeFnAttr(llvm::Attribute::MinSize);
2838 }
else if (D->
hasAttr<NakedAttr>()) {
2840 B.addAttribute(llvm::Attribute::Naked);
2841 B.addAttribute(llvm::Attribute::NoInline);
2842 }
else if (D->
hasAttr<NoDuplicateAttr>()) {
2843 B.addAttribute(llvm::Attribute::NoDuplicate);
2844 }
else if (D->
hasAttr<NoInlineAttr>() &&
2845 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2847 B.addAttribute(llvm::Attribute::NoInline);
2848 }
else if (D->
hasAttr<AlwaysInlineAttr>() &&
2849 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
2851 B.addAttribute(llvm::Attribute::AlwaysInline);
2855 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
2856 B.addAttribute(llvm::Attribute::NoInline);
2860 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
2863 auto CheckRedeclForInline = [](
const FunctionDecl *Redecl) {
2864 return Redecl->isInlineSpecified();
2866 if (any_of(FD->
redecls(), CheckRedeclForInline))
2871 return any_of(Pattern->
redecls(), CheckRedeclForInline);
2873 if (CheckForInline(FD)) {
2874 B.addAttribute(llvm::Attribute::InlineHint);
2875 }
else if (CodeGenOpts.getInlining() ==
2878 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2879 B.addAttribute(llvm::Attribute::NoInline);
2886 if (!D->
hasAttr<OptimizeNoneAttr>()) {
2888 if (!ShouldAddOptNone)
2889 B.addAttribute(llvm::Attribute::OptimizeForSize);
2890 B.addAttribute(llvm::Attribute::Cold);
2893 B.addAttribute(llvm::Attribute::Hot);
2894 if (D->
hasAttr<MinSizeAttr>())
2895 B.addAttribute(llvm::Attribute::MinSize);
2902 F->setAlignment(llvm::Align(alignment));
2904 if (!D->
hasAttr<AlignedAttr>())
2905 if (LangOpts.FunctionAlignment)
2906 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
2914 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
2919 if (CodeGenOpts.SanitizeCfiCrossDso &&
2920 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2921 if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
2929 if (CodeGenOpts.CallGraphSection) {
2930 if (
auto *FD = dyn_cast<FunctionDecl>(D))
2937 auto *MD = dyn_cast<CXXMethodDecl>(D);
2940 llvm::Metadata *Id =
2942 MD->getType(), std::nullopt,
Base));
2943 F->addTypeMetadata(0, Id);
2950 if (isa_and_nonnull<NamedDecl>(D))
2953 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2955 if (D && D->
hasAttr<UsedAttr>())
2958 if (
const auto *VD = dyn_cast_if_present<VarDecl>(D);
2960 ((CodeGenOpts.KeepPersistentStorageVariables &&
2961 (VD->getStorageDuration() ==
SD_Static ||
2962 VD->getStorageDuration() ==
SD_Thread)) ||
2963 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
2964 VD->getType().isConstQualified())))
2969static std::vector<std::string>
2971 llvm::StringMap<bool> &FeatureMap) {
2972 llvm::StringMap<bool> DefaultFeatureMap;
2976 std::vector<std::string> Delta;
2977 for (
const auto &[K,
V] : FeatureMap) {
2978 auto DefaultIt = DefaultFeatureMap.find(K);
2979 if (DefaultIt == DefaultFeatureMap.end() || DefaultIt->getValue() !=
V)
2980 Delta.push_back((
V ?
"+" :
"-") + K.str());
2986bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
2987 llvm::AttrBuilder &Attrs,
2988 bool SetTargetFeatures) {
2994 std::vector<std::string> Features;
2995 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.
getDecl());
2998 const auto *TV = FD ? FD->
getAttr<TargetVersionAttr>() :
nullptr;
2999 assert((!TD || !TV) &&
"both target_version and target specified");
3002 bool AddedAttr =
false;
3003 if (TD || TV || SD || TC) {
3004 llvm::StringMap<bool> FeatureMap;
3012 ParsedTargetAttr ParsedAttr =
3013 Target.parseTargetAttr(TD->getFeaturesStr());
3014 if (!ParsedAttr.
CPU.empty() &&
3016 TargetCPU = ParsedAttr.
CPU;
3019 if (!ParsedAttr.
Tune.empty() &&
3021 TuneCPU = ParsedAttr.
Tune;
3037 for (
const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
3038 Features.push_back((Entry.getValue() ?
"+" :
"-") +
3039 Entry.getKey().str());
3045 llvm::StringMap<bool> FeatureMap;
3059 if (!TargetCPU.empty()) {
3060 Attrs.addAttribute(
"target-cpu", TargetCPU);
3063 if (!TuneCPU.empty()) {
3064 Attrs.addAttribute(
"tune-cpu", TuneCPU);
3067 if (!Features.empty() && SetTargetFeatures) {
3068 llvm::erase_if(Features, [&](
const std::string& F) {
3071 llvm::sort(Features);
3072 Attrs.addAttribute(
"target-features", llvm::join(Features,
","));
3077 llvm::SmallVector<StringRef, 8> Feats;
3078 bool IsDefault =
false;
3080 IsDefault = TV->isDefaultVersion();
3081 TV->getFeatures(Feats);
3087 Attrs.addAttribute(
"fmv-features");
3089 }
else if (!Feats.empty()) {
3091 std::set<StringRef> OrderedFeats(Feats.begin(), Feats.end());
3092 std::string FMVFeatures;
3093 for (StringRef F : OrderedFeats)
3094 FMVFeatures.append(
"," + F.str());
3095 Attrs.addAttribute(
"fmv-features", FMVFeatures.substr(1));
3102void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
3103 llvm::GlobalObject *GO) {
3108 if (
auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
3111 if (
auto *SA = D->
getAttr<PragmaClangBSSSectionAttr>())
3112 GV->addAttribute(
"bss-section", SA->getName());
3113 if (
auto *SA = D->
getAttr<PragmaClangDataSectionAttr>())
3114 GV->addAttribute(
"data-section", SA->getName());
3115 if (
auto *SA = D->
getAttr<PragmaClangRodataSectionAttr>())
3116 GV->addAttribute(
"rodata-section", SA->getName());
3117 if (
auto *SA = D->
getAttr<PragmaClangRelroSectionAttr>())
3118 GV->addAttribute(
"relro-section", SA->getName());
3121 if (
auto *F = dyn_cast<llvm::Function>(GO)) {
3124 if (
auto *SA = D->
getAttr<PragmaClangTextSectionAttr>())
3125 if (!D->
getAttr<SectionAttr>())
3126 F->setSection(SA->getName());
3128 llvm::AttrBuilder Attrs(F->getContext());
3129 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
3133 llvm::AttributeMask RemoveAttrs;
3134 RemoveAttrs.addAttribute(
"target-cpu");
3135 RemoveAttrs.addAttribute(
"target-features");
3136 RemoveAttrs.addAttribute(
"fmv-features");
3137 RemoveAttrs.addAttribute(
"tune-cpu");
3138 F->removeFnAttrs(RemoveAttrs);
3139 F->addFnAttrs(Attrs);
3143 if (
const auto *CSA = D->
getAttr<CodeSegAttr>())
3144 GO->setSection(CSA->getName());
3145 else if (
const auto *SA = D->
getAttr<SectionAttr>())
3146 GO->setSection(SA->getName());
3159 F->setLinkage(llvm::Function::InternalLinkage);
3161 setNonAliasAttributes(GD, F);
3172 GV->
setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
3176 llvm::MDNode *MD = F->getMetadata(llvm::LLVMContext::MD_type);
3177 return MD && MD->hasGeneralizedMDString();
3181 llvm::Function *F) {
3188 if (!F->hasLocalLinkage() ||
3189 F->getFunction().hasAddressTaken(
nullptr,
true,
3196 llvm::Function *F) {
3198 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
3209 F->addTypeMetadata(0, MD);
3218 if (CodeGenOpts.SanitizeCfiCrossDso)
3220 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
3224 llvm::CallBase *CB) {
3226 if (!CodeGenOpts.CallGraphSection || !CB->isIndirectCall())
3230 llvm::MDTuple *TypeTuple = llvm::MDTuple::get(
3231 getLLVMContext(), {llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
3234 llvm::MDTuple *MDN = llvm::MDNode::get(
getLLVMContext(), {TypeTuple});
3235 CB->setMetadata(llvm::LLVMContext::MD_callee_type, MDN);
3239 llvm::LLVMContext &Ctx = F->getContext();
3240 llvm::MDBuilder MDB(Ctx);
3241 llvm::StringRef Salt;
3244 if (
const auto &Info = FP->getExtraAttributeInfo())
3245 Salt = Info.CFISalt;
3247 F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
3256 return llvm::all_of(Name, [](
const char &
C) {
3257 return llvm::isAlnum(
C) ||
C ==
'_' ||
C ==
'.';
3263 for (
auto &F : M.functions()) {
3265 bool AddressTaken = F.hasAddressTaken();
3266 if (!AddressTaken && F.hasLocalLinkage())
3267 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
3272 if (!AddressTaken || !F.isDeclaration())
3275 const llvm::ConstantInt *
Type;
3276 if (
const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
3277 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
3281 StringRef Name = F.getName();
3285 std::string
Asm = (
".weak __kcfi_typeid_" + Name +
"\n.set __kcfi_typeid_" +
3286 Name +
", " + Twine(
Type->getZExtValue()) +
" /* " +
3287 Twine(
Type->getSExtValue()) +
" */\n")
3289 M.appendModuleInlineAsm(
Asm);
3293void CodeGenModule::SetFunctionAttributes(
GlobalDecl GD, llvm::Function *F,
3294 bool IsIncompleteFunction,
3297 if (F->getIntrinsicID() != llvm::Intrinsic::not_intrinsic) {
3305 if (!IsIncompleteFunction)
3312 if (!IsThunk &&
getCXXABI().HasThisReturn(GD) &&
3314 assert(!F->arg_empty() &&
3315 F->arg_begin()->getType()
3316 ->canLosslesslyBitCastTo(F->getReturnType()) &&
3317 "unexpected this return");
3318 F->addParamAttr(0, llvm::Attribute::Returned);
3328 if (!IsIncompleteFunction && F->isDeclaration())
3331 if (
const auto *CSA = FD->
getAttr<CodeSegAttr>())
3332 F->setSection(CSA->getName());
3333 else if (
const auto *SA = FD->
getAttr<SectionAttr>())
3334 F->setSection(SA->getName());
3336 if (
const auto *EA = FD->
getAttr<ErrorAttr>()) {
3338 F->addFnAttr(
"dontcall-error", EA->getUserDiagnostic());
3339 else if (EA->isWarning())
3340 F->addFnAttr(
"dontcall-warn", EA->getUserDiagnostic());
3345 const FunctionDecl *FDBody;
3346 bool HasBody = FD->
hasBody(FDBody);
3348 assert(HasBody &&
"Inline builtin declarations should always have an "
3350 if (shouldEmitFunction(FDBody))
3351 F->addFnAttr(llvm::Attribute::NoBuiltin);
3357 F->addFnAttr(llvm::Attribute::NoBuiltin);
3361 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3362 else if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
3363 if (MD->isVirtual())
3364 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3370 if (!CodeGenOpts.SanitizeCfiCrossDso ||
3371 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
3374 if (CodeGenOpts.CallGraphSection)
3377 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
3383 if (CodeGenOpts.InlineMaxStackSize !=
UINT_MAX)
3384 F->addFnAttr(
"inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
3386 if (
const auto *CB = FD->
getAttr<CallbackAttr>()) {
3390 llvm::LLVMContext &Ctx = F->getContext();
3391 llvm::MDBuilder MDB(Ctx);
3395 int CalleeIdx = *CB->encoding_begin();
3396 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
3397 F->addMetadata(llvm::LLVMContext::MD_callback,
3398 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
3399 CalleeIdx, PayloadIndices,
3406 "Only globals with definition can force usage.");
3407 LLVMUsed.emplace_back(GV);
3411 assert(!GV->isDeclaration() &&
3412 "Only globals with definition can force usage.");
3413 LLVMCompilerUsed.emplace_back(GV);
3418 "Only globals with definition can force usage.");
3420 LLVMCompilerUsed.emplace_back(GV);
3422 LLVMUsed.emplace_back(GV);
3426 std::vector<llvm::WeakTrackingVH> &List) {
3433 UsedArray.resize(List.size());
3434 for (
unsigned i = 0, e = List.size(); i != e; ++i) {
3436 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3440 if (UsedArray.empty())
3442 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.
Int8PtrTy, UsedArray.size());
3444 auto *GV =
new llvm::GlobalVariable(
3445 CGM.
getModule(), ATy,
false, llvm::GlobalValue::AppendingLinkage,
3446 llvm::ConstantArray::get(ATy, UsedArray), Name);
3448 GV->setSection(
"llvm.metadata");
3451void CodeGenModule::emitLLVMUsed() {
3452 emitUsed(*
this,
"llvm.used", LLVMUsed);
3453 emitUsed(*
this,
"llvm.compiler.used", LLVMCompilerUsed);
3458 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3467 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
getLLVMContext(), MDOpts));
3473 ELFDependentLibraries.push_back(
3474 llvm::MDNode::get(
C, llvm::MDString::get(
C, Lib)));
3481 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
C, MDOpts));
3490 if (Mod->
Parent && Visited.insert(Mod->
Parent).second) {
3496 if (Visited.insert(Import).second)
3513 if (LL.IsFramework) {
3514 llvm::Metadata *Args[2] = {llvm::MDString::get(Context,
"-framework"),
3515 llvm::MDString::get(Context, LL.Library)};
3517 Metadata.push_back(llvm::MDNode::get(Context, Args));
3523 llvm::Metadata *Args[2] = {
3524 llvm::MDString::get(Context,
"lib"),
3525 llvm::MDString::get(Context, LL.Library),
3527 Metadata.push_back(llvm::MDNode::get(Context, Args));
3531 auto *OptString = llvm::MDString::get(Context, Opt);
3532 Metadata.push_back(llvm::MDNode::get(Context, OptString));
3537void CodeGenModule::EmitModuleInitializers(
clang::Module *Primary) {
3539 "We should only emit module initializers for named modules.");
3547 assert(
isa<VarDecl>(D) &&
"GMF initializer decl is not a var?");
3564 assert(
isa<VarDecl>(D) &&
"PMF initializer decl is not a var?");
3570void CodeGenModule::EmitModuleLinkOptions() {
3574 llvm::SetVector<clang::Module *> LinkModules;
3575 llvm::SmallPtrSet<clang::Module *, 16> Visited;
3576 SmallVector<clang::Module *, 16> Stack;
3579 for (
Module *M : ImportedModules) {
3582 if (M->getTopLevelModuleName() ==
getLangOpts().CurrentModule &&
3585 if (Visited.insert(M).second)
3591 while (!Stack.empty()) {
3594 bool AnyChildren =
false;
3603 if (Visited.insert(
SM).second) {
3604 Stack.push_back(
SM);
3612 LinkModules.insert(Mod);
3619 SmallVector<llvm::MDNode *, 16> MetadataArgs;
3621 for (
Module *M : LinkModules)
3622 if (Visited.insert(M).second)
3624 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
3625 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
3628 if (!LinkerOptionsMetadata.empty()) {
3629 auto *NMD =
getModule().getOrInsertNamedMetadata(
"llvm.linker.options");
3630 for (
auto *MD : LinkerOptionsMetadata)
3631 NMD->addOperand(MD);
3635void CodeGenModule::EmitDeferred() {
3644 if (!DeferredVTables.empty()) {
3645 EmitDeferredVTables();
3650 assert(DeferredVTables.empty());
3657 llvm::append_range(DeferredDeclsToEmit,
3661 if (DeferredDeclsToEmit.empty())
3666 std::vector<GlobalDecl> CurDeclsToEmit;
3667 CurDeclsToEmit.swap(DeferredDeclsToEmit);
3669 for (GlobalDecl &D : CurDeclsToEmit) {
3675 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>() &&
3679 if (!FD->
getAttr<SYCLKernelEntryPointAttr>()->isInvalidAttr()) {
3695 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
3713 if (!GV->isDeclaration())
3717 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
3721 EmitGlobalDefinition(D, GV);
3726 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
3728 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
3733void CodeGenModule::EmitVTablesOpportunistically() {
3739 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
3740 &&
"Only emit opportunistic vtables with optimizations");
3742 for (
const CXXRecordDecl *RD : OpportunisticVTables) {
3744 "This queue should only contain external vtables");
3745 if (
getCXXABI().canSpeculativelyEmitVTable(RD))
3746 VTables.GenerateClassData(RD);
3748 OpportunisticVTables.clear();
3752 for (
const auto& [MangledName, VD] : DeferredAnnotations) {
3757 DeferredAnnotations.clear();
3759 if (Annotations.empty())
3763 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
3764 Annotations[0]->
getType(), Annotations.size()), Annotations);
3765 auto *gv =
new llvm::GlobalVariable(
getModule(), Array->getType(),
false,
3766 llvm::GlobalValue::AppendingLinkage,
3767 Array,
"llvm.global.annotations");
3772 llvm::Constant *&AStr = AnnotationStrings[Str];
3777 llvm::Constant *
s = llvm::ConstantDataArray::getString(
getLLVMContext(), Str);
3778 auto *gv =
new llvm::GlobalVariable(
3779 getModule(),
s->getType(),
true, llvm::GlobalValue::PrivateLinkage,
s,
3780 ".str",
nullptr, llvm::GlobalValue::NotThreadLocal,
3783 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3800 SM.getExpansionLineNumber(L);
3801 return llvm::ConstantInt::get(
Int32Ty, LineNo);
3809 llvm::FoldingSetNodeID ID;
3810 for (
Expr *E : Exprs) {
3813 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
3818 LLVMArgs.reserve(Exprs.size());
3820 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](
const Expr *E) {
3822 return ConstEmiter.
emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
3825 auto *
Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
3826 auto *GV =
new llvm::GlobalVariable(
getModule(),
Struct->getType(),
true,
3827 llvm::GlobalValue::PrivateLinkage,
Struct,
3830 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3837 const AnnotateAttr *AA,
3845 llvm::Constant *GVInGlobalsAS = GV;
3846 if (GV->getAddressSpace() !=
3848 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
3850 llvm::PointerType::get(
3851 GV->getContext(),
getDataLayout().getDefaultGlobalsAddressSpace()));
3855 llvm::Constant *Fields[] = {
3856 GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
3858 return llvm::ConstantStruct::getAnon(Fields);
3862 llvm::GlobalValue *GV) {
3863 assert(D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
3873 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
3876 auto &
SM = Context.getSourceManager();
3878 if (NoSanitizeL.containsMainFile(Kind, MainFile.
getName()))
3883 return NoSanitizeL.containsLocation(Kind, Loc);
3886 return NoSanitizeL.containsFile(Kind, MainFile.
getName());
3890 llvm::GlobalVariable *GV,
3892 StringRef Category)
const {
3894 if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
3896 auto &
SM = Context.getSourceManager();
3897 if (NoSanitizeL.containsMainFile(
3898 Kind,
SM.getFileEntryRefForID(
SM.getMainFileID())->getName(),
3901 if (NoSanitizeL.containsLocation(Kind, Loc, Category))
3908 while (
auto AT = dyn_cast<ArrayType>(Ty.
getTypePtr()))
3909 Ty = AT->getElementType();
3914 if (NoSanitizeL.containsType(Kind, TypeStr, Category))
3922 StringRef Category)
const {
3925 auto Attr = ImbueAttr::NONE;
3927 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
3928 if (
Attr == ImbueAttr::NONE)
3929 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
3931 case ImbueAttr::NONE:
3933 case ImbueAttr::ALWAYS:
3934 Fn->addFnAttr(
"function-instrument",
"xray-always");
3936 case ImbueAttr::ALWAYS_ARG1:
3937 Fn->addFnAttr(
"function-instrument",
"xray-always");
3938 Fn->addFnAttr(
"xray-log-args",
"1");
3940 case ImbueAttr::NEVER:
3941 Fn->addFnAttr(
"function-instrument",
"xray-never");
3954 llvm::driver::ProfileInstrKind Kind =
getCodeGenOpts().getProfileInstr();
3964 auto &
SM = Context.getSourceManager();
3965 if (
auto MainFile =
SM.getFileEntryRefForID(
SM.getMainFileID()))
3979 if (NumGroups > 1) {
3980 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
3989 if (LangOpts.EmitAllDecls)
3992 const auto *VD = dyn_cast<VarDecl>(
Global);
3994 ((CodeGenOpts.KeepPersistentStorageVariables &&
3995 (VD->getStorageDuration() ==
SD_Static ||
3996 VD->getStorageDuration() ==
SD_Thread)) ||
3997 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() ==
SD_Static &&
3998 VD->getType().isConstQualified())))
4011 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
4012 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
4013 OMPDeclareTargetDeclAttr::getActiveAttr(
Global);
4014 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (
unsigned)-1)
4018 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
4028 if (LangOpts.SYCLIsDevice && FD->
hasAttr<SYCLKernelEntryPointAttr>())
4031 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
4032 if (Context.getInlineVariableDefinitionKind(VD) ==
4037 if (CXX20ModuleInits && VD->getOwningModule() &&
4038 !VD->getOwningModule()->isModuleMapModule()) {
4047 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
4050 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
Global))
4063 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
4067 llvm::Constant *
Init;
4070 if (!
V.isAbsent()) {
4081 llvm::Constant *Fields[4] = {
4085 llvm::ConstantDataArray::getRaw(
4086 StringRef(
reinterpret_cast<char *
>(Parts.
Part4And5), 8), 8,
4088 Init = llvm::ConstantStruct::getAnon(Fields);
4091 auto *GV =
new llvm::GlobalVariable(
4093 true, llvm::GlobalValue::LinkOnceODRLinkage,
Init, Name);
4095 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4098 if (!
V.isAbsent()) {
4111 llvm::GlobalVariable **Entry =
nullptr;
4112 Entry = &UnnamedGlobalConstantDeclMap[GCD];
4117 llvm::Constant *
Init;
4121 assert(!
V.isAbsent());
4125 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
4127 llvm::GlobalValue::PrivateLinkage,
Init,
4129 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4143 if (llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name))
4147 llvm::Constant *
Init =
Emitter.emitForInitializer(
4155 llvm::GlobalValue::LinkageTypes
Linkage =
4157 ? llvm::GlobalValue::LinkOnceODRLinkage
4158 : llvm::GlobalValue::InternalLinkage;
4159 auto *GV =
new llvm::GlobalVariable(
getModule(),
Init->getType(),
4163 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4170 const AliasAttr *AA = VD->
getAttr<AliasAttr>();
4171 assert(AA &&
"No alias?");
4181 llvm::Constant *Aliasee;
4183 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
4191 F->setLinkage(llvm::Function::ExternalWeakLinkage);
4192 WeakRefReferences.insert(F);
4200 if (
auto *A = D->
getAttr<AttrT>())
4201 return A->isImplicit();
4208 if (!LangOpts.OpenMPIsTargetDevice && !LangOpts.CUDA)
4211 const auto *AA =
Global->getAttr<AliasAttr>();
4219 const auto *AliaseeDecl = dyn_cast<ValueDecl>(AliaseeGD.getDecl());
4220 if (LangOpts.OpenMPIsTargetDevice)
4221 return !AliaseeDecl ||
4222 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(AliaseeDecl);
4225 const bool HasDeviceAttr =
Global->hasAttr<CUDADeviceAttr>();
4226 const bool AliaseeHasDeviceAttr =
4227 AliaseeDecl && AliaseeDecl->hasAttr<CUDADeviceAttr>();
4229 if (LangOpts.CUDAIsDevice)
4230 return !HasDeviceAttr || !AliaseeHasDeviceAttr;
4237bool CodeGenModule::shouldEmitCUDAGlobalVar(
const VarDecl *
Global)
const {
4238 assert(LangOpts.CUDA &&
"Should not be called by non-CUDA languages");
4243 return !LangOpts.CUDAIsDevice ||
Global->hasAttr<CUDADeviceAttr>() ||
4244 Global->hasAttr<CUDAConstantAttr>() ||
4245 Global->hasAttr<CUDASharedAttr>() ||
4246 Global->getType()->isCUDADeviceBuiltinSurfaceType() ||
4247 Global->getType()->isCUDADeviceBuiltinTextureType();
4254 if (
Global->hasAttr<WeakRefAttr>())
4259 if (
Global->hasAttr<AliasAttr>()) {
4262 return EmitAliasDefinition(GD);
4266 if (
Global->hasAttr<IFuncAttr>())
4267 return emitIFuncDefinition(GD);
4270 if (
Global->hasAttr<CPUDispatchAttr>())
4271 return emitCPUDispatchDefinition(GD);
4276 if (LangOpts.CUDA) {
4278 "Expected Variable or Function");
4279 if (
const auto *VD = dyn_cast<VarDecl>(
Global)) {
4280 if (!shouldEmitCUDAGlobalVar(VD))
4282 }
else if (LangOpts.CUDAIsDevice) {
4283 const auto *FD = dyn_cast<FunctionDecl>(
Global);
4284 if ((!
Global->hasAttr<CUDADeviceAttr>() ||
4285 (LangOpts.OffloadImplicitHostDeviceTemplates &&
4289 !
getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
4290 !
Global->hasAttr<CUDAGlobalAttr>() &&
4292 !
Global->hasAttr<CUDAHostAttr>()))
4295 }
else if (!
Global->hasAttr<CUDAHostAttr>() &&
4296 Global->hasAttr<CUDADeviceAttr>())
4300 if (LangOpts.OpenMP) {
4302 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
4304 if (
auto *DRD = dyn_cast<OMPDeclareReductionDecl>(
Global)) {
4305 if (MustBeEmitted(
Global))
4309 if (
auto *DMD = dyn_cast<OMPDeclareMapperDecl>(
Global)) {
4310 if (MustBeEmitted(
Global))
4317 if (
const auto *FD = dyn_cast<FunctionDecl>(
Global)) {
4318 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
4324 if (FD->
hasAttr<AnnotateAttr>()) {
4327 DeferredAnnotations[MangledName] = FD;
4342 GetOrCreateLLVMFunction(MangledName, Ty, GD,
false,
4348 assert(VD->isFileVarDecl() &&
"Cannot emit local var decl as global.");
4350 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
4351 if (LangOpts.OpenMP) {
4353 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
4354 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
4358 if (VD->hasExternalStorage() &&
4359 Res != OMPDeclareTargetDeclAttr::MT_Link)
4362 bool UnifiedMemoryEnabled =
4364 if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4365 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4366 !UnifiedMemoryEnabled) {
4369 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
4370 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4371 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4372 UnifiedMemoryEnabled)) &&
4373 "Link clause or to clause with unified memory expected.");
4382 if (Context.getInlineVariableDefinitionKind(VD) ==
4392 if (MustBeEmitted(
Global) && MayBeEmittedEagerly(
Global)) {
4394 EmitGlobalDefinition(GD);
4395 addEmittedDeferredDecl(GD);
4403 DelayedCXXInitPosition[
Global] = CXXGlobalInits.size();
4404 CXXGlobalInits.push_back(
nullptr);
4410 addDeferredDeclToEmit(GD);
4411 }
else if (MustBeEmitted(
Global)) {
4413 assert(!MayBeEmittedEagerly(
Global));
4414 addDeferredDeclToEmit(GD);
4419 DeferredDecls[MangledName] = GD;
4425 if (
const auto *RT =
4426 T->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
4427 if (
auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
4428 RD = RD->getDefinitionOrSelf();
4429 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
4437 struct FunctionIsDirectlyRecursive
4438 :
public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
4439 const StringRef Name;
4440 const Builtin::Context &BI;
4441 FunctionIsDirectlyRecursive(StringRef N,
const Builtin::Context &
C)
4444 bool VisitCallExpr(
const CallExpr *E) {
4448 AsmLabelAttr *Attr = FD->
getAttr<AsmLabelAttr>();
4449 if (Attr && Name == Attr->getLabel())
4454 std::string BuiltinNameStr = BI.
getName(BuiltinID);
4455 StringRef BuiltinName = BuiltinNameStr;
4456 return BuiltinName.consume_front(
"__builtin_") && Name == BuiltinName;
4459 bool VisitStmt(
const Stmt *S) {
4460 for (
const Stmt *Child : S->
children())
4461 if (Child && this->Visit(Child))
4468 struct DLLImportFunctionVisitor
4469 :
public RecursiveASTVisitor<DLLImportFunctionVisitor> {
4470 bool SafeToInline =
true;
4472 bool shouldVisitImplicitCode()
const {
return true; }
4474 bool VisitVarDecl(VarDecl *VD) {
4477 SafeToInline =
false;
4478 return SafeToInline;
4485 return SafeToInline;
4488 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
4490 SafeToInline = D->
hasAttr<DLLImportAttr>();
4491 return SafeToInline;
4494 bool VisitDeclRefExpr(DeclRefExpr *E) {
4497 SafeToInline = VD->
hasAttr<DLLImportAttr>();
4498 else if (VarDecl *
V = dyn_cast<VarDecl>(VD))
4499 SafeToInline = !
V->hasGlobalStorage() ||
V->hasAttr<DLLImportAttr>();
4500 return SafeToInline;
4503 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
4505 return SafeToInline;
4508 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4512 SafeToInline =
true;
4514 SafeToInline = M->
hasAttr<DLLImportAttr>();
4516 return SafeToInline;
4519 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
4521 return SafeToInline;
4524 bool VisitCXXNewExpr(CXXNewExpr *E) {
4526 return SafeToInline;
4535CodeGenModule::isTriviallyRecursive(
const FunctionDecl *FD) {
4537 if (
getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
4539 AsmLabelAttr *Attr = FD->
getAttr<AsmLabelAttr>();
4542 Name = Attr->getLabel();
4547 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
4548 const Stmt *Body = FD->
getBody();
4549 return Body ? Walker.Visit(Body) :
false;
4552bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
4559 if (F->isInlineBuiltinDeclaration())
4562 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
4567 if (
const Module *M = F->getOwningModule();
4568 M && M->getTopLevelModule()->isNamedModule() &&
4569 getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
4579 if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
4584 if (F->hasAttr<NoInlineAttr>())
4587 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
4589 DLLImportFunctionVisitor Visitor;
4590 Visitor.TraverseFunctionDecl(
const_cast<FunctionDecl*
>(F));
4591 if (!Visitor.SafeToInline)
4594 if (
const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
4597 for (
const Decl *
Member : Dtor->getParent()->decls())
4601 for (
const CXXBaseSpecifier &B : Dtor->getParent()->bases())
4612 return !isTriviallyRecursive(F);
4615bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
4616 return CodeGenOpts.OptimizationLevel > 0;
4619void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
4620 llvm::GlobalValue *GV) {
4624 auto *Spec = FD->
getAttr<CPUSpecificAttr>();
4625 for (
unsigned I = 0; I < Spec->cpus_size(); ++I)
4627 }
else if (
auto *TC = FD->
getAttr<TargetClonesAttr>()) {
4628 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I)
4629 if (TC->isFirstOfVersion(I))
4632 EmitGlobalFunctionDefinition(GD, GV);
4638 AddDeferredMultiVersionResolverToEmit(GD);
4640 GetOrCreateMultiVersionResolver(GD);
4644void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
4647 PrettyStackTraceDecl CrashInfo(
const_cast<ValueDecl *
>(D), D->
getLocation(),
4648 Context.getSourceManager(),
4649 "Generating code for declaration");
4651 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
4654 if (!shouldEmitFunction(GD))
4657 llvm::TimeTraceScope TimeScope(
"CodeGen Function", [&]() {
4659 llvm::raw_string_ostream
OS(Name);
4665 if (
const auto *
Method = dyn_cast<CXXMethodDecl>(D)) {
4669 ABI->emitCXXStructor(GD);
4671 EmitMultiVersionFunctionDefinition(GD, GV);
4673 EmitGlobalFunctionDefinition(GD, GV);
4682 return EmitMultiVersionFunctionDefinition(GD, GV);
4683 return EmitGlobalFunctionDefinition(GD, GV);
4686 if (
const auto *VD = dyn_cast<VarDecl>(D))
4687 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
4689 llvm_unreachable(
"Invalid argument to EmitGlobalDefinition()");
4693 llvm::Function *NewFn);
4709static llvm::GlobalValue::LinkageTypes
4713 return llvm::GlobalValue::InternalLinkage;
4714 return llvm::GlobalValue::WeakODRLinkage;
4717void CodeGenModule::emitMultiVersionFunctions() {
4718 std::vector<GlobalDecl> MVFuncsToEmit;
4719 MultiVersionFuncs.swap(MVFuncsToEmit);
4720 for (GlobalDecl GD : MVFuncsToEmit) {
4722 assert(FD &&
"Expected a FunctionDecl");
4724 auto createFunction = [&](
const FunctionDecl *
Decl,
unsigned MVIdx = 0) {
4725 GlobalDecl CurGD{
Decl->isDefined() ?
Decl->getDefinition() :
Decl, MVIdx};
4729 if (
Decl->isDefined()) {
4730 EmitGlobalFunctionDefinition(CurGD,
nullptr);
4738 assert(
Func &&
"This should have just been created");
4747 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
4748 llvm::DenseMap<llvm::Function *, const FunctionDecl *> DeclMap;
4751 FD, [&](
const FunctionDecl *CurFD) {
4752 llvm::SmallVector<StringRef, 8> Feats;
4755 if (
const auto *TA = CurFD->
getAttr<TargetAttr>()) {
4757 TA->getX86AddedFeatures(Feats);
4758 llvm::Function *
Func = createFunction(CurFD);
4759 DeclMap.insert({
Func, CurFD});
4760 Options.emplace_back(
Func, Feats, TA->getX86Architecture());
4761 }
else if (
const auto *TVA = CurFD->
getAttr<TargetVersionAttr>()) {
4762 if (TVA->isDefaultVersion() && IsDefined)
4763 ShouldEmitResolver =
true;
4764 llvm::Function *
Func = createFunction(CurFD);
4765 DeclMap.insert({
Func, CurFD});
4767 TVA->getFeatures(Feats, Delim);
4768 Options.emplace_back(
Func, Feats);
4769 }
else if (
const auto *TC = CurFD->
getAttr<TargetClonesAttr>()) {
4770 for (
unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
4771 if (!TC->isFirstOfVersion(I))
4773 if (TC->isDefaultVersion(I) && IsDefined)
4774 ShouldEmitResolver =
true;
4775 llvm::Function *
Func = createFunction(CurFD, I);
4776 DeclMap.insert({
Func, CurFD});
4779 TC->getX86Feature(Feats, I);
4780 Options.emplace_back(
Func, Feats, TC->getX86Architecture(I));
4783 TC->getFeatures(Feats, I, Delim);
4784 Options.emplace_back(
Func, Feats);
4788 llvm_unreachable(
"unexpected MultiVersionKind");
4791 if (!ShouldEmitResolver)
4794 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
4795 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
4796 ResolverConstant = IFunc->getResolver();
4800 *
this, GD, FD,
true);
4807 auto *Alias = llvm::GlobalAlias::create(
4809 MangledName +
".ifunc", IFunc, &
getModule());
4818 Options, [&TI](
const CodeGenFunction::FMVResolverOption &LHS,
4819 const CodeGenFunction::FMVResolverOption &RHS) {
4825 for (
auto I = Options.begin() + 1, E = Options.end(); I != E; ++I) {
4826 llvm::APInt RHS = llvm::AArch64::getCpuSupportsMask(I->Features);
4827 if (std::any_of(Options.begin(), I, [RHS](
auto RO) {
4828 llvm::APInt LHS = llvm::AArch64::getCpuSupportsMask(RO.Features);
4829 return LHS.isSubsetOf(RHS);
4831 Diags.Report(DeclMap[I->Function]->getLocation(),
4832 diag::warn_unreachable_version)
4833 << I->Function->getName();
4834 assert(I->Function->user_empty() &&
"unexpected users");
4835 I->Function->eraseFromParent();
4836 I->Function =
nullptr;
4840 CodeGenFunction CGF(*
this);
4841 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4843 setMultiVersionResolverAttributes(ResolverFunc, GD);
4845 ResolverFunc->setComdat(
4846 getModule().getOrInsertComdat(ResolverFunc->getName()));
4852 if (!MVFuncsToEmit.empty())
4857 if (!MultiVersionFuncs.empty())
4858 emitMultiVersionFunctions();
4862 llvm::Constant *
New) {
4865 Old->replaceAllUsesWith(
New);
4866 Old->eraseFromParent();
4869void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
4871 assert(FD &&
"Not a FunctionDecl?");
4873 const auto *DD = FD->
getAttr<CPUDispatchAttr>();
4874 assert(DD &&
"Not a cpu_dispatch Function?");
4880 UpdateMultiVersionNames(GD, FD, ResolverName);
4882 llvm::Type *ResolverType;
4883 GlobalDecl ResolverGD;
4885 ResolverType = llvm::FunctionType::get(
4896 ResolverName, ResolverType, ResolverGD,
false));
4899 ResolverFunc->setComdat(
4900 getModule().getOrInsertComdat(ResolverFunc->getName()));
4902 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
4905 for (
const IdentifierInfo *II : DD->cpus()) {
4913 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
4916 EmitGlobalFunctionDefinition(ExistingDecl,
nullptr);
4922 Func = GetOrCreateLLVMFunction(
4923 MangledName, DeclTy, ExistingDecl,
4929 llvm::SmallVector<StringRef, 32> Features;
4930 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
4931 llvm::transform(Features, Features.begin(),
4932 [](StringRef Str) { return Str.substr(1); });
4933 llvm::erase_if(Features, [&Target](StringRef Feat) {
4934 return !Target.validateCpuSupports(Feat);
4940 llvm::stable_sort(Options, [](
const CodeGenFunction::FMVResolverOption &LHS,
4941 const CodeGenFunction::FMVResolverOption &RHS) {
4942 return llvm::X86::getCpuSupportsMask(LHS.
Features) >
4943 llvm::X86::getCpuSupportsMask(RHS.
Features);
4950 while (Options.size() > 1 && llvm::all_of(llvm::X86::getCpuSupportsMask(
4951 (Options.end() - 2)->Features),
4952 [](
auto X) { return X == 0; })) {
4953 StringRef LHSName = (Options.end() - 2)->Function->getName();
4954 StringRef RHSName = (Options.end() - 1)->Function->getName();
4955 if (LHSName.compare(RHSName) < 0)
4956 Options.erase(Options.end() - 2);
4958 Options.erase(Options.end() - 1);
4961 CodeGenFunction CGF(*
this);
4962 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4963 setMultiVersionResolverAttributes(ResolverFunc, GD);
4968 unsigned AS = IFunc->getType()->getPointerAddressSpace();
4973 auto *GI = llvm::GlobalIFunc::create(DeclTy, AS,
Linkage,
"",
4980 *
this, GD, FD,
true);
4983 auto *GA = llvm::GlobalAlias::create(DeclTy, AS,
Linkage, AliasName,
4991void CodeGenModule::AddDeferredMultiVersionResolverToEmit(GlobalDecl GD) {
4993 assert(FD &&
"Not a FunctionDecl?");
4996 std::string MangledName =
4998 if (!DeferredResolversToEmit.insert(MangledName).second)
5001 MultiVersionFuncs.push_back(GD);
5007llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
5009 assert(FD &&
"Not a FunctionDecl?");
5011 std::string MangledName =
5016 std::string ResolverName = MangledName;
5020 llvm_unreachable(
"unexpected MultiVersionKind::None for resolver");
5024 ResolverName +=
".ifunc";
5031 ResolverName +=
".resolver";
5034 bool ShouldReturnIFunc =
5053 AddDeferredMultiVersionResolverToEmit(GD);
5057 if (ShouldReturnIFunc) {
5059 llvm::Type *ResolverType = llvm::FunctionType::get(
5061 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
5062 MangledName +
".resolver", ResolverType, GlobalDecl{},
5064 llvm::GlobalIFunc *GIF =
5067 GIF->setName(ResolverName);
5074 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
5075 ResolverName, DeclTy, GlobalDecl{},
false);
5077 "Resolver should be created for the first time");
5082void CodeGenModule::setMultiVersionResolverAttributes(llvm::Function *Resolver,
5084 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(GD.
getDecl());
5096 Resolver->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
5107bool CodeGenModule::shouldDropDLLAttribute(
const Decl *D,
5108 const llvm::GlobalValue *GV)
const {
5109 auto SC = GV->getDLLStorageClass();
5110 if (SC == llvm::GlobalValue::DefaultStorageClass)
5113 return (((SC == llvm::GlobalValue::DLLImportStorageClass &&
5114 !MRD->
hasAttr<DLLImportAttr>()) ||
5115 (SC == llvm::GlobalValue::DLLExportStorageClass &&
5116 !MRD->
hasAttr<DLLExportAttr>())) &&
5127llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
5128 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD,
bool ForVTable,
5129 bool DontDefer,
bool IsThunk, llvm::AttributeList ExtraAttrs,
5133 std::string NameWithoutMultiVersionMangling;
5134 if (
const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
5136 if (
getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
5137 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->
isDefined() &&
5138 !DontDefer && !IsForDefinition) {
5141 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
5143 else if (
const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
5146 GDDef = GlobalDecl(FDDef);
5154 UpdateMultiVersionNames(GD, FD, MangledName);
5155 if (!IsForDefinition) {
5161 AddDeferredMultiVersionResolverToEmit(GD);
5163 *
this, GD, FD,
true);
5165 return GetOrCreateMultiVersionResolver(GD);
5170 if (!NameWithoutMultiVersionMangling.empty())
5171 MangledName = NameWithoutMultiVersionMangling;
5176 if (WeakRefReferences.erase(Entry)) {
5177 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
5178 if (FD && !FD->
hasAttr<WeakAttr>())
5179 Entry->setLinkage(llvm::Function::ExternalLinkage);
5183 if (D && shouldDropDLLAttribute(D, Entry)) {
5184 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5190 if (IsForDefinition && !Entry->isDeclaration()) {
5197 DiagnosedConflictingDefinitions.insert(GD).second) {
5201 diag::note_previous_definition);
5206 (Entry->getValueType() == Ty)) {
5213 if (!IsForDefinition)
5220 bool IsIncompleteFunction =
false;
5222 llvm::FunctionType *FTy;
5226 FTy = llvm::FunctionType::get(
VoidTy,
false);
5227 IsIncompleteFunction =
true;
5231 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
5232 Entry ? StringRef() : MangledName, &
getModule());
5236 if (D && D->
hasAttr<AnnotateAttr>())
5254 if (!Entry->use_empty()) {
5256 Entry->removeDeadConstantUsers();
5262 assert(F->getName() == MangledName &&
"name was uniqued!");
5264 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
5265 if (ExtraAttrs.hasFnAttrs()) {
5266 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
5274 if (isa_and_nonnull<CXXDestructorDecl>(D) &&
5277 addDeferredDeclToEmit(GD);
5282 auto DDI = DeferredDecls.find(MangledName);
5283 if (DDI != DeferredDecls.end()) {
5287 addDeferredDeclToEmit(DDI->second);
5288 DeferredDecls.erase(DDI);
5316 if (!IsIncompleteFunction) {
5317 assert(F->getFunctionType() == Ty);
5335 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
5345 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(GD.
getDecl())) {
5348 DD->getParent()->getNumVBases() == 0)
5353 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
5354 false, llvm::AttributeList(),
5357 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
5361 if (IsForDefinition)
5369 llvm::GlobalValue *F =
5372 return llvm::NoCFIValue::get(F);
5381 for (
const auto *Result : DC->
lookup(&CII))
5382 if (
const auto *FD = dyn_cast<FunctionDecl>(Result))
5385 if (!
C.getLangOpts().CPlusPlus)
5390 (Name ==
"_ZSt9terminatev" || Name ==
"?terminate@@YAXXZ")
5391 ?
C.Idents.get(
"terminate")
5392 :
C.Idents.get(Name);
5394 for (
const auto &N : {
"__cxxabiv1",
"std"}) {
5396 for (
const auto *Result : DC->
lookup(&NS)) {
5398 if (
auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
5399 for (
const auto *Result : LSD->lookup(&NS))
5400 if ((ND = dyn_cast<NamespaceDecl>(Result)))
5404 for (
const auto *Result : ND->
lookup(&CXXII))
5405 if (
const auto *FD = dyn_cast<FunctionDecl>(Result))
5414 llvm::Function *F, StringRef Name) {
5420 if (!Local && CGM.
getTriple().isWindowsItaniumEnvironment() &&
5423 if (!FD || FD->
hasAttr<DLLImportAttr>()) {
5424 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
5425 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
5432 llvm::AttributeList ExtraAttrs,
bool Local,
bool AssumeConvergent) {
5433 if (AssumeConvergent) {
5435 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5438 QualType FTy = Context.getFunctionType(ReturnTy, ArgTys,
5443 llvm::Constant *
C = GetOrCreateLLVMFunction(
5445 false,
false, ExtraAttrs);
5447 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
5463 llvm::AttributeList ExtraAttrs,
bool Local,
5464 bool AssumeConvergent) {
5465 if (AssumeConvergent) {
5467 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5471 GetOrCreateLLVMFunction(Name, FTy,
GlobalDecl(),
false,
5475 if (
auto *F = dyn_cast<llvm::Function>(
C)) {
5484 markRegisterParameterAttributes(F);
5510 if (WeakRefReferences.erase(Entry)) {
5511 if (D && !D->
hasAttr<WeakAttr>())
5512 Entry->setLinkage(llvm::Function::ExternalLinkage);
5516 if (D && shouldDropDLLAttribute(D, Entry))
5517 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5519 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
5522 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
5527 if (IsForDefinition && !Entry->isDeclaration()) {
5535 (OtherD = dyn_cast<VarDecl>(OtherGD.
getDecl())) &&
5537 DiagnosedConflictingDefinitions.insert(D).second) {
5541 diag::note_previous_definition);
5546 if (Entry->getType()->getAddressSpace() != TargetAS)
5547 return llvm::ConstantExpr::getAddrSpaceCast(
5548 Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
5552 if (!IsForDefinition)
5558 auto *GV =
new llvm::GlobalVariable(
5559 getModule(), Ty,
false, llvm::GlobalValue::ExternalLinkage,
nullptr,
5560 MangledName,
nullptr, llvm::GlobalVariable::NotThreadLocal,
5561 getContext().getTargetAddressSpace(DAddrSpace));
5566 GV->takeName(Entry);
5568 if (!Entry->use_empty()) {
5569 Entry->replaceAllUsesWith(GV);
5572 Entry->eraseFromParent();
5578 auto DDI = DeferredDecls.find(MangledName);
5579 if (DDI != DeferredDecls.end()) {
5582 addDeferredDeclToEmit(DDI->second);
5583 DeferredDecls.erase(DDI);
5588 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
5595 GV->setAlignment(
getContext().getDeclAlign(D).getAsAlign());
5601 CXXThreadLocals.push_back(D);
5609 if (
getContext().isMSStaticDataMemberInlineDefinition(D)) {
5610 EmitGlobalVarDefinition(D);
5615 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>())
5616 GV->setSection(SA->getName());
5620 if (
getTriple().getArch() == llvm::Triple::xcore &&
5624 GV->setSection(
".cp.rodata");
5627 if (
const auto *CMA = D->
getAttr<CodeModelAttr>())
5628 GV->setCodeModel(CMA->getModel());
5633 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
5637 Context.getBaseElementType(D->
getType())->getAsCXXRecordDecl();
5638 bool HasMutableFields =
Record &&
Record->hasMutableFields();
5639 if (!HasMutableFields) {
5646 auto *InitType =
Init->getType();
5647 if (GV->getValueType() != InitType) {
5652 GV->setName(StringRef());
5657 ->stripPointerCasts());
5660 GV->eraseFromParent();
5663 GV->setInitializer(
Init);
5664 GV->setConstant(
true);
5665 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
5685 SanitizerMD->reportGlobal(GV, *D);
5690 assert(
getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
5691 if (DAddrSpace != ExpectedAS) {
5693 *
this, GV, DAddrSpace,
5706 false, IsForDefinition);
5727 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes
Linkage,
5728 llvm::Align Alignment) {
5729 llvm::GlobalVariable *GV =
getModule().getNamedGlobal(Name);
5730 llvm::GlobalVariable *OldGV =
nullptr;
5734 if (GV->getValueType() == Ty)
5739 assert(GV->isDeclaration() &&
"Declaration has wrong type!");
5744 GV =
new llvm::GlobalVariable(
getModule(), Ty,
true,
5749 GV->takeName(OldGV);
5751 if (!OldGV->use_empty()) {
5752 OldGV->replaceAllUsesWith(GV);
5755 OldGV->eraseFromParent();
5759 !GV->hasAvailableExternallyLinkage())
5760 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5762 GV->setAlignment(Alignment);
5799 assert(!D->
getInit() &&
"Cannot emit definite definitions here!");
5807 if (GV && !GV->isDeclaration())
5812 if (!MustBeEmitted(D) && !GV) {
5813 DeferredDecls[MangledName] = D;
5818 EmitGlobalVarDefinition(D);
5823 if (
auto const *CD = dyn_cast<const CXXConstructorDecl>(D))
5825 else if (
auto const *DD = dyn_cast<const CXXDestructorDecl>(D))
5840 if (
const auto *VD = dyn_cast<VarDecl>(D)) {
5843 }
else if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
5845 if (!Fn->getSubprogram())
5851 return Context.toCharUnitsFromBits(
5856 if (LangOpts.OpenCL) {
5867 if (LangOpts.SYCLIsDevice &&
5871 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
5873 if (D->
hasAttr<CUDAConstantAttr>())
5875 if (D->
hasAttr<CUDASharedAttr>())
5877 if (D->
hasAttr<CUDADeviceAttr>())
5885 if (LangOpts.OpenMP) {
5887 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
5895 if (LangOpts.OpenCL)
5897 if (LangOpts.SYCLIsDevice)
5899 if (LangOpts.HIP && LangOpts.CUDAIsDevice &&
getTriple().isSPIRV())
5907 if (
auto AS =
getTarget().getConstantAddressSpace())
5920static llvm::Constant *
5922 llvm::GlobalVariable *GV) {
5923 llvm::Constant *Cast = GV;
5929 llvm::PointerType::get(
5936template<
typename SomeDecl>
5938 llvm::GlobalValue *GV) {
5953 const SomeDecl *
First = D->getFirstDecl();
5954 if (
First->getDeclContext()->isRecord() || !
First->isInExternCContext())
5960 std::pair<StaticExternCMap::iterator, bool> R =
5961 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
5966 R.first->second =
nullptr;
5973 if (D.
hasAttr<SelectAnyAttr>())
5977 if (
auto *VD = dyn_cast<VarDecl>(&D))
5991 llvm_unreachable(
"No such linkage");
5999 llvm::GlobalObject &GO) {
6002 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
6010void CodeGenModule::EmitGlobalVarDefinition(
const VarDecl *D,
6025 if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
6026 OpenMPRuntime->emitTargetGlobalVariable(D))
6029 llvm::TrackingVH<llvm::Constant>
Init;
6030 bool NeedsGlobalCtor =
false;
6034 bool IsDefinitionAvailableExternally =
6036 bool NeedsGlobalDtor =
6037 !IsDefinitionAvailableExternally &&
6044 if (IsDefinitionAvailableExternally &&
6055 std::optional<ConstantEmitter> emitter;
6060 bool IsCUDASharedVar =
6065 bool IsCUDAShadowVar =
6067 (D->
hasAttr<CUDAConstantAttr>() || D->
hasAttr<CUDADeviceAttr>() ||
6068 D->
hasAttr<CUDASharedAttr>());
6069 bool IsCUDADeviceShadowVar =
6074 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) {
6075 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
6079 Init = llvm::PoisonValue::get(
getTypes().ConvertType(ASTTy));
6082 }
else if (D->
hasAttr<LoaderUninitializedAttr>()) {
6083 Init = llvm::UndefValue::get(
getTypes().ConvertTypeForMem(ASTTy));
6084 }
else if (!InitExpr) {
6097 initializedGlobalDecl = GlobalDecl(D);
6098 emitter.emplace(*
this);
6099 llvm::Constant *
Initializer = emitter->tryEmitForInitializer(*InitDecl);
6107 if (!IsDefinitionAvailableExternally)
6108 NeedsGlobalCtor =
true;
6112 NeedsGlobalCtor =
false;
6124 DelayedCXXInitPosition.erase(D);
6131 assert(VarSize == CstSize &&
"Emitted constant has unexpected size");
6136 llvm::Type* InitType =
Init->getType();
6137 llvm::Constant *Entry =
6141 Entry = Entry->stripPointerCasts();
6144 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
6155 if (!GV || GV->getValueType() != InitType ||
6156 GV->getType()->getAddressSpace() !=
6160 Entry->setName(StringRef());
6165 ->stripPointerCasts());
6168 llvm::Constant *NewPtrForOldDecl =
6169 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
6171 Entry->replaceAllUsesWith(NewPtrForOldDecl);
6179 if (D->
hasAttr<AnnotateAttr>())
6192 if (LangOpts.CUDA) {
6193 if (LangOpts.CUDAIsDevice) {
6194 if (
Linkage != llvm::GlobalValue::InternalLinkage &&
6195 (D->
hasAttr<CUDADeviceAttr>() || D->
hasAttr<CUDAConstantAttr>() ||
6198 GV->setExternallyInitialized(
true);
6205 if (LangOpts.HLSL &&
6210 GV->setExternallyInitialized(
true);
6212 GV->setInitializer(
Init);
6219 emitter->finalize(GV);
6222 GV->setConstant((D->
hasAttr<CUDAConstantAttr>() && LangOpts.CUDAIsDevice) ||
6223 (!NeedsGlobalCtor && !NeedsGlobalDtor &&
6227 if (
const SectionAttr *SA = D->
getAttr<SectionAttr>()) {
6228 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
6230 GV->setConstant(
true);
6235 if (std::optional<CharUnits> AlignValFromAllocate =
6237 AlignVal = *AlignValFromAllocate;
6255 Linkage == llvm::GlobalValue::ExternalLinkage &&
6256 Context.getTargetInfo().getTriple().isOSDarwin() &&
6258 Linkage = llvm::GlobalValue::InternalLinkage;
6263 if (LangOpts.HLSL &&
6265 Linkage = llvm::GlobalValue::ExternalLinkage;
6268 if (D->
hasAttr<DLLImportAttr>())
6269 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
6270 else if (D->
hasAttr<DLLExportAttr>())
6271 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
6273 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6275 if (
Linkage == llvm::GlobalVariable::CommonLinkage) {
6277 GV->setConstant(
false);
6282 if (!GV->getInitializer()->isNullValue())
6283 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
6286 setNonAliasAttributes(D, GV);
6288 if (D->
getTLSKind() && !GV->isThreadLocal()) {
6290 CXXThreadLocals.push_back(D);
6297 if (NeedsGlobalCtor || NeedsGlobalDtor)
6298 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
6300 SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
6305 DI->EmitGlobalVariable(GV, D);
6313 if ((NoCommon || D->
hasAttr<NoCommonAttr>()) && !D->
hasAttr<CommonAttr>())
6324 if (D->
hasAttr<SectionAttr>())
6330 if (D->
hasAttr<PragmaClangBSSSectionAttr>() ||
6331 D->
hasAttr<PragmaClangDataSectionAttr>() ||
6332 D->
hasAttr<PragmaClangRelroSectionAttr>() ||
6333 D->
hasAttr<PragmaClangRodataSectionAttr>())
6341 if (D->
hasAttr<WeakImportAttr>())
6350 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6351 if (D->
hasAttr<AlignedAttr>())
6354 if (Context.isAlignmentRequired(VarType))
6358 for (
const FieldDecl *FD : RD->fields()) {
6359 if (FD->isBitField())
6361 if (FD->
hasAttr<AlignedAttr>())
6363 if (Context.isAlignmentRequired(FD->
getType()))
6375 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
6376 Context.getTypeAlignIfKnown(D->
getType()) >
6383llvm::GlobalValue::LinkageTypes
6387 return llvm::Function::InternalLinkage;
6390 return llvm::GlobalVariable::WeakAnyLinkage;
6394 return llvm::GlobalVariable::LinkOnceAnyLinkage;
6399 return llvm::GlobalValue::AvailableExternallyLinkage;
6413 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
6414 : llvm::Function::InternalLinkage;
6428 return llvm::Function::ExternalLinkage;
6431 return D->
hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
6432 : llvm::Function::InternalLinkage;
6433 return llvm::Function::WeakODRLinkage;
6440 CodeGenOpts.NoCommon))
6441 return llvm::GlobalVariable::CommonLinkage;
6447 if (D->
hasAttr<SelectAnyAttr>())
6448 return llvm::GlobalVariable::WeakODRLinkage;
6452 return llvm::GlobalVariable::ExternalLinkage;
6455llvm::GlobalValue::LinkageTypes
6464 llvm::Function *newFn) {
6466 if (old->use_empty())
6469 llvm::Type *newRetTy = newFn->getReturnType();
6474 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
6476 llvm::User *user = ui->getUser();
6480 if (
auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
6481 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
6487 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
6490 if (!callSite->isCallee(&*ui))
6495 if (callSite->getType() != newRetTy && !callSite->use_empty())
6500 llvm::AttributeList oldAttrs = callSite->getAttributes();
6503 unsigned newNumArgs = newFn->arg_size();
6504 if (callSite->arg_size() < newNumArgs)
6510 bool dontTransform =
false;
6511 for (llvm::Argument &A : newFn->args()) {
6512 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
6513 dontTransform =
true;
6518 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
6526 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
6530 callSite->getOperandBundlesAsDefs(newBundles);
6532 llvm::CallBase *newCall;
6534 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles,
"",
6535 callSite->getIterator());
6538 newCall = llvm::InvokeInst::Create(
6539 newFn, oldInvoke->getNormalDest(), oldInvoke->getUnwindDest(),
6540 newArgs, newBundles,
"", callSite->getIterator());
6544 if (!newCall->getType()->isVoidTy())
6545 newCall->takeName(callSite);
6546 newCall->setAttributes(
6547 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
6548 oldAttrs.getRetAttrs(), newArgAttrs));
6549 newCall->setCallingConv(callSite->getCallingConv());
6552 if (!callSite->use_empty())
6553 callSite->replaceAllUsesWith(newCall);
6556 if (callSite->getDebugLoc())
6557 newCall->setDebugLoc(callSite->getDebugLoc());
6559 callSitesToBeRemovedFromParent.push_back(callSite);
6562 for (
auto *callSite : callSitesToBeRemovedFromParent) {
6563 callSite->eraseFromParent();
6577 llvm::Function *NewFn) {
6587 (LangOpts.CUDA && !shouldEmitCUDAGlobalVar(VD)))
6599void CodeGenModule::EmitGlobalFunctionDefinition(
GlobalDecl GD,
6600 llvm::GlobalValue *GV) {
6608 if (!GV || (GV->getValueType() != Ty))
6614 if (!GV->isDeclaration())
6633 setNonAliasAttributes(GD, Fn);
6635 bool ShouldAddOptNone = !CodeGenOpts.DisableO0ImplyOptNone &&
6636 (CodeGenOpts.OptimizationLevel == 0) &&
6639 if (DeviceKernelAttr::isOpenCLSpelling(D->
getAttr<DeviceKernelAttr>())) {
6641 !D->
hasAttr<NoInlineAttr>() &&
6642 !Fn->hasFnAttribute(llvm::Attribute::NoInline) &&
6643 !D->
hasAttr<OptimizeNoneAttr>() &&
6644 !Fn->hasFnAttribute(llvm::Attribute::OptimizeNone) &&
6645 !ShouldAddOptNone) {
6646 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
6652 auto GetPriority = [
this](
const auto *
Attr) ->
int {
6657 return Attr->DefaultPriority;
6660 if (
const ConstructorAttr *CA = D->
getAttr<ConstructorAttr>())
6662 if (
const DestructorAttr *DA = D->
getAttr<DestructorAttr>())
6668void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
6670 const AliasAttr *AA = D->
getAttr<AliasAttr>();
6671 assert(AA &&
"Not an alias?");
6675 if (AA->getAliasee() == MangledName) {
6676 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6683 if (Entry && !Entry->isDeclaration())
6686 Aliases.push_back(GD);
6692 llvm::Constant *Aliasee;
6693 llvm::GlobalValue::LinkageTypes
LT;
6695 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
6701 if (
const auto *VD = dyn_cast<VarDecl>(GD.
getDecl()))
6708 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
6710 llvm::GlobalAlias::create(DeclTy, AS, LT,
"", Aliasee, &
getModule());
6713 if (GA->getAliasee() == Entry) {
6714 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6718 assert(Entry->isDeclaration());
6727 GA->takeName(Entry);
6729 Entry->replaceAllUsesWith(GA);
6730 Entry->eraseFromParent();
6732 GA->setName(MangledName);
6740 GA->setLinkage(llvm::Function::WeakAnyLinkage);
6743 if (
const auto *VD = dyn_cast<VarDecl>(D))
6744 if (VD->getTLSKind())
6755void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
6757 const IFuncAttr *IFA = D->
getAttr<IFuncAttr>();
6758 assert(IFA &&
"Not an ifunc?");
6762 if (IFA->getResolver() == MangledName) {
6763 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6769 if (Entry && !Entry->isDeclaration()) {
6772 DiagnosedConflictingDefinitions.insert(GD).second) {
6773 Diags.Report(D->
getLocation(), diag::err_duplicate_mangled_name)
6776 diag::note_previous_definition);
6781 Aliases.push_back(GD);
6787 llvm::Constant *Resolver =
6788 GetOrCreateLLVMFunction(IFA->getResolver(),
VoidTy, {},
6792 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
6793 DeclTy, AS, llvm::Function::ExternalLinkage,
"", Resolver, &
getModule());
6795 if (GIF->getResolver() == Entry) {
6796 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6799 assert(Entry->isDeclaration());
6808 GIF->takeName(Entry);
6810 Entry->replaceAllUsesWith(GIF);
6811 Entry->eraseFromParent();
6813 GIF->setName(MangledName);
6819 return llvm::Intrinsic::getOrInsertDeclaration(&
getModule(),
6820 (llvm::Intrinsic::ID)IID, Tys);
6823static llvm::StringMapEntry<llvm::GlobalVariable *> &
6826 bool &IsUTF16,
unsigned &StringLength) {
6827 StringRef String = Literal->getString();
6828 unsigned NumBytes = String.size();
6831 if (!Literal->containsNonAsciiOrNull()) {
6832 StringLength = NumBytes;
6833 return *Map.insert(std::make_pair(String,
nullptr)).first;
6840 const llvm::UTF8 *FromPtr = (
const llvm::UTF8 *)String.data();
6841 llvm::UTF16 *ToPtr = &ToBuf[0];
6843 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6844 ToPtr + NumBytes, llvm::strictConversion);
6847 StringLength = ToPtr - &ToBuf[0];
6851 return *Map.insert(std::make_pair(
6852 StringRef(
reinterpret_cast<const char *
>(ToBuf.data()),
6853 (StringLength + 1) * 2),
6859 unsigned StringLength = 0;
6860 bool isUTF16 =
false;
6861 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
6866 if (
auto *
C = Entry.second)
6871 const llvm::Triple &Triple =
getTriple();
6874 const bool IsSwiftABI =
6875 static_cast<unsigned>(CFRuntime) >=
6880 if (!CFConstantStringClassRef) {
6881 const char *CFConstantStringClassName =
"__CFConstantStringClassReference";
6883 Ty = llvm::ArrayType::get(Ty, 0);
6885 switch (CFRuntime) {
6889 CFConstantStringClassName =
6890 Triple.isOSDarwin() ?
"$s15SwiftFoundation19_NSCFConstantStringCN"
6891 :
"$s10Foundation19_NSCFConstantStringCN";
6895 CFConstantStringClassName =
6896 Triple.isOSDarwin() ?
"$S15SwiftFoundation19_NSCFConstantStringCN"
6897 :
"$S10Foundation19_NSCFConstantStringCN";
6901 CFConstantStringClassName =
6902 Triple.isOSDarwin() ?
"__T015SwiftFoundation19_NSCFConstantStringCN"
6903 :
"__T010Foundation19_NSCFConstantStringCN";
6910 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
6911 llvm::GlobalValue *GV =
nullptr;
6913 if ((GV = dyn_cast<llvm::GlobalValue>(
C))) {
6920 if ((VD = dyn_cast<VarDecl>(
Result)))
6923 if (Triple.isOSBinFormatELF()) {
6925 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6927 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6928 if (!VD || !VD->
hasAttr<DLLExportAttr>())
6929 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
6931 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
6939 CFConstantStringClassRef =
6940 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(
C, Ty) :
C;
6943 QualType CFTy = Context.getCFConstantStringType();
6948 auto Fields = Builder.beginStruct(STy);
6957 Fields.addInt(
IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
6958 Fields.addInt(
Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
6960 Fields.addInt(
IntTy, isUTF16 ? 0x07d0 : 0x07C8);
6964 llvm::Constant *
C =
nullptr;
6967 reinterpret_cast<uint16_t *
>(
const_cast<char *
>(Entry.first().data())),
6968 Entry.first().size() / 2);
6969 C = llvm::ConstantDataArray::get(VMContext, Arr);
6971 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
6977 new llvm::GlobalVariable(
getModule(),
C->getType(),
true,
6978 llvm::GlobalValue::PrivateLinkage,
C,
".str");
6979 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6982 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
6983 : Context.getTypeAlignInChars(Context.CharTy);
6989 if (Triple.isOSBinFormatMachO())
6990 GV->setSection(isUTF16 ?
"__TEXT,__ustring"
6991 :
"__TEXT,__cstring,cstring_literals");
6994 else if (Triple.isOSBinFormatELF())
6995 GV->setSection(
".rodata");
7001 llvm::IntegerType *LengthTy =
7011 Fields.addInt(LengthTy, StringLength);
7019 GV = Fields.finishAndCreateGlobal(
"_unnamed_cfstring_", Alignment,
7021 llvm::GlobalVariable::PrivateLinkage);
7022 GV->addAttribute(
"objc_arc_inert");
7023 switch (Triple.getObjectFormat()) {
7024 case llvm::Triple::UnknownObjectFormat:
7025 llvm_unreachable(
"unknown file format");
7026 case llvm::Triple::DXContainer:
7027 case llvm::Triple::GOFF:
7028 case llvm::Triple::SPIRV:
7029 case llvm::Triple::XCOFF:
7030 llvm_unreachable(
"unimplemented");
7031 case llvm::Triple::COFF:
7032 case llvm::Triple::ELF:
7033 case llvm::Triple::Wasm:
7034 GV->setSection(
"cfstring");
7036 case llvm::Triple::MachO:
7037 GV->setSection(
"__DATA,__cfstring");
7046 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
7050 if (ObjCFastEnumerationStateType.isNull()) {
7051 RecordDecl *D = Context.buildImplicitRecord(
"__objcFastEnumerationState");
7055 Context.UnsignedLongTy, Context.getPointerType(Context.getObjCIdType()),
7056 Context.getPointerType(Context.UnsignedLongTy),
7057 Context.getConstantArrayType(Context.UnsignedLongTy, llvm::APInt(32, 5),
7060 for (
size_t i = 0; i < 4; ++i) {
7065 FieldTypes[i],
nullptr,
7074 ObjCFastEnumerationStateType = Context.getCanonicalTagType(D);
7077 return ObjCFastEnumerationStateType;
7091 assert(CAT &&
"String literal not of constant array type!");
7093 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
7097 llvm::Type *ElemTy = AType->getElementType();
7098 unsigned NumElements = AType->getNumElements();
7101 if (ElemTy->getPrimitiveSizeInBits() == 16) {
7103 Elements.reserve(NumElements);
7105 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
7107 Elements.resize(NumElements);
7108 return llvm::ConstantDataArray::get(VMContext, Elements);
7111 assert(ElemTy->getPrimitiveSizeInBits() == 32);
7113 Elements.reserve(NumElements);
7115 for(
unsigned i = 0, e = E->
getLength(); i != e; ++i)
7117 Elements.resize(NumElements);
7118 return llvm::ConstantDataArray::get(VMContext, Elements);
7121static llvm::GlobalVariable *
7130 auto *GV =
new llvm::GlobalVariable(
7131 M,
C->getType(), !CGM.
getLangOpts().WritableStrings, LT,
C, GlobalName,
7132 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
7134 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
7135 if (GV->isWeakForLinker()) {
7136 assert(CGM.
supportsCOMDAT() &&
"Only COFF uses weak string literals");
7137 GV->setComdat(M.getOrInsertComdat(GV->getName()));
7153 llvm::GlobalVariable **Entry =
nullptr;
7154 if (!LangOpts.WritableStrings) {
7155 Entry = &ConstantStringMap[
C];
7156 if (
auto GV = *Entry) {
7157 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
7160 GV->getValueType(), Alignment);
7165 StringRef GlobalVariableName;
7166 llvm::GlobalValue::LinkageTypes LT;
7171 if (
getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
7172 !LangOpts.WritableStrings) {
7173 llvm::raw_svector_ostream Out(MangledNameBuffer);
7175 LT = llvm::GlobalValue::LinkOnceODRLinkage;
7176 GlobalVariableName = MangledNameBuffer;
7178 LT = llvm::GlobalValue::PrivateLinkage;
7179 GlobalVariableName = Name;
7191 SanitizerMD->reportGlobal(GV, S->
getStrTokenLoc(0),
"<string literal>");
7194 GV->getValueType(), Alignment);
7211 StringRef GlobalName) {
7212 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
7217 llvm::ConstantDataArray::getString(
getLLVMContext(), StrWithNull,
false);
7220 llvm::GlobalVariable **Entry =
nullptr;
7221 if (!LangOpts.WritableStrings) {
7222 Entry = &ConstantStringMap[
C];
7223 if (
auto GV = *Entry) {
7224 if (uint64_t(Alignment.
getQuantity()) > GV->getAlignment())
7227 GV->getValueType(), Alignment);
7233 GlobalName, Alignment);
7238 GV->getValueType(), Alignment);
7251 MaterializedType = E->
getType();
7255 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E,
nullptr});
7256 if (!InsertResult.second) {
7259 if (!InsertResult.first->second) {
7264 InsertResult.first->second =
new llvm::GlobalVariable(
7265 getModule(),
Type,
false, llvm::GlobalVariable::InternalLinkage,
7269 llvm::cast<llvm::GlobalVariable>(
7270 InsertResult.first->second->stripPointerCasts())
7279 llvm::raw_svector_ostream Out(Name);
7301 std::optional<ConstantEmitter> emitter;
7302 llvm::Constant *InitialValue =
nullptr;
7303 bool Constant =
false;
7307 emitter.emplace(*
this);
7308 InitialValue = emitter->emitForInitializer(*
Value, AddrSpace,
7313 Type = InitialValue->getType();
7322 if (
Linkage == llvm::GlobalVariable::ExternalLinkage) {
7324 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
7328 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
7332 Linkage = llvm::GlobalVariable::InternalLinkage;
7336 auto *GV =
new llvm::GlobalVariable(
7338 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
7339 if (emitter) emitter->finalize(GV);
7341 if (!llvm::GlobalValue::isLocalLinkage(
Linkage)) {
7343 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
7345 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
7349 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
7350 if (VD->getTLSKind())
7352 llvm::Constant *CV = GV;
7355 *
this, GV, AddrSpace,
7356 llvm::PointerType::get(
7362 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
7364 Entry->replaceAllUsesWith(CV);
7365 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
7374void CodeGenModule::EmitObjCPropertyImplementations(
const
7387 if (!Getter || Getter->isSynthesizedAccessorStub())
7390 auto *Setter = PID->getSetterMethodDecl();
7391 if (!PD->
isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
7402 if (ivar->getType().isDestructedType())
7423void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
7436 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod,
false);
7451 getContext().getObjCIdType(),
nullptr, D,
true,
7457 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod,
true);
7462void CodeGenModule::EmitLinkageSpec(
const LinkageSpecDecl *LSD) {
7469 EmitDeclContext(LSD);
7472void CodeGenModule::EmitTopLevelStmt(
const TopLevelStmtDecl *D) {
7474 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7477 std::unique_ptr<CodeGenFunction> &CurCGF =
7478 GlobalTopLevelStmtBlockInFlight.first;
7482 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
7490 std::string Name =
"__stmts__" + llvm::utostr(CXXGlobalInits.size());
7491 FunctionArgList Args;
7493 const CGFunctionInfo &FnInfo =
7496 llvm::Function *
Fn = llvm::Function::Create(
7497 FnTy, llvm::GlobalValue::InternalLinkage, Name, &
getModule());
7499 CurCGF.reset(
new CodeGenFunction(*
this));
7500 GlobalTopLevelStmtBlockInFlight.second = D;
7501 CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
7503 CXXGlobalInits.push_back(Fn);
7506 CurCGF->EmitStmt(D->
getStmt());
7509void CodeGenModule::EmitDeclContext(
const DeclContext *DC) {
7510 for (
auto *I : DC->
decls()) {
7516 if (
auto *OID = dyn_cast<ObjCImplDecl>(I)) {
7517 for (
auto *M : OID->methods())
7536 case Decl::CXXConversion:
7537 case Decl::CXXMethod:
7538 case Decl::Function:
7545 case Decl::CXXDeductionGuide:
7550 case Decl::Decomposition:
7551 case Decl::VarTemplateSpecialization:
7553 if (
auto *DD = dyn_cast<DecompositionDecl>(D))
7554 for (
auto *B : DD->flat_bindings())
7555 if (
auto *HD = B->getHoldingVar())
7562 case Decl::IndirectField:
7566 case Decl::Namespace:
7569 case Decl::ClassTemplateSpecialization: {
7572 if (Spec->getSpecializationKind() ==
7574 Spec->hasDefinition())
7575 DI->completeTemplateDefinition(*Spec);
7577 case Decl::CXXRecord: {
7581 DI->EmitAndRetainType(
7585 DI->completeUnusedClass(*CRD);
7588 for (
auto *I : CRD->
decls())
7594 case Decl::UsingShadow:
7595 case Decl::ClassTemplate:
7596 case Decl::VarTemplate:
7598 case Decl::VarTemplatePartialSpecialization:
7599 case Decl::FunctionTemplate:
7600 case Decl::TypeAliasTemplate:
7609 case Decl::UsingEnum:
7613 case Decl::NamespaceAlias:
7617 case Decl::UsingDirective:
7621 case Decl::CXXConstructor:
7624 case Decl::CXXDestructor:
7628 case Decl::StaticAssert:
7635 case Decl::ObjCInterface:
7636 case Decl::ObjCCategory:
7639 case Decl::ObjCProtocol: {
7641 if (Proto->isThisDeclarationADefinition())
7642 ObjCRuntime->GenerateProtocol(Proto);
7646 case Decl::ObjCCategoryImpl:
7652 case Decl::ObjCImplementation: {
7654 EmitObjCPropertyImplementations(OMD);
7655 EmitObjCIvarInitializations(OMD);
7656 ObjCRuntime->GenerateClass(OMD);
7660 DI->getOrCreateInterfaceType(
getContext().getObjCInterfaceType(
7661 OMD->getClassInterface()), OMD->getLocation());
7664 case Decl::ObjCMethod: {
7671 case Decl::ObjCCompatibleAlias:
7675 case Decl::PragmaComment: {
7677 switch (PCD->getCommentKind()) {
7679 llvm_unreachable(
"unexpected pragma comment kind");
7694 case Decl::PragmaDetectMismatch: {
7700 case Decl::LinkageSpec:
7704 case Decl::FileScopeAsm: {
7706 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7709 if (LangOpts.OpenMPIsTargetDevice)
7712 if (LangOpts.SYCLIsDevice)
7715 getModule().appendModuleInlineAsm(AD->getAsmString());
7719 case Decl::TopLevelStmt:
7723 case Decl::Import: {
7727 if (!ImportedModules.insert(Import->getImportedModule()))
7731 if (!Import->getImportedOwningModule()) {
7733 DI->EmitImportDecl(*Import);
7739 if (CXX20ModuleInits && Import->getImportedModule() &&
7740 Import->getImportedModule()->isNamedModule())
7749 Visited.insert(Import->getImportedModule());
7750 Stack.push_back(Import->getImportedModule());
7752 while (!Stack.empty()) {
7754 if (!EmittedModuleInitializers.insert(Mod).second)
7757 for (
auto *D : Context.getModuleInitializers(Mod))
7764 if (Submodule->IsExplicit)
7767 if (Visited.insert(Submodule).second)
7768 Stack.push_back(Submodule);
7778 case Decl::OMPThreadPrivate:
7782 case Decl::OMPAllocate:
7786 case Decl::OMPDeclareReduction:
7790 case Decl::OMPDeclareMapper:
7794 case Decl::OMPRequires:
7799 case Decl::TypeAlias:
7801 DI->EmitAndRetainType(
getContext().getTypedefType(
7809 DI->EmitAndRetainType(
7816 DI->EmitAndRetainType(
7820 case Decl::HLSLRootSignature:
7823 case Decl::HLSLBuffer:
7827 case Decl::OpenACCDeclare:
7830 case Decl::OpenACCRoutine:
7845 if (!CodeGenOpts.CoverageMapping)
7848 case Decl::CXXConversion:
7849 case Decl::CXXMethod:
7850 case Decl::Function:
7851 case Decl::ObjCMethod:
7852 case Decl::CXXConstructor:
7853 case Decl::CXXDestructor: {
7862 DeferredEmptyCoverageMappingDecls.try_emplace(D,
true);
7872 if (!CodeGenOpts.CoverageMapping)
7874 if (
const auto *Fn = dyn_cast<FunctionDecl>(D)) {
7875 if (Fn->isTemplateInstantiation())
7878 DeferredEmptyCoverageMappingDecls.insert_or_assign(D,
false);
7886 for (
const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
7889 const Decl *D = Entry.first;
7891 case Decl::CXXConversion:
7892 case Decl::CXXMethod:
7893 case Decl::Function:
7894 case Decl::ObjCMethod: {
7901 case Decl::CXXConstructor: {
7908 case Decl::CXXDestructor: {
7925 if (llvm::Function *F =
getModule().getFunction(
"main")) {
7926 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
7927 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
7928 auto *GA = llvm::GlobalAlias::create(
"__main_void", F);
7929 GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
7938 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
7939 return llvm::ConstantInt::get(i64, PtrInt);
7943 llvm::NamedMDNode *&GlobalMetadata,
7945 llvm::GlobalValue *
Addr) {
7946 if (!GlobalMetadata)
7948 CGM.
getModule().getOrInsertNamedMetadata(
"clang.global.decl.ptrs");
7951 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(
Addr),
7954 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.
getLLVMContext(), Ops));
7957bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
7958 llvm::GlobalValue *CppFunc) {
7960 llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
7963 llvm::SmallVector<llvm::ConstantExpr *> CEs;
7966 if (Elem == CppFunc)
7972 for (llvm::User *User : Elem->users()) {
7976 if (
auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
7977 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
7980 for (llvm::User *CEUser : ConstExpr->users()) {
7981 if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
7982 IFuncs.push_back(IFunc);
7987 CEs.push_back(ConstExpr);
7988 }
else if (
auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
7989 IFuncs.push_back(IFunc);
8001 for (llvm::GlobalIFunc *IFunc : IFuncs)
8002 IFunc->setResolver(
nullptr);
8003 for (llvm::ConstantExpr *ConstExpr : CEs)
8004 ConstExpr->destroyConstant();
8008 Elem->eraseFromParent();
8010 for (llvm::GlobalIFunc *IFunc : IFuncs) {
8015 llvm::FunctionType::get(IFunc->getType(),
false);
8016 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
8017 CppFunc->getName(), ResolverTy, {},
false);
8018 IFunc->setResolver(Resolver);
8028void CodeGenModule::EmitStaticExternCAliases() {
8031 for (
auto &I : StaticExternCValues) {
8032 const IdentifierInfo *Name = I.first;
8033 llvm::GlobalValue *Val = I.second;
8041 llvm::GlobalValue *ExistingElem =
8046 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
8053 auto Res = Manglings.find(MangledName);
8054 if (Res == Manglings.end())
8056 Result = Res->getValue();
8067void CodeGenModule::EmitDeclMetadata() {
8068 llvm::NamedMDNode *GlobalMetadata =
nullptr;
8070 for (
auto &I : MangledDeclNames) {
8071 llvm::GlobalValue *
Addr =
getModule().getNamedValue(I.second);
8081void CodeGenFunction::EmitDeclMetadata() {
8082 if (LocalDeclMap.empty())
return;
8087 unsigned DeclPtrKind = Context.getMDKindID(
"clang.decl.ptr");
8089 llvm::NamedMDNode *GlobalMetadata =
nullptr;
8091 for (
auto &I : LocalDeclMap) {
8092 const Decl *D = I.first;
8093 llvm::Value *
Addr = I.second.emitRawPointer(*
this);
8094 if (
auto *Alloca = dyn_cast<llvm::AllocaInst>(
Addr)) {
8096 Alloca->setMetadata(
8097 DeclPtrKind, llvm::MDNode::get(
8098 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
8099 }
else if (
auto *GV = dyn_cast<llvm::GlobalValue>(
Addr)) {
8106void CodeGenModule::EmitVersionIdentMetadata() {
8107 llvm::NamedMDNode *IdentMetadata =
8108 TheModule.getOrInsertNamedMetadata(
"llvm.ident");
8110 llvm::LLVMContext &Ctx = TheModule.getContext();
8112 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
8113 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
8116void CodeGenModule::EmitCommandLineMetadata() {
8117 llvm::NamedMDNode *CommandLineMetadata =
8118 TheModule.getOrInsertNamedMetadata(
"llvm.commandline");
8120 llvm::LLVMContext &Ctx = TheModule.getContext();
8122 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
8123 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
8126void CodeGenModule::EmitCoverageFile() {
8127 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(
"llvm.dbg.cu");
8131 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(
"llvm.gcov");
8132 llvm::LLVMContext &Ctx = TheModule.getContext();
8133 auto *CoverageDataFile =
8135 auto *CoverageNotesFile =
8137 for (
int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
8138 llvm::MDNode *CU = CUNode->getOperand(i);
8139 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
8140 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
8153 LangOpts.ObjCRuntime.isGNUFamily())
8154 return ObjCRuntime->GetEHType(Ty);
8161 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
8163 for (
auto RefExpr : D->
varlist()) {
8166 VD->getAnyInitializer() &&
8167 !VD->getAnyInitializer()->isConstantInitializer(
getContext(),
8174 VD,
Addr, RefExpr->getBeginLoc(), PerformInit))
8175 CXXGlobalInits.push_back(InitFunction);
8180CodeGenModule::CreateMetadataIdentifierImpl(
QualType T, MetadataTypeMap &Map,
8184 FnType->getReturnType(), FnType->getParamTypes(),
8185 FnType->getExtProtoInfo().withExceptionSpec(
EST_None));
8187 llvm::Metadata *&InternalId = Map[
T.getCanonicalType()];
8192 std::string OutName;
8193 llvm::raw_string_ostream Out(OutName);
8198 Out <<
".normalized";
8221 return CreateMetadataIdentifierImpl(
T, MetadataIdMap,
"");
8226 return CreateMetadataIdentifierImpl(
T, VirtualMetadataIdMap,
".virtual");
8230 return CreateMetadataIdentifierImpl(
T, GeneralizedMetadataIdMap,
8238 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
8239 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
8240 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
8241 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
8242 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
8243 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
8244 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
8245 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
8253 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8255 if (CodeGenOpts.SanitizeCfiCrossDso)
8257 VTable->addTypeMetadata(Offset.getQuantity(),
8258 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
8261 llvm::Metadata *MD = llvm::MDString::get(
getLLVMContext(),
"all-vtables");
8262 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8268 SanStats = std::make_unique<llvm::SanitizerStatReport>(&
getModule());
8278 auto *FTy = llvm::FunctionType::get(SamplerT, {
C->getType()},
false);
8293 bool forPointeeType) {
8304 if (
auto Align = TT->getDecl()->getMaxAlignment()) {
8311 bool AlignForArray =
T->isArrayType();
8317 if (
T->isIncompleteType()) {
8334 if (
T.getQualifiers().hasUnaligned()) {
8336 }
else if (forPointeeType && !AlignForArray &&
8337 (RD =
T->getAsCXXRecordDecl())) {
8348 if (
unsigned MaxAlign =
getLangOpts().MaxTypeAlign) {
8361 if (NumAutoVarInit >= StopAfter) {
8364 if (!NumAutoVarInit) {
8378 const Decl *D)
const {
8382 OS << (isa<VarDecl>(D) ?
".static." :
".intern.");
8384 OS << (isa<VarDecl>(D) ?
"__static__" :
"__intern__");
8390 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
8394 llvm::MD5::MD5Result
Result;
8395 for (
const auto &Arg : PreprocessorOpts.Macros)
8396 Hash.update(Arg.first);
8400 llvm::sys::fs::UniqueID ID;
8404 assert(PLoc.
isValid() &&
"Source location is expected to be valid.");
8408 SM.getDiagnostics().Report(diag::err_cannot_open_file)
8409 << PLoc.
getFilename() << Status.getError().message();
8411 ID = Status->getUniqueID();
8413 OS << llvm::format(
"%x", ID.getFile()) << llvm::format(
"%x", ID.getDevice())
8414 <<
"_" << llvm::utohexstr(
Result.low(),
true, 8);
8421 assert(DeferredDeclsToEmit.empty() &&
8422 "Should have emitted all decls deferred to emit.");
8423 assert(NewBuilder->DeferredDecls.empty() &&
8424 "Newly created module should not have deferred decls");
8425 NewBuilder->DeferredDecls = std::move(DeferredDecls);
8426 assert(EmittedDeferredDecls.empty() &&
8427 "Still have (unmerged) EmittedDeferredDecls deferred decls");
8429 assert(NewBuilder->DeferredVTables.empty() &&
8430 "Newly created module should not have deferred vtables");
8431 NewBuilder->DeferredVTables = std::move(DeferredVTables);
8433 assert(NewBuilder->MangledDeclNames.empty() &&
8434 "Newly created module should not have mangled decl names");
8435 assert(NewBuilder->Manglings.empty() &&
8436 "Newly created module should not have manglings");
8437 NewBuilder->Manglings = std::move(Manglings);
8439 NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
8441 NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines the Diagnostic-related interfaces.
Defines enum values for all the target-independent builtin functions.
static bool shouldAssumeDSOLocal(const CIRGenModule &cgm, cir::CIRGlobalValueInterface gv)
static bool shouldBeInCOMDAT(CIRGenModule &cgm, const Decl &d)
static void setWindowsItaniumDLLImport(CIRGenModule &cgm, bool isLocal, cir::FuncOp funcOp, StringRef name)
static std::string getMangledNameImpl(CIRGenModule &cgm, GlobalDecl gd, const NamedDecl *nd)
static CIRGenCXXABI * createCXXABI(CIRGenModule &cgm)
static bool isVarDeclStrongDefinition(const ASTContext &astContext, CIRGenModule &cgm, const VarDecl *vd, bool noCommon)
static void setLinkageForGV(cir::GlobalOp &gv, const NamedDecl *nd)
static bool hasExistingGeneralizedTypeMD(llvm::Function *F)
static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, const CPUSpecificAttr *Attr, unsigned CPUIndex, raw_ostream &Out)
static bool AllTrivialInitializers(CodeGenModule &CGM, ObjCImplementationDecl *D)
static const FunctionDecl * GetRuntimeFunctionDecl(ASTContext &C, StringRef Name)
static GlobalDecl getBaseVariantGlobalDecl(const NamedDecl *D)
static void checkAliasForTocData(llvm::GlobalVariable *GVar, const CodeGenOptions &CodeGenOpts, DiagnosticsEngine &Diags, SourceLocation Location)
static bool hasImplicitAttr(const ValueDecl *D)
static void emitUsed(CodeGenModule &CGM, StringRef Name, std::vector< llvm::WeakTrackingVH > &List)
static bool HasNonDllImportDtor(QualType T)
static llvm::Constant * GetPointerConstant(llvm::LLVMContext &Context, const void *Ptr)
Turns the given pointer into a constant.
static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S)
static llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM, GlobalDecl GD)
static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO, llvm::Module &M)
static QualType GeneralizeTransparentUnion(QualType Ty)
static std::string getCPUSpecificMangling(const CodeGenModule &CGM, StringRef Name)
static const char AnnotationSection[]
static bool isUniqueInternalLinkageDecl(GlobalDecl GD, CodeGenModule &CGM)
static bool allowKCFIIdentifier(StringRef Name)
static void replaceUsesOfNonProtoConstant(llvm::Constant *old, llvm::Function *newFn)
Replace the uses of a function that was declared with a non-proto type.
static llvm::Constant * castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, llvm::GlobalVariable *GV)
static void checkDataLayoutConsistency(const TargetInfo &Target, llvm::LLVMContext &Context, const LangOptions &Opts)
static std::vector< std::string > getFeatureDeltaFromDefault(const CodeGenModule &CGM, StringRef TargetCPU, llvm::StringMap< bool > &FeatureMap)
Get the feature delta from the default feature map for the given target CPU.
static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty, bool GeneralizePointers)
static bool needsDestructMethod(ObjCImplementationDecl *impl)
static bool isStackProtectorOn(const LangOptions &LangOpts, const llvm::Triple &Triple, clang::LangOptions::StackProtectorMode Mode)
static void removeImageAccessQualifier(std::string &TyName)
static llvm::StringMapEntry< llvm::GlobalVariable * > & GetConstantCFStringEntry(llvm::StringMap< llvm::GlobalVariable * > &Map, const StringLiteral *Literal, bool TargetIsLSB, bool &IsUTF16, unsigned &StringLength)
static void setLLVMVisibility(llvm::GlobalValue &GV, std::optional< llvm::GlobalValue::VisibilityTypes > V)
static llvm::GlobalVariable * GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, CodeGenModule &CGM, StringRef GlobalName, CharUnits Alignment)
static bool hasUnwindExceptions(const LangOptions &LangOpts)
Determines whether the language options require us to model unwind exceptions.
static llvm::APInt getFMVPriority(const TargetInfo &TI, const CodeGenFunction::FMVResolverOption &RO)
static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, SmallVectorImpl< llvm::MDNode * > &Metadata, llvm::SmallPtrSet< Module *, 16 > &Visited)
Add link options implied by the given module, including modules it depends on, using a postorder walk...
static llvm::cl::opt< bool > LimitedCoverage("limited-coverage-experimental", llvm::cl::Hidden, llvm::cl::desc("Emit limited coverage mapping information (experimental)"))
static CGCXXABI * createCXXABI(CodeGenModule &CGM)
static std::unique_ptr< TargetCodeGenInfo > createTargetCodeGenInfo(CodeGenModule &CGM)
static const llvm::GlobalValue * getAliasedGlobal(const llvm::GlobalValue *GV)
static QualType GeneralizeType(ASTContext &Ctx, QualType Ty, bool GeneralizePointers)
static bool shouldSkipAliasEmission(const CodeGenModule &CGM, const ValueDecl *Global)
static constexpr auto ErrnoTBAAMDName
static unsigned ArgInfoAddressSpace(LangAS AS)
static void replaceDeclarationWith(llvm::GlobalValue *Old, llvm::Constant *New)
static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, llvm::Function *NewFn)
ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we implement a function with...
static std::optional< llvm::GlobalValue::VisibilityTypes > getLLVMVisibility(clang::LangOptions::VisibilityFromDLLStorageClassKinds K)
static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, const CXXMethodDecl *MD)
static bool checkAliasedGlobal(const ASTContext &Context, DiagnosticsEngine &Diags, SourceLocation Location, bool IsIFunc, const llvm::GlobalValue *Alias, const llvm::GlobalValue *&GV, const llvm::MapVector< GlobalDecl, StringRef > &MangledDeclNames, SourceRange AliasRange)
static void EmitGlobalDeclMetadata(CodeGenModule &CGM, llvm::NamedMDNode *&GlobalMetadata, GlobalDecl D, llvm::GlobalValue *Addr)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
llvm::MachO::Target Target
llvm::MachO::Record Record
Defines the clang::Module class, which describes a module in the source code.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
static const NamedDecl * getDefinition(const Decl *D)
Defines the SourceManager interface.
static CharUnits getTypeAllocSize(CodeGenModule &CGM, llvm::Type *type)
Defines version macros and version-related utility functions for Clang.
__device__ __2f16 float __ockl_bool s
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
SourceManager & getSourceManager()
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
@ Strong
Strong definition.
@ WeakUnknown
Weak for now, might become strong later in this TU.
const ProfileList & getProfileList() const
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
const XRayFunctionFilter & getXRayFilter() const
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
StringRef getCUIDHash() const
const LangOptions & getLangOpts() const
SelectorTable & Selectors
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
const NoSanitizeList & getNoSanitizeList() const
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const
Return the alignment in characters that should be given to a global variable with type T.
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
DiagnosticsEngine & getDiagnostics() const
const TargetInfo & getTargetInfo() const
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
CanQualType getCanonicalTagType(const TagDecl *TD) const
unsigned getTargetAddressSpace(LangAS AS) const
Module * getCurrentNamedModule() const
Get module under construction, nullptr if this is not a C++20 module.
Attr - This represents one attribute.
Represents a block literal declaration, which is like an unnamed FunctionDecl.
bool isLibFunction(unsigned ID) const
Return true if this is a builtin for a libc/libm function, with a "__builtin_" prefix (e....
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Represents a base class of a C++ class.
CXXTemporary * getTemporary()
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Represents a C++ base or member initializer.
Expr * getInit() const
Get the initializer.
FunctionDecl * getOperatorDelete() const
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Represents a static or instance method of a struct/union/class.
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
FunctionDecl * getOperatorNew() const
Represents a C++ struct/union/class.
unsigned getNumBases() const
Retrieves the number of base classes of this class.
bool hasDefinition() const
const CXXDestructorDecl * getDestructor() const
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
CharUnits - This is an opaque type for sizes expressed in character units.
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
static CharUnits One()
One - Construct a CharUnits quantity of one.
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::string MSSecureHotPatchFunctionsFile
The name of a file that contains functions which will be compiled for hotpatching.
std::string RecordCommandLine
The string containing the commandline for the llvm.commandline metadata, if non-empty.
std::string FloatABI
The ABI to use for passing floating point arguments.
llvm::Reloc::Model RelocationModel
The name of the relocation model to use.
std::vector< std::string > TocDataVarsUserSpecified
List of global variables explicitly specified by the user as toc-data.
PointerAuthOptions PointerAuth
Configuration for pointer-signing.
std::vector< std::string > MSSecureHotPatchFunctionsList
A list of functions which will be compiled for hotpatching.
ABIInfo - Target specific hooks for defining how a type should be passed or returned from functions.
virtual void appendAttributeMangling(TargetAttr *Attr, raw_ostream &Out) const
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
virtual void handleVarRegistration(const VarDecl *VD, llvm::GlobalVariable &Var)=0
Check whether a variable is a device variable and register it if true.
virtual llvm::GlobalValue * getKernelHandle(llvm::Function *Stub, GlobalDecl GD)=0
Get kernel handle by stub function.
virtual void internalizeDeviceSideVar(const VarDecl *D, llvm::GlobalValue::LinkageTypes &Linkage)=0
Adjust linkage of shadow variables in host compilation.
Implements C++ ABI-specific code generation functions.
virtual void EmitCXXConstructors(const CXXConstructorDecl *D)=0
Emit constructor variants required by this ABI.
virtual llvm::Constant * getAddrOfRTTIDescriptor(QualType Ty)=0
virtual void EmitCXXDestructors(const CXXDestructorDecl *D)=0
Emit destructor variants required by this ABI.
virtual void setCXXDestructorDLLStorage(llvm::GlobalValue *GV, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
virtual llvm::GlobalValue::LinkageTypes getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
MangleContext & getMangleContext()
Gets the mangle context.
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
void EmitExternalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl)
Emit information about an external variable.
void EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc, QualType FnType, llvm::Function *Fn=nullptr)
Emit debug info for a function declaration.
void AddStringLiteralDebugInfo(llvm::GlobalVariable *GV, const StringLiteral *S)
DebugInfo isn't attached to string literals by default.
CGFunctionInfo - Class to encapsulate the information about a function definition.
void handleGlobalVarDefinition(const VarDecl *VD, llvm::GlobalVariable *Var)
void addRootSignature(const HLSLRootSignatureDecl *D)
void addBuffer(const HLSLBufferDecl *D)
llvm::Type * getSamplerType(const Type *T)
void emitDeferredTargetDecls() const
Emit deferred declare target variables marked for deferred emission.
virtual void emitDeclareTargetFunction(const FunctionDecl *FD, llvm::GlobalValue *GV)
Emit code for handling declare target functions in the runtime.
virtual ConstantAddress getAddrOfDeclareTargetVar(const VarDecl *VD)
Returns the address of the variable marked as declare target with link clause OR as declare target wi...
bool hasRequiresUnifiedSharedMemory() const
Return whether the unified_shared_memory has been specified.
virtual void emitDeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn)
Marks function Fn with properly mangled versions of vector functions.
virtual void registerTargetGlobalVariable(const VarDecl *VD, llvm::Constant *Addr)
Checks if the provided global decl GD is a declare target variable and registers it when emitting cod...
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
void EmitCfiCheckFail()
Emit a cross-DSO CFI failure handling function.
void GenerateObjCGetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCGetter - Synthesize an Objective-C property getter function.
void EmitCfiCheckStub()
Emit a stub for the cross-DSO CFI check function.
void GenerateObjCMethod(const ObjCMethodDecl *OMD)
Generate an Objective-C method.
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
void GenerateObjCSetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCSetter - Synthesize an Objective-C property setter function for the given property.
llvm::LLVMContext & getLLVMContext()
bool isTrivialInitializer(const Expr *Init)
Determine whether the given initializer is trivial in the sense that it requires no code to be genera...
This class organizes the cross-function state that is used while generating LLVM code.
StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD)
ConstantAddress GetAddrOfMSGuidDecl(const MSGuidDecl *GD)
Get the address of a GUID.
void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const
Set visibility, dllimport/dllexport and dso_local.
void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD)
Create and attach type metadata for the given vtable.
void UpdateCompletedType(const TagDecl *TD)
llvm::MDNode * getTBAAAccessTagInfo(TBAAAccessInfo Info)
getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
llvm::GlobalVariable::ThreadLocalMode GetDefaultLLVMTLSModel() const
Get LLVM TLS mode from CodeGenOptions.
void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F, const CGFunctionInfo &FI)
Set the attributes on the LLVM function for the given decl and function info.
void setDSOLocal(llvm::GlobalValue *GV) const
llvm::MDNode * getTBAAStructInfo(QualType QTy)
CGHLSLRuntime & getHLSLRuntime()
Return a reference to the configured HLSL runtime.
llvm::Constant * EmitAnnotationArgs(const AnnotateAttr *Attr)
Emit additional args of the annotation.
llvm::Module & getModule() const
std::optional< llvm::Attribute::AttrKind > StackProtectorAttribute(const Decl *D) const
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
llvm::ConstantInt * CreateKCFITypeId(QualType T, StringRef Salt)
Generate a KCFI type identifier for T.
CGDebugInfo * getModuleDebugInfo()
bool NeedAllVtablesTypeId() const
Returns whether this module needs the "all-vtables" type identifier.
void addCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
CodeGenVTables & getVTables()
llvm::ConstantInt * CreateCrossDsoCfiTypeId(llvm::Metadata *MD)
Generate a cross-DSO type identifier for MD.
CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const
Return the store size, in character units, of the given LLVM type.
void createFunctionTypeMetadataForIcall(const FunctionDecl *FD, llvm::Function *F)
Create and attach type metadata to the given function.
bool getExpressionLocationsEnabled() const
Return true if we should emit location information for expressions.
void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C)
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
void setGVPropertiesAux(llvm::GlobalValue *GV, const NamedDecl *D) const
const IntrusiveRefCntPtr< llvm::vfs::FileSystem > & getFileSystem() const
const ABIInfo & getABIInfo()
void EmitMainVoidAlias()
Emit an alias for "main" if it has no arguments (needed for wasm).
void DecorateInstructionWithInvariantGroup(llvm::Instruction *I, const CXXRecordDecl *RD)
Adds !invariant.barrier !tag to instruction.
DiagnosticsEngine & getDiags() const
bool isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, SourceLocation Loc) const
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
llvm::Constant * getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the constructor/destructor of the given type.
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
llvm::Constant * EmitAnnotateAttr(llvm::GlobalValue *GV, const AnnotateAttr *AA, SourceLocation L)
Generate the llvm::ConstantStruct which contains the annotation information for a given GlobalValue.
void EmitOpenACCDeclare(const OpenACCDeclareDecl *D, CodeGenFunction *CGF=nullptr)
llvm::GlobalValue::LinkageTypes getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage)
Returns LLVM linkage for a declarator.
TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, TBAAAccessInfo SrcInfo)
mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the purposes of memory transfer call...
const LangOptions & getLangOpts() const
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
llvm::Constant * EmitAnnotationLineNo(SourceLocation L)
Emit the annotation line number.
QualType getObjCFastEnumerationStateType()
Retrieve the record type that describes the state of an Objective-C fast enumeration loop (for....
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
CodeGenTypes & getTypes()
bool shouldMapVisibilityToDLLExport(const NamedDecl *D) const
CGOpenCLRuntime & getOpenCLRuntime()
Return a reference to the configured OpenCL runtime.
const std::string & getModuleNameHash() const
const TargetInfo & getTarget() const
bool shouldEmitRTTI(bool ForEH=false)
void EmitGlobal(GlobalDecl D)
Emit code for a single global function or var decl.
llvm::Metadata * CreateMetadataIdentifierForType(QualType T)
Create a metadata identifier for the given type.
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
void createIndirectFunctionTypeMD(const FunctionDecl *FD, llvm::Function *F)
Create and attach type metadata if the function is a potential indirect call target to support call g...
void AppendLinkerOptions(StringRef Opts)
Appends Opts to the "llvm.linker.options" metadata value.
void createCalleeTypeMetadataForIcall(const QualType &QT, llvm::CallBase *CB)
Create and attach type metadata to the given call.
void EmitExternalDeclaration(const DeclaratorDecl *D)
void AddDependentLib(StringRef Lib)
Appends a dependent lib to the appropriate metadata value.
void Release()
Finalize LLVM code generation.
ProfileList::ExclusionType isFunctionBlockedByProfileList(llvm::Function *Fn, SourceLocation Loc) const
llvm::MDNode * getTBAABaseTypeInfo(QualType QTy)
getTBAABaseTypeInfo - Get metadata that describes the given base access type.
bool lookupRepresentativeDecl(StringRef MangledName, GlobalDecl &Result) const
void EmitOMPAllocateDecl(const OMPAllocateDecl *D)
Emit a code for the allocate directive.
void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const
Set the visibility for the given LLVM GlobalValue.
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD)
Returns LLVM linkage for a declarator.
bool HasHiddenLTOVisibility(const CXXRecordDecl *RD)
Returns whether the given record has hidden LTO visibility and therefore may participate in (single-m...
const llvm::DataLayout & getDataLayout() const
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can't be done.
TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType)
getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an access to a virtual table poi...
CGCXXABI & getCXXABI() const
ConstantAddress GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
llvm::Constant * GetFunctionStart(const ValueDecl *Decl)
static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V)
void EmitTentativeDefinition(const VarDecl *D)
void EmitDeferredUnusedCoverageMappings()
Emit all the deferred coverage mappings for the uninstrumented functions.
void addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, StringRef Category=StringRef()) const
Imbue XRay attributes to a function, applying the always/never attribute lists in the process.
SanitizerMetadata * getSanitizerMetadata()
llvm::Metadata * CreateMetadataIdentifierGeneralized(QualType T)
Create a metadata identifier for the generalization of the given type.
void EmitGlobalAnnotations()
Emit all the global annotations.
CharUnits getClassPointerAlignment(const CXXRecordDecl *CD)
Returns the assumed alignment of an opaque pointer to the given class.
const llvm::Triple & getTriple() const
SmallVector< const CXXRecordDecl *, 0 > getMostBaseClasses(const CXXRecordDecl *RD)
Return a vector of most-base classes for RD.
void AddDeferredUnusedCoverageMapping(Decl *D)
Stored a deferred empty coverage mapping for an unused and thus uninstrumented top level declaration.
void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV)
If the declaration has internal linkage but is inside an extern "C" linkage specification,...
void DecorateInstructionWithTBAA(llvm::Instruction *Inst, TBAAAccessInfo TBAAInfo)
DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD)
void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535, bool IsDtorAttrFunc=false)
AddGlobalDtor - Add a function to the list that will be called when the module is unloaded.
llvm::Constant * CreateRuntimeVariable(llvm::Type *Ty, StringRef Name)
Create a new runtime global variable with the specified type and name.
void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info, CGCalleeInfo CalleeInfo, llvm::AttributeList &Attrs, unsigned &CallingConv, bool AttrOnCallSite, bool IsThunk)
Get the LLVM attributes and calling convention to use for a particular function type.
llvm::Constant * GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, LangAS AddrSpace, const VarDecl *D, ForDefinition_t IsForDefinition=NotForDefinition)
GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, create and return an llvm...
TBAAAccessInfo getTBAAAccessInfo(QualType AccessType)
getTBAAAccessInfo - Get TBAA information that describes an access to an object of the given type.
void setFunctionLinkage(GlobalDecl GD, llvm::Function *F)
llvm::Constant * GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition=NotForDefinition)
AtomicOptions getAtomicOpts()
Get the current Atomic options.
ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal)
Return a pointer to a constant CFString object for the given string.
ProfileList::ExclusionType isFunctionBlockedFromProfileInstr(llvm::Function *Fn, SourceLocation Loc) const
void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV)
Add global annotations that are set on D, for the global GV.
void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const
Set the TLS mode for the given LLVM GlobalValue for the thread-local variable declaration D.
ConstantAddress GetAddrOfConstantStringFromLiteral(const StringLiteral *S, StringRef Name=".str")
Return a pointer to a constant array for the given string literal.
ASTContext & getContext() const
ConstantAddress GetAddrOfTemplateParamObject(const TemplateParamObjectDecl *TPO)
Get the address of a template parameter object.
void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D)
Emit a code for threadprivate directive.
ConstantAddress GetAddrOfUnnamedGlobalConstantDecl(const UnnamedGlobalConstantDecl *GCD)
Get the address of a UnnamedGlobalConstant.
TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, TBAAAccessInfo TargetInfo)
mergeTBAAInfoForCast - Get merged TBAA information for the purposes of type casts.
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
llvm::SanitizerStatReport & getSanStats()
llvm::Constant * EmitAnnotationString(StringRef Str)
Emit an annotation string.
void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare mapper construct.
bool supportsCOMDAT() const
void RefreshTypeCacheForClass(const CXXRecordDecl *Class)
llvm::MDNode * getTBAATypeInfo(QualType QTy)
getTBAATypeInfo - Get metadata used to describe accesses to objects of the given type.
void EmitOMPRequiresDecl(const OMPRequiresDecl *D)
Emit a code for requires directive.
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD)
Tell the consumer that this variable has been instantiated.
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
llvm::Constant * GetConstantArrayFromStringLiteral(const StringLiteral *E)
Return a constant array for the given string.
void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV)
Set attributes which are common to any form of a global definition (alias, Objective-C method,...
std::optional< CharUnits > getOMPAllocateAlignment(const VarDecl *VD)
Return the alignment specified in an allocate directive, if present.
llvm::GlobalVariable * CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, llvm::Align Alignment)
Will return a global variable of the given type.
CharUnits getNaturalPointeeTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, TBAAAccessInfo InfoB)
mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the purposes of conditional ope...
llvm::LLVMContext & getLLVMContext()
llvm::GlobalValue * GetGlobalValue(StringRef Ref)
void GenKernelArgMetadata(llvm::Function *FN, const FunctionDecl *FD=nullptr, CodeGenFunction *CGF=nullptr)
OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument information in the program executab...
void setKCFIType(const FunctionDecl *FD, llvm::Function *F)
Set type metadata to the given function.
void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO)
void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare reduction construct.
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
void AddDetectMismatch(StringRef Name, StringRef Value)
Appends a detect mismatch command to the linker options.
void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const
llvm::Value * createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF)
ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
LangAS GetGlobalConstantAddressSpace() const
Return the AST address space of constant literal, which is used to emit the constant literal as globa...
LangAS GetGlobalVarAddressSpace(const VarDecl *D)
Return the AST address space of the underlying global variable for D, as determined by its declaratio...
void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info, llvm::Function *F, bool IsThunk)
Set the LLVM function attributes (sext, zext, etc).
void EmitOpenACCRoutine(const OpenACCRoutineDecl *D, CodeGenFunction *CGF=nullptr)
void addReplacement(StringRef Name, llvm::Constant *C)
llvm::Constant * getConstantSignedPointer(llvm::Constant *Pointer, const PointerAuthSchema &Schema, llvm::Constant *StorageAddress, GlobalDecl SchemaDecl, QualType SchemaType)
Sign a constant pointer using the given scheme, producing a constant with the same IR type.
void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535, unsigned LexOrder=~0U, llvm::Constant *AssociatedData=nullptr)
AddGlobalCtor - Add a function to the list that will be called before main() runs.
llvm::Metadata * CreateMetadataIdentifierForFnType(QualType T)
Create a metadata identifier for the given function type.
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
llvm::Metadata * CreateMetadataIdentifierForVirtualMemPtrType(QualType T)
Create a metadata identifier that is intended to be used to check virtual calls via a member function...
ConstantAddress GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *)
Return a pointer to a constant array for the given ObjCEncodeExpr node.
const GlobalDecl getMangledNameDecl(StringRef)
void ClearUnusedCoverageMapping(const Decl *D)
Remove the deferred empty coverage mapping as this declaration is actually instrumented.
void EmitTopLevelDecl(Decl *D)
Emit code for a single top level declaration.
llvm::Constant * EmitAnnotationUnit(SourceLocation Loc)
Emit the annotation's translation unit.
ConstantAddress GetAddrOfConstantCString(const std::string &Str, StringRef GlobalName=".str")
Returns a pointer to a character array containing the literal and a terminating '\0' character.
void printPostfixForExternalizedDecl(llvm::raw_ostream &OS, const Decl *D) const
Print the postfix for externalized static variable or kernels for single source offloading languages ...
void moveLazyEmissionStates(CodeGenModule *NewBuilder)
Move some lazily-emitted states to the NewBuilder.
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
void finalizeKCFITypes()
Emit KCFI type identifier constants and remove unused identifiers.
void setValueProfilingFlag(llvm::Module &M)
void setProfileVersion(llvm::Module &M)
void emitEmptyCounterMapping(const Decl *D, StringRef FuncName, llvm::GlobalValue::LinkageTypes Linkage)
Emit a coverage mapping range with a counter zero for an unused declaration.
CodeGenTBAA - This class organizes the cross-module state that is used while lowering AST types to LL...
This class organizes the cross-module state that is used while lowering AST types to LLVM types.
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
const CGFunctionInfo & arrangeCXXMethodDeclaration(const CXXMethodDecl *MD)
C++ methods have some special rules and also have implicit parameters.
const CGFunctionInfo & arrangeFreeFunctionType(CanQual< FunctionProtoType > Ty)
Arrange the argument and result information for a value of the given freestanding function type.
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
unsigned getTargetAddressSpace(QualType T) const
void RefreshTypeCacheForClass(const CXXRecordDecl *RD)
Remove stale types from the type cache when an inheritance model gets assigned to a class.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
void UpdateCompletedType(const TagDecl *TD)
UpdateCompletedType - When we find the full definition for a TagDecl, replace the 'opaque' type we pr...
const CGFunctionInfo & arrangeGlobalDeclaration(GlobalDecl GD)
void EmitThunks(GlobalDecl GD)
EmitThunks - Emit the associated thunks for the given global decl.
A specialization of Address that requires the address to be an LLVM Constant.
static ConstantAddress invalid()
llvm::Constant * tryEmitForInitializer(const VarDecl &D)
Try to emit the initiaizer of the given declaration as an abstract constant.
void finalize(llvm::GlobalVariable *global)
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded.
The standard implementation of ConstantInitBuilder used in Clang.
Organizes the cross-function state that is used while generating code coverage mapping data.
bool hasDiagnostics()
Whether or not the stats we've gathered indicate any potential problems.
void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile)
Report potential problems we've found to Diags.
TargetCodeGenInfo - This class organizes various target-specific codegeneration issues,...
virtual void getDependentLibraryOption(llvm::StringRef Lib, llvm::SmallString< 24 > &Opt) const
Gets the linker options necessary to link a dependent library on this platform.
Address performAddrSpaceCast(CodeGen::CodeGenFunction &CGF, Address Addr, LangAS SrcAddr, llvm::Type *DestTy, bool IsNonNull=false) const
const T & getABIInfo() const
virtual LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, const VarDecl *D) const
Get target favored AST address space of a global variable for languages other than OpenCL and CUDA.
virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const
setTargetAttributes - Provides a convenient hook to handle extra target-specific attributes for the g...
virtual LangAS getASTAllocaAddressSpace() const
Get the AST address space for alloca.
virtual void emitTargetMetadata(CodeGen::CodeGenModule &CGM, const llvm::MapVector< GlobalDecl, StringRef > &MangledDeclNames) const
emitTargetMetadata - Provides a convenient hook to handle extra target-specific metadata for the give...
virtual void emitTargetGlobals(CodeGen::CodeGenModule &CGM) const
Provides a convenient hook to handle extra target-specific globals.
virtual void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, llvm::SmallString< 32 > &Opt) const
Gets the linker options necessary to detect object file mismatches on this platform.
Represents the canonical version of C arrays with a specified constant size.
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Stores additional source code information like skipped ranges which is required by the coverage mappi...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
void addDecl(Decl *D)
Add the declaration D into this context.
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Decl - This represents one declaration (or definition), e.g.
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
SourceLocation getEndLoc() const LLVM_READONLY
ASTContext & getASTContext() const LLVM_READONLY
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
SourceLocation getLocation() const
SourceLocation getBeginLoc() const LLVM_READONLY
TranslationUnitDecl * getTranslationUnitDecl()
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Represents a ValueDecl that came out of a declarator.
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
This represents one expression.
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Represents a member of a struct/union/class.
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
StringRef getName() const
The name of this FileEntry.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Represents a function declaration or definition.
bool isTargetClonesMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target-clones functional...
bool isMultiVersion() const
True if this function is considered a multiversioned function.
const ParmVarDecl * getParamDecl(unsigned i) const
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
bool isImmediateFunction() const
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
bool isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
bool isInlineBuiltinDeclaration() const
Determine if this function provides an inline implementation of a builtin.
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
FunctionDecl * getDefinition()
Get the definition for this declaration.
bool isTargetVersionMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target-version functiona...
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
bool doesDeclarationForceExternallyVisibleDefinition() const
For a function declaration in C or C++, determine whether this declaration causes the definition to b...
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const override
Appends a human-readable name for this declaration into the given stream.
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Represents a prototype with parameter type info, e.g.
FunctionType - C99 6.7.5.3 - Function Declarators.
CallingConv getCallConv() const
GlobalDecl - represents a global declaration.
GlobalDecl getWithMultiVersionIndex(unsigned Index)
CXXCtorType getCtorType() const
GlobalDecl getWithKernelReferenceKind(KernelReferenceKind Kind)
GlobalDecl getCanonicalDecl() const
KernelReferenceKind getKernelReferenceKind() const
GlobalDecl getWithDecl(const Decl *D)
unsigned getMultiVersionIndex() const
CXXDtorType getDtorType() const
const Decl * getDecl() const
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
@ None
No signing for any function.
@ Swift5_0
Interoperability with the Swift 5.0 runtime.
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
VisibilityFromDLLStorageClassKinds
@ Keep
Keep the IR-gen assigned visibility.
@ Protected
Override the IR-gen assigned visibility with protected visibility.
@ Default
Override the IR-gen assigned visibility with default visibility.
@ Hidden
Override the IR-gen assigned visibility with hidden visibility.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
clang::ObjCRuntime ObjCRuntime
CoreFoundationABI CFRuntime
std::string CUID
The user provided compilation unit ID, if non-empty.
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Visibility getVisibility() const
void setLinkage(Linkage L)
Linkage getLinkage() const
bool isVisibilityExplicit() const
LinkageSpecLanguageIDs getLanguage() const
Return the language specified by this linkage specification.
Parts getParts() const
Get the decomposed parts of this declaration.
APValue & getAsAPValue() const
Get the value of this MSGuidDecl as an APValue.
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
void mangleBlock(const DeclContext *DC, const BlockDecl *BD, raw_ostream &Out)
void mangleCtorBlock(const CXXConstructorDecl *CD, CXXCtorType CT, const BlockDecl *BD, raw_ostream &Out)
void mangleGlobalBlock(const BlockDecl *BD, const NamedDecl *ID, raw_ostream &Out)
bool shouldMangleDeclName(const NamedDecl *D)
void mangleName(GlobalDecl GD, raw_ostream &)
virtual void mangleCanonicalTypeName(QualType T, raw_ostream &, bool NormalizeIntegers=false)=0
Generates a unique string for an externally visible type for use with TBAA or type uniquing.
virtual void mangleStringLiteral(const StringLiteral *SL, raw_ostream &)=0
ManglerKind getKind() const
virtual void needsUniqueInternalLinkageNames()
virtual void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber, raw_ostream &)=0
void mangleDtorBlock(const CXXDestructorDecl *CD, CXXDtorType DT, const BlockDecl *BD, raw_ostream &Out)
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
unsigned getManglingNumber() const
Describes a module or submodule.
bool isInterfaceOrPartition() const
bool isNamedModuleUnit() const
Is this a C++20 named module unit.
Module * Parent
The parent of this module.
Module * getPrivateModuleFragment() const
Get the Private Module Fragment (sub-module) for this module, it there is one.
llvm::SmallSetVector< Module *, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Module * getGlobalModuleFragment() const
Get the Global Module Fragment (sub-module) for this module, it there is one.
llvm::iterator_range< submodule_iterator > submodules()
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used.
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
bool UseExportAsModuleLinkName
Autolinking uses the framework name for linking purposes when this is false and the export_as name ot...
This represents a decl that may have a name.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
LinkageInfo getLinkageAndVisibility() const
Determines the linkage and visibility of this entity.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
bool isExternallyVisible() const
Represent a C++ namespace.
This represents 'pragma omp threadprivate ...' directive.
ObjCEncodeExpr, used for @encode in Objective-C.
QualType getEncodedType() const
propimpl_range property_impls() const
const ObjCInterfaceDecl * getClassInterface() const
void addInstanceMethod(ObjCMethodDecl *method)
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
init_iterator init_end()
init_end() - Retrieve an iterator past the last initializer.
CXXCtorInitializer ** init_iterator
init_iterator - Iterates through the ivar initializer list.
init_iterator init_begin()
init_begin() - Retrieve an iterator to the first initializer.
unsigned getNumIvarInitializers() const
getNumArgs - Number of ivars which must be initialized.
void setHasDestructors(bool val)
void setHasNonZeroConstructors(bool val)
Represents an ObjC class declaration.
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
ObjCIvarDecl - Represents an ObjC instance variable.
ObjCIvarDecl * getNextIvar()
static ObjCMethodDecl * Create(ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc, Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo, DeclContext *contextDecl, bool isInstance=true, bool isVariadic=false, bool isPropertyAccessor=false, bool isSynthesizedAccessorStub=false, bool isImplicitlyDeclared=false, bool isDefined=false, ObjCImplementationControl impControl=ObjCImplementationControl::None, bool HasRelatedResultType=false)
Represents one property declaration in an Objective-C interface.
ObjCMethodDecl * getGetterMethodDecl() const
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
The basic abstraction for the target Objective-C runtime.
bool hasUnwindExceptions() const
Does this runtime use zero-cost exceptions?
@ MacOSX
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
@ FragileMacOSX
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
@ GNUstep
'gnustep' is the modern non-fragile GNUstep runtime.
@ ObjFW
'objfw' is the Objective-C runtime included in ObjFW
@ iOS
'ios' is the Apple-provided NeXT-derived runtime on iOS or the iOS simulator; it is always non-fragil...
@ GCC
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI
@ WatchOS
'watchos' is a variant of iOS for Apple's watchOS.
Represents a parameter to a function.
bool isAddressDiscriminated() const
uint16_t getConstantDiscrimination() const
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
Represents an unpacked "presumed" location which can be presented to the user.
const char * getFilename() const
Return the presumed filename of this location.
unsigned getLine() const
Return the presumed line number of this location.
ExclusionType getDefault(llvm::driver::ProfileInstrKind Kind) const
std::optional< ExclusionType > isFunctionExcluded(StringRef FunctionName, llvm::driver::ProfileInstrKind Kind) const
std::optional< ExclusionType > isFileExcluded(StringRef FileName, llvm::driver::ProfileInstrKind Kind) const
ExclusionType
Represents if an how something should be excluded from profiling.
@ Skip
Profiling is skipped using the skipprofile attribute.
@ Allow
Profiling is allowed.
std::optional< ExclusionType > isLocationExcluded(SourceLocation Loc, llvm::driver::ProfileInstrKind Kind) const
A (possibly-)qualified type.
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
LangAS getAddressSpace() const
Return the address space of this type.
bool isConstant(const ASTContext &Ctx) const
QualType getCanonicalType() const
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
QualType withCVRQualifiers(unsigned CVR) const
bool isConstQualified() const
Determine whether this type is const-qualified.
bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Represents a struct/union/class.
field_range fields() const
virtual void completeDefinition()
Note that the definition of this type is now complete.
Selector getSelector(unsigned NumArgs, const IdentifierInfo **IIV)
Can create any sort of selector.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
Stmt - This represents one statement.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
SourceLocation getBeginLoc() const LLVM_READONLY
StringLiteral - This represents a string literal expression, e.g.
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
unsigned getLength() const
uint32_t getCodeUnit(size_t i) const
StringRef getString() const
unsigned getCharByteWidth() const
Represents the declaration of a struct/union/class/enum.
void startDefinition()
Starts the definition of this tag declaration.
Exposes information about the current target.
TargetOptions & getTargetOpts() const
Retrieve the target options.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
bool isReadOnlyFeature(StringRef Feature) const
Determine whether the given target feature is read only.
virtual llvm::APInt getFMVPriority(ArrayRef< StringRef > Features) const
bool supportsIFunc() const
Identify whether this target supports IFuncs.
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
virtual bool initFeatureMap(llvm::StringMap< bool > &Features, DiagnosticsEngine &Diags, StringRef CPU, const std::vector< std::string > &FeatureVec) const
Initialize the map with the default set of target features for the CPU this should include all legal ...
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
std::string TuneCPU
If given, the name of the target CPU to tune code for.
std::string CPU
If given, the name of the target CPU to generate code for.
@ Hostcall
printf lowering scheme involving hostcalls, currently used by HIP programs by default
A template parameter object.
const APValue & getValue() const
A declaration that models statements at global scope.
The top declaration context.
static DeclContext * castToDeclContext(const TranslationUnitDecl *D)
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
bool isPointerType() const
const T * castAs() const
Member-template castAs<specific type>.
bool isReferenceType() const
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
bool isHLSLResourceRecord() const
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
bool isObjCObjectPointerType() const
const T * getAs() const
Member-template getAs<specific type>'.
bool isRecordType() const
bool isHLSLResourceRecordArray() const
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
const APValue & getValue() const
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Represents a variable declaration or definition.
TLSKind getTLSKind() const
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
bool hasFlexibleArrayInit(const ASTContext &Ctx) const
Whether this variable has a flexible array member initialized with one or more elements.
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
const Expr * getInit() const
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
@ TLS_Dynamic
TLS with a dynamic initializer.
@ DeclarationOnly
This declaration is only a declaration.
@ Definition
This declaration is definitely a definition.
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
StorageClass getStorageClass() const
Returns the storage class as written in the source.
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Defines the clang::TargetInfo interface.
std::unique_ptr< TargetCodeGenInfo > createARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind Kind)
std::unique_ptr< TargetCodeGenInfo > createM68kTargetCodeGenInfo(CodeGenModule &CGM)
@ AttributedType
The l-value was considered opaque, so the alignment was determined from a type, but that type was an ...
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
std::unique_ptr< TargetCodeGenInfo > createBPFTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createMSP430TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel)
std::unique_ptr< TargetCodeGenInfo > createWebAssemblyTargetCodeGenInfo(CodeGenModule &CGM, WebAssemblyABIKind K)
std::unique_ptr< TargetCodeGenInfo > createPPC64_SVR4_TargetCodeGenInfo(CodeGenModule &CGM, PPC64_SVR4_ABIKind Kind, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createMIPSTargetCodeGenInfo(CodeGenModule &CGM, bool IsOS32)
std::unique_ptr< TargetCodeGenInfo > createHexagonTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createNVPTXTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createSystemZTargetCodeGenInfo(CodeGenModule &CGM, bool HasVector, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createWinX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters)
std::unique_ptr< TargetCodeGenInfo > createAIXTargetCodeGenInfo(CodeGenModule &CGM, bool Is64Bit)
std::unique_ptr< TargetCodeGenInfo > createAMDGPUTargetCodeGenInfo(CodeGenModule &CGM)
CGObjCRuntime * CreateMacObjCRuntime(CodeGenModule &CGM)
X86AVXABILevel
The AVX ABI level for X86 targets.
std::unique_ptr< TargetCodeGenInfo > createTCETargetCodeGenInfo(CodeGenModule &CGM)
CGObjCRuntime * CreateGNUObjCRuntime(CodeGenModule &CGM)
Creates an instance of an Objective-C runtime class.
std::unique_ptr< TargetCodeGenInfo > createWindowsARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind K)
std::unique_ptr< TargetCodeGenInfo > createAVRTargetCodeGenInfo(CodeGenModule &CGM, unsigned NPR, unsigned NRR)
std::unique_ptr< TargetCodeGenInfo > createDirectXTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createARCTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createDefaultTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind Kind)
std::unique_ptr< TargetCodeGenInfo > createSPIRVTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createWindowsMIPSTargetCodeGenInfo(CodeGenModule &CGM, bool IsOS32)
std::unique_ptr< TargetCodeGenInfo > createSparcV8TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createVETargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createCommonSPIRTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createRISCVTargetCodeGenInfo(CodeGenModule &CGM, unsigned XLen, unsigned FLen, bool EABI)
std::unique_ptr< TargetCodeGenInfo > createWindowsAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind K)
std::unique_ptr< TargetCodeGenInfo > createSparcV9TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters, bool SoftFloatABI)
std::unique_ptr< TargetCodeGenInfo > createLanaiTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createPPC32TargetCodeGenInfo(CodeGenModule &CGM, bool SoftFloatABI)
CGCUDARuntime * CreateNVCUDARuntime(CodeGenModule &CGM)
Creates an instance of a CUDA runtime class.
std::unique_ptr< TargetCodeGenInfo > createLoongArchTargetCodeGenInfo(CodeGenModule &CGM, unsigned GRLen, unsigned FLen)
std::unique_ptr< TargetCodeGenInfo > createPPC64TargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createWinX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel)
std::unique_ptr< TargetCodeGenInfo > createXCoreTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createCSKYTargetCodeGenInfo(CodeGenModule &CGM, unsigned FLen)
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
constexpr bool isInitializedByPipeline(LangAS AS)
bool LT(InterpState &S, CodePtr OpPC)
llvm::PointerUnion< const Decl *, const Expr * > DeclTy
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
CXXCtorType
C++ constructor types.
@ Ctor_Base
Base object ctor.
@ Ctor_Complete
Complete object ctor.
bool isa(CodeGen::Address addr)
GVALinkage
A more specific kind of linkage than enum Linkage.
@ GVA_AvailableExternally
std::string getClangVendor()
Retrieves the Clang vendor tag.
@ ICIS_NoInit
No in-class initializer.
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
@ Asm
Assembly: we accept this only so that we can preprocess it.
@ SD_Thread
Thread storage duration.
@ SD_Static
Static storage duration.
bool isLambdaCallOperator(const CXXMethodDecl *MD)
@ Result
The result type of a method or function.
const FunctionProtoType * T
StringRef languageToString(Language L)
@ Dtor_Base
Base object dtor.
@ Dtor_Complete
Complete object dtor.
LangAS
Defines the address space values used by the address space qualifier of QualType.
@ FirstTargetAddressSpace
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::vfs::FileSystem &VFS, DiagnosticsEngine &Diags)
static const char * getCFBranchLabelSchemeFlagVal(const CFBranchLabelSchemeKind Scheme)
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
U cast(CodeGen::Address addr)
@ None
No keyword precedes the qualified type name.
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
bool isExternallyVisible(Linkage L)
@ EST_None
no exception specification
std::string getClangFullVersion()
Retrieves a string representing the complete clang version, which includes the clang version number,...
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
@ DefaultVisibility
Objects with "default" visibility are seen by the dynamic linker and act like normal objects.
cl::opt< bool > SystemHeadersCoverage
int const char * function
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
std::optional< StringRef > Architecture
llvm::SmallVector< StringRef, 8 > Features
llvm::CallingConv::ID RuntimeCC
llvm::IntegerType * Int64Ty
llvm::PointerType * ConstGlobalsPtrTy
void* in the address space for constant globals
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::IntegerType * CharTy
char
LangAS ASTAllocaAddressSpace
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
unsigned char IntAlignInBytes
llvm::Type * HalfTy
half, bfloat, float, double
unsigned char SizeSizeInBytes
llvm::CallingConv::ID getRuntimeCC() const
llvm::IntegerType * SizeTy
llvm::PointerType * GlobalsInt8PtrTy
llvm::IntegerType * Int32Ty
llvm::IntegerType * IntPtrTy
llvm::IntegerType * IntTy
int
llvm::IntegerType * Int16Ty
unsigned char PointerAlignInBytes
llvm::PointerType * Int8PtrTy
CharUnits getPointerAlign() const
llvm::PointerType * AllocaInt8PtrTy
EvalResult is a struct with detailed info about an evaluated expression.
APValue Val
Val - This is the value the expression can be folded to.
bool hasSideEffects() const
Return true if the evaluated expression has side effects.
Extra information about a function prototype.
static const LangStandard & getLangStandardForKind(Kind K)
uint16_t Part2
...-89ab-...
uint32_t Part1
{01234567-...
uint16_t Part3
...-cdef-...
uint8_t Part4And5[8]
...-0123-456789abcdef}
A library or framework to link against when an entity from this module is used.
PointerAuthSchema InitFiniPointers
The ABI for function addresses in .init_array and .fini_array.
Describes how types, statements, expressions, and declarations should be printed.