79 assert(&Context == &
Other.Context &&
"Module must be in the same Context");
83 ModuleID = std::move(
Other.ModuleID);
84 SourceFileName = std::move(
Other.SourceFileName);
87 GlobalList.splice(GlobalList.begin(),
Other.GlobalList);
90 FunctionList.splice(FunctionList.begin(),
Other.FunctionList);
93 AliasList.splice(AliasList.begin(),
Other.AliasList);
96 IFuncList.splice(IFuncList.begin(),
Other.IFuncList);
99 NamedMDList.splice(NamedMDList.begin(),
Other.NamedMDList);
100 GlobalScopeAsm = std::move(
Other.GlobalScopeAsm);
101 OwnedMemoryBuffer = std::move(
Other.OwnedMemoryBuffer);
102 Materializer = std::move(
Other.Materializer);
103 TargetTriple = std::move(
Other.TargetTriple);
105 CurrentIntrinsicIds = std::move(
Other.CurrentIntrinsicIds);
106 UniquedIntrinsicNames = std::move(
Other.UniquedIntrinsicNames);
107 ModuleFlags = std::move(
Other.ModuleFlags);
116 FunctionList.clear();
121void Module::removeDebugIntrinsicDeclarations() {
122 if (
auto *DeclareIntrinsicFn =
123 Intrinsic::getDeclarationIfExists(
this, Intrinsic::dbg_declare)) {
124 assert((!isMaterialized() || DeclareIntrinsicFn->hasZeroLiveUses()) &&
125 "Debug declare intrinsic should have had uses removed.");
126 DeclareIntrinsicFn->eraseFromParent();
128 if (
auto *ValueIntrinsicFn =
129 Intrinsic::getDeclarationIfExists(
this, Intrinsic::dbg_value)) {
130 assert((!isMaterialized() || ValueIntrinsicFn->hasZeroLiveUses()) &&
131 "Debug value intrinsic should have had uses removed.");
132 ValueIntrinsicFn->eraseFromParent();
134 if (
auto *AssignIntrinsicFn =
135 Intrinsic::getDeclarationIfExists(
this, Intrinsic::dbg_assign)) {
136 assert((!isMaterialized() || AssignIntrinsicFn->hasZeroLiveUses()) &&
137 "Debug assign intrinsic should have had uses removed.");
138 AssignIntrinsicFn->eraseFromParent();
140 if (
auto *LabelntrinsicFn =
141 Intrinsic::getDeclarationIfExists(
this, Intrinsic::dbg_label)) {
142 assert((!isMaterialized() || LabelntrinsicFn->hasZeroLiveUses()) &&
143 "Debug label intrinsic should have had uses removed.");
144 LabelntrinsicFn->eraseFromParent();
148std::unique_ptr<RandomNumberGenerator>
162 Salt += sys::path::filename(getModuleIdentifier());
164 return std::unique_ptr<RandomNumberGenerator>(
172 return cast_or_null<GlobalValue>(getValueSymbolTable().
lookup(
Name));
175unsigned Module::getNumNamedValues()
const {
176 return getValueSymbolTable().size();
189 return Context.getMDKindNames(Result);
193 return Context.getOperandBundleTags(Result);
211 Function *
New = Function::Create(Ty, GlobalVariable::ExternalLinkage,
212 DL.getProgramAddressSpace(),
Name,
this);
213 if (!
New->isIntrinsic())
230 return dyn_cast_or_null<Function>(getNamedValue(
Name));
245 bool AllowLocal)
const {
247 dyn_cast_or_null<GlobalVariable>(getNamedValue(
Name)))
248 if (AllowLocal || !
Result->hasLocalLinkage())
262 GV = CreateGlobalCallback();
263 assert(GV &&
"The CreateGlobalCallback is expected to create a global");
272 return new GlobalVariable(*
this, Ty,
false, GlobalVariable::ExternalLinkage,
285 return dyn_cast_or_null<GlobalAlias>(getNamedValue(
Name));
289 return dyn_cast_or_null<GlobalIFunc>(getNamedValue(
Name));
296 return NamedMDSymTab.lookup(
Name);
306 NMD->setParent(
this);
307 insertNamedMDNode(NMD);
308 if (
Name ==
"llvm.module.flags")
317 NamedMDSymTab.erase(NMD->
getName());
318 if (NMD == ModuleFlags)
319 ModuleFlags =
nullptr;
320 eraseNamedMDNode(NMD);
323bool Module::isValidModFlagBehavior(
Metadata *MD, ModFlagBehavior &MFB) {
324 if (
ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
325 uint64_t Val = Behavior->getLimitedValue();
326 if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
327 MFB =
static_cast<ModFlagBehavior
>(Val);
337 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
338 if (!ModFlags)
return;
342 auto *MFBConstant = mdconst::extract<ConstantInt>(
Flag->getOperand(0));
343 auto MFB =
static_cast<ModFlagBehavior
>(MFBConstant->getLimitedValue());
346 Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
353 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
357 if (Key == cast<MDString>(
Flag->getOperand(1))->getString())
358 return Flag->getOperand(2);
366NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
369 return getOrInsertNamedMetadata(
"llvm.module.flags");
375void Module::addModuleFlag(ModFlagBehavior Behavior,
StringRef Key,
377 Type *Int32Ty = Type::getInt32Ty(Context);
379 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
380 MDString::get(Context, Key), Val};
381 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
383void Module::addModuleFlag(ModFlagBehavior Behavior,
StringRef Key,
385 addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
387void Module::addModuleFlag(ModFlagBehavior Behavior,
StringRef Key,
389 Type *Int32Ty = Type::getInt32Ty(Context);
390 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
394 "Invalid number of operands for module flag!");
395 assert(mdconst::hasa<ConstantInt>(
Node->getOperand(0)) &&
396 isa<MDString>(
Node->getOperand(1)) &&
397 "Invalid operand types for module flag!");
398 getOrInsertModuleFlagsMetadata()->addOperand(
Node);
401void Module::setModuleFlag(ModFlagBehavior Behavior,
StringRef Key,
403 NamedMDNode *ModFlags = getOrInsertModuleFlagsMetadata();
406 if (cast<MDString>(
Flag->getOperand(1))->getString() == Key) {
407 Flag->replaceOperandWith(2, Val);
411 addModuleFlag(Behavior, Key, Val);
413void Module::setModuleFlag(ModFlagBehavior Behavior,
StringRef Key,
415 setModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
417void Module::setModuleFlag(ModFlagBehavior Behavior,
StringRef Key,
419 Type *Int32Ty = Type::getInt32Ty(Context);
420 setModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
427DICompileUnit *Module::debug_compile_units_iterator::operator*()
const {
428 return cast<DICompileUnit>(CUs->getOperand(
Idx));
430DICompileUnit *Module::debug_compile_units_iterator::operator->()
const {
431 return cast<DICompileUnit>(CUs->getOperand(
Idx));
434void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
435 while (CUs && (Idx < CUs->getNumOperands()) &&
436 ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
444Module::global_objects()
const {
452Module::global_values()
const {
453 return concat<const GlobalValue>(
functions(),
globals(), aliases(), ifuncs());
461 "Module already has a GVMaterializer. Call materializeAll"
462 " to clear it out before setting another one.");
463 Materializer.reset(GVM);
468 return Error::success();
470 return Materializer->materialize(GV);
473Error Module::materializeAll() {
475 return Error::success();
476 std::unique_ptr<GVMaterializer>
M = std::move(Materializer);
477 return M->materializeModule();
480Error Module::materializeMetadata() {
482 return Error::success();
483 return Materializer->materializeMetadata();
490std::vector<StructType *> Module::getIdentifiedStructTypes()
const {
495 return Materializer->getIdentifiedStructTypes();
497 std::vector<StructType *>
Ret;
499 SrcStructTypes.
run(*
this,
true);
500 Ret.assign(SrcStructTypes.
begin(), SrcStructTypes.
end());
506 auto Encode = [&BaseName](
unsigned Suffix) {
507 return (
Twine(BaseName) +
"." +
Twine(Suffix)).str();
512 auto UinItInserted = UniquedIntrinsicNames.insert({{
Id, Proto}, 0});
513 if (!UinItInserted.second)
514 return Encode(UinItInserted.first->second);
521 auto NiidItInserted = CurrentIntrinsicIds.insert({BaseName, 0});
522 unsigned Count = NiidItInserted.first->second;
528 NewName = Encode(Count);
532 UniquedIntrinsicNames[{
Id, Proto}] = Count;
537 FunctionType *FT = dyn_cast<FunctionType>(
F->getValueType());
538 auto UinItInserted = UniquedIntrinsicNames.insert({{
Id, FT}, Count});
542 UinItInserted.first->second = Count;
549 NiidItInserted.first->second = Count + 1;
561void Module::dropAllReferences() {
563 F.dropAllReferences();
569 GA.dropAllReferences();
572 GIF.dropAllReferences();
575unsigned Module::getNumberRegisterParameters()
const {
577 cast_or_null<ConstantAsMetadata>(getModuleFlag(
"NumRegisterParameters"));
580 return cast<ConstantInt>(Val->getValue())->getZExtValue();
583unsigned Module::getDwarfVersion()
const {
584 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag(
"Dwarf Version"));
587 return cast<ConstantInt>(Val->getValue())->getZExtValue();
590bool Module::isDwarf64()
const {
591 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag(
"DWARF64"));
592 return Val && cast<ConstantInt>(Val->getValue())->isOne();
595unsigned Module::getCodeViewFlag()
const {
596 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag(
"CodeView"));
599 return cast<ConstantInt>(Val->getValue())->getZExtValue();
602unsigned Module::getInstructionCount()
const {
603 unsigned NumInstrs = 0;
605 NumInstrs +=
F.getInstructionCount();
610 auto &
Entry = *ComdatSymTab.insert(std::make_pair(
Name,
Comdat())).first;
612 return &
Entry.second;
616 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag(
"PIC Level"));
619 return PICLevel::NotPIC;
622 cast<ConstantInt>(Val->getValue())->getZExtValue());
628 addModuleFlag(ModFlagBehavior::Min,
"PIC Level", PL);
632 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag(
"PIE Level"));
635 return PIELevel::Default;
638 cast<ConstantInt>(Val->getValue())->getZExtValue());
642 addModuleFlag(ModFlagBehavior::Max,
"PIE Level", PL);
645std::optional<CodeModel::Model> Module::getCodeModel()
const {
646 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag(
"Code Model"));
652 cast<ConstantInt>(Val->getValue())->getZExtValue());
660 addModuleFlag(ModFlagBehavior::Error,
"Code Model", CL);
663std::optional<uint64_t> Module::getLargeDataThreshold()
const {
665 cast_or_null<ConstantAsMetadata>(getModuleFlag(
"Large Data Threshold"));
670 return cast<ConstantInt>(Val->getValue())->getZExtValue();
673void Module::setLargeDataThreshold(
uint64_t Threshold) {
676 addModuleFlag(ModFlagBehavior::Error,
"Large Data Threshold",
677 ConstantInt::get(Type::getInt64Ty(Context), Threshold));
681 if (Kind == ProfileSummary::PSK_CSInstr)
682 setModuleFlag(ModFlagBehavior::Error,
"CSProfileSummary", M);
684 setModuleFlag(ModFlagBehavior::Error,
"ProfileSummary", M);
687Metadata *Module::getProfileSummary(
bool IsCS)
const {
688 return (IsCS ? getModuleFlag(
"CSProfileSummary")
689 : getModuleFlag(
"ProfileSummary"));
692bool Module::getSemanticInterposition()
const {
693 Metadata *MF = getModuleFlag(
"SemanticInterposition");
695 auto *Val = cast_or_null<ConstantAsMetadata>(MF);
699 return cast<ConstantInt>(Val->getValue())->getZExtValue();
702void Module::setSemanticInterposition(
bool SI) {
703 addModuleFlag(ModFlagBehavior::Error,
"SemanticInterposition",
SI);
706void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
707 OwnedMemoryBuffer = std::move(MB);
710bool Module::getRtLibUseGOT()
const {
711 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag(
"RtLibUseGOT"));
712 return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
715void Module::setRtLibUseGOT() {
716 addModuleFlag(ModFlagBehavior::Max,
"RtLibUseGOT", 1);
719bool Module::getDirectAccessExternalData()
const {
720 auto *Val = cast_or_null<ConstantAsMetadata>(
721 getModuleFlag(
"direct-access-external-data"));
723 return cast<ConstantInt>(Val->getValue())->getZExtValue() > 0;
724 return getPICLevel() == PICLevel::NotPIC;
727void Module::setDirectAccessExternalData(
bool Value) {
728 addModuleFlag(ModFlagBehavior::Max,
"direct-access-external-data",
Value);
732 if (
auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag(
"uwtable")))
733 return UWTableKind(cast<ConstantInt>(Val->getValue())->getZExtValue());
734 return UWTableKind::None;
738 addModuleFlag(ModFlagBehavior::Max,
"uwtable",
uint32_t(Kind));
742 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag(
"frame-pointer"));
744 Val ? cast<ConstantInt>(Val->getValue())->getZExtValue() : 0);
748 addModuleFlag(ModFlagBehavior::Max,
"frame-pointer",
static_cast<int>(Kind));
751StringRef Module::getStackProtectorGuard()
const {
752 Metadata *MD = getModuleFlag(
"stack-protector-guard");
753 if (
auto *MDS = dyn_cast_or_null<MDString>(MD))
754 return MDS->getString();
758void Module::setStackProtectorGuard(
StringRef Kind) {
759 MDString *
ID = MDString::get(getContext(), Kind);
760 addModuleFlag(ModFlagBehavior::Error,
"stack-protector-guard",
ID);
763StringRef Module::getStackProtectorGuardReg()
const {
764 Metadata *MD = getModuleFlag(
"stack-protector-guard-reg");
765 if (
auto *MDS = dyn_cast_or_null<MDString>(MD))
766 return MDS->getString();
772 addModuleFlag(ModFlagBehavior::Error,
"stack-protector-guard-reg",
ID);
775StringRef Module::getStackProtectorGuardSymbol()
const {
776 Metadata *MD = getModuleFlag(
"stack-protector-guard-symbol");
777 if (
auto *MDS = dyn_cast_or_null<MDString>(MD))
778 return MDS->getString();
782void Module::setStackProtectorGuardSymbol(
StringRef Symbol) {
783 MDString *
ID = MDString::get(getContext(), Symbol);
784 addModuleFlag(ModFlagBehavior::Error,
"stack-protector-guard-symbol",
ID);
787int Module::getStackProtectorGuardOffset()
const {
788 Metadata *MD = getModuleFlag(
"stack-protector-guard-offset");
789 if (
auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
790 return CI->getSExtValue();
794void Module::setStackProtectorGuardOffset(
int Offset) {
795 addModuleFlag(ModFlagBehavior::Error,
"stack-protector-guard-offset",
Offset);
798unsigned Module::getOverrideStackAlignment()
const {
799 Metadata *MD = getModuleFlag(
"override-stack-alignment");
800 if (
auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
801 return CI->getZExtValue();
805unsigned Module::getMaxTLSAlignment()
const {
806 Metadata *MD = getModuleFlag(
"MaxTLSAlign");
807 if (
auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
808 return CI->getZExtValue();
812void Module::setOverrideStackAlignment(
unsigned Align) {
813 addModuleFlag(ModFlagBehavior::Error,
"override-stack-alignment",
Align);
818 Entries.push_back(
V.getMajor());
819 if (
auto Minor =
V.getMinor()) {
820 Entries.push_back(*Minor);
821 if (
auto Subminor =
V.getSubminor())
822 Entries.push_back(*Subminor);
826 M.addModuleFlag(Module::ModFlagBehavior::Warning,
Name,
827 ConstantDataArray::get(
M.getContext(), Entries));
835 auto *CM = dyn_cast_or_null<ConstantAsMetadata>(MD);
838 auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue());
841 auto getVersionComponent = [&](
unsigned Index) -> std::optional<unsigned> {
842 if (
Index >= Arr->getNumElements())
844 return (
unsigned)Arr->getElementAsInteger(
Index);
846 auto Major = getVersionComponent(0);
850 if (
auto Minor = getVersionComponent(1)) {
852 if (
auto Subminor = getVersionComponent(2)) {
865 const char *
Name = CompilerUsed ?
"llvm.compiler.used" :
"llvm.used";
879 if (
auto *SummaryMD = getProfileSummary(
false)) {
881 ProfileSummary::getFromMD(SummaryMD));
890 double Ratio = (double)BlockCount / NumCounts;
893 ProfileSummary::PSK_Sample);
898StringRef Module::getDarwinTargetVariantTriple()
const {
899 if (
const auto *MD = getModuleFlag(
"darwin.target_variant.triple"))
900 return cast<MDString>(MD)->getString();
904void Module::setDarwinTargetVariantTriple(
StringRef T) {
905 addModuleFlag(ModFlagBehavior::Warning,
"darwin.target_variant.triple",
906 MDString::get(getContext(),
T));
909VersionTuple Module::getDarwinTargetVariantSDKVersion()
const {
910 return getSDKVersionMD(getModuleFlag(
"darwin.target_variant.SDK Version"));
913void Module::setDarwinTargetVariantSDKVersion(
VersionTuple Version) {
919 if (
auto *TargetABIMD =
920 dyn_cast_or_null<MDString>(getModuleFlag(
"target-abi")))
921 TargetABI = TargetABIMD->getString();
926 Metadata *MD = getModuleFlag(
"winx64-eh-unwindv2");
927 if (
auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
929 return WinX64EHUnwindV2Mode::Disabled;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
Lower uses of LDS variables from non kernel functions
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
#define LLVM_EXPORT_TEMPLATE
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
std::optional< std::vector< StOtherPiece > > Other
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
Module.h This file contains the declarations for the Module class.
static bool lookup(const GsymReader &GR, DataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
static Constant * getOrInsertGlobal(Module &M, StringRef Name, Type *Ty)
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
StandardInstrumentations SI(Mod->getContext(), Debug, VerifyEach)
static VersionTuple getSDKVersionMD(Metadata *MD)
static void addSDKVersionMD(const VersionTuple &V, Module &M, StringRef Name)
This file defines the SmallString class.
This file defines the SmallVector class.
Defines the llvm::VersionTuple class, which represents a version in the form major[....
ConstantArray - Constant Array Declarations.
This is the shared class of boolean and integer constants.
This is an important base class in LLVM.
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Lightweight error class with error context and mandatory checking.
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
This is an important class for using LLVM in a threaded context.
Class to hold module path string table and global value map, and encapsulate methods for operating on...
A Module instance is used to store all the information related to an LLVM module.
LLVM_ABI StringRef getName() const
iterator_range< op_iterator > operands()
void setPartialProfileRatio(double R)
LLVM_ABI Metadata * getMD(LLVMContext &Context, bool AddPartialField=true, bool AddPartialProfileRatioField=true)
Return summary information as metadata.
uint32_t getNumCounts() const
bool isPartialProfile() const
A random number generator.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
TypeFinder - Walk over a module, identifying all of the types that are used by the module.
void run(const Module &M, bool onlyNamed)
The instances of the Type class are immutable: once they are created, they are never changed.
void dropAllReferences()
Drop all references to operands.
This class provides a symbol table of name/value pairs.
LLVM Value Representation.
Represents a version number in the form major[.minor[.subminor[.build]]].
An efficient, type-erasing, non-owning reference to a callable.
A range adaptor for a pair of iterators.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
Implement std::hash so that hash_code can be used in STL containers.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Description of the encoding of one expression Op.