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 = {})
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()) {
358 if (DAlign || SAlign)
361 SGVar->setAlignment(
Align);
362 DGVar->setAlignment(
Align);
377 if (!DGV && !shouldOverrideFromSrc() &&
385 LinkFrom ComdatFrom = LinkFrom::Dst;
387 std::tie(std::ignore, ComdatFrom) = ComdatsChosen[
SC];
388 if (ComdatFrom == LinkFrom::Dst)
392 bool LinkFromSrc =
true;
393 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
395 if (DGV && ComdatFrom == LinkFrom::Both)
396 GVToClone.push_back(LinkFromSrc ? DGV : &GV);
405 !shouldLinkOnlyNeeded())
408 if (InternalizeCallback)
417 bool LinkFromSrc =
true;
418 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
422 if (InternalizeCallback)
423 Internalize.
insert(GV2->getName());
428 void ModuleLinker::dropReplacedComdat(
433 if (!ReplacedDstComdats.
count(
C))
440 if (
auto *
F = dyn_cast<Function>(&GV)) {
442 }
else if (
auto *Var = dyn_cast<GlobalVariable>(&GV)) {
443 Var->setInitializer(
nullptr);
445 auto &Alias = cast<GlobalAlias>(GV);
446 Module &
M = *Alias.getParent();
448 if (
auto *FTy = dyn_cast<FunctionType>(Alias.getValueType())) {
457 Alias.replaceAllUsesWith(Declaration);
458 Alias.eraseFromParent();
466 for (
const auto &SMEC : SrcM->getComdatSymbolTable()) {
467 const Comdat &
C = SMEC.getValue();
468 if (ComdatsChosen.
count(&
C))
472 if (getComdatResult(&
C, SK,
From))
474 ComdatsChosen[&
C] = std::make_pair(SK,
From);
476 if (
From != LinkFrom::Src)
481 if (DstCI == ComdatSymTab.
end())
485 const Comdat *DstC = &DstCI->second;
486 ReplacedDstComdats.
insert(DstC);
492 dropReplacedComdat(GV, ReplacedDstComdats);
495 dropReplacedComdat(GV, ReplacedDstComdats);
498 dropReplacedComdat(GV, ReplacedDstComdats);
503 LazyComdatMembers[
SC].push_back(&GV);
506 if (SF.hasLinkOnceLinkage())
507 if (
const Comdat *
SC = SF.getComdat())
508 LazyComdatMembers[
SC].push_back(&SF);
511 if (GA.hasLinkOnceLinkage())
512 if (
const Comdat *
SC = GA.getComdat())
513 LazyComdatMembers[
SC].push_back(&GA);
519 if (linkIfNeeded(GV, GVToClone))
523 if (linkIfNeeded(SF, GVToClone))
527 if (linkIfNeeded(GA, GVToClone))
531 if (linkIfNeeded(GI, GVToClone))
539 if (
auto *Var = dyn_cast<GlobalVariable>(GV)) {
540 auto *NewVar =
new GlobalVariable(*Var->getParent(), Var->getValueType(),
541 Var->isConstant(), Var->getLinkage(),
542 Var->getInitializer());
543 NewVar->copyAttributesFrom(Var);
546 NewVar->setDSOLocal(
true);
547 NewVar->setComdat(Var->getComdat());
548 if (Var->getParent() != &Mover.
getModule())
549 ValuesToLink.
insert(NewVar);
551 emitError(
"linking '" + GV->
getName() +
552 "': non-variables in comdat nodeduplicate are not handled");
556 for (
unsigned I = 0;
I < ValuesToLink.
size(); ++
I) {
563 bool LinkFromSrc =
true;
564 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
571 if (InternalizeCallback) {
578 bool HasErrors =
false;
594 if (InternalizeCallback)
595 InternalizeCallback(DstM, Internalize);
603 std::unique_ptr<Module> Src,
unsigned Flags,
607 return ModLinker.run();
620 Module &Dest, std::unique_ptr<Module> Src,
unsigned Flags,
632 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)
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
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.
Expected< ExpressionValue > max(const ExpressionValue &Lhs, const ExpressionValue &Rhs)
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.
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...