Go to the documentation of this file.
26 enum class LinkFrom { Dst, Src,
Both };
32 std::unique_ptr<Module> SrcM;
56 bool shouldLinkFromSource(
bool &LinkFromSrc,
const GlobalValue &Dest,
60 bool emitError(
const Twine &Message) {
67 bool computeResultingSelectionKind(
StringRef ComdatName,
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!");
179 From = LinkFrom::Dst;
181 case Comdat::SelectionKind::NoDeduplicate:
182 From = LinkFrom::Both;
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!");
201 From = LinkFrom::Dst;
202 }
else if (Result == Comdat::SelectionKind::Largest) {
203 From = SrcSize > DstSize ? LinkFrom::Src : LinkFrom::Dst;
204 }
else if (Result == Comdat::SelectionKind::SameSize) {
205 if (SrcSize != DstSize)
206 return emitError(
"Linking COMDATs named '" + ComdatName +
207 "': SameSize violated!");
208 From = LinkFrom::Dst;
219 bool ModuleLinker::getComdatResult(
const Comdat *SrcC,
228 if (DstCI == ComdatSymTab.
end()) {
230 From = LinkFrom::Src;
235 const Comdat *DstC = &DstCI->second;
237 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
From);
240 bool ModuleLinker::shouldLinkFromSource(
bool &LinkFromSrc,
245 if (shouldOverrideFromSrc()) {
256 bool SrcIsDeclaration = Src.isDeclarationForLinker();
259 if (SrcIsDeclaration) {
262 if (Src.hasDLLImportStorageClass()) {
264 LinkFromSrc = DestIsDeclaration;
277 if (DestIsDeclaration) {
283 if (Src.hasCommonLinkage()) {
296 uint64_t SrcSize =
DL.getTypeAllocSize(Src.getValueType());
297 LinkFromSrc = SrcSize > DestSize;
301 if (Src.isWeakForLinker()) {
315 assert(Src.hasExternalLinkage());
320 assert(!Src.hasExternalWeakLinkage());
323 "Unexpected linkage type!");
324 return emitError(
"Linking globals named '" + Src.getName() +
325 "': symbol multiply defined!");
332 if (shouldLinkOnlyNeeded()) {
346 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
347 auto *SGVar = dyn_cast<GlobalVariable>(&GV);
348 if (DGVar && SGVar) {
349 if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
350 (!DGVar->isConstant() || !SGVar->isConstant())) {
351 DGVar->setConstant(
false);
352 SGVar->setConstant(
false);
354 if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
356 std::max(DGVar->getAlignment(), SGVar->getAlignment()));
357 SGVar->setAlignment(
Align);
358 DGVar->setAlignment(
Align);
373 if (!DGV && !shouldOverrideFromSrc() &&
381 LinkFrom ComdatFrom = LinkFrom::Dst;
383 std::tie(std::ignore, ComdatFrom) = ComdatsChosen[
SC];
384 if (ComdatFrom == LinkFrom::Dst)
388 bool LinkFromSrc =
true;
389 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
391 if (DGV && ComdatFrom == LinkFrom::Both)
392 GVToClone.push_back(LinkFromSrc ? DGV : &GV);
401 !shouldLinkOnlyNeeded())
404 if (InternalizeCallback)
413 bool LinkFromSrc =
true;
414 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
418 if (InternalizeCallback)
419 Internalize.
insert(GV2->getName());
424 void ModuleLinker::dropReplacedComdat(
429 if (!ReplacedDstComdats.
count(
C))
436 if (
auto *
F = dyn_cast<Function>(&GV)) {
438 }
else if (
auto *Var = dyn_cast<GlobalVariable>(&GV)) {
439 Var->setInitializer(
nullptr);
441 auto &Alias = cast<GlobalAlias>(GV);
442 Module &
M = *Alias.getParent();
444 if (
auto *FTy = dyn_cast<FunctionType>(Alias.getValueType())) {
453 Alias.replaceAllUsesWith(Declaration);
454 Alias.eraseFromParent();
462 for (
const auto &SMEC : SrcM->getComdatSymbolTable()) {
463 const Comdat &
C = SMEC.getValue();
464 if (ComdatsChosen.
count(&
C))
468 if (getComdatResult(&
C, SK,
From))
470 ComdatsChosen[&
C] = std::make_pair(SK,
From);
472 if (
From != LinkFrom::Src)
477 if (DstCI == ComdatSymTab.
end())
481 const Comdat *DstC = &DstCI->second;
482 ReplacedDstComdats.
insert(DstC);
488 dropReplacedComdat(GV, ReplacedDstComdats);
491 dropReplacedComdat(GV, ReplacedDstComdats);
494 dropReplacedComdat(GV, ReplacedDstComdats);
499 LazyComdatMembers[
SC].push_back(&GV);
502 if (SF.hasLinkOnceLinkage())
503 if (
const Comdat *
SC = SF.getComdat())
504 LazyComdatMembers[
SC].push_back(&SF);
507 if (GA.hasLinkOnceLinkage())
508 if (
const Comdat *
SC = GA.getComdat())
509 LazyComdatMembers[
SC].push_back(&GA);
515 if (linkIfNeeded(GV, GVToClone))
519 if (linkIfNeeded(SF, GVToClone))
523 if (linkIfNeeded(GA, GVToClone))
527 if (linkIfNeeded(GI, GVToClone))
535 if (
auto *Var = dyn_cast<GlobalVariable>(GV)) {
536 auto *NewVar =
new GlobalVariable(*Var->getParent(), Var->getValueType(),
537 Var->isConstant(), Var->getLinkage(),
538 Var->getInitializer());
539 NewVar->copyAttributesFrom(Var);
542 NewVar->setDSOLocal(
true);
543 NewVar->setComdat(Var->getComdat());
544 if (Var->getParent() != &Mover.
getModule())
545 ValuesToLink.
insert(NewVar);
547 emitError(
"linking '" + GV->
getName() +
548 "': non-variables in comdat nodeduplicate are not handled");
552 for (
unsigned I = 0;
I < ValuesToLink.
size(); ++
I) {
559 bool LinkFromSrc =
true;
560 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
567 if (InternalizeCallback) {
574 bool HasErrors =
false;
590 if (InternalizeCallback)
591 InternalizeCallback(DstM, Internalize);
599 std::unique_ptr<Module> Src,
unsigned Flags,
603 return ModLinker.run();
616 Module &Dest, std::unique_ptr<Module> Src,
unsigned Flags,
628 std::unique_ptr<Module>
M(
unwrap(Src));
This is an optimization pass for GlobalISel generic memory operations.
We currently emits eax Perhaps this is what we really should generate is Is imull three or four cycles eax eax The current instruction priority is based on pattern complexity The former is more complex because it folds a load so the latter will not be emitted Perhaps we should use AddedComplexity to give LEA32r a higher priority We should always try to match LEA first since the LEA matching code does some estimate to determine whether the match is profitable if we care more about code then imull is better It s two bytes shorter than movl leal On a Pentium M
StringRef getName() const
bool hasCommonLinkage() const
A parsed version of the target data layout string in and methods for querying it.
bool hasExternalLinkage() const
unique_function is a type-erasing functor similar to std::function.
LinkageTypes getLinkage() const
@ HiddenVisibility
The GV is hidden.
size_type size() const
Determine the number of elements in the SetVector.
bool hasWeakLinkage() const
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
static bool isLocalLinkage(LinkageTypes Linkage)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
@ DefaultVisibility
The GV is visible.
std::pair< typename Base::iterator, bool > insert(StringRef key)
void setUnnamedAddr(UnnamedAddr Val)
iterator find(StringRef Key)
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.
bool hasExternalWeakLinkage() const
LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src)
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
@ SC
CHAIN = SC CHAIN, Imm128 - System call.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
bool hasAppendingLinkage() const
iterator_range< global_iterator > globals()
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
(vector float) vec_cmpeq(*A, *B) C
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...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
const ComdatSymTabType & getComdatSymbolTable() const
Get the Module's symbol table for COMDATs (constant).
Error move(std::unique_ptr< Module > Src, ArrayRef< GlobalValue * > ValuesToLink, LazyCallback AddLazyFor, bool IsPerformingImport)
Move in the provide values in ValuesToLink from Src.
Attribute unwrap(LLVMAttributeRef Attr)
This struct is a compact representation of a valid (non-zero power of two) alignment.
Base class for error info classes.
virtual std::string message() const
Return the error message as a string.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
Implements a dense probed hash-table based set.
iterator_range< alias_iterator > aliases()
bool hasAvailableExternallyLinkage() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
VisibilityTypes getVisibility() const
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
Module * getParent()
Get the module that this global value is contained inside of...
compiles ldr LCPI1_0 ldr ldr mov lsr tst moveq r1 ldr LCPI1_1 and r0 bx lr It would be better to do something like to fold the shift into the conditional move
std::function< void(GlobalValue &)> ValueAdder
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...
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool hasLocalLinkage() const
print Print MemDeps of function
static GlobalValue::VisibilityTypes getMinVisibility(GlobalValue::VisibilityTypes A, GlobalValue::VisibilityTypes B)
A Module instance is used to store all the information related to an LLVM module.
This class provides the core functionality of linking in LLVM.
bool insert(const value_type &X)
Insert a new element into the SetVector.
StringSet - A wrapper for StringMap that provides set-like functionality.
StringRef - Represent a constant reference to a string, i.e.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
const GlobalObject * getAliaseeObject() const
StringRef getName() const
Return a constant reference to the value's name.
void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
UnnamedAddr getUnnamedAddr() const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Lightweight error class with error context and mandatory checking.
bool linkInModule(std::unique_ptr< Module > Src, unsigned Flags=Flags::None, std::function< void(Module &, const StringSet<> &)> InternalizeCallback={})
Link Src into the composite.
const Comdat * getComdat() const
LLVMContext & getContext() const
Get the global data context.
@ ProtectedVisibility
The GV is protected.
@ ExternalLinkage
Externally visible function.
@ PrivateLinkage
Like Internal, but omit from symbol table.
Align max(MaybeAlign Lhs, Align Rhs)
bool isDeclarationForLinker() const
bool hasLinkOnceLinkage() const
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Type * getValueType() const
BlockVerifier::State From
void takeName(Value *V)
Transfer the name from V to this value.
SelectionKind getSelectionKind() const
A vector that has set insertion semantics.
void setVisibility(VisibilityTypes V)
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
static UnnamedAddr getMinUnnamedAddr(UnnamedAddr A, UnnamedAddr B)
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type.
struct LLVMOpaqueModule * LLVMModuleRef
The top-level container for all other LLVM Intermediate Representation (IR) objects.
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...