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"
20 #include "llvm/IR/LLVMContext.h"
25 /// This is an implementation class for the LinkModules function, which is the
26 /// entrypoint for this file.
31 SetVector<GlobalValue *> ValuesToLink;
32 StringSet<> Internalize;
34 /// For symbol clashes, prefer those from Src.
37 /// Function index passed into ModuleLinker for using in function
38 /// importing/exporting handling.
39 const FunctionInfoIndex *ImportIndex;
41 /// Function to import from source module, all other functions are
42 /// imported as declarations instead of definitions.
43 DenseSet<const GlobalValue *> *ImportFunction;
45 /// Set to true if the given FunctionInfoIndex contains any functions
46 /// from this source module, in which case we must conservatively assume
47 /// that any of its functions may be imported into another module
48 /// as part of a different backend compilation process.
49 bool HasExportedFunctions = false;
51 /// Used as the callback for lazy linking.
52 /// The mover has just hit GV and we have to decide if it, and other members
53 /// of the same comdat, should be linked. Every member to be linked is passed
55 void addLazyFor(GlobalValue &GV, IRMover::ValueAdder Add);
57 bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
58 bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
59 bool shouldInternalizeLinkedSymbols() {
60 return Flags & Linker::InternalizeLinkedSymbols;
63 /// Check if we should promote the given local value to global scope.
64 bool doPromoteLocalToGlobal(const GlobalValue *SGV);
66 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
67 const GlobalValue &Src);
69 /// Should we have mover and linker error diag info?
70 bool emitError(const Twine &Message) {
71 SrcM.getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
75 bool getComdatLeader(Module &M, StringRef ComdatName,
76 const GlobalVariable *&GVar);
77 bool computeResultingSelectionKind(StringRef ComdatName,
78 Comdat::SelectionKind Src,
79 Comdat::SelectionKind Dst,
80 Comdat::SelectionKind &Result,
82 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
84 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
86 // Keep track of the global value members of each comdat in source.
87 DenseMap<const Comdat *, std::vector<GlobalValue *>> ComdatMembers;
89 /// Given a global in the source module, return the global in the
90 /// destination module that is being linked to, if any.
91 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
92 Module &DstM = Mover.getModule();
93 // If the source has no name it can't link. If it has local linkage,
94 // there is no name match-up going on.
95 if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(getLinkage(SrcGV)))
98 // Otherwise see if we have a match in the destination module's symtab.
99 GlobalValue *DGV = DstM.getNamedValue(getName(SrcGV));
103 // If we found a global with the same name in the dest module, but it has
104 // internal linkage, we are really not doing any linkage here.
105 if (DGV->hasLocalLinkage())
108 // Otherwise, we do in fact link to the destination global.
112 bool linkIfNeeded(GlobalValue &GV);
114 /// Helper methods to check if we are importing from or potentially
115 /// exporting from the current source module.
116 bool isPerformingImport() const { return ImportFunction != nullptr; }
117 bool isModuleExporting() const { return HasExportedFunctions; }
119 /// If we are importing from the source module, checks if we should
120 /// import SGV as a definition, otherwise import as a declaration.
121 bool doImportAsDefinition(const GlobalValue *SGV);
123 /// Get the name for SGV that should be used in the linked destination
124 /// module. Specifically, this handles the case where we need to rename
125 /// a local that is being promoted to global scope.
126 std::string getName(const GlobalValue *SGV);
128 /// Process globals so that they can be used in ThinLTO. This includes
129 /// promoting local variables so that they can be reference externally by
130 /// thin lto imported globals and converting strong external globals to
131 /// available_externally.
132 void processGlobalsForThinLTO();
133 void processGlobalForThinLTO(GlobalValue &GV);
135 /// Get the new linkage for SGV that should be used in the linked destination
136 /// module. Specifically, for ThinLTO importing or exporting it may need
138 GlobalValue::LinkageTypes getLinkage(const GlobalValue *SGV);
140 /// Copies the necessary global value attributes and name from the source
141 /// to the newly cloned global value.
142 void copyGVAttributes(GlobalValue *NewGV, const GlobalValue *SrcGV);
144 /// Updates the visibility for the new global cloned from the source
145 /// and, if applicable, linked with an existing destination global.
146 /// Handles visibility change required for promoted locals.
147 void setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
148 const GlobalValue *DGV = nullptr);
151 ModuleLinker(IRMover &Mover, Module &SrcM, unsigned Flags,
152 const FunctionInfoIndex *Index = nullptr,
153 DenseSet<const GlobalValue *> *FunctionsToImport = nullptr)
154 : Mover(Mover), SrcM(SrcM), Flags(Flags), ImportIndex(Index),
155 ImportFunction(FunctionsToImport) {
156 assert((ImportIndex || !ImportFunction) &&
157 "Expect a FunctionInfoIndex when importing");
158 // If we have a FunctionInfoIndex but no function to import,
159 // then this is the primary module being compiled in a ThinLTO
160 // backend compilation, and we need to see if it has functions that
161 // may be exported to another backend compilation.
162 if (ImportIndex && !ImportFunction)
163 HasExportedFunctions = ImportIndex->hasExportedFunctions(SrcM);
170 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
171 /// table. This is good for all clients except for us. Go through the trouble
172 /// to force this back.
173 static void forceRenaming(GlobalValue *GV, StringRef Name) {
174 // If the global doesn't force its name or if it already has the right name,
175 // there is nothing for us to do.
176 // Note that any required local to global promotion should already be done,
177 // so promoted locals will not skip this handling as their linkage is no
179 if (GV->hasLocalLinkage() || GV->getName() == Name)
182 Module *M = GV->getParent();
184 // If there is a conflict, rename the conflict.
185 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
186 GV->takeName(ConflictGV);
187 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
188 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
190 GV->setName(Name); // Force the name back
194 /// copy additional attributes (those not needed to construct a GlobalValue)
195 /// from the SrcGV to the DestGV.
196 void ModuleLinker::copyGVAttributes(GlobalValue *NewGV,
197 const GlobalValue *SrcGV) {
198 NewGV->copyAttributesFrom(SrcGV);
199 forceRenaming(NewGV, getName(SrcGV));
202 bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
203 if (!isPerformingImport())
205 auto *GA = dyn_cast<GlobalAlias>(SGV);
207 if (GA->hasWeakAnyLinkage())
209 const GlobalObject *GO = GA->getBaseObject();
210 if (!GO->hasLinkOnceODRLinkage())
212 return doImportAsDefinition(GO);
214 // Always import GlobalVariable definitions, except for the special
215 // case of WeakAny which are imported as ExternalWeak declarations
216 // (see comments in ModuleLinker::getLinkage). The linkage changes
217 // described in ModuleLinker::getLinkage ensure the correct behavior (e.g.
218 // global variables with external linkage are transformed to
219 // available_externally definitions, which are ultimately turned into
220 // declarations after the EliminateAvailableExternally pass).
221 if (isa<GlobalVariable>(SGV) && !SGV->isDeclaration() &&
222 !SGV->hasWeakAnyLinkage())
224 // Only import the function requested for importing.
225 auto *SF = dyn_cast<Function>(SGV);
226 if (SF && ImportFunction->count(SF))
232 bool ModuleLinker::doPromoteLocalToGlobal(const GlobalValue *SGV) {
233 assert(SGV->hasLocalLinkage());
234 // Both the imported references and the original local variable must
236 if (!isPerformingImport() && !isModuleExporting())
239 // Local const variables never need to be promoted unless they are address
240 // taken. The imported uses can simply use the clone created in this module.
241 // For now we are conservative in determining which variables are not
242 // address taken by checking the unnamed addr flag. To be more aggressive,
243 // the address taken information must be checked earlier during parsing
244 // of the module and recorded in the function index for use when importing
246 auto *GVar = dyn_cast<GlobalVariable>(SGV);
247 if (GVar && GVar->isConstant() && GVar->hasUnnamedAddr())
250 // Eventually we only need to promote functions in the exporting module that
251 // are referenced by a potentially exported function (i.e. one that is in the
256 std::string ModuleLinker::getName(const GlobalValue *SGV) {
257 // For locals that must be promoted to global scope, ensure that
258 // the promoted name uniquely identifies the copy in the original module,
259 // using the ID assigned during combined index creation. When importing,
260 // we rename all locals (not just those that are promoted) in order to
261 // avoid naming conflicts between locals imported from different modules.
262 if (SGV->hasLocalLinkage() &&
263 (doPromoteLocalToGlobal(SGV) || isPerformingImport()))
264 return FunctionInfoIndex::getGlobalNameForLocal(
266 ImportIndex->getModuleId(SGV->getParent()->getModuleIdentifier()));
267 return SGV->getName();
270 GlobalValue::LinkageTypes ModuleLinker::getLinkage(const GlobalValue *SGV) {
271 // Any local variable that is referenced by an exported function needs
272 // to be promoted to global scope. Since we don't currently know which
273 // functions reference which local variables/functions, we must treat
274 // all as potentially exported if this module is exporting anything.
275 if (isModuleExporting()) {
276 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
277 return GlobalValue::ExternalLinkage;
278 return SGV->getLinkage();
281 // Otherwise, if we aren't importing, no linkage change is needed.
282 if (!isPerformingImport())
283 return SGV->getLinkage();
285 switch (SGV->getLinkage()) {
286 case GlobalValue::ExternalLinkage:
287 // External defnitions are converted to available_externally
288 // definitions upon import, so that they are available for inlining
289 // and/or optimization, but are turned into declarations later
290 // during the EliminateAvailableExternally pass.
291 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
292 return GlobalValue::AvailableExternallyLinkage;
293 // An imported external declaration stays external.
294 return SGV->getLinkage();
296 case GlobalValue::AvailableExternallyLinkage:
297 // An imported available_externally definition converts
298 // to external if imported as a declaration.
299 if (!doImportAsDefinition(SGV))
300 return GlobalValue::ExternalLinkage;
301 // An imported available_externally declaration stays that way.
302 return SGV->getLinkage();
304 case GlobalValue::LinkOnceAnyLinkage:
305 case GlobalValue::LinkOnceODRLinkage:
306 // These both stay the same when importing the definition.
307 // The ThinLTO pass will eventually force-import their definitions.
308 return SGV->getLinkage();
310 case GlobalValue::WeakAnyLinkage:
311 // Can't import weak_any definitions correctly, or we might change the
312 // program semantics, since the linker will pick the first weak_any
313 // definition and importing would change the order they are seen by the
314 // linker. The module linking caller needs to enforce this.
315 assert(!doImportAsDefinition(SGV));
316 // If imported as a declaration, it becomes external_weak.
317 return GlobalValue::ExternalWeakLinkage;
319 case GlobalValue::WeakODRLinkage:
320 // For weak_odr linkage, there is a guarantee that all copies will be
321 // equivalent, so the issue described above for weak_any does not exist,
322 // and the definition can be imported. It can be treated similarly
323 // to an imported externally visible global value.
324 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
325 return GlobalValue::AvailableExternallyLinkage;
327 return GlobalValue::ExternalLinkage;
329 case GlobalValue::AppendingLinkage:
330 // It would be incorrect to import an appending linkage variable,
331 // since it would cause global constructors/destructors to be
332 // executed multiple times. This should have already been handled
333 // by linkIfNeeded, and we will assert in shouldLinkFromSource
334 // if we try to import, so we simply return AppendingLinkage here
335 // as this helper is called more widely in getLinkedToGlobal.
336 return GlobalValue::AppendingLinkage;
338 case GlobalValue::InternalLinkage:
339 case GlobalValue::PrivateLinkage:
340 // If we are promoting the local to global scope, it is handled
341 // similarly to a normal externally visible global.
342 if (doPromoteLocalToGlobal(SGV)) {
343 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
344 return GlobalValue::AvailableExternallyLinkage;
346 return GlobalValue::ExternalLinkage;
348 // A non-promoted imported local definition stays local.
349 // The ThinLTO pass will eventually force-import their definitions.
350 return SGV->getLinkage();
352 case GlobalValue::ExternalWeakLinkage:
353 // External weak doesn't apply to definitions, must be a declaration.
354 assert(!doImportAsDefinition(SGV));
355 // Linkage stays external_weak.
356 return SGV->getLinkage();
358 case GlobalValue::CommonLinkage:
359 // Linkage stays common on definitions.
360 // The ThinLTO pass will eventually force-import their definitions.
361 return SGV->getLinkage();
364 llvm_unreachable("unknown linkage type");
367 static GlobalValue::VisibilityTypes
368 getMinVisibility(GlobalValue::VisibilityTypes A,
369 GlobalValue::VisibilityTypes B) {
370 if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
371 return GlobalValue::HiddenVisibility;
372 if (A == GlobalValue::ProtectedVisibility ||
373 B == GlobalValue::ProtectedVisibility)
374 return GlobalValue::ProtectedVisibility;
375 return GlobalValue::DefaultVisibility;
378 void ModuleLinker::setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
379 const GlobalValue *DGV) {
380 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
382 Visibility = getMinVisibility(DGV->getVisibility(), Visibility);
383 // For promoted locals, mark them hidden so that they can later be
384 // stripped from the symbol table to reduce bloat.
385 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
386 Visibility = GlobalValue::HiddenVisibility;
387 NewGV->setVisibility(Visibility);
390 bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
391 const GlobalVariable *&GVar) {
392 const GlobalValue *GVal = M.getNamedValue(ComdatName);
393 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
394 GVal = GA->getBaseObject();
396 // We cannot resolve the size of the aliasee yet.
397 return emitError("Linking COMDATs named '" + ComdatName +
398 "': COMDAT key involves incomputable alias size.");
401 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
404 "Linking COMDATs named '" + ComdatName +
405 "': GlobalVariable required for data dependent selection!");
410 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
411 Comdat::SelectionKind Src,
412 Comdat::SelectionKind Dst,
413 Comdat::SelectionKind &Result,
415 Module &DstM = Mover.getModule();
416 // The ability to mix Comdat::SelectionKind::Any with
417 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
418 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
419 Dst == Comdat::SelectionKind::Largest;
420 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
421 Src == Comdat::SelectionKind::Largest;
422 if (DstAnyOrLargest && SrcAnyOrLargest) {
423 if (Dst == Comdat::SelectionKind::Largest ||
424 Src == Comdat::SelectionKind::Largest)
425 Result = Comdat::SelectionKind::Largest;
427 Result = Comdat::SelectionKind::Any;
428 } else if (Src == Dst) {
431 return emitError("Linking COMDATs named '" + ComdatName +
432 "': invalid selection kinds!");
436 case Comdat::SelectionKind::Any:
440 case Comdat::SelectionKind::NoDuplicates:
441 return emitError("Linking COMDATs named '" + ComdatName +
442 "': noduplicates has been violated!");
443 case Comdat::SelectionKind::ExactMatch:
444 case Comdat::SelectionKind::Largest:
445 case Comdat::SelectionKind::SameSize: {
446 const GlobalVariable *DstGV;
447 const GlobalVariable *SrcGV;
448 if (getComdatLeader(DstM, ComdatName, DstGV) ||
449 getComdatLeader(SrcM, ComdatName, SrcGV))
452 const DataLayout &DstDL = DstM.getDataLayout();
453 const DataLayout &SrcDL = SrcM.getDataLayout();
455 DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
457 SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
458 if (Result == Comdat::SelectionKind::ExactMatch) {
459 if (SrcGV->getInitializer() != DstGV->getInitializer())
460 return emitError("Linking COMDATs named '" + ComdatName +
461 "': ExactMatch violated!");
463 } else if (Result == Comdat::SelectionKind::Largest) {
464 LinkFromSrc = SrcSize > DstSize;
465 } else if (Result == Comdat::SelectionKind::SameSize) {
466 if (SrcSize != DstSize)
467 return emitError("Linking COMDATs named '" + ComdatName +
468 "': SameSize violated!");
471 llvm_unreachable("unknown selection kind");
480 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
481 Comdat::SelectionKind &Result,
483 Module &DstM = Mover.getModule();
484 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
485 StringRef ComdatName = SrcC->getName();
486 Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
487 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
489 if (DstCI == ComdatSymTab.end()) {
490 // Use the comdat if it is only available in one of the modules.
496 const Comdat *DstC = &DstCI->second;
497 Comdat::SelectionKind DSK = DstC->getSelectionKind();
498 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
502 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
503 const GlobalValue &Dest,
504 const GlobalValue &Src) {
505 // Should we unconditionally use the Src?
506 if (shouldOverrideFromSrc()) {
511 // We always have to add Src if it has appending linkage.
512 if (Src.hasAppendingLinkage()) {
513 // Should have prevented importing for appending linkage in linkIfNeeded.
514 assert(!isPerformingImport());
519 bool SrcIsDeclaration = Src.isDeclarationForLinker();
520 bool DestIsDeclaration = Dest.isDeclarationForLinker();
522 if (isPerformingImport()) {
523 if (isa<Function>(&Src)) {
524 // For functions, LinkFromSrc iff this is the function requested
525 // for importing. For variables, decide below normally.
526 LinkFromSrc = ImportFunction->count(&Src);
530 // Check if this is an alias with an already existing definition
531 // in Dest, which must have come from a prior importing pass from
532 // the same Src module. Unlike imported function and variable
533 // definitions, which are imported as available_externally and are
534 // not definitions for the linker, that is not a valid linkage for
535 // imported aliases which must be definitions. Simply use the existing
537 if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
538 assert(isa<GlobalAlias>(&Dest));
544 if (SrcIsDeclaration) {
545 // If Src is external or if both Src & Dest are external.. Just link the
546 // external globals, we aren't adding anything.
547 if (Src.hasDLLImportStorageClass()) {
548 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
549 LinkFromSrc = DestIsDeclaration;
552 // If the Dest is weak, use the source linkage.
553 if (Dest.hasExternalWeakLinkage()) {
557 // Link an available_externally over a declaration.
558 LinkFromSrc = !Src.isDeclaration() && Dest.isDeclaration();
562 if (DestIsDeclaration) {
563 // If Dest is external but Src is not:
568 if (Src.hasCommonLinkage()) {
569 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
574 if (!Dest.hasCommonLinkage()) {
579 const DataLayout &DL = Dest.getParent()->getDataLayout();
580 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
581 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
582 LinkFromSrc = SrcSize > DestSize;
586 if (Src.isWeakForLinker()) {
587 assert(!Dest.hasExternalWeakLinkage());
588 assert(!Dest.hasAvailableExternallyLinkage());
590 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
599 if (Dest.isWeakForLinker()) {
600 assert(Src.hasExternalLinkage());
605 assert(!Src.hasExternalWeakLinkage());
606 assert(!Dest.hasExternalWeakLinkage());
607 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
608 "Unexpected linkage type!");
609 return emitError("Linking globals named '" + Src.getName() +
610 "': symbol multiply defined!");
613 bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
614 GlobalValue *DGV = getLinkedToGlobal(&GV);
616 if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
619 if (DGV && !GV.hasLocalLinkage() && !GV.hasAppendingLinkage()) {
620 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
621 auto *SGVar = dyn_cast<GlobalVariable>(&GV);
622 if (DGVar && SGVar) {
623 if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
624 (!DGVar->isConstant() || !SGVar->isConstant())) {
625 DGVar->setConstant(false);
626 SGVar->setConstant(false);
628 if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
629 unsigned Align = std::max(DGVar->getAlignment(), SGVar->getAlignment());
630 SGVar->setAlignment(Align);
631 DGVar->setAlignment(Align);
635 GlobalValue::VisibilityTypes Visibility =
636 getMinVisibility(DGV->getVisibility(), GV.getVisibility());
637 DGV->setVisibility(Visibility);
638 GV.setVisibility(Visibility);
640 bool HasUnnamedAddr = GV.hasUnnamedAddr() && DGV->hasUnnamedAddr();
641 DGV->setUnnamedAddr(HasUnnamedAddr);
642 GV.setUnnamedAddr(HasUnnamedAddr);
645 // Don't want to append to global_ctors list, for example, when we
646 // are importing for ThinLTO, otherwise the global ctors and dtors
647 // get executed multiple times for local variables (the latter causing
649 if (GV.hasAppendingLinkage() && isPerformingImport())
652 if (isPerformingImport() && !doImportAsDefinition(&GV))
655 if (!DGV && !shouldOverrideFromSrc() &&
656 (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
657 GV.hasAvailableExternallyLinkage()))
660 if (GV.isDeclaration())
663 if (const Comdat *SC = GV.getComdat()) {
665 Comdat::SelectionKind SK;
666 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
668 ValuesToLink.insert(&GV);
672 bool LinkFromSrc = true;
673 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
676 ValuesToLink.insert(&GV);
680 void ModuleLinker::addLazyFor(GlobalValue &GV, IRMover::ValueAdder Add) {
681 // Add these to the internalize list
682 if (!GV.hasLinkOnceLinkage())
685 if (shouldInternalizeLinkedSymbols())
686 Internalize.insert(GV.getName());
689 const Comdat *SC = GV.getComdat();
692 for (GlobalValue *GV2 : ComdatMembers[SC]) {
693 if (!GV2->hasLocalLinkage() && shouldInternalizeLinkedSymbols())
694 Internalize.insert(GV2->getName());
699 void ModuleLinker::processGlobalForThinLTO(GlobalValue &GV) {
700 if (GV.hasLocalLinkage() &&
701 (doPromoteLocalToGlobal(&GV) || isPerformingImport())) {
702 GV.setName(getName(&GV));
703 GV.setLinkage(getLinkage(&GV));
704 if (!GV.hasLocalLinkage())
705 GV.setVisibility(GlobalValue::HiddenVisibility);
706 if (isModuleExporting())
707 ValuesToLink.insert(&GV);
710 GV.setLinkage(getLinkage(&GV));
713 void ModuleLinker::processGlobalsForThinLTO() {
714 for (GlobalVariable &GV : SrcM.globals())
715 processGlobalForThinLTO(GV);
716 for (Function &SF : SrcM)
717 processGlobalForThinLTO(SF);
718 for (GlobalAlias &GA : SrcM.aliases())
719 processGlobalForThinLTO(GA);
722 bool ModuleLinker::run() {
723 for (const auto &SMEC : SrcM.getComdatSymbolTable()) {
724 const Comdat &C = SMEC.getValue();
725 if (ComdatsChosen.count(&C))
727 Comdat::SelectionKind SK;
729 if (getComdatResult(&C, SK, LinkFromSrc))
731 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
734 for (GlobalVariable &GV : SrcM.globals())
735 if (const Comdat *SC = GV.getComdat())
736 ComdatMembers[SC].push_back(&GV);
738 for (Function &SF : SrcM)
739 if (const Comdat *SC = SF.getComdat())
740 ComdatMembers[SC].push_back(&SF);
742 for (GlobalAlias &GA : SrcM.aliases())
743 if (const Comdat *SC = GA.getComdat())
744 ComdatMembers[SC].push_back(&GA);
746 // Insert all of the globals in src into the DstM module... without linking
747 // initializers (which could refer to functions not yet mapped over).
748 for (GlobalVariable &GV : SrcM.globals())
749 if (linkIfNeeded(GV))
752 for (Function &SF : SrcM)
753 if (linkIfNeeded(SF))
756 for (GlobalAlias &GA : SrcM.aliases())
757 if (linkIfNeeded(GA))
760 processGlobalsForThinLTO();
762 for (unsigned I = 0; I < ValuesToLink.size(); ++I) {
763 GlobalValue *GV = ValuesToLink[I];
764 const Comdat *SC = GV->getComdat();
767 for (GlobalValue *GV2 : ComdatMembers[SC])
768 ValuesToLink.insert(GV2);
771 if (shouldInternalizeLinkedSymbols()) {
772 for (GlobalValue *GV : ValuesToLink)
773 Internalize.insert(GV->getName());
776 if (Mover.move(SrcM, ValuesToLink.getArrayRef(),
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) : Mover(M) {}
792 bool Linker::linkInModule(std::unique_ptr<Module> Src, unsigned Flags,
793 const FunctionInfoIndex *Index,
794 DenseSet<const GlobalValue *> *FunctionsToImport) {
795 ModuleLinker TheLinker(Mover, *Src, Flags, Index, FunctionsToImport);
796 return TheLinker.run();
799 bool Linker::linkInModuleForCAPI(Module &Src) {
800 ModuleLinker TheLinker(Mover, Src, 0, nullptr, nullptr);
801 return TheLinker.run();
804 //===----------------------------------------------------------------------===//
805 // LinkModules entrypoint.
806 //===----------------------------------------------------------------------===//
808 /// This function links two modules together, with the resulting Dest module
809 /// modified to be the composite of the two input modules. If an error occurs,
810 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
811 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
812 /// relied on to be consistent.
813 bool Linker::linkModules(Module &Dest, std::unique_ptr<Module> Src,
816 return L.linkInModule(std::move(Src), Flags);
819 std::unique_ptr<Module>
820 llvm::renameModuleForThinLTO(std::unique_ptr<Module> M,
821 const FunctionInfoIndex *Index) {
822 std::unique_ptr<llvm::Module> RenamedModule(
823 new llvm::Module(M->getModuleIdentifier(), M->getContext()));
824 Linker L(*RenamedModule.get());
825 if (L.linkInModule(std::move(M), llvm::Linker::Flags::None, Index))
827 return RenamedModule;
830 //===----------------------------------------------------------------------===//
832 //===----------------------------------------------------------------------===//
834 static void diagnosticHandler(const DiagnosticInfo &DI, void *C) {
835 auto *Message = reinterpret_cast<std::string *>(C);
836 raw_string_ostream Stream(*Message);
837 DiagnosticPrinterRawOStream DP(Stream);
841 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
842 LLVMLinkerMode Unused, char **OutMessages) {
843 Module *D = unwrap(Dest);
844 LLVMContext &Ctx = D->getContext();
846 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
847 Ctx.getDiagnosticHandler();
848 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
850 Ctx.setDiagnosticHandler(diagnosticHandler, &Message, true);
853 Module *M = unwrap(Src);
854 LLVMBool Result = L.linkInModuleForCAPI(*M);
856 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext, true);
858 if (OutMessages && Result)
859 *OutMessages = strdup(Message.c_str());
863 LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src) {
864 Module *D = unwrap(Dest);
865 std::unique_ptr<Module> M(unwrap(Src));
866 return Linker::linkModules(*D, std::move(M));