xref: /freebsd/contrib/llvm-project/llvm/lib/Linker/LinkModules.cpp (revision 5956d97f4b3204318ceb6aa9c77bd0bc6ea87a41)
1 //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the LLVM module linker.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "LinkDiagnosticInfo.h"
14 #include "llvm-c/Linker.h"
15 #include "llvm/ADT/SetVector.h"
16 #include "llvm/IR/Comdat.h"
17 #include "llvm/IR/DiagnosticPrinter.h"
18 #include "llvm/IR/GlobalValue.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/Linker/Linker.h"
22 #include "llvm/Support/Error.h"
23 using namespace llvm;
24 
25 namespace {
26 
27 enum class LinkFrom { Dst, Src, Both };
28 
29 /// This is an implementation class for the LinkModules function, which is the
30 /// entrypoint for this file.
31 class ModuleLinker {
32   IRMover &Mover;
33   std::unique_ptr<Module> SrcM;
34 
35   SetVector<GlobalValue *> ValuesToLink;
36 
37   /// For symbol clashes, prefer those from Src.
38   unsigned Flags;
39 
40   /// List of global value names that should be internalized.
41   StringSet<> Internalize;
42 
43   /// Function that will perform the actual internalization. The reason for a
44   /// callback is that the linker cannot call internalizeModule without
45   /// creating a circular dependency between IPO and the linker.
46   std::function<void(Module &, const StringSet<> &)> InternalizeCallback;
47 
48   /// Used as the callback for lazy linking.
49   /// The mover has just hit GV and we have to decide if it, and other members
50   /// of the same comdat, should be linked. Every member to be linked is passed
51   /// to Add.
52   void addLazyFor(GlobalValue &GV, const IRMover::ValueAdder &Add);
53 
54   bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
55   bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
56 
57   bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
58                             const GlobalValue &Src);
59 
60   /// Should we have mover and linker error diag info?
61   bool emitError(const Twine &Message) {
62     SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
63     return true;
64   }
65 
66   bool getComdatLeader(Module &M, StringRef ComdatName,
67                        const GlobalVariable *&GVar);
68   bool computeResultingSelectionKind(StringRef ComdatName,
69                                      Comdat::SelectionKind Src,
70                                      Comdat::SelectionKind Dst,
71                                      Comdat::SelectionKind &Result,
72                                      LinkFrom &From);
73   DenseMap<const Comdat *, std::pair<Comdat::SelectionKind, LinkFrom>>
74       ComdatsChosen;
75   bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
76                        LinkFrom &From);
77   // Keep track of the lazy linked global members of each comdat in source.
78   DenseMap<const Comdat *, std::vector<GlobalValue *>> LazyComdatMembers;
79 
80   /// Given a global in the source module, return the global in the
81   /// destination module that is being linked to, if any.
82   GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
83     Module &DstM = Mover.getModule();
84     // If the source has no name it can't link.  If it has local linkage,
85     // there is no name match-up going on.
86     if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(SrcGV->getLinkage()))
87       return nullptr;
88 
89     // Otherwise see if we have a match in the destination module's symtab.
90     GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
91     if (!DGV)
92       return nullptr;
93 
94     // If we found a global with the same name in the dest module, but it has
95     // internal linkage, we are really not doing any linkage here.
96     if (DGV->hasLocalLinkage())
97       return nullptr;
98 
99     // Otherwise, we do in fact link to the destination global.
100     return DGV;
101   }
102 
103   /// Drop GV if it is a member of a comdat that we are dropping.
104   /// This can happen with COFF's largest selection kind.
105   void dropReplacedComdat(GlobalValue &GV,
106                           const DenseSet<const Comdat *> &ReplacedDstComdats);
107 
108   bool linkIfNeeded(GlobalValue &GV, SmallVectorImpl<GlobalValue *> &GVToClone);
109 
110 public:
111   ModuleLinker(IRMover &Mover, std::unique_ptr<Module> SrcM, unsigned Flags,
112                std::function<void(Module &, const StringSet<> &)>
113                    InternalizeCallback = {})
114       : Mover(Mover), SrcM(std::move(SrcM)), Flags(Flags),
115         InternalizeCallback(std::move(InternalizeCallback)) {}
116 
117   bool run();
118 };
119 } // namespace
120 
121 static GlobalValue::VisibilityTypes
122 getMinVisibility(GlobalValue::VisibilityTypes A,
123                  GlobalValue::VisibilityTypes B) {
124   if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
125     return GlobalValue::HiddenVisibility;
126   if (A == GlobalValue::ProtectedVisibility ||
127       B == GlobalValue::ProtectedVisibility)
128     return GlobalValue::ProtectedVisibility;
129   return GlobalValue::DefaultVisibility;
130 }
131 
132 bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
133                                    const GlobalVariable *&GVar) {
134   const GlobalValue *GVal = M.getNamedValue(ComdatName);
135   if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
136     GVal = GA->getAliaseeObject();
137     if (!GVal)
138       // We cannot resolve the size of the aliasee yet.
139       return emitError("Linking COMDATs named '" + ComdatName +
140                        "': COMDAT key involves incomputable alias size.");
141   }
142 
143   GVar = dyn_cast_or_null<GlobalVariable>(GVal);
144   if (!GVar)
145     return emitError(
146         "Linking COMDATs named '" + ComdatName +
147         "': GlobalVariable required for data dependent selection!");
148 
149   return false;
150 }
151 
152 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
153                                                  Comdat::SelectionKind Src,
154                                                  Comdat::SelectionKind Dst,
155                                                  Comdat::SelectionKind &Result,
156                                                  LinkFrom &From) {
157   Module &DstM = Mover.getModule();
158   // The ability to mix Comdat::SelectionKind::Any with
159   // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
160   bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
161                          Dst == Comdat::SelectionKind::Largest;
162   bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
163                          Src == Comdat::SelectionKind::Largest;
164   if (DstAnyOrLargest && SrcAnyOrLargest) {
165     if (Dst == Comdat::SelectionKind::Largest ||
166         Src == Comdat::SelectionKind::Largest)
167       Result = Comdat::SelectionKind::Largest;
168     else
169       Result = Comdat::SelectionKind::Any;
170   } else if (Src == Dst) {
171     Result = Dst;
172   } else {
173     return emitError("Linking COMDATs named '" + ComdatName +
174                      "': invalid selection kinds!");
175   }
176 
177   switch (Result) {
178   case Comdat::SelectionKind::Any:
179     // Go with Dst.
180     From = LinkFrom::Dst;
181     break;
182   case Comdat::SelectionKind::NoDeduplicate:
183     From = LinkFrom::Both;
184     break;
185   case Comdat::SelectionKind::ExactMatch:
186   case Comdat::SelectionKind::Largest:
187   case Comdat::SelectionKind::SameSize: {
188     const GlobalVariable *DstGV;
189     const GlobalVariable *SrcGV;
190     if (getComdatLeader(DstM, ComdatName, DstGV) ||
191         getComdatLeader(*SrcM, ComdatName, SrcGV))
192       return true;
193 
194     const DataLayout &DstDL = DstM.getDataLayout();
195     const DataLayout &SrcDL = SrcM->getDataLayout();
196     uint64_t DstSize = DstDL.getTypeAllocSize(DstGV->getValueType());
197     uint64_t SrcSize = SrcDL.getTypeAllocSize(SrcGV->getValueType());
198     if (Result == Comdat::SelectionKind::ExactMatch) {
199       if (SrcGV->getInitializer() != DstGV->getInitializer())
200         return emitError("Linking COMDATs named '" + ComdatName +
201                          "': ExactMatch violated!");
202       From = LinkFrom::Dst;
203     } else if (Result == Comdat::SelectionKind::Largest) {
204       From = SrcSize > DstSize ? LinkFrom::Src : LinkFrom::Dst;
205     } else if (Result == Comdat::SelectionKind::SameSize) {
206       if (SrcSize != DstSize)
207         return emitError("Linking COMDATs named '" + ComdatName +
208                          "': SameSize violated!");
209       From = LinkFrom::Dst;
210     } else {
211       llvm_unreachable("unknown selection kind");
212     }
213     break;
214   }
215   }
216 
217   return false;
218 }
219 
220 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
221                                    Comdat::SelectionKind &Result,
222                                    LinkFrom &From) {
223   Module &DstM = Mover.getModule();
224   Comdat::SelectionKind SSK = SrcC->getSelectionKind();
225   StringRef ComdatName = SrcC->getName();
226   Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
227   Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
228 
229   if (DstCI == ComdatSymTab.end()) {
230     // Use the comdat if it is only available in one of the modules.
231     From = LinkFrom::Src;
232     Result = SSK;
233     return false;
234   }
235 
236   const Comdat *DstC = &DstCI->second;
237   Comdat::SelectionKind DSK = DstC->getSelectionKind();
238   return computeResultingSelectionKind(ComdatName, SSK, DSK, Result, From);
239 }
240 
241 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
242                                         const GlobalValue &Dest,
243                                         const GlobalValue &Src) {
244 
245   // Should we unconditionally use the Src?
246   if (shouldOverrideFromSrc()) {
247     LinkFromSrc = true;
248     return false;
249   }
250 
251   // We always have to add Src if it has appending linkage.
252   if (Src.hasAppendingLinkage() || Dest.hasAppendingLinkage()) {
253     LinkFromSrc = true;
254     return false;
255   }
256 
257   bool SrcIsDeclaration = Src.isDeclarationForLinker();
258   bool DestIsDeclaration = Dest.isDeclarationForLinker();
259 
260   if (SrcIsDeclaration) {
261     // If Src is external or if both Src & Dest are external..  Just link the
262     // external globals, we aren't adding anything.
263     if (Src.hasDLLImportStorageClass()) {
264       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
265       LinkFromSrc = DestIsDeclaration;
266       return false;
267     }
268     // If the Dest is weak, use the source linkage.
269     if (Dest.hasExternalWeakLinkage()) {
270       LinkFromSrc = true;
271       return false;
272     }
273     // Link an available_externally over a declaration.
274     LinkFromSrc = !Src.isDeclaration() && Dest.isDeclaration();
275     return false;
276   }
277 
278   if (DestIsDeclaration) {
279     // If Dest is external but Src is not:
280     LinkFromSrc = true;
281     return false;
282   }
283 
284   if (Src.hasCommonLinkage()) {
285     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
286       LinkFromSrc = true;
287       return false;
288     }
289 
290     if (!Dest.hasCommonLinkage()) {
291       LinkFromSrc = false;
292       return false;
293     }
294 
295     const DataLayout &DL = Dest.getParent()->getDataLayout();
296     uint64_t DestSize = DL.getTypeAllocSize(Dest.getValueType());
297     uint64_t SrcSize = DL.getTypeAllocSize(Src.getValueType());
298     LinkFromSrc = SrcSize > DestSize;
299     return false;
300   }
301 
302   if (Src.isWeakForLinker()) {
303     assert(!Dest.hasExternalWeakLinkage());
304     assert(!Dest.hasAvailableExternallyLinkage());
305 
306     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
307       LinkFromSrc = true;
308       return false;
309     }
310 
311     LinkFromSrc = false;
312     return false;
313   }
314 
315   if (Dest.isWeakForLinker()) {
316     assert(Src.hasExternalLinkage());
317     LinkFromSrc = true;
318     return false;
319   }
320 
321   assert(!Src.hasExternalWeakLinkage());
322   assert(!Dest.hasExternalWeakLinkage());
323   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
324          "Unexpected linkage type!");
325   return emitError("Linking globals named '" + Src.getName() +
326                    "': symbol multiply defined!");
327 }
328 
329 bool ModuleLinker::linkIfNeeded(GlobalValue &GV,
330                                 SmallVectorImpl<GlobalValue *> &GVToClone) {
331   GlobalValue *DGV = getLinkedToGlobal(&GV);
332 
333   if (shouldLinkOnlyNeeded()) {
334     // Always import variables with appending linkage.
335     if (!GV.hasAppendingLinkage()) {
336       // Don't import globals unless they are referenced by the destination
337       // module.
338       if (!DGV)
339         return false;
340       // Don't import globals that are already defined in the destination module
341       if (!DGV->isDeclaration())
342         return false;
343     }
344   }
345 
346   if (DGV && !GV.hasLocalLinkage() && !GV.hasAppendingLinkage()) {
347     auto *DGVar = dyn_cast<GlobalVariable>(DGV);
348     auto *SGVar = dyn_cast<GlobalVariable>(&GV);
349     if (DGVar && SGVar) {
350       if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
351           (!DGVar->isConstant() || !SGVar->isConstant())) {
352         DGVar->setConstant(false);
353         SGVar->setConstant(false);
354       }
355       if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
356         MaybeAlign Align(
357             std::max(DGVar->getAlignment(), SGVar->getAlignment()));
358         SGVar->setAlignment(Align);
359         DGVar->setAlignment(Align);
360       }
361     }
362 
363     GlobalValue::VisibilityTypes Visibility =
364         getMinVisibility(DGV->getVisibility(), GV.getVisibility());
365     DGV->setVisibility(Visibility);
366     GV.setVisibility(Visibility);
367 
368     GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::getMinUnnamedAddr(
369         DGV->getUnnamedAddr(), GV.getUnnamedAddr());
370     DGV->setUnnamedAddr(UnnamedAddr);
371     GV.setUnnamedAddr(UnnamedAddr);
372   }
373 
374   if (!DGV && !shouldOverrideFromSrc() &&
375       (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
376        GV.hasAvailableExternallyLinkage()))
377     return false;
378 
379   if (GV.isDeclaration())
380     return false;
381 
382   LinkFrom ComdatFrom = LinkFrom::Dst;
383   if (const Comdat *SC = GV.getComdat()) {
384     std::tie(std::ignore, ComdatFrom) = ComdatsChosen[SC];
385     if (ComdatFrom == LinkFrom::Dst)
386       return false;
387   }
388 
389   bool LinkFromSrc = true;
390   if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
391     return true;
392   if (DGV && ComdatFrom == LinkFrom::Both)
393     GVToClone.push_back(LinkFromSrc ? DGV : &GV);
394   if (LinkFromSrc)
395     ValuesToLink.insert(&GV);
396   return false;
397 }
398 
399 void ModuleLinker::addLazyFor(GlobalValue &GV, const IRMover::ValueAdder &Add) {
400   // Add these to the internalize list
401   if (!GV.hasLinkOnceLinkage() && !GV.hasAvailableExternallyLinkage() &&
402       !shouldLinkOnlyNeeded())
403     return;
404 
405   if (InternalizeCallback)
406     Internalize.insert(GV.getName());
407   Add(GV);
408 
409   const Comdat *SC = GV.getComdat();
410   if (!SC)
411     return;
412   for (GlobalValue *GV2 : LazyComdatMembers[SC]) {
413     GlobalValue *DGV = getLinkedToGlobal(GV2);
414     bool LinkFromSrc = true;
415     if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
416       return;
417     if (!LinkFromSrc)
418       continue;
419     if (InternalizeCallback)
420       Internalize.insert(GV2->getName());
421     Add(*GV2);
422   }
423 }
424 
425 void ModuleLinker::dropReplacedComdat(
426     GlobalValue &GV, const DenseSet<const Comdat *> &ReplacedDstComdats) {
427   Comdat *C = GV.getComdat();
428   if (!C)
429     return;
430   if (!ReplacedDstComdats.count(C))
431     return;
432   if (GV.use_empty()) {
433     GV.eraseFromParent();
434     return;
435   }
436 
437   if (auto *F = dyn_cast<Function>(&GV)) {
438     F->deleteBody();
439   } else if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
440     Var->setInitializer(nullptr);
441   } else {
442     auto &Alias = cast<GlobalAlias>(GV);
443     Module &M = *Alias.getParent();
444     GlobalValue *Declaration;
445     if (auto *FTy = dyn_cast<FunctionType>(Alias.getValueType())) {
446       Declaration = Function::Create(FTy, GlobalValue::ExternalLinkage, "", &M);
447     } else {
448       Declaration =
449           new GlobalVariable(M, Alias.getValueType(), /*isConstant*/ false,
450                              GlobalValue::ExternalLinkage,
451                              /*Initializer*/ nullptr);
452     }
453     Declaration->takeName(&Alias);
454     Alias.replaceAllUsesWith(Declaration);
455     Alias.eraseFromParent();
456   }
457 }
458 
459 bool ModuleLinker::run() {
460   Module &DstM = Mover.getModule();
461   DenseSet<const Comdat *> ReplacedDstComdats;
462 
463   for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
464     const Comdat &C = SMEC.getValue();
465     if (ComdatsChosen.count(&C))
466       continue;
467     Comdat::SelectionKind SK;
468     LinkFrom From;
469     if (getComdatResult(&C, SK, From))
470       return true;
471     ComdatsChosen[&C] = std::make_pair(SK, From);
472 
473     if (From != LinkFrom::Src)
474       continue;
475 
476     Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
477     Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(C.getName());
478     if (DstCI == ComdatSymTab.end())
479       continue;
480 
481     // The source comdat is replacing the dest one.
482     const Comdat *DstC = &DstCI->second;
483     ReplacedDstComdats.insert(DstC);
484   }
485 
486   // Alias have to go first, since we are not able to find their comdats
487   // otherwise.
488   for (GlobalAlias &GV : llvm::make_early_inc_range(DstM.aliases()))
489     dropReplacedComdat(GV, ReplacedDstComdats);
490 
491   for (GlobalVariable &GV : llvm::make_early_inc_range(DstM.globals()))
492     dropReplacedComdat(GV, ReplacedDstComdats);
493 
494   for (Function &GV : llvm::make_early_inc_range(DstM))
495     dropReplacedComdat(GV, ReplacedDstComdats);
496 
497   for (GlobalVariable &GV : SrcM->globals())
498     if (GV.hasLinkOnceLinkage())
499       if (const Comdat *SC = GV.getComdat())
500         LazyComdatMembers[SC].push_back(&GV);
501 
502   for (Function &SF : *SrcM)
503     if (SF.hasLinkOnceLinkage())
504       if (const Comdat *SC = SF.getComdat())
505         LazyComdatMembers[SC].push_back(&SF);
506 
507   for (GlobalAlias &GA : SrcM->aliases())
508     if (GA.hasLinkOnceLinkage())
509       if (const Comdat *SC = GA.getComdat())
510         LazyComdatMembers[SC].push_back(&GA);
511 
512   // Insert all of the globals in src into the DstM module... without linking
513   // initializers (which could refer to functions not yet mapped over).
514   SmallVector<GlobalValue *, 0> GVToClone;
515   for (GlobalVariable &GV : SrcM->globals())
516     if (linkIfNeeded(GV, GVToClone))
517       return true;
518 
519   for (Function &SF : *SrcM)
520     if (linkIfNeeded(SF, GVToClone))
521       return true;
522 
523   for (GlobalAlias &GA : SrcM->aliases())
524     if (linkIfNeeded(GA, GVToClone))
525       return true;
526 
527   for (GlobalIFunc &GI : SrcM->ifuncs())
528     if (linkIfNeeded(GI, GVToClone))
529       return true;
530 
531   // For a variable in a comdat nodeduplicate, its initializer should be
532   // preserved (its content may be implicitly used by other members) even if
533   // symbol resolution does not pick it. Clone it into an unnamed private
534   // variable.
535   for (GlobalValue *GV : GVToClone) {
536     if (auto *Var = dyn_cast<GlobalVariable>(GV)) {
537       auto *NewVar = new GlobalVariable(*Var->getParent(), Var->getValueType(),
538                                         Var->isConstant(), Var->getLinkage(),
539                                         Var->getInitializer());
540       NewVar->copyAttributesFrom(Var);
541       NewVar->setVisibility(GlobalValue::DefaultVisibility);
542       NewVar->setLinkage(GlobalValue::PrivateLinkage);
543       NewVar->setDSOLocal(true);
544       NewVar->setComdat(Var->getComdat());
545       if (Var->getParent() != &Mover.getModule())
546         ValuesToLink.insert(NewVar);
547     } else {
548       emitError("linking '" + GV->getName() +
549                 "': non-variables in comdat nodeduplicate are not handled");
550     }
551   }
552 
553   for (unsigned I = 0; I < ValuesToLink.size(); ++I) {
554     GlobalValue *GV = ValuesToLink[I];
555     const Comdat *SC = GV->getComdat();
556     if (!SC)
557       continue;
558     for (GlobalValue *GV2 : LazyComdatMembers[SC]) {
559       GlobalValue *DGV = getLinkedToGlobal(GV2);
560       bool LinkFromSrc = true;
561       if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
562         return true;
563       if (LinkFromSrc)
564         ValuesToLink.insert(GV2);
565     }
566   }
567 
568   if (InternalizeCallback) {
569     for (GlobalValue *GV : ValuesToLink)
570       Internalize.insert(GV->getName());
571   }
572 
573   // FIXME: Propagate Errors through to the caller instead of emitting
574   // diagnostics.
575   bool HasErrors = false;
576   if (Error E = Mover.move(std::move(SrcM), ValuesToLink.getArrayRef(),
577                            [this](GlobalValue &GV, IRMover::ValueAdder Add) {
578                              addLazyFor(GV, Add);
579                            },
580                            /* IsPerformingImport */ false)) {
581     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
582       DstM.getContext().diagnose(LinkDiagnosticInfo(DS_Error, EIB.message()));
583       HasErrors = true;
584     });
585   }
586   if (HasErrors)
587     return true;
588 
589   if (InternalizeCallback)
590     InternalizeCallback(DstM, Internalize);
591 
592   return false;
593 }
594 
595 Linker::Linker(Module &M) : Mover(M) {}
596 
597 bool Linker::linkInModule(
598     std::unique_ptr<Module> Src, unsigned Flags,
599     std::function<void(Module &, const StringSet<> &)> InternalizeCallback) {
600   ModuleLinker ModLinker(Mover, std::move(Src), Flags,
601                          std::move(InternalizeCallback));
602   return ModLinker.run();
603 }
604 
605 //===----------------------------------------------------------------------===//
606 // LinkModules entrypoint.
607 //===----------------------------------------------------------------------===//
608 
609 /// This function links two modules together, with the resulting Dest module
610 /// modified to be the composite of the two input modules. If an error occurs,
611 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
612 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
613 /// relied on to be consistent.
614 bool Linker::linkModules(
615     Module &Dest, std::unique_ptr<Module> Src, unsigned Flags,
616     std::function<void(Module &, const StringSet<> &)> InternalizeCallback) {
617   Linker L(Dest);
618   return L.linkInModule(std::move(Src), Flags, std::move(InternalizeCallback));
619 }
620 
621 //===----------------------------------------------------------------------===//
622 // C API.
623 //===----------------------------------------------------------------------===//
624 
625 LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src) {
626   Module *D = unwrap(Dest);
627   std::unique_ptr<Module> M(unwrap(Src));
628   return Linker::linkModules(*D, std::move(M));
629 }
630