41 if (!ExportGV.hasLocalLinkage())
44 auto Name = ExportGV.getName();
46 const bool MustPromote = PromoteExtra && PromoteExtra->count(&ExportGV);
61 if (
const auto *
C = ExportGV.getComdat())
62 if (
C->getName() == Name)
67 Aliasee = GA->getAliasee();
79 ExportGV.getValueType(), ExportGV.getAddressSpace(),
84 ExportGV.replaceUsesWithIf(
86 PromoteExtra->remove(&ExportGV);
87 PromoteExtra->insert(ExternalAlias);
97 if (!RenamedComdats.
empty())
99 if (
auto *
C = GO.getComdat()) {
100 auto Replacement = RenamedComdats.
find(
C);
101 if (Replacement != RenamedComdats.
end())
102 GO.setComdat(Replacement->second);
113 auto ExternalizeTypeId = [&](
CallInst *CI,
unsigned ArgNo) {
118 Metadata *&GlobalMD = LocalToGlobal[MD];
120 std::string NewName =
121 (
Twine(LocalToGlobal.
size()) +
"." + ModuleId).str();
132 for (
const Use &U : TypeTestFunc->
uses()) {
134 ExternalizeTypeId(CI, 1);
140 for (
const Use &U : PublicTypeTestFunc->
uses()) {
142 ExternalizeTypeId(CI, 1);
148 for (
const Use &U : TypeCheckedLoadFunc->
uses()) {
150 ExternalizeTypeId(CI, 2);
155 &M, Intrinsic::type_checked_load_relative)) {
156 for (
const Use &U : TypeCheckedLoadRelativeFunc->
uses()) {
158 ExternalizeTypeId(CI, 2);
164 GO.getMetadata(LLVMContext::MD_type, MDs);
166 GO.eraseMetadata(LLVMContext::MD_type);
167 for (
auto *MD : MDs) {
168 auto I = LocalToGlobal.
find(MD->getOperand(1));
169 if (
I == LocalToGlobal.
end()) {
170 GO.addMetadata(LLVMContext::MD_type, *MD);
174 LLVMContext::MD_type,
175 *
MDNode::get(M.getContext(), {MD->getOperand(0), I->second}));
179 GO.getMetadata(LLVMContext::MD_callgraph, CGMDs);
181 GO.eraseMetadata(LLVMContext::MD_callgraph);
182 for (
auto *MD : CGMDs) {
183 if (MD->getNumOperands() == 1) {
184 auto I = LocalToGlobal.
find(MD->getOperand(0));
185 if (
I == LocalToGlobal.
end()) {
186 GO.addMetadata(LLVMContext::MD_callgraph, *MD);
189 GO.addMetadata(LLVMContext::MD_callgraph,
198void simplifyExternals(
Module &M) {
203 if (
F.isDeclaration() &&
F.use_empty()) {
208 if (!
F.isDeclaration() ||
F.getFunctionType() == EmptyFT ||
210 F.getName().starts_with(
"llvm."))
214 F.getAddressSpace(),
"", &M);
218 AttributeList::FunctionIndex,
219 F.getAttributes().getFnAttrs()));
222 F.getMetadata(LLVMContext::MD_guid));
223 F.replaceAllUsesWith(NewF);
231 assert(
I.getResolverFunction() &&
"ifunc misses its resolver function");
235 if (GV.isDeclaration() && GV.use_empty()) {
236 GV.eraseFromParent();
245 std::vector<GlobalValue *>
V;
247 if (!ShouldKeepDefinition(&GV))
252 GV->eraseFromParent();
266static void cloneUsedGlobalVariables(
const Module &SrcM,
Module &DestM,
272 for (
auto *
V : Used) {
274 if (GV && !GV->isDeclaration())
285static bool enableUnifiedLTO(
Module &M) {
286 bool UnifiedLTO =
false;
289 UnifiedLTO = MD->getZExtValue();
294bool mustEmitToMergedModule(
const GlobalValue *GV) {
297 return GV->
getName() ==
"__cfi_check";
303void splitAndWriteThinLTOBitcode(
307 const bool ShouldPreserveUseListOrder) {
309 if (ModuleId.empty()) {
310 assert(!enableUnifiedLTO(M));
328 promoteTypeIds(M, ModuleId);
350 forEachVirtualFunction(GV.getInitializer(), [&](
Function *
F) {
351 auto *RT = dyn_cast<IntegerType>(F->getReturnType());
352 if (!RT || RT->getBitWidth() > 64 || F->arg_empty() ||
353 !F->arg_begin()->use_empty())
355 for (auto &Arg : drop_begin(F->args())) {
356 auto *ArgT = dyn_cast<IntegerType>(Arg.getType());
357 if (!ArgT || ArgT->getBitWidth() > 64)
360 if (!
F->isDeclaration() &&
362 .doesNotAccessMemory())
368 std::unique_ptr<Module> MergedM(
371 if (MergedMComdats.
count(
C))
373 if (mustEmitToMergedModule(GV))
376 return EligibleVirtualFns.
count(
F);
383 MergedM->removeModuleInlineAsm();
387 cloneUsedGlobalVariables(M, *MergedM,
false);
388 cloneUsedGlobalVariables(M, *MergedM,
true);
391 if (!
F.isDeclaration() && !mustEmitToMergedModule(&
F)) {
396 F.setComdat(
nullptr);
408 if (MergedMComdats.
count(
C))
410 if (mustEmitToMergedModule(GV))
419 promoteInternals(*MergedM, M, ModuleId,
nullptr);
420 promoteInternals(M, *MergedM, ModuleId, &CfiFunctions);
428 simplifyExternals(*MergedM);
446 W.writeModule(M, ShouldPreserveUseListOrder, &Index,
448 W.writeModule(*MergedM, ShouldPreserveUseListOrder, &MergedMIndex);
460 W2.writeThinLinkBitcode(M, Index, ModHash);
461 W2.writeModule(*MergedM,
false,
465 *ThinLinkOS << Buffer;
470bool enableSplitLTOUnit(
Module &M) {
471 bool EnableSplitLTOUnit =
false;
473 M.getModuleFlag(
"EnableSplitLTOUnit")))
474 EnableSplitLTOUnit = MD->getZExtValue();
475 return EnableSplitLTOUnit;
479bool requiresSplit(
Module &M) {
480 for (
auto &GO : M.global_objects()) {
481 if (GO.hasMetadata(LLVMContext::MD_type))
483 if (mustEmitToMergedModule(&GO))
489bool writeThinLTOBitcode(
494 std::unique_ptr<ModuleSummaryIndex> NewIndex =
nullptr;
497 if (requiresSplit(M)) {
498 if (enableSplitLTOUnit(M)) {
499 splitAndWriteThinLTOBitcode(OS, ThinLinkOS, AARGetter, BFIGetter, M,
500 ShouldPreserveUseListOrder);
505 if (!ModuleId.empty()) {
506 promoteTypeIds(M, ModuleId);
516 NewIndex = std::make_unique<ModuleSummaryIndex>(
518 Index = NewIndex.get();
533 if (ThinLinkOS && Index)
545 bool Changed = writeThinLTOBitcode(
554 ShouldPreserveUseListOrder);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This is the interface for LLVM's primary stateless and local alias analysis.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Provides passes for computing function attributes based on interprocedural analyses.
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This is the interface to build a ModuleSummaryIndex for a module.
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
FunctionAnalysisManager FAM
A manager for alias analyses.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Value * getArgOperand(unsigned i) const
void setArgOperand(unsigned i, Value *v)
This class represents a function call, abstracting a target machine's calling convention.
This is an important base class in LLVM.
LLVM_ABI void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Implements a dense probed hash-table based set.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
LLVM_ABI const Comdat * getComdat() const
LLVM_ABI const GlobalObject * getAliaseeObject() const
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
@ HiddenVisibility
The GV is hidden.
void setVisibility(VisibilityTypes V)
LLVM_ABI void reassignGUID()
Recompute and assign a GUID to this value, replacing the existing GUID.
@ ExternalLinkage
Externally visible function.
@ AvailableExternallyLinkage
Available for inspection, not emission.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Analysis pass to provide the ModuleSummaryIndex object.
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static std::string getGlobalNameForLocal(StringRef Name, ModuleHash ModHash)
Convenience method for creating a promoted global name for the given value name of a local,...
A Module instance is used to store all the information related to an LLVM module.
@ Error
Emits an error if two values disagree, otherwise the resulting value is that of the operands.
iterator_range< global_object_iterator > global_objects()
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type.
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
iterator_range< global_value_iterator > global_values()
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Analysis providing profile information.
A vector that has set insertion semantics.
ArrayRef< value_type > getArrayRef() const
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
A Use represents the edge between a Value definition and its users.
LLVM Value Representation.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
iterator_range< use_iterator > uses()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
std::pair< iterator, bool > insert(const ValueT &V)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
LLVM_ABI void createCfiMetadata(Module &DestM, const Module &SrcM, ArrayRef< GlobalValue * > CfiFunctions, ProfileSummaryInfo &PSI, function_ref< const BlockFrequencyInfo &(Function &)> BFIGetter)
Creates cfi.functions, aliases, and symvers named metadata in DestM for CFI functions in CfiFunctions...
LLVM_ABI bool hasTypeMetadata(const GlobalObject &GO)
Returns whether a global or its associated global has attached type metadata.
LLVM_ABI SetVector< GlobalValue * > findCfiFunctions(Module &M)
Finds all functions and aliases in M that may need CFI jump table entries.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI MemoryEffects computeFunctionBodyMemoryAccess(Function &F, AAResults &AAR)
Returns the memory access properties of this copy of the function.
LLVM_ABI void WriteBitcodeToFile(const Module &M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the specified raw output stream.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI void writeThinLinkBitcodeToFile(const Module &M, raw_ostream &Out, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the given raw output...
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
LLVM_ABI bool convertToDeclaration(GlobalValue &GV)
Converts value GV to declaration, or replaces with a declaration if it is an alias.
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
LLVM_ABI ModuleSummaryIndex buildModuleSummaryIndex(const Module &M, std::function< BlockFrequencyInfo *(const Function &F)> GetBFICallback, ProfileSummaryInfo *PSI, std::function< const StackSafetyInfo *(const Function &F)> GetSSICallback=[](const Function &F) -> const StackSafetyInfo *{ return nullptr;})
Direct function to compute a ModuleSummaryIndex from a given module.
auto dyn_cast_or_null(const Y &Val)
LLVM_ABI std::string getUniqueModuleId(Module *M)
Produce a unique identifier for this module by taking the MD5 sum of the names of the module's strong...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
DWARFExpression::Operation Op
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI std::unique_ptr< Module > CloneModule(const Module &M)
Return an exact copy of the specified module.
LLVM_ABI void appendToUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.used list.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
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 ...