41 if (!ExportGV.hasLocalLinkage())
44 auto Name = ExportGV.getName();
46 if (!PromoteExtra.
count(&ExportGV)) {
57 std::string NewName = (
Name + ModuleId).str();
59 if (
const auto *
C = ExportGV.getComdat())
63 ExportGV.setName(NewName);
73 if (!RenamedComdats.
empty())
75 if (
auto *
C = GO.getComdat()) {
76 auto Replacement = RenamedComdats.
find(
C);
77 if (Replacement != RenamedComdats.
end())
78 GO.setComdat(Replacement->second);
89 auto ExternalizeTypeId = [&](
CallInst *CI,
unsigned ArgNo) {
91 cast<MetadataAsValue>(CI->
getArgOperand(ArgNo))->getMetadata();
93 if (isa<MDNode>(MD) && cast<MDNode>(MD)->isDistinct()) {
94 Metadata *&GlobalMD = LocalToGlobal[MD];
96 std::string NewName = (
Twine(LocalToGlobal.
size()) + ModuleId).str();
107 for (
const Use &U : TypeTestFunc->
uses()) {
108 auto CI = cast<CallInst>(U.getUser());
109 ExternalizeTypeId(CI, 1);
115 for (
const Use &U : TypeCheckedLoadFunc->
uses()) {
116 auto CI = cast<CallInst>(U.getUser());
117 ExternalizeTypeId(CI, 2);
123 GO.getMetadata(LLVMContext::MD_type, MDs);
125 GO.eraseMetadata(LLVMContext::MD_type);
126 for (
auto MD : MDs) {
127 auto I = LocalToGlobal.
find(MD->getOperand(1));
128 if (
I == LocalToGlobal.
end()) {
129 GO.addMetadata(LLVMContext::MD_type, *MD);
133 LLVMContext::MD_type,
141 void simplifyExternals(
Module &M) {
178 std::vector<GlobalValue *> V;
180 if (!ShouldKeepDefinition(&GV))
189 if (
auto *F = dyn_cast<Function>(C))
191 if (isa<GlobalValue>(C))
194 forEachVirtualFunction(cast<Constant>(
Op), Fn);
200 void splitAndWriteThinLTOBitcode(
204 if (ModuleId.empty()) {
221 promoteTypeIds(M, ModuleId);
230 if (
MDNode *MD = GO->getMetadata(LLVMContext::MD_associated))
231 if (
auto *AssocVM = dyn_cast_or_null<ValueAsMetadata>(MD->getOperand(0)))
232 if (
auto *AssocGO = dyn_cast<GlobalObject>(AssocVM->getValue()))
233 if (AssocGO->hasMetadata(LLVMContext::MD_type))
235 return GO->hasMetadata(LLVMContext::MD_type);
255 if (HasTypeMetadata(&GV)) {
260 if (!RT || RT->getBitWidth() > 64 || F->
arg_empty() ||
265 if (!ArgT || ArgT->getBitWidth() > 64)
270 EligibleVirtualFns.
insert(F);
275 std::unique_ptr<Module> MergedM(
278 if (MergedMComdats.
count(C))
280 if (
auto *F = dyn_cast<Function>(GV))
281 return EligibleVirtualFns.
count(F);
282 if (
auto *GVar = dyn_cast_or_null<GlobalVariable>(GV->
getBaseObject()))
283 return HasTypeMetadata(GVar);
287 MergedM->setModuleInlineAsm(
"");
306 if (
auto *GVar = dyn_cast_or_null<GlobalVariable>(GV->
getBaseObject()))
307 if (HasTypeMetadata(GVar))
310 if (MergedMComdats.
count(C))
315 promoteInternals(*MergedM, M, ModuleId, CfiFunctions);
316 promoteInternals(M, *MergedM, ModuleId, CfiFunctions);
318 auto &Ctx = MergedM->getContext();
320 for (
auto V : CfiFunctions) {
336 for (
auto Type : Types)
341 if(!CfiFunctionMDs.
empty()) {
342 NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata(
"cfi.functions");
343 for (
auto MD : CfiFunctionMDs)
348 for (
auto &A : M.aliases()) {
349 if (!isa<Function>(
A.getAliasee()))
352 auto *F = cast<Function>(
A.getAliasee());
366 if (!FunctionAliases.
empty()) {
367 NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata(
"aliases");
368 for (
auto MD : FunctionAliases)
382 if (!Symvers.
empty()) {
383 NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata(
"symvers");
384 for (
auto MD : Symvers)
388 simplifyExternals(*MergedM);
407 W.writeModule(M,
false, &Index,
409 W.writeModule(*MergedM,
false, &MergedMIndex);
421 W2.writeThinLinkBitcode(M, Index, ModHash);
422 W2.writeModule(*MergedM,
false,
426 *ThinLinkOS << Buffer;
431 bool enableSplitLTOUnit(
Module &M) {
432 bool EnableSplitLTOUnit =
false;
433 if (
auto *MD = mdconst::extract_or_null<ConstantInt>(
435 EnableSplitLTOUnit = MD->getZExtValue();
436 return EnableSplitLTOUnit;
440 bool hasTypeMetadata(
Module &M) {
442 if (GO.hasMetadata(LLVMContext::MD_type))
451 std::unique_ptr<ModuleSummaryIndex> NewIndex =
nullptr;
454 if (hasTypeMetadata(M)) {
455 if (enableSplitLTOUnit(M))
456 return splitAndWriteThinLTOBitcode(OS, ThinLinkOS, AARGetter, M);
459 if (!ModuleId.empty()) {
460 promoteTypeIds(M, ModuleId);
470 NewIndex = std::make_unique<ModuleSummaryIndex>(
472 Index = NewIndex.get();
487 if (ThinLinkOS && Index)
491 class WriteThinLTOBitcode :
public ModulePass {
499 WriteThinLTOBitcode() :
ModulePass(ID), OS(
dbgs()), ThinLinkOS(nullptr) {
504 :
ModulePass(ID), OS(o), ThinLinkOS(ThinLinkOS) {
508 StringRef getPassName()
const override {
return "ThinLTO Bitcode Writer"; }
510 bool runOnModule(
Module &M)
override {
512 &(getAnalysis<ModuleSummaryIndexWrapperPass>().getIndex());
527 "Write ThinLTO Bitcode",
false,
true)
536 return new WriteThinLTOBitcode(Str, ThinLinkOS);
543 writeThinLTOBitcode(OS, ThinLinkOS,
void setVisibility(VisibilityTypes V)
const Function & getFunction() const
ModulePass * createWriteThinLTOBitcodePass(raw_ostream &Str, raw_ostream *ThinLinkOS=nullptr)
Write ThinLTO-ready bitcode to Str.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
iterator_range< use_iterator > uses()
bool hasLocalLinkage() const
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
This class represents lattice values for constants.
A Module instance is used to store all the information related to an LLVM module. ...
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
static MDString * get(LLVMContext &Context, StringRef Str)
This is the interface to build a ModuleSummaryIndex for a module.
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Implements a dense probed hash-table based set.
Available for inspection, not emission.
void push_back(const T &Elt)
Analysis providing profile information.
void addOperand(MDNode *M)
This class represents a function call, abstracting a target machine's calling convention.
An immutable pass that tracks lazily created AssumptionCache objects.
bool convertToDeclaration(GlobalValue &GV)
Converts value GV to declaration, or replaces with a declaration if it is an alias.
An efficient, type-erasing, non-owning reference to a callable.
CfiFunctionLinkage
The type of CFI jumptable needed for a function.
Externally visible function.
void setArgOperand(unsigned i, Value *v)
block Block Frequency true
bool hasExternalWeakLinkage() const
MemoryAccessKind computeFunctionBodyMemoryAccess(Function &F, AAResults &AAR)
Returns the memory access properties of this copy of the function.
Analysis pass to provide the ModuleSummaryIndex object.
ModuleSummaryIndex buildModuleSummaryIndex(const Module &M, std::function< BlockFrequencyInfo *(const Function &F)> GetBFICallback, ProfileSummaryInfo *PSI)
Direct function to compute a ModuleSummaryIndex from a given module.
Value * getArgOperand(unsigned i) const
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVMContext & getContext() const
Get the global data context.
A Use represents the edge between a Value definition and its users.
This class is a functor to be used in legacy module or SCC passes for computing AA results for a func...
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
void setName(const Twine &Name)
Change the name of the value.
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...
global_iterator global_begin()
Class to represent function types.
bool insert(const value_type &X)
Insert a new element into the SetVector.
void setComdat(Comdat *C)
bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type. ...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void takeName(Value *V)
Transfer the name from V to this value.
Class to hold module path string table and global value map, and encapsulate methods for operating on...
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
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)
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
std::unique_ptr< Module > CloneModule(const Module &M)
Return an exact copy of the specified module.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Type * getReturnType() const
Returns the type of the ret val.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
static void CollectAsmSymvers(const Module &M, function_ref< void(StringRef, StringRef)> AsmSymver)
Parse inline ASM and collect the symvers directives that are defined in the current module...
Emits an error if two values disagree, otherwise the resulting value is that of the operands...
A set of analyses that are preserved following a run of a transformation pass.
VisibilityTypes getVisibility() const
write thinlto Write ThinLTO Bitcode
The instances of the Type class are immutable: once they are created, they are never changed...
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
A manager for alias analyses.
std::pair< iterator, bool > insert(const ValueT &V)
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
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.
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val)
Add a module-level flag to the module-level flags metadata.
unsigned getAddressSpace() const
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Class to represent integer types.
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...
static void write(bool isBE, void *P, T V)
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&... Args)
global_iterator global_end()
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void initializeWriteThinLTOBitcodePass(PassRegistry &)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
void setLinkage(LinkageTypes LT)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
const Comdat * getComdat() const
void setPreservesAll()
Set by analyses that do not transform their input at all.
const Comdat * getComdat() const
void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
Linkage
Describes symbol linkage.
LLVM_NODISCARD bool empty() const
StringRef getName() const
Return a constant reference to the value's name.
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
bool isJumpTableCanonical(Function *F)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Provides passes for computing function attributes based on interprocedural analyses.
LLVM_NODISCARD bool empty() const
const GlobalObject * getBaseObject() const
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
bool hasAddressTaken(const User **=nullptr) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
LLVM Value Representation.
A vector that has set insertion semantics.
This class implements an extremely fast bulk output stream that can only output to a stream...
iterator_range< global_iterator > globals()
iterator_range< global_object_iterator > global_objects()
StringRef - Represent a constant reference to a string, i.e.
This is the interface for LLVM's primary stateless and local alias analysis.
A container for analyses that lazily runs them and caches their results.
This header defines various interfaces for pass management in LLVM.
INITIALIZE_PASS_BEGIN(WriteThinLTOBitcode, "write-thinlto-bitcode", "Write ThinLTO Bitcode", false, true) INITIALIZE_PASS_END(WriteThinLTOBitcode
static IntegerType * getInt8Ty(LLVMContext &C)
PointerType * getType() const
Global values are always pointers.
Legacy wrapper pass to provide the ModuleSummaryIndex object.
iterator_range< global_value_iterator > global_values()
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...