32 std::unique_ptr<Module> SrcM;
45 std::function<void(Module &, const StringSet<> &)> InternalizeCallback;
56 bool shouldLinkFromSource(
bool &LinkFromSrc,
const GlobalValue &Dest,
60 bool emitError(
const Twine &Message) {
67 bool computeResultingSelectionKind(
StringRef ComdatName,
72 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
110 ModuleLinker(
IRMover &Mover, std::unique_ptr<Module> SrcM,
unsigned Flags,
112 InternalizeCallback = {})
113 : Mover(Mover), SrcM(std::move(SrcM)), Flags(Flags),
114 InternalizeCallback(std::move(InternalizeCallback)) {}
134 if (
const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
138 return emitError(
"Linking COMDATs named '" + ComdatName +
139 "': COMDAT key involves incomputable alias size.");
142 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
145 "Linking COMDATs named '" + ComdatName +
146 "': GlobalVariable required for data dependent selection!");
151 bool ModuleLinker::computeResultingSelectionKind(
StringRef ComdatName,
160 Dst == Comdat::SelectionKind::Largest;
162 Src == Comdat::SelectionKind::Largest;
163 if (DstAnyOrLargest && SrcAnyOrLargest) {
164 if (Dst == Comdat::SelectionKind::Largest ||
165 Src == Comdat::SelectionKind::Largest)
166 Result = Comdat::SelectionKind::Largest;
169 }
else if (Src == Dst) {
172 return emitError(
"Linking COMDATs named '" + ComdatName +
173 "': invalid selection kinds!");
181 case Comdat::SelectionKind::NoDuplicates:
182 return emitError(
"Linking COMDATs named '" + ComdatName +
183 "': noduplicates has been violated!");
184 case Comdat::SelectionKind::ExactMatch:
185 case Comdat::SelectionKind::Largest:
186 case Comdat::SelectionKind::SameSize: {
189 if (getComdatLeader(DstM, ComdatName, DstGV) ||
190 getComdatLeader(*SrcM, ComdatName, SrcGV))
194 const DataLayout &SrcDL = SrcM->getDataLayout();
197 if (Result == Comdat::SelectionKind::ExactMatch) {
199 return emitError(
"Linking COMDATs named '" + ComdatName +
200 "': ExactMatch violated!");
202 }
else if (Result == Comdat::SelectionKind::Largest) {
203 LinkFromSrc = SrcSize > DstSize;
204 }
else if (Result == Comdat::SelectionKind::SameSize) {
205 if (SrcSize != DstSize)
206 return emitError(
"Linking COMDATs named '" + ComdatName +
207 "': SameSize violated!");
219 bool ModuleLinker::getComdatResult(
const Comdat *SrcC,
228 if (DstCI == ComdatSymTab.
end()) {
235 const Comdat *DstC = &DstCI->second;
237 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
241 bool ModuleLinker::shouldLinkFromSource(
bool &LinkFromSrc,
246 if (shouldOverrideFromSrc()) {
260 if (SrcIsDeclaration) {
265 LinkFromSrc = DestIsDeclaration;
278 if (DestIsDeclaration) {
298 LinkFromSrc = SrcSize > DestSize;
324 "Unexpected linkage type!");
325 return emitError(
"Linking globals named '" + Src.
getName() +
326 "': symbol multiply defined!");
332 if (shouldLinkOnlyNeeded()) {
348 if (DGVar && SGVar) {
349 if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
350 (!DGVar->isConstant() || !SGVar->isConstant())) {
352 SGVar->setConstant(
false);
354 if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
355 unsigned Align =
std::max(DGVar->getAlignment(), SGVar->getAlignment());
356 SGVar->setAlignment(Align);
357 DGVar->setAlignment(Align);
372 if (!DGV && !shouldOverrideFromSrc() &&
383 std::tie(SK, LinkFromSrc) = ComdatsChosen[
SC];
388 bool LinkFromSrc =
true;
389 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
399 !shouldLinkOnlyNeeded())
402 if (InternalizeCallback)
411 bool LinkFromSrc =
true;
412 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
416 if (InternalizeCallback)
417 Internalize.
insert(GV2->getName());
422 void ModuleLinker::dropReplacedComdat(
427 if (!ReplacedDstComdats.
count(C))
434 if (
auto *
F = dyn_cast<Function>(&GV)) {
436 }
else if (
auto *Var = dyn_cast<GlobalVariable>(&GV)) {
437 Var->setInitializer(
nullptr);
439 auto &Alias = cast<GlobalAlias>(GV);
440 Module &M = *Alias.getParent();
441 PointerType &Ty = *cast<PointerType>(Alias.getType());
443 if (
auto *FTy = dyn_cast<FunctionType>(Alias.getValueType())) {
452 Alias.replaceAllUsesWith(Declaration);
453 Alias.eraseFromParent();
457 bool ModuleLinker::run() {
461 for (
const auto &SMEC : SrcM->getComdatSymbolTable()) {
462 const Comdat &
C = SMEC.getValue();
463 if (ComdatsChosen.count(&C))
467 if (getComdatResult(&C, SK, LinkFromSrc))
469 ComdatsChosen[&
C] = std::make_pair(SK, LinkFromSrc);
476 if (DstCI == ComdatSymTab.
end())
480 const Comdat *DstC = &DstCI->second;
481 ReplacedDstComdats.
insert(DstC);
488 dropReplacedComdat(GV, ReplacedDstComdats);
493 dropReplacedComdat(GV, ReplacedDstComdats);
498 dropReplacedComdat(GV, ReplacedDstComdats);
504 LazyComdatMembers[
SC].push_back(&GV);
507 if (SF.hasLinkOnceLinkage())
508 if (
const Comdat *
SC = SF.getComdat())
509 LazyComdatMembers[
SC].push_back(&SF);
512 if (GA.hasLinkOnceLinkage())
513 if (
const Comdat *
SC = GA.getComdat())
514 LazyComdatMembers[
SC].push_back(&GA);
519 if (linkIfNeeded(GV))
523 if (linkIfNeeded(SF))
527 if (linkIfNeeded(GA))
530 for (
unsigned I = 0;
I < ValuesToLink.
size(); ++
I) {
537 bool LinkFromSrc =
true;
538 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
545 if (InternalizeCallback) {
552 bool HasErrors =
false;
566 if (InternalizeCallback)
567 InternalizeCallback(DstM, Internalize);
575 std::unique_ptr<Module> Src,
unsigned Flags,
577 ModuleLinker ModLinker(Mover, std::move(Src), Flags,
578 std::move(InternalizeCallback));
579 return ModLinker.run();
592 Module &Dest, std::unique_ptr<Module> Src,
unsigned Flags,
595 return L.
linkInModule(std::move(Src), Flags, std::move(InternalizeCallback));
604 std::unique_ptr<Module> M(
unwrap(Src));
void setVisibility(VisibilityTypes V)
bool isDeclarationForLinker() const
A parsed version of the target data layout string in and methods for querying it. ...
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
bool hasLocalLinkage() const
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
This class represents lattice values for constants.
struct LLVMOpaqueModule * LLVMModuleRef
The top-level container for all other LLVM Intermediate Representation (IR) objects.
ArrayRef< T > getArrayRef() const
size_type size() const
Determine the number of elements in the SetVector.
A Module instance is used to store all the information related to an LLVM module. ...
Implements a dense probed hash-table based set.
bool hasAvailableExternallyLinkage() const
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
iterator find(StringRef Key)
virtual std::string message() const
Return the error message as a string.
Externally visible function.
bool hasDLLImportStorageClass() const
ELFYAML::ELF_STV Visibility
bool hasExternalWeakLinkage() const
Base class for error info classes.
LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src)
static bool isLocalLinkage(LinkageTypes Linkage)
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Attribute unwrap(LLVMAttributeRef Attr)
const ComdatSymTabType & getComdatSymbolTable() const
Get the Module's symbol table for COMDATs (constant).
LLVMContext & getContext() const
Get the global data context.
UnnamedAddr getUnnamedAddr() const
static bool linkModules(Module &Dest, std::unique_ptr< Module > Src, unsigned Flags=Flags::None, std::function< void(Module &, const StringSet<> &)> InternalizeCallback={})
This function links two modules together, with the resulting Dest module modified to be the composite...
bool hasCommonLinkage() const
global_iterator global_begin()
bool hasExternalLinkage() const
bool insert(const value_type &X)
Insert a new element into the SetVector.
Error move(std::unique_ptr< Module > Src, ArrayRef< GlobalValue *> ValuesToLink, std::function< void(GlobalValue &GV, ValueAdder Add)> AddLazyFor, bool IsPerformingImport)
Move in the provide values in ValuesToLink from Src.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type. ...
This class provides the core functionality of linking in LLVM.
LinkageTypes getLinkage() const
bool hasLinkOnceLinkage() const
void takeName(Value *V)
Transfer the name from V to this value.
Class to represent pointers.
bool hasAppendingLinkage() const
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
StringRef getName() const
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
VisibilityTypes getVisibility() const
alias_iterator alias_end()
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
std::pair< iterator, bool > insert(const ValueT &V)
static GlobalValue::VisibilityTypes getMinVisibility(GlobalValue::VisibilityTypes A, GlobalValue::VisibilityTypes B)
void setConstant(bool Val)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::pair< typename base::iterator, bool > insert(StringRef Key)
bool hasWeakLinkage() const
global_iterator global_end()
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Module.h This file contains the declarations for the Module class.
CHAIN = SC CHAIN, Imm128 - System call.
alias_iterator alias_begin()
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
const Comdat * getComdat() const
bool linkInModule(std::unique_ptr< Module > Src, unsigned Flags=Flags::None, std::function< void(Module &, const StringSet<> &)> InternalizeCallback={})
Link Src into the composite.
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
void setUnnamedAddr(UnnamedAddr Val)
StringRef getName() const
Return a constant reference to the value's name.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Type * getValueType() const
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
const GlobalObject * getBaseObject() const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
std::function< void(GlobalValue &)> ValueAdder
Module * getParent()
Get the module that this global value is contained inside of...
A vector that has set insertion semantics.
Lightweight error class with error context and mandatory checking.
StringSet - A wrapper for StringMap that provides set-like functionality.
print Print MemDeps of function
StringRef - Represent a constant reference to a string, i.e.
static UnnamedAddr getMinUnnamedAddr(UnnamedAddr A, UnnamedAddr B)
Type * getElementType() const
SelectionKind getSelectionKind() const