1 //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LLVM module linker.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Linker/Linker.h"
15 #include "LinkDiagnosticInfo.h"
16 #include "llvm-c/Linker.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/StringSet.h"
19 #include "llvm/IR/DiagnosticPrinter.h"
24 /// This is an implementation class for the LinkModules function, which is the
25 /// entrypoint for this file.
30 SetVector<GlobalValue *> ValuesToLink;
31 StringSet<> Internalize;
33 /// For symbol clashes, prefer those from Src.
36 /// Function index passed into ModuleLinker for using in function
37 /// importing/exporting handling.
38 const FunctionInfoIndex *ImportIndex;
40 /// Function to import from source module, all other functions are
41 /// imported as declarations instead of definitions.
42 DenseSet<const GlobalValue *> *ImportFunction;
44 /// Set to true if the given FunctionInfoIndex contains any functions
45 /// from this source module, in which case we must conservatively assume
46 /// that any of its functions may be imported into another module
47 /// as part of a different backend compilation process.
48 bool HasExportedFunctions = false;
50 /// Used as the callback for lazy linking.
51 /// The mover has just hit GV and we have to decide if it, and other members
52 /// of the same comdat, should be linked. Every member to be linked is passed
54 void addLazyFor(GlobalValue &GV, IRMover::ValueAdder Add);
56 bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
57 bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
58 bool shouldInternalizeLinkedSymbols() {
59 return Flags & Linker::InternalizeLinkedSymbols;
62 /// Check if we should promote the given local value to global scope.
63 bool doPromoteLocalToGlobal(const GlobalValue *SGV);
65 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
66 const GlobalValue &Src);
68 /// Should we have mover and linker error diag info?
69 bool emitError(const Twine &Message) {
70 Mover.getDiagnosticHandler()(LinkDiagnosticInfo(DS_Error, Message));
74 bool getComdatLeader(Module &M, StringRef ComdatName,
75 const GlobalVariable *&GVar);
76 bool computeResultingSelectionKind(StringRef ComdatName,
77 Comdat::SelectionKind Src,
78 Comdat::SelectionKind Dst,
79 Comdat::SelectionKind &Result,
81 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
83 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
85 // Keep track of the global value members of each comdat in source.
86 DenseMap<const Comdat *, std::vector<GlobalValue *>> ComdatMembers;
88 /// Given a global in the source module, return the global in the
89 /// destination module that is being linked to, if any.
90 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
91 Module &DstM = Mover.getModule();
92 // If the source has no name it can't link. If it has local linkage,
93 // there is no name match-up going on.
94 if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(getLinkage(SrcGV)))
97 // Otherwise see if we have a match in the destination module's symtab.
98 GlobalValue *DGV = DstM.getNamedValue(getName(SrcGV));
102 // If we found a global with the same name in the dest module, but it has
103 // internal linkage, we are really not doing any linkage here.
104 if (DGV->hasLocalLinkage())
107 // Otherwise, we do in fact link to the destination global.
111 bool linkIfNeeded(GlobalValue &GV);
113 /// Helper methods to check if we are importing from or potentially
114 /// exporting from the current source module.
115 bool isPerformingImport() { return ImportFunction != nullptr; }
116 bool isModuleExporting() { return HasExportedFunctions; }
118 /// If we are importing from the source module, checks if we should
119 /// import SGV as a definition, otherwise import as a declaration.
120 bool doImportAsDefinition(const GlobalValue *SGV);
122 /// Get the name for SGV that should be used in the linked destination
123 /// module. Specifically, this handles the case where we need to rename
124 /// a local that is being promoted to global scope.
125 std::string getName(const GlobalValue *SGV);
127 /// Process globals so that they can be used in ThinLTO. This includes
128 /// promoting local variables so that they can be reference externally by
129 /// thin lto imported globals and converting strong external globals to
130 /// available_externally.
131 void processGlobalsForThinLTO();
132 void processGlobalForThinLTO(GlobalValue &GV);
134 /// Get the new linkage for SGV that should be used in the linked destination
135 /// module. Specifically, for ThinLTO importing or exporting it may need
137 GlobalValue::LinkageTypes getLinkage(const GlobalValue *SGV);
139 /// Copies the necessary global value attributes and name from the source
140 /// to the newly cloned global value.
141 void copyGVAttributes(GlobalValue *NewGV, const GlobalValue *SrcGV);
143 /// Updates the visibility for the new global cloned from the source
144 /// and, if applicable, linked with an existing destination global.
145 /// Handles visibility change required for promoted locals.
146 void setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
147 const GlobalValue *DGV = nullptr);
150 ModuleLinker(IRMover &Mover, Module &SrcM, unsigned Flags,
151 const FunctionInfoIndex *Index = nullptr,
152 DenseSet<const GlobalValue *> *FunctionsToImport = nullptr)
153 : Mover(Mover), SrcM(SrcM), Flags(Flags), ImportIndex(Index),
154 ImportFunction(FunctionsToImport) {
155 assert((ImportIndex || !ImportFunction) &&
156 "Expect a FunctionInfoIndex when importing");
157 // If we have a FunctionInfoIndex but no function to import,
158 // then this is the primary module being compiled in a ThinLTO
159 // backend compilation, and we need to see if it has functions that
160 // may be exported to another backend compilation.
161 if (ImportIndex && !ImportFunction)
162 HasExportedFunctions = ImportIndex->hasExportedFunctions(SrcM);
169 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
170 /// table. This is good for all clients except for us. Go through the trouble
171 /// to force this back.
172 static void forceRenaming(GlobalValue *GV, StringRef Name) {
173 // If the global doesn't force its name or if it already has the right name,
174 // there is nothing for us to do.
175 // Note that any required local to global promotion should already be done,
176 // so promoted locals will not skip this handling as their linkage is no
178 if (GV->hasLocalLinkage() || GV->getName() == Name)
181 Module *M = GV->getParent();
183 // If there is a conflict, rename the conflict.
184 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
185 GV->takeName(ConflictGV);
186 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
187 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
189 GV->setName(Name); // Force the name back
193 /// copy additional attributes (those not needed to construct a GlobalValue)
194 /// from the SrcGV to the DestGV.
195 void ModuleLinker::copyGVAttributes(GlobalValue *NewGV,
196 const GlobalValue *SrcGV) {
197 NewGV->copyAttributesFrom(SrcGV);
198 forceRenaming(NewGV, getName(SrcGV));
201 bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
202 if (!isPerformingImport())
204 auto *GA = dyn_cast<GlobalAlias>(SGV);
206 if (GA->hasWeakAnyLinkage())
208 const GlobalObject *GO = GA->getBaseObject();
209 if (!GO->hasLinkOnceODRLinkage())
211 return doImportAsDefinition(GO);
213 // Always import GlobalVariable definitions, except for the special
214 // case of WeakAny which are imported as ExternalWeak declarations
215 // (see comments in ModuleLinker::getLinkage). The linkage changes
216 // described in ModuleLinker::getLinkage ensure the correct behavior (e.g.
217 // global variables with external linkage are transformed to
218 // available_externally definitions, which are ultimately turned into
219 // declarations after the EliminateAvailableExternally pass).
220 if (isa<GlobalVariable>(SGV) && !SGV->isDeclaration() &&
221 !SGV->hasWeakAnyLinkage())
223 // Only import the function requested for importing.
224 auto *SF = dyn_cast<Function>(SGV);
225 if (SF && ImportFunction->count(SF))
231 bool ModuleLinker::doPromoteLocalToGlobal(const GlobalValue *SGV) {
232 assert(SGV->hasLocalLinkage());
233 // Both the imported references and the original local variable must
235 if (!isPerformingImport() && !isModuleExporting())
238 // Local const variables never need to be promoted unless they are address
239 // taken. The imported uses can simply use the clone created in this module.
240 // For now we are conservative in determining which variables are not
241 // address taken by checking the unnamed addr flag. To be more aggressive,
242 // the address taken information must be checked earlier during parsing
243 // of the module and recorded in the function index for use when importing
245 auto *GVar = dyn_cast<GlobalVariable>(SGV);
246 if (GVar && GVar->isConstant() && GVar->hasUnnamedAddr())
249 // Eventually we only need to promote functions in the exporting module that
250 // are referenced by a potentially exported function (i.e. one that is in the
255 std::string ModuleLinker::getName(const GlobalValue *SGV) {
256 // For locals that must be promoted to global scope, ensure that
257 // the promoted name uniquely identifies the copy in the original module,
258 // using the ID assigned during combined index creation. When importing,
259 // we rename all locals (not just those that are promoted) in order to
260 // avoid naming conflicts between locals imported from different modules.
261 if (SGV->hasLocalLinkage() &&
262 (doPromoteLocalToGlobal(SGV) || isPerformingImport()))
263 return FunctionInfoIndex::getGlobalNameForLocal(
265 ImportIndex->getModuleId(SGV->getParent()->getModuleIdentifier()));
266 return SGV->getName();
269 GlobalValue::LinkageTypes ModuleLinker::getLinkage(const GlobalValue *SGV) {
270 // Any local variable that is referenced by an exported function needs
271 // to be promoted to global scope. Since we don't currently know which
272 // functions reference which local variables/functions, we must treat
273 // all as potentially exported if this module is exporting anything.
274 if (isModuleExporting()) {
275 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
276 return GlobalValue::ExternalLinkage;
277 return SGV->getLinkage();
280 // Otherwise, if we aren't importing, no linkage change is needed.
281 if (!isPerformingImport())
282 return SGV->getLinkage();
284 switch (SGV->getLinkage()) {
285 case GlobalValue::ExternalLinkage:
286 // External defnitions are converted to available_externally
287 // definitions upon import, so that they are available for inlining
288 // and/or optimization, but are turned into declarations later
289 // during the EliminateAvailableExternally pass.
290 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
291 return GlobalValue::AvailableExternallyLinkage;
292 // An imported external declaration stays external.
293 return SGV->getLinkage();
295 case GlobalValue::AvailableExternallyLinkage:
296 // An imported available_externally definition converts
297 // to external if imported as a declaration.
298 if (!doImportAsDefinition(SGV))
299 return GlobalValue::ExternalLinkage;
300 // An imported available_externally declaration stays that way.
301 return SGV->getLinkage();
303 case GlobalValue::LinkOnceAnyLinkage:
304 case GlobalValue::LinkOnceODRLinkage:
305 // These both stay the same when importing the definition.
306 // The ThinLTO pass will eventually force-import their definitions.
307 return SGV->getLinkage();
309 case GlobalValue::WeakAnyLinkage:
310 // Can't import weak_any definitions correctly, or we might change the
311 // program semantics, since the linker will pick the first weak_any
312 // definition and importing would change the order they are seen by the
313 // linker. The module linking caller needs to enforce this.
314 assert(!doImportAsDefinition(SGV));
315 // If imported as a declaration, it becomes external_weak.
316 return GlobalValue::ExternalWeakLinkage;
318 case GlobalValue::WeakODRLinkage:
319 // For weak_odr linkage, there is a guarantee that all copies will be
320 // equivalent, so the issue described above for weak_any does not exist,
321 // and the definition can be imported. It can be treated similarly
322 // to an imported externally visible global value.
323 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
324 return GlobalValue::AvailableExternallyLinkage;
326 return GlobalValue::ExternalLinkage;
328 case GlobalValue::AppendingLinkage:
329 // It would be incorrect to import an appending linkage variable,
330 // since it would cause global constructors/destructors to be
331 // executed multiple times. This should have already been handled
332 // by linkIfNeeded, and we will assert in shouldLinkFromSource
333 // if we try to import, so we simply return AppendingLinkage here
334 // as this helper is called more widely in getLinkedToGlobal.
335 return GlobalValue::AppendingLinkage;
337 case GlobalValue::InternalLinkage:
338 case GlobalValue::PrivateLinkage:
339 // If we are promoting the local to global scope, it is handled
340 // similarly to a normal externally visible global.
341 if (doPromoteLocalToGlobal(SGV)) {
342 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
343 return GlobalValue::AvailableExternallyLinkage;
345 return GlobalValue::ExternalLinkage;
347 // A non-promoted imported local definition stays local.
348 // The ThinLTO pass will eventually force-import their definitions.
349 return SGV->getLinkage();
351 case GlobalValue::ExternalWeakLinkage:
352 // External weak doesn't apply to definitions, must be a declaration.
353 assert(!doImportAsDefinition(SGV));
354 // Linkage stays external_weak.
355 return SGV->getLinkage();
357 case GlobalValue::CommonLinkage:
358 // Linkage stays common on definitions.
359 // The ThinLTO pass will eventually force-import their definitions.
360 return SGV->getLinkage();
363 llvm_unreachable("unknown linkage type");
366 static GlobalValue::VisibilityTypes
367 getMinVisibility(GlobalValue::VisibilityTypes A,
368 GlobalValue::VisibilityTypes B) {
369 if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
370 return GlobalValue::HiddenVisibility;
371 if (A == GlobalValue::ProtectedVisibility ||
372 B == GlobalValue::ProtectedVisibility)
373 return GlobalValue::ProtectedVisibility;
374 return GlobalValue::DefaultVisibility;
377 void ModuleLinker::setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
378 const GlobalValue *DGV) {
379 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
381 Visibility = getMinVisibility(DGV->getVisibility(), Visibility);
382 // For promoted locals, mark them hidden so that they can later be
383 // stripped from the symbol table to reduce bloat.
384 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
385 Visibility = GlobalValue::HiddenVisibility;
386 NewGV->setVisibility(Visibility);
389 bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
390 const GlobalVariable *&GVar) {
391 const GlobalValue *GVal = M.getNamedValue(ComdatName);
392 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
393 GVal = GA->getBaseObject();
395 // We cannot resolve the size of the aliasee yet.
396 return emitError("Linking COMDATs named '" + ComdatName +
397 "': COMDAT key involves incomputable alias size.");
400 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
403 "Linking COMDATs named '" + ComdatName +
404 "': GlobalVariable required for data dependent selection!");
409 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
410 Comdat::SelectionKind Src,
411 Comdat::SelectionKind Dst,
412 Comdat::SelectionKind &Result,
414 Module &DstM = Mover.getModule();
415 // The ability to mix Comdat::SelectionKind::Any with
416 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
417 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
418 Dst == Comdat::SelectionKind::Largest;
419 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
420 Src == Comdat::SelectionKind::Largest;
421 if (DstAnyOrLargest && SrcAnyOrLargest) {
422 if (Dst == Comdat::SelectionKind::Largest ||
423 Src == Comdat::SelectionKind::Largest)
424 Result = Comdat::SelectionKind::Largest;
426 Result = Comdat::SelectionKind::Any;
427 } else if (Src == Dst) {
430 return emitError("Linking COMDATs named '" + ComdatName +
431 "': invalid selection kinds!");
435 case Comdat::SelectionKind::Any:
439 case Comdat::SelectionKind::NoDuplicates:
440 return emitError("Linking COMDATs named '" + ComdatName +
441 "': noduplicates has been violated!");
442 case Comdat::SelectionKind::ExactMatch:
443 case Comdat::SelectionKind::Largest:
444 case Comdat::SelectionKind::SameSize: {
445 const GlobalVariable *DstGV;
446 const GlobalVariable *SrcGV;
447 if (getComdatLeader(DstM, ComdatName, DstGV) ||
448 getComdatLeader(SrcM, ComdatName, SrcGV))
451 const DataLayout &DstDL = DstM.getDataLayout();
452 const DataLayout &SrcDL = SrcM.getDataLayout();
454 DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
456 SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
457 if (Result == Comdat::SelectionKind::ExactMatch) {
458 if (SrcGV->getInitializer() != DstGV->getInitializer())
459 return emitError("Linking COMDATs named '" + ComdatName +
460 "': ExactMatch violated!");
462 } else if (Result == Comdat::SelectionKind::Largest) {
463 LinkFromSrc = SrcSize > DstSize;
464 } else if (Result == Comdat::SelectionKind::SameSize) {
465 if (SrcSize != DstSize)
466 return emitError("Linking COMDATs named '" + ComdatName +
467 "': SameSize violated!");
470 llvm_unreachable("unknown selection kind");
479 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
480 Comdat::SelectionKind &Result,
482 Module &DstM = Mover.getModule();
483 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
484 StringRef ComdatName = SrcC->getName();
485 Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
486 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
488 if (DstCI == ComdatSymTab.end()) {
489 // Use the comdat if it is only available in one of the modules.
495 const Comdat *DstC = &DstCI->second;
496 Comdat::SelectionKind DSK = DstC->getSelectionKind();
497 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
501 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
502 const GlobalValue &Dest,
503 const GlobalValue &Src) {
504 // Should we unconditionally use the Src?
505 if (shouldOverrideFromSrc()) {
510 // We always have to add Src if it has appending linkage.
511 if (Src.hasAppendingLinkage()) {
512 // Should have prevented importing for appending linkage in linkIfNeeded.
513 assert(!isPerformingImport());
518 bool SrcIsDeclaration = Src.isDeclarationForLinker();
519 bool DestIsDeclaration = Dest.isDeclarationForLinker();
521 if (isPerformingImport()) {
522 if (isa<Function>(&Src)) {
523 // For functions, LinkFromSrc iff this is the function requested
524 // for importing. For variables, decide below normally.
525 LinkFromSrc = ImportFunction->count(&Src);
529 // Check if this is an alias with an already existing definition
530 // in Dest, which must have come from a prior importing pass from
531 // the same Src module. Unlike imported function and variable
532 // definitions, which are imported as available_externally and are
533 // not definitions for the linker, that is not a valid linkage for
534 // imported aliases which must be definitions. Simply use the existing
536 if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
537 assert(isa<GlobalAlias>(&Dest));
543 if (SrcIsDeclaration) {
544 // If Src is external or if both Src & Dest are external.. Just link the
545 // external globals, we aren't adding anything.
546 if (Src.hasDLLImportStorageClass()) {
547 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
548 LinkFromSrc = DestIsDeclaration;
551 // If the Dest is weak, use the source linkage.
552 if (Dest.hasExternalWeakLinkage()) {
556 // Link an available_externally over a declaration.
557 LinkFromSrc = !Src.isDeclaration() && Dest.isDeclaration();
561 if (DestIsDeclaration) {
562 // If Dest is external but Src is not:
567 if (Src.hasCommonLinkage()) {
568 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
573 if (!Dest.hasCommonLinkage()) {
578 const DataLayout &DL = Dest.getParent()->getDataLayout();
579 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
580 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
581 LinkFromSrc = SrcSize > DestSize;
585 if (Src.isWeakForLinker()) {
586 assert(!Dest.hasExternalWeakLinkage());
587 assert(!Dest.hasAvailableExternallyLinkage());
589 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
598 if (Dest.isWeakForLinker()) {
599 assert(Src.hasExternalLinkage());
604 assert(!Src.hasExternalWeakLinkage());
605 assert(!Dest.hasExternalWeakLinkage());
606 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
607 "Unexpected linkage type!");
608 return emitError("Linking globals named '" + Src.getName() +
609 "': symbol multiply defined!");
612 bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
613 GlobalValue *DGV = getLinkedToGlobal(&GV);
615 if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
618 if (DGV && !GV.hasLocalLinkage() && !GV.hasAppendingLinkage()) {
619 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
620 auto *SGVar = dyn_cast<GlobalVariable>(&GV);
621 if (DGVar && SGVar) {
622 if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
623 (!DGVar->isConstant() || !SGVar->isConstant())) {
624 DGVar->setConstant(false);
625 SGVar->setConstant(false);
627 if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
628 unsigned Align = std::max(DGVar->getAlignment(), SGVar->getAlignment());
629 SGVar->setAlignment(Align);
630 DGVar->setAlignment(Align);
634 GlobalValue::VisibilityTypes Visibility =
635 getMinVisibility(DGV->getVisibility(), GV.getVisibility());
636 DGV->setVisibility(Visibility);
637 GV.setVisibility(Visibility);
639 bool HasUnnamedAddr = GV.hasUnnamedAddr() && DGV->hasUnnamedAddr();
640 DGV->setUnnamedAddr(HasUnnamedAddr);
641 GV.setUnnamedAddr(HasUnnamedAddr);
644 // Don't want to append to global_ctors list, for example, when we
645 // are importing for ThinLTO, otherwise the global ctors and dtors
646 // get executed multiple times for local variables (the latter causing
648 if (GV.hasAppendingLinkage() && isPerformingImport())
651 if (isPerformingImport() && !doImportAsDefinition(&GV))
654 if (!DGV && !shouldOverrideFromSrc() &&
655 (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
656 GV.hasAvailableExternallyLinkage()))
659 if (GV.isDeclaration())
662 if (const Comdat *SC = GV.getComdat()) {
664 Comdat::SelectionKind SK;
665 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
667 ValuesToLink.insert(&GV);
671 bool LinkFromSrc = true;
672 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
675 ValuesToLink.insert(&GV);
679 void ModuleLinker::addLazyFor(GlobalValue &GV, IRMover::ValueAdder Add) {
680 // Add these to the internalize list
681 if (!GV.hasLinkOnceLinkage())
684 if (shouldInternalizeLinkedSymbols())
685 Internalize.insert(GV.getName());
688 const Comdat *SC = GV.getComdat();
691 for (GlobalValue *GV2 : ComdatMembers[SC]) {
692 if (!GV2->hasLocalLinkage() && shouldInternalizeLinkedSymbols())
693 Internalize.insert(GV2->getName());
698 void ModuleLinker::processGlobalForThinLTO(GlobalValue &GV) {
699 if (GV.hasLocalLinkage() &&
700 (doPromoteLocalToGlobal(&GV) || isPerformingImport())) {
701 GV.setName(getName(&GV));
702 GV.setLinkage(getLinkage(&GV));
703 if (!GV.hasLocalLinkage())
704 GV.setVisibility(GlobalValue::HiddenVisibility);
705 if (isModuleExporting())
706 ValuesToLink.insert(&GV);
709 GV.setLinkage(getLinkage(&GV));
712 void ModuleLinker::processGlobalsForThinLTO() {
713 for (GlobalVariable &GV : SrcM.globals())
714 processGlobalForThinLTO(GV);
715 for (Function &SF : SrcM)
716 processGlobalForThinLTO(SF);
717 for (GlobalAlias &GA : SrcM.aliases())
718 processGlobalForThinLTO(GA);
721 bool ModuleLinker::run() {
722 for (const auto &SMEC : SrcM.getComdatSymbolTable()) {
723 const Comdat &C = SMEC.getValue();
724 if (ComdatsChosen.count(&C))
726 Comdat::SelectionKind SK;
728 if (getComdatResult(&C, SK, LinkFromSrc))
730 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
733 for (GlobalVariable &GV : SrcM.globals())
734 if (const Comdat *SC = GV.getComdat())
735 ComdatMembers[SC].push_back(&GV);
737 for (Function &SF : SrcM)
738 if (const Comdat *SC = SF.getComdat())
739 ComdatMembers[SC].push_back(&SF);
741 for (GlobalAlias &GA : SrcM.aliases())
742 if (const Comdat *SC = GA.getComdat())
743 ComdatMembers[SC].push_back(&GA);
745 // Insert all of the globals in src into the DstM module... without linking
746 // initializers (which could refer to functions not yet mapped over).
747 for (GlobalVariable &GV : SrcM.globals())
748 if (linkIfNeeded(GV))
751 for (Function &SF : SrcM)
752 if (linkIfNeeded(SF))
755 for (GlobalAlias &GA : SrcM.aliases())
756 if (linkIfNeeded(GA))
759 processGlobalsForThinLTO();
761 for (unsigned I = 0; I < ValuesToLink.size(); ++I) {
762 GlobalValue *GV = ValuesToLink[I];
763 const Comdat *SC = GV->getComdat();
766 for (GlobalValue *GV2 : ComdatMembers[SC])
767 ValuesToLink.insert(GV2);
770 if (shouldInternalizeLinkedSymbols()) {
771 for (GlobalValue *GV : ValuesToLink)
772 Internalize.insert(GV->getName());
776 makeArrayRef(&*ValuesToLink.begin(), ValuesToLink.size()),
777 [this](GlobalValue &GV, IRMover::ValueAdder Add) {
781 Module &DstM = Mover.getModule();
782 for (auto &P : Internalize) {
783 GlobalValue *GV = DstM.getNamedValue(P.first());
784 GV->setLinkage(GlobalValue::InternalLinkage);
790 Linker::Linker(Module &M, DiagnosticHandlerFunction DiagnosticHandler)
791 : Mover(M, DiagnosticHandler) {}
793 bool Linker::linkInModule(Module &Src, unsigned Flags,
794 const FunctionInfoIndex *Index,
795 DenseSet<const GlobalValue *> *FunctionsToImport) {
796 ModuleLinker TheLinker(Mover, Src, Flags, Index, FunctionsToImport);
797 return TheLinker.run();
800 //===----------------------------------------------------------------------===//
801 // LinkModules entrypoint.
802 //===----------------------------------------------------------------------===//
804 /// This function links two modules together, with the resulting Dest module
805 /// modified to be the composite of the two input modules. If an error occurs,
806 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
807 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
808 /// relied on to be consistent.
809 bool Linker::linkModules(Module &Dest, Module &Src,
810 DiagnosticHandlerFunction DiagnosticHandler,
812 Linker L(Dest, DiagnosticHandler);
813 return L.linkInModule(Src, Flags);
816 std::unique_ptr<Module>
817 llvm::renameModuleForThinLTO(std::unique_ptr<Module> &M,
818 const FunctionInfoIndex *Index,
819 DiagnosticHandlerFunction DiagnosticHandler) {
820 std::unique_ptr<llvm::Module> RenamedModule(
821 new llvm::Module(M->getModuleIdentifier(), M->getContext()));
822 Linker L(*RenamedModule.get(), DiagnosticHandler);
823 if (L.linkInModule(*M.get(), llvm::Linker::Flags::None, Index))
825 return RenamedModule;
828 //===----------------------------------------------------------------------===//
830 //===----------------------------------------------------------------------===//
832 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
833 LLVMLinkerMode Unused, char **OutMessages) {
834 Module *D = unwrap(Dest);
836 raw_string_ostream Stream(Message);
837 DiagnosticPrinterRawOStream DP(Stream);
839 LLVMBool Result = Linker::linkModules(
840 *D, *unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
842 if (OutMessages && Result) {
844 *OutMessages = strdup(Message.c_str());