LinkModules.cpp 20 KB

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