LinkModules.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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/GlobalValue.h"
  17. #include "llvm/IR/LLVMContext.h"
  18. #include "llvm/IR/Module.h"
  19. #include "llvm/Linker/Linker.h"
  20. #include "llvm/Support/Error.h"
  21. using namespace llvm;
  22. namespace {
  23. enum class LinkFrom { Dst, Src, Both };
  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. LinkFrom &From);
  59. DenseMap<const Comdat *, std::pair<Comdat::SelectionKind, LinkFrom>>
  60. ComdatsChosen;
  61. bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
  62. LinkFrom &From);
  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, SmallVectorImpl<GlobalValue *> &GVToClone);
  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. } // namespace
  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->getAliaseeObject();
  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. LinkFrom &From) {
  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. From = LinkFrom::Dst;
  153. break;
  154. case Comdat::SelectionKind::NoDeduplicate:
  155. From = LinkFrom::Both;
  156. break;
  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. From = LinkFrom::Dst;
  174. } else if (Result == Comdat::SelectionKind::Largest) {
  175. From = SrcSize > DstSize ? LinkFrom::Src : LinkFrom::Dst;
  176. } else if (Result == Comdat::SelectionKind::SameSize) {
  177. if (SrcSize != DstSize)
  178. return emitError("Linking COMDATs named '" + ComdatName +
  179. "': SameSize violated!");
  180. From = LinkFrom::Dst;
  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. LinkFrom &From) {
  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. From = LinkFrom::Src;
  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, From);
  206. }
  207. bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
  208. const GlobalValue &Dest,
  209. const GlobalValue &Src) {
  210. // Should we unconditionally use the Src?
  211. if (shouldOverrideFromSrc()) {
  212. LinkFromSrc = true;
  213. return false;
  214. }
  215. // We always have to add Src if it has appending linkage.
  216. if (Src.hasAppendingLinkage() || Dest.hasAppendingLinkage()) {
  217. LinkFromSrc = true;
  218. return false;
  219. }
  220. bool SrcIsDeclaration = Src.isDeclarationForLinker();
  221. bool DestIsDeclaration = Dest.isDeclarationForLinker();
  222. if (SrcIsDeclaration) {
  223. // If Src is external or if both Src & Dest are external.. Just link the
  224. // external globals, we aren't adding anything.
  225. if (Src.hasDLLImportStorageClass()) {
  226. // If one of GVs is marked as DLLImport, result should be dllimport'ed.
  227. LinkFromSrc = DestIsDeclaration;
  228. return false;
  229. }
  230. // If the Dest is weak, use the source linkage.
  231. if (Dest.hasExternalWeakLinkage()) {
  232. LinkFromSrc = true;
  233. return false;
  234. }
  235. // Link an available_externally over a declaration.
  236. LinkFromSrc = !Src.isDeclaration() && Dest.isDeclaration();
  237. return false;
  238. }
  239. if (DestIsDeclaration) {
  240. // If Dest is external but Src is not:
  241. LinkFromSrc = true;
  242. return false;
  243. }
  244. if (Src.hasCommonLinkage()) {
  245. if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
  246. LinkFromSrc = true;
  247. return false;
  248. }
  249. if (!Dest.hasCommonLinkage()) {
  250. LinkFromSrc = false;
  251. return false;
  252. }
  253. const DataLayout &DL = Dest.getParent()->getDataLayout();
  254. uint64_t DestSize = DL.getTypeAllocSize(Dest.getValueType());
  255. uint64_t SrcSize = DL.getTypeAllocSize(Src.getValueType());
  256. LinkFromSrc = SrcSize > DestSize;
  257. return false;
  258. }
  259. if (Src.isWeakForLinker()) {
  260. assert(!Dest.hasExternalWeakLinkage());
  261. assert(!Dest.hasAvailableExternallyLinkage());
  262. if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
  263. LinkFromSrc = true;
  264. return false;
  265. }
  266. LinkFromSrc = false;
  267. return false;
  268. }
  269. if (Dest.isWeakForLinker()) {
  270. assert(Src.hasExternalLinkage());
  271. LinkFromSrc = true;
  272. return false;
  273. }
  274. assert(!Src.hasExternalWeakLinkage());
  275. assert(!Dest.hasExternalWeakLinkage());
  276. assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
  277. "Unexpected linkage type!");
  278. return emitError("Linking globals named '" + Src.getName() +
  279. "': symbol multiply defined!");
  280. }
  281. bool ModuleLinker::linkIfNeeded(GlobalValue &GV,
  282. SmallVectorImpl<GlobalValue *> &GVToClone) {
  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 DAlign = DGVar->getAlign();
  307. MaybeAlign SAlign = SGVar->getAlign();
  308. MaybeAlign Align = std::nullopt;
  309. if (DAlign || SAlign)
  310. Align = std::max(DAlign.valueOrOne(), SAlign.valueOrOne());
  311. SGVar->setAlignment(Align);
  312. DGVar->setAlignment(Align);
  313. }
  314. }
  315. GlobalValue::VisibilityTypes Visibility =
  316. getMinVisibility(DGV->getVisibility(), GV.getVisibility());
  317. DGV->setVisibility(Visibility);
  318. GV.setVisibility(Visibility);
  319. GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::getMinUnnamedAddr(
  320. DGV->getUnnamedAddr(), GV.getUnnamedAddr());
  321. DGV->setUnnamedAddr(UnnamedAddr);
  322. GV.setUnnamedAddr(UnnamedAddr);
  323. }
  324. if (!DGV && !shouldOverrideFromSrc() &&
  325. (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
  326. GV.hasAvailableExternallyLinkage()))
  327. return false;
  328. if (GV.isDeclaration())
  329. return false;
  330. LinkFrom ComdatFrom = LinkFrom::Dst;
  331. if (const Comdat *SC = GV.getComdat()) {
  332. std::tie(std::ignore, ComdatFrom) = ComdatsChosen[SC];
  333. if (ComdatFrom == LinkFrom::Dst)
  334. return false;
  335. }
  336. bool LinkFromSrc = true;
  337. if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
  338. return true;
  339. if (DGV && ComdatFrom == LinkFrom::Both)
  340. GVToClone.push_back(LinkFromSrc ? DGV : &GV);
  341. if (LinkFromSrc)
  342. ValuesToLink.insert(&GV);
  343. return false;
  344. }
  345. void ModuleLinker::addLazyFor(GlobalValue &GV, const IRMover::ValueAdder &Add) {
  346. // Add these to the internalize list
  347. if (!GV.hasLinkOnceLinkage() && !GV.hasAvailableExternallyLinkage() &&
  348. !shouldLinkOnlyNeeded())
  349. return;
  350. if (InternalizeCallback)
  351. Internalize.insert(GV.getName());
  352. Add(GV);
  353. const Comdat *SC = GV.getComdat();
  354. if (!SC)
  355. return;
  356. for (GlobalValue *GV2 : LazyComdatMembers[SC]) {
  357. GlobalValue *DGV = getLinkedToGlobal(GV2);
  358. bool LinkFromSrc = true;
  359. if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
  360. return;
  361. if (!LinkFromSrc)
  362. continue;
  363. if (InternalizeCallback)
  364. Internalize.insert(GV2->getName());
  365. Add(*GV2);
  366. }
  367. }
  368. void ModuleLinker::dropReplacedComdat(
  369. GlobalValue &GV, const DenseSet<const Comdat *> &ReplacedDstComdats) {
  370. Comdat *C = GV.getComdat();
  371. if (!C)
  372. return;
  373. if (!ReplacedDstComdats.count(C))
  374. return;
  375. if (GV.use_empty()) {
  376. GV.eraseFromParent();
  377. return;
  378. }
  379. if (auto *F = dyn_cast<Function>(&GV)) {
  380. F->deleteBody();
  381. } else if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
  382. Var->setInitializer(nullptr);
  383. } else {
  384. auto &Alias = cast<GlobalAlias>(GV);
  385. Module &M = *Alias.getParent();
  386. GlobalValue *Declaration;
  387. if (auto *FTy = dyn_cast<FunctionType>(Alias.getValueType())) {
  388. Declaration = Function::Create(FTy, GlobalValue::ExternalLinkage, "", &M);
  389. } else {
  390. Declaration =
  391. new GlobalVariable(M, Alias.getValueType(), /*isConstant*/ false,
  392. GlobalValue::ExternalLinkage,
  393. /*Initializer*/ nullptr);
  394. }
  395. Declaration->takeName(&Alias);
  396. Alias.replaceAllUsesWith(Declaration);
  397. Alias.eraseFromParent();
  398. }
  399. }
  400. bool ModuleLinker::run() {
  401. Module &DstM = Mover.getModule();
  402. DenseSet<const Comdat *> ReplacedDstComdats;
  403. for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
  404. const Comdat &C = SMEC.getValue();
  405. if (ComdatsChosen.count(&C))
  406. continue;
  407. Comdat::SelectionKind SK;
  408. LinkFrom From;
  409. if (getComdatResult(&C, SK, From))
  410. return true;
  411. ComdatsChosen[&C] = std::make_pair(SK, From);
  412. if (From != LinkFrom::Src)
  413. continue;
  414. Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
  415. Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(C.getName());
  416. if (DstCI == ComdatSymTab.end())
  417. continue;
  418. // The source comdat is replacing the dest one.
  419. const Comdat *DstC = &DstCI->second;
  420. ReplacedDstComdats.insert(DstC);
  421. }
  422. // Alias have to go first, since we are not able to find their comdats
  423. // otherwise.
  424. for (GlobalAlias &GV : llvm::make_early_inc_range(DstM.aliases()))
  425. dropReplacedComdat(GV, ReplacedDstComdats);
  426. for (GlobalVariable &GV : llvm::make_early_inc_range(DstM.globals()))
  427. dropReplacedComdat(GV, ReplacedDstComdats);
  428. for (Function &GV : llvm::make_early_inc_range(DstM))
  429. dropReplacedComdat(GV, ReplacedDstComdats);
  430. for (GlobalVariable &GV : SrcM->globals())
  431. if (GV.hasLinkOnceLinkage())
  432. if (const Comdat *SC = GV.getComdat())
  433. LazyComdatMembers[SC].push_back(&GV);
  434. for (Function &SF : *SrcM)
  435. if (SF.hasLinkOnceLinkage())
  436. if (const Comdat *SC = SF.getComdat())
  437. LazyComdatMembers[SC].push_back(&SF);
  438. for (GlobalAlias &GA : SrcM->aliases())
  439. if (GA.hasLinkOnceLinkage())
  440. if (const Comdat *SC = GA.getComdat())
  441. LazyComdatMembers[SC].push_back(&GA);
  442. // Insert all of the globals in src into the DstM module... without linking
  443. // initializers (which could refer to functions not yet mapped over).
  444. SmallVector<GlobalValue *, 0> GVToClone;
  445. for (GlobalVariable &GV : SrcM->globals())
  446. if (linkIfNeeded(GV, GVToClone))
  447. return true;
  448. for (Function &SF : *SrcM)
  449. if (linkIfNeeded(SF, GVToClone))
  450. return true;
  451. for (GlobalAlias &GA : SrcM->aliases())
  452. if (linkIfNeeded(GA, GVToClone))
  453. return true;
  454. for (GlobalIFunc &GI : SrcM->ifuncs())
  455. if (linkIfNeeded(GI, GVToClone))
  456. return true;
  457. // For a variable in a comdat nodeduplicate, its initializer should be
  458. // preserved (its content may be implicitly used by other members) even if
  459. // symbol resolution does not pick it. Clone it into an unnamed private
  460. // variable.
  461. for (GlobalValue *GV : GVToClone) {
  462. if (auto *Var = dyn_cast<GlobalVariable>(GV)) {
  463. auto *NewVar = new GlobalVariable(*Var->getParent(), Var->getValueType(),
  464. Var->isConstant(), Var->getLinkage(),
  465. Var->getInitializer());
  466. NewVar->copyAttributesFrom(Var);
  467. NewVar->setVisibility(GlobalValue::DefaultVisibility);
  468. NewVar->setLinkage(GlobalValue::PrivateLinkage);
  469. NewVar->setDSOLocal(true);
  470. NewVar->setComdat(Var->getComdat());
  471. if (Var->getParent() != &Mover.getModule())
  472. ValuesToLink.insert(NewVar);
  473. } else {
  474. emitError("linking '" + GV->getName() +
  475. "': non-variables in comdat nodeduplicate are not handled");
  476. }
  477. }
  478. for (unsigned I = 0; I < ValuesToLink.size(); ++I) {
  479. GlobalValue *GV = ValuesToLink[I];
  480. const Comdat *SC = GV->getComdat();
  481. if (!SC)
  482. continue;
  483. for (GlobalValue *GV2 : LazyComdatMembers[SC]) {
  484. GlobalValue *DGV = getLinkedToGlobal(GV2);
  485. bool LinkFromSrc = true;
  486. if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
  487. return true;
  488. if (LinkFromSrc)
  489. ValuesToLink.insert(GV2);
  490. }
  491. }
  492. if (InternalizeCallback) {
  493. for (GlobalValue *GV : ValuesToLink)
  494. Internalize.insert(GV->getName());
  495. }
  496. // FIXME: Propagate Errors through to the caller instead of emitting
  497. // diagnostics.
  498. bool HasErrors = false;
  499. if (Error E =
  500. Mover.move(std::move(SrcM), ValuesToLink.getArrayRef(),
  501. IRMover::LazyCallback(
  502. [this](GlobalValue &GV, IRMover::ValueAdder Add) {
  503. addLazyFor(GV, Add);
  504. }),
  505. /* IsPerformingImport */ false)) {
  506. handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
  507. DstM.getContext().diagnose(LinkDiagnosticInfo(DS_Error, EIB.message()));
  508. HasErrors = true;
  509. });
  510. }
  511. if (HasErrors)
  512. return true;
  513. if (InternalizeCallback)
  514. InternalizeCallback(DstM, Internalize);
  515. return false;
  516. }
  517. Linker::Linker(Module &M) : Mover(M) {}
  518. bool Linker::linkInModule(
  519. std::unique_ptr<Module> Src, unsigned Flags,
  520. std::function<void(Module &, const StringSet<> &)> InternalizeCallback) {
  521. ModuleLinker ModLinker(Mover, std::move(Src), Flags,
  522. std::move(InternalizeCallback));
  523. return ModLinker.run();
  524. }
  525. //===----------------------------------------------------------------------===//
  526. // LinkModules entrypoint.
  527. //===----------------------------------------------------------------------===//
  528. /// This function links two modules together, with the resulting Dest module
  529. /// modified to be the composite of the two input modules. If an error occurs,
  530. /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
  531. /// Upon failure, the Dest module could be in a modified state, and shouldn't be
  532. /// relied on to be consistent.
  533. bool Linker::linkModules(
  534. Module &Dest, std::unique_ptr<Module> Src, unsigned Flags,
  535. std::function<void(Module &, const StringSet<> &)> InternalizeCallback) {
  536. Linker L(Dest);
  537. return L.linkInModule(std::move(Src), Flags, std::move(InternalizeCallback));
  538. }
  539. //===----------------------------------------------------------------------===//
  540. // C API.
  541. //===----------------------------------------------------------------------===//
  542. LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src) {
  543. Module *D = unwrap(Dest);
  544. std::unique_ptr<Module> M(unwrap(Src));
  545. return Linker::linkModules(*D, std::move(M));
  546. }