LinkModules.cpp 21 KB

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