blob: 25f31a3401a6b94146101fac15143c948dff0d92 [file] [log] [blame]
Mikhail Glushenkovc834bbf2009-03-03 10:04:23 +00001//===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
Misha Brukmanf976c852005-04-21 22:55:34 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanf976c852005-04-21 22:55:34 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner52f7e902001-10-13 07:03:50 +00009//
10// This file implements the LLVM module linker.
11//
Chris Lattner52f7e902001-10-13 07:03:50 +000012//===----------------------------------------------------------------------===//
13
Rafael Espindolada513202015-12-10 14:19:35 +000014#include "LinkDiagnosticInfo.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000015#include "llvm-c/Linker.h"
Bill Wendlingd34cb1e2012-02-11 11:38:06 +000016#include "llvm/ADT/SetVector.h"
Peter Collingbournefa65bcf2017-02-03 16:58:19 +000017#include "llvm/IR/Comdat.h"
Rafael Espindola72478e52014-10-25 04:06:10 +000018#include "llvm/IR/DiagnosticPrinter.h"
Peter Collingbournefa65bcf2017-02-03 16:58:19 +000019#include "llvm/IR/GlobalValue.h"
Rafael Espindola7a1fc2d2015-12-14 23:17:03 +000020#include "llvm/IR/LLVMContext.h"
Peter Collingbournefa65bcf2017-02-03 16:58:19 +000021#include "llvm/IR/Module.h"
Teresa Johnsonc6f574d2016-02-10 18:11:31 +000022#include "llvm/Linker/Linker.h"
Peter Collingbourneb7bfc992016-05-27 05:21:35 +000023#include "llvm/Support/Error.h"
Chris Lattnerf7703df2004-01-09 06:12:26 +000024using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000025
Chris Lattner62a81a12008-06-16 21:00:18 +000026namespace {
Rafael Espindola86657152014-11-25 06:11:24 +000027
28/// This is an implementation class for the LinkModules function, which is the
29/// entrypoint for this file.
30class ModuleLinker {
Rafael Espindolada513202015-12-10 14:19:35 +000031 IRMover &Mover;
Rafael Espindola2dcb92d2016-02-16 18:50:12 +000032 std::unique_ptr<Module> SrcM;
Rafael Espindola86657152014-11-25 06:11:24 +000033
Rafael Espindola4744e8b2015-12-02 22:59:04 +000034 SetVector<GlobalValue *> ValuesToLink;
Chris Lattner1afcace2011-07-09 17:41:24 +000035
Duncan P. N. Exon Smithfae374b2015-04-22 04:11:00 +000036 /// For symbol clashes, prefer those from Src.
Artem Belevich20264d62015-09-01 17:55:55 +000037 unsigned Flags;
Duncan P. N. Exon Smithfae374b2015-04-22 04:11:00 +000038
Jonas Devlieghere2ebca362017-03-13 18:08:11 +000039 /// List of global value names that should be internalized.
40 StringSet<> Internalize;
41
42 /// Function that will perform the actual internalization. The reason for a
43 /// callback is that the linker cannot call internalizeModule without
44 /// creating a circular dependency between IPO and the linker.
45 std::function<void(Module &, const StringSet<> &)> InternalizeCallback;
46
Rafael Espindolada513202015-12-10 14:19:35 +000047 /// Used as the callback for lazy linking.
48 /// The mover has just hit GV and we have to decide if it, and other members
49 /// of the same comdat, should be linked. Every member to be linked is passed
50 /// to Add.
Benjamin Kramer36538ff2016-06-08 19:09:22 +000051 void addLazyFor(GlobalValue &GV, const IRMover::ValueAdder &Add);
Rafael Espindola39e89e82015-12-01 15:19:48 +000052
Artem Belevich20264d62015-09-01 17:55:55 +000053 bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
54 bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
Artem Belevich20264d62015-09-01 17:55:55 +000055
Rafael Espindola86657152014-11-25 06:11:24 +000056 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
57 const GlobalValue &Src);
Rafael Espindola2439e5d2014-05-09 14:39:25 +000058
Rafael Espindolada513202015-12-10 14:19:35 +000059 /// Should we have mover and linker error diag info?
Rafael Espindola86657152014-11-25 06:11:24 +000060 bool emitError(const Twine &Message) {
Rafael Espindola2dcb92d2016-02-16 18:50:12 +000061 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
Rafael Espindola86657152014-11-25 06:11:24 +000062 return true;
63 }
Rafael Espindola2439e5d2014-05-09 14:39:25 +000064
Rafael Espindola76c60c32015-12-01 19:50:54 +000065 bool getComdatLeader(Module &M, StringRef ComdatName,
Rafael Espindola86657152014-11-25 06:11:24 +000066 const GlobalVariable *&GVar);
67 bool computeResultingSelectionKind(StringRef ComdatName,
68 Comdat::SelectionKind Src,
69 Comdat::SelectionKind Dst,
70 Comdat::SelectionKind &Result,
71 bool &LinkFromSrc);
72 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
73 ComdatsChosen;
74 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
75 bool &LinkFromSrc);
Rafael Espindola6f5ddf82016-03-24 00:06:03 +000076 // Keep track of the lazy linked global members of each comdat in source.
77 DenseMap<const Comdat *, std::vector<GlobalValue *>> LazyComdatMembers;
Rafael Espindola0660f172014-10-27 23:02:10 +000078
Rafael Espindola86657152014-11-25 06:11:24 +000079 /// Given a global in the source module, return the global in the
80 /// destination module that is being linked to, if any.
81 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
Rafael Espindolada513202015-12-10 14:19:35 +000082 Module &DstM = Mover.getModule();
Rafael Espindola86657152014-11-25 06:11:24 +000083 // If the source has no name it can't link. If it has local linkage,
84 // there is no name match-up going on.
Teresa Johnson73ef4812016-01-08 15:00:00 +000085 if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(SrcGV->getLinkage()))
Rafael Espindola86657152014-11-25 06:11:24 +000086 return nullptr;
Eli Benderskyf17f2142014-02-20 22:19:24 +000087
Rafael Espindola86657152014-11-25 06:11:24 +000088 // Otherwise see if we have a match in the destination module's symtab.
Teresa Johnson73ef4812016-01-08 15:00:00 +000089 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
Rafael Espindola86657152014-11-25 06:11:24 +000090 if (!DGV)
91 return nullptr;
Rafael Espindola2439e5d2014-05-09 14:39:25 +000092
Rafael Espindola86657152014-11-25 06:11:24 +000093 // If we found a global with the same name in the dest module, but it has
94 // internal linkage, we are really not doing any linkage here.
95 if (DGV->hasLocalLinkage())
96 return nullptr;
Rafael Espindola7b1723d2014-09-09 15:21:00 +000097
Rafael Espindola86657152014-11-25 06:11:24 +000098 // Otherwise, we do in fact link to the destination global.
99 return DGV;
100 }
Rafael Espindola2439e5d2014-05-09 14:39:25 +0000101
Rafael Espindolaa8fd6582016-03-22 21:35:47 +0000102 /// Drop GV if it is a member of a comdat that we are dropping.
103 /// This can happen with COFF's largest selection kind.
104 void dropReplacedComdat(GlobalValue &GV,
105 const DenseSet<const Comdat *> &ReplacedDstComdats);
106
Rafael Espindola39e89e82015-12-01 15:19:48 +0000107 bool linkIfNeeded(GlobalValue &GV);
Teresa Johnson0292f062015-11-03 00:14:15 +0000108
Teresa Johnson73ef4812016-01-08 15:00:00 +0000109public:
Jonas Devlieghere2ebca362017-03-13 18:08:11 +0000110 ModuleLinker(IRMover &Mover, std::unique_ptr<Module> SrcM, unsigned Flags,
111 std::function<void(Module &, const StringSet<> &)>
112 InternalizeCallback = {})
113 : Mover(Mover), SrcM(std::move(SrcM)), Flags(Flags),
114 InternalizeCallback(std::move(InternalizeCallback)) {}
Teresa Johnson73ef4812016-01-08 15:00:00 +0000115
116 bool run();
117};
Teresa Johnson73ef4812016-01-08 15:00:00 +0000118}
119
Rafael Espindola91f2c7b2015-11-29 14:33:06 +0000120static GlobalValue::VisibilityTypes
121getMinVisibility(GlobalValue::VisibilityTypes A,
122 GlobalValue::VisibilityTypes B) {
123 if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
124 return GlobalValue::HiddenVisibility;
125 if (A == GlobalValue::ProtectedVisibility ||
126 B == GlobalValue::ProtectedVisibility)
127 return GlobalValue::ProtectedVisibility;
128 return GlobalValue::DefaultVisibility;
129}
130
Rafael Espindola76c60c32015-12-01 19:50:54 +0000131bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
David Majnemerc8a11692014-06-27 18:19:56 +0000132 const GlobalVariable *&GVar) {
Rafael Espindola76c60c32015-12-01 19:50:54 +0000133 const GlobalValue *GVal = M.getNamedValue(ComdatName);
David Majnemerc8a11692014-06-27 18:19:56 +0000134 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
135 GVal = GA->getBaseObject();
136 if (!GVal)
137 // We cannot resolve the size of the aliasee yet.
138 return emitError("Linking COMDATs named '" + ComdatName +
139 "': COMDAT key involves incomputable alias size.");
140 }
141
142 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
143 if (!GVar)
144 return emitError(
145 "Linking COMDATs named '" + ComdatName +
146 "': GlobalVariable required for data dependent selection!");
147
148 return false;
149}
150
151bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
152 Comdat::SelectionKind Src,
153 Comdat::SelectionKind Dst,
154 Comdat::SelectionKind &Result,
155 bool &LinkFromSrc) {
Rafael Espindolada513202015-12-10 14:19:35 +0000156 Module &DstM = Mover.getModule();
David Majnemerc8a11692014-06-27 18:19:56 +0000157 // The ability to mix Comdat::SelectionKind::Any with
158 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
159 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
160 Dst == Comdat::SelectionKind::Largest;
161 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
162 Src == Comdat::SelectionKind::Largest;
163 if (DstAnyOrLargest && SrcAnyOrLargest) {
164 if (Dst == Comdat::SelectionKind::Largest ||
165 Src == Comdat::SelectionKind::Largest)
166 Result = Comdat::SelectionKind::Largest;
167 else
168 Result = Comdat::SelectionKind::Any;
169 } else if (Src == Dst) {
170 Result = Dst;
171 } else {
172 return emitError("Linking COMDATs named '" + ComdatName +
173 "': invalid selection kinds!");
174 }
175
176 switch (Result) {
177 case Comdat::SelectionKind::Any:
178 // Go with Dst.
179 LinkFromSrc = false;
180 break;
181 case Comdat::SelectionKind::NoDuplicates:
182 return emitError("Linking COMDATs named '" + ComdatName +
183 "': noduplicates has been violated!");
184 case Comdat::SelectionKind::ExactMatch:
185 case Comdat::SelectionKind::Largest:
186 case Comdat::SelectionKind::SameSize: {
187 const GlobalVariable *DstGV;
188 const GlobalVariable *SrcGV;
189 if (getComdatLeader(DstM, ComdatName, DstGV) ||
Rafael Espindola2dcb92d2016-02-16 18:50:12 +0000190 getComdatLeader(*SrcM, ComdatName, SrcGV))
David Majnemerc8a11692014-06-27 18:19:56 +0000191 return true;
192
Rafael Espindola76c60c32015-12-01 19:50:54 +0000193 const DataLayout &DstDL = DstM.getDataLayout();
Rafael Espindola2dcb92d2016-02-16 18:50:12 +0000194 const DataLayout &SrcDL = SrcM->getDataLayout();
Manuel Jacob75e1cfb2016-01-16 20:30:46 +0000195 uint64_t DstSize = DstDL.getTypeAllocSize(DstGV->getValueType());
196 uint64_t SrcSize = SrcDL.getTypeAllocSize(SrcGV->getValueType());
David Majnemerc8a11692014-06-27 18:19:56 +0000197 if (Result == Comdat::SelectionKind::ExactMatch) {
198 if (SrcGV->getInitializer() != DstGV->getInitializer())
199 return emitError("Linking COMDATs named '" + ComdatName +
200 "': ExactMatch violated!");
201 LinkFromSrc = false;
202 } else if (Result == Comdat::SelectionKind::Largest) {
203 LinkFromSrc = SrcSize > DstSize;
204 } else if (Result == Comdat::SelectionKind::SameSize) {
205 if (SrcSize != DstSize)
206 return emitError("Linking COMDATs named '" + ComdatName +
207 "': SameSize violated!");
208 LinkFromSrc = false;
209 } else {
210 llvm_unreachable("unknown selection kind");
211 }
212 break;
213 }
214 }
215
216 return false;
217}
218
219bool ModuleLinker::getComdatResult(const Comdat *SrcC,
220 Comdat::SelectionKind &Result,
221 bool &LinkFromSrc) {
Rafael Espindolada513202015-12-10 14:19:35 +0000222 Module &DstM = Mover.getModule();
Rafael Espindola69ca26c2014-08-11 17:07:34 +0000223 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
David Majnemerc8a11692014-06-27 18:19:56 +0000224 StringRef ComdatName = SrcC->getName();
Rafael Espindola76c60c32015-12-01 19:50:54 +0000225 Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
David Majnemerc8a11692014-06-27 18:19:56 +0000226 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
Rafael Espindolacb7da632014-08-11 16:55:42 +0000227
Rafael Espindola69ca26c2014-08-11 17:07:34 +0000228 if (DstCI == ComdatSymTab.end()) {
229 // Use the comdat if it is only available in one of the modules.
230 LinkFromSrc = true;
231 Result = SSK;
Rafael Espindolacb7da632014-08-11 16:55:42 +0000232 return false;
Rafael Espindola69ca26c2014-08-11 17:07:34 +0000233 }
Rafael Espindolacb7da632014-08-11 16:55:42 +0000234
235 const Comdat *DstC = &DstCI->second;
Rafael Espindolacb7da632014-08-11 16:55:42 +0000236 Comdat::SelectionKind DSK = DstC->getSelectionKind();
237 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
238 LinkFromSrc);
David Majnemerc8a11692014-06-27 18:19:56 +0000239}
James Molloya84a83b2013-05-28 15:17:05 +0000240
Rafael Espindola72478e52014-10-25 04:06:10 +0000241bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
242 const GlobalValue &Dest,
Rafael Espindola7b1723d2014-09-09 15:21:00 +0000243 const GlobalValue &Src) {
Teresa Johnsond0f8afa2015-12-17 17:14:09 +0000244
Duncan P. N. Exon Smithfae374b2015-04-22 04:11:00 +0000245 // Should we unconditionally use the Src?
Artem Belevich20264d62015-09-01 17:55:55 +0000246 if (shouldOverrideFromSrc()) {
Duncan P. N. Exon Smithfae374b2015-04-22 04:11:00 +0000247 LinkFromSrc = true;
248 return false;
249 }
250
Rafael Espindola0a6665e2014-11-02 13:28:57 +0000251 // We always have to add Src if it has appending linkage.
252 if (Src.hasAppendingLinkage()) {
253 LinkFromSrc = true;
254 return false;
255 }
256
Rafael Espindola68b02dc2014-10-24 18:13:04 +0000257 bool SrcIsDeclaration = Src.isDeclarationForLinker();
258 bool DestIsDeclaration = Dest.isDeclarationForLinker();
Rafael Espindola7b1723d2014-09-09 15:21:00 +0000259
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.
Rafael Espindola72478e52014-10-25 04:06:10 +0000263 if (Src.hasDLLImportStorageClass()) {
Rafael Espindola7b1723d2014-09-09 15:21:00 +0000264 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
Rafael Espindola72478e52014-10-25 04:06:10 +0000265 LinkFromSrc = DestIsDeclaration;
266 return false;
267 }
Rafael Espindola7b1723d2014-09-09 15:21:00 +0000268 // If the Dest is weak, use the source linkage.
Rafael Espindolafad81ab2015-12-09 22:44:00 +0000269 if (Dest.hasExternalWeakLinkage()) {
270 LinkFromSrc = true;
271 return false;
272 }
273 // Link an available_externally over a declaration.
274 LinkFromSrc = !Src.isDeclaration() && Dest.isDeclaration();
Rafael Espindola72478e52014-10-25 04:06:10 +0000275 return false;
Rafael Espindola7b1723d2014-09-09 15:21:00 +0000276 }
277
Rafael Espindola72478e52014-10-25 04:06:10 +0000278 if (DestIsDeclaration) {
Rafael Espindola7b1723d2014-09-09 15:21:00 +0000279 // If Dest is external but Src is not:
Rafael Espindola72478e52014-10-25 04:06:10 +0000280 LinkFromSrc = true;
281 return false;
282 }
Rafael Espindola7b1723d2014-09-09 15:21:00 +0000283
Rafael Espindolae549e392014-09-09 15:59:12 +0000284 if (Src.hasCommonLinkage()) {
Rafael Espindola72478e52014-10-25 04:06:10 +0000285 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
286 LinkFromSrc = true;
Rafael Espindolae549e392014-09-09 15:59:12 +0000287 return false;
Rafael Espindola72478e52014-10-25 04:06:10 +0000288 }
289
290 if (!Dest.hasCommonLinkage()) {
291 LinkFromSrc = false;
292 return false;
293 }
Rafael Espindolae549e392014-09-09 15:59:12 +0000294
Mehdi Amini529919f2015-03-10 02:37:25 +0000295 const DataLayout &DL = Dest.getParent()->getDataLayout();
Manuel Jacob75e1cfb2016-01-16 20:30:46 +0000296 uint64_t DestSize = DL.getTypeAllocSize(Dest.getValueType());
297 uint64_t SrcSize = DL.getTypeAllocSize(Src.getValueType());
Rafael Espindola72478e52014-10-25 04:06:10 +0000298 LinkFromSrc = SrcSize > DestSize;
299 return false;
Rafael Espindolae549e392014-09-09 15:59:12 +0000300 }
301
Rafael Espindola7b1723d2014-09-09 15:21:00 +0000302 if (Src.isWeakForLinker()) {
303 assert(!Dest.hasExternalWeakLinkage());
304 assert(!Dest.hasAvailableExternallyLinkage());
Rafael Espindolae549e392014-09-09 15:59:12 +0000305
Rafael Espindola72478e52014-10-25 04:06:10 +0000306 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
307 LinkFromSrc = true;
308 return false;
309 }
Rafael Espindola7b1723d2014-09-09 15:21:00 +0000310
Rafael Espindola72478e52014-10-25 04:06:10 +0000311 LinkFromSrc = false;
Rafael Espindolae549e392014-09-09 15:59:12 +0000312 return false;
Rafael Espindola7b1723d2014-09-09 15:21:00 +0000313 }
314
315 if (Dest.isWeakForLinker()) {
316 assert(Src.hasExternalLinkage());
Rafael Espindola72478e52014-10-25 04:06:10 +0000317 LinkFromSrc = true;
318 return false;
Rafael Espindola7b1723d2014-09-09 15:21:00 +0000319 }
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
Rafael Espindola39e89e82015-12-01 15:19:48 +0000329bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
330 GlobalValue *DGV = getLinkedToGlobal(&GV);
331
Benoit Belleybad5f182017-08-09 20:58:39 +0000332 if (shouldLinkOnlyNeeded()) {
333 // Always import variables with appending linkage.
334 if (!GV.hasAppendingLinkage()) {
335 // Don't import globals unless they are referenced by the destination
336 // module.
337 if (!DGV)
338 return false;
339 // Don't import globals that are already defined in the destination module
340 if (!DGV->isDeclaration())
341 return false;
342 }
343 }
Rafael Espindola39e89e82015-12-01 15:19:48 +0000344
Rafael Espindola4744e8b2015-12-02 22:59:04 +0000345 if (DGV && !GV.hasLocalLinkage() && !GV.hasAppendingLinkage()) {
346 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
347 auto *SGVar = dyn_cast<GlobalVariable>(&GV);
348 if (DGVar && SGVar) {
349 if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
350 (!DGVar->isConstant() || !SGVar->isConstant())) {
351 DGVar->setConstant(false);
352 SGVar->setConstant(false);
353 }
354 if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
355 unsigned Align = std::max(DGVar->getAlignment(), SGVar->getAlignment());
356 SGVar->setAlignment(Align);
357 DGVar->setAlignment(Align);
358 }
359 }
360
Rafael Espindola39e89e82015-12-01 15:19:48 +0000361 GlobalValue::VisibilityTypes Visibility =
362 getMinVisibility(DGV->getVisibility(), GV.getVisibility());
363 DGV->setVisibility(Visibility);
364 GV.setVisibility(Visibility);
Rafael Espindola4744e8b2015-12-02 22:59:04 +0000365
Peter Collingbourne63b34cd2016-06-14 21:01:22 +0000366 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::getMinUnnamedAddr(
367 DGV->getUnnamedAddr(), GV.getUnnamedAddr());
368 DGV->setUnnamedAddr(UnnamedAddr);
369 GV.setUnnamedAddr(UnnamedAddr);
Rafael Espindola39e89e82015-12-01 15:19:48 +0000370 }
371
Peter Collingbournefa65bcf2017-02-03 16:58:19 +0000372 if (!DGV && !shouldOverrideFromSrc() &&
373 (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
374 GV.hasAvailableExternallyLinkage()))
Rafael Espindola4744e8b2015-12-02 22:59:04 +0000375 return false;
376
Rafael Espindola0178d232015-12-07 16:31:41 +0000377 if (GV.isDeclaration())
378 return false;
379
Rafael Espindola39e89e82015-12-01 15:19:48 +0000380 if (const Comdat *SC = GV.getComdat()) {
381 bool LinkFromSrc;
382 Comdat::SelectionKind SK;
383 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
Rafael Espindolad7bb2de2016-03-23 21:16:33 +0000384 if (!LinkFromSrc)
385 return false;
Rafael Espindola39e89e82015-12-01 15:19:48 +0000386 }
Rafael Espindola4744e8b2015-12-02 22:59:04 +0000387
388 bool LinkFromSrc = true;
389 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
390 return true;
391 if (LinkFromSrc)
392 ValuesToLink.insert(&GV);
393 return false;
Rafael Espindola39e89e82015-12-01 15:19:48 +0000394}
395
Benjamin Kramer36538ff2016-06-08 19:09:22 +0000396void ModuleLinker::addLazyFor(GlobalValue &GV, const IRMover::ValueAdder &Add) {
Rafael Espindolada513202015-12-10 14:19:35 +0000397 // Add these to the internalize list
Peter Collingbournee482a052017-02-02 05:12:15 +0000398 if (!GV.hasLinkOnceLinkage() && !GV.hasAvailableExternallyLinkage() &&
399 !shouldLinkOnlyNeeded())
Rafael Espindolada513202015-12-10 14:19:35 +0000400 return;
401
Jonas Devlieghere2ebca362017-03-13 18:08:11 +0000402 if (InternalizeCallback)
Rafael Espindolada513202015-12-10 14:19:35 +0000403 Internalize.insert(GV.getName());
404 Add(GV);
405
406 const Comdat *SC = GV.getComdat();
407 if (!SC)
408 return;
Rafael Espindola6f5ddf82016-03-24 00:06:03 +0000409 for (GlobalValue *GV2 : LazyComdatMembers[SC]) {
Rafael Espindolac0521dd2016-03-24 15:23:01 +0000410 GlobalValue *DGV = getLinkedToGlobal(GV2);
411 bool LinkFromSrc = true;
412 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
413 return;
414 if (!LinkFromSrc)
415 continue;
Jonas Devlieghere2ebca362017-03-13 18:08:11 +0000416 if (InternalizeCallback)
Rafael Espindolada513202015-12-10 14:19:35 +0000417 Internalize.insert(GV2->getName());
418 Add(*GV2);
419 }
420}
421
Rafael Espindolaa8fd6582016-03-22 21:35:47 +0000422void ModuleLinker::dropReplacedComdat(
423 GlobalValue &GV, const DenseSet<const Comdat *> &ReplacedDstComdats) {
424 Comdat *C = GV.getComdat();
425 if (!C)
426 return;
427 if (!ReplacedDstComdats.count(C))
428 return;
429 if (GV.use_empty()) {
430 GV.eraseFromParent();
431 return;
432 }
433
434 if (auto *F = dyn_cast<Function>(&GV)) {
435 F->deleteBody();
436 } else if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
437 Var->setInitializer(nullptr);
438 } else {
439 auto &Alias = cast<GlobalAlias>(GV);
440 Module &M = *Alias.getParent();
441 PointerType &Ty = *cast<PointerType>(Alias.getType());
442 GlobalValue *Declaration;
443 if (auto *FTy = dyn_cast<FunctionType>(Alias.getValueType())) {
444 Declaration = Function::Create(FTy, GlobalValue::ExternalLinkage, "", &M);
445 } else {
446 Declaration =
447 new GlobalVariable(M, Ty.getElementType(), /*isConstant*/ false,
448 GlobalValue::ExternalLinkage,
449 /*Initializer*/ nullptr);
450 }
451 Declaration->takeName(&Alias);
452 Alias.replaceAllUsesWith(Declaration);
453 Alias.eraseFromParent();
454 }
455}
456
Chris Lattner1afcace2011-07-09 17:41:24 +0000457bool ModuleLinker::run() {
Rafael Espindolaa8fd6582016-03-22 21:35:47 +0000458 Module &DstM = Mover.getModule();
459 DenseSet<const Comdat *> ReplacedDstComdats;
460
Rafael Espindola2dcb92d2016-02-16 18:50:12 +0000461 for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
David Majnemerc8a11692014-06-27 18:19:56 +0000462 const Comdat &C = SMEC.getValue();
463 if (ComdatsChosen.count(&C))
464 continue;
465 Comdat::SelectionKind SK;
466 bool LinkFromSrc;
467 if (getComdatResult(&C, SK, LinkFromSrc))
468 return true;
469 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
Rafael Espindolaa8fd6582016-03-22 21:35:47 +0000470
471 if (!LinkFromSrc)
472 continue;
473
474 Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
475 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(C.getName());
476 if (DstCI == ComdatSymTab.end())
477 continue;
478
479 // The source comdat is replacing the dest one.
480 const Comdat *DstC = &DstCI->second;
481 ReplacedDstComdats.insert(DstC);
482 }
483
484 // Alias have to go first, since we are not able to find their comdats
485 // otherwise.
486 for (auto I = DstM.alias_begin(), E = DstM.alias_end(); I != E;) {
487 GlobalAlias &GV = *I++;
488 dropReplacedComdat(GV, ReplacedDstComdats);
489 }
490
491 for (auto I = DstM.global_begin(), E = DstM.global_end(); I != E;) {
492 GlobalVariable &GV = *I++;
493 dropReplacedComdat(GV, ReplacedDstComdats);
494 }
495
496 for (auto I = DstM.begin(), E = DstM.end(); I != E;) {
497 Function &GV = *I++;
498 dropReplacedComdat(GV, ReplacedDstComdats);
David Majnemerc8a11692014-06-27 18:19:56 +0000499 }
500
Rafael Espindola2dcb92d2016-02-16 18:50:12 +0000501 for (GlobalVariable &GV : SrcM->globals())
Rafael Espindola6f5ddf82016-03-24 00:06:03 +0000502 if (GV.hasLinkOnceLinkage())
503 if (const Comdat *SC = GV.getComdat())
504 LazyComdatMembers[SC].push_back(&GV);
Rafael Espindola39e89e82015-12-01 15:19:48 +0000505
Rafael Espindola2dcb92d2016-02-16 18:50:12 +0000506 for (Function &SF : *SrcM)
Rafael Espindola6f5ddf82016-03-24 00:06:03 +0000507 if (SF.hasLinkOnceLinkage())
508 if (const Comdat *SC = SF.getComdat())
509 LazyComdatMembers[SC].push_back(&SF);
Rafael Espindola39e89e82015-12-01 15:19:48 +0000510
Rafael Espindola2dcb92d2016-02-16 18:50:12 +0000511 for (GlobalAlias &GA : SrcM->aliases())
Rafael Espindola6f5ddf82016-03-24 00:06:03 +0000512 if (GA.hasLinkOnceLinkage())
513 if (const Comdat *SC = GA.getComdat())
514 LazyComdatMembers[SC].push_back(&GA);
Rafael Espindola39e89e82015-12-01 15:19:48 +0000515
Chris Lattner1afcace2011-07-09 17:41:24 +0000516 // Insert all of the globals in src into the DstM module... without linking
517 // initializers (which could refer to functions not yet mapped over).
Rafael Espindola2dcb92d2016-02-16 18:50:12 +0000518 for (GlobalVariable &GV : SrcM->globals())
Rafael Espindola39e89e82015-12-01 15:19:48 +0000519 if (linkIfNeeded(GV))
Chris Lattner1afcace2011-07-09 17:41:24 +0000520 return true;
521
Rafael Espindola2dcb92d2016-02-16 18:50:12 +0000522 for (Function &SF : *SrcM)
Rafael Espindola39e89e82015-12-01 15:19:48 +0000523 if (linkIfNeeded(SF))
Chris Lattner1afcace2011-07-09 17:41:24 +0000524 return true;
525
Rafael Espindola2dcb92d2016-02-16 18:50:12 +0000526 for (GlobalAlias &GA : SrcM->aliases())
Rafael Espindola39e89e82015-12-01 15:19:48 +0000527 if (linkIfNeeded(GA))
Chris Lattner1afcace2011-07-09 17:41:24 +0000528 return true;
529
Rafael Espindolada513202015-12-10 14:19:35 +0000530 for (unsigned I = 0; I < ValuesToLink.size(); ++I) {
531 GlobalValue *GV = ValuesToLink[I];
532 const Comdat *SC = GV->getComdat();
533 if (!SC)
534 continue;
Rafael Espindola87fa43b2016-03-24 14:58:44 +0000535 for (GlobalValue *GV2 : LazyComdatMembers[SC]) {
536 GlobalValue *DGV = getLinkedToGlobal(GV2);
537 bool LinkFromSrc = true;
538 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
539 return true;
540 if (LinkFromSrc)
541 ValuesToLink.insert(GV2);
542 }
Rafael Espindoladcc44c62014-12-08 18:05:48 +0000543 }
544
Jonas Devlieghere2ebca362017-03-13 18:08:11 +0000545 if (InternalizeCallback) {
Rafael Espindolada513202015-12-10 14:19:35 +0000546 for (GlobalValue *GV : ValuesToLink)
547 Internalize.insert(GV->getName());
548 }
Teresa Johnson99ee8972015-11-06 17:50:53 +0000549
Peter Collingbourneb7bfc992016-05-27 05:21:35 +0000550 // FIXME: Propagate Errors through to the caller instead of emitting
551 // diagnostics.
552 bool HasErrors = false;
553 if (Error E = Mover.move(std::move(SrcM), ValuesToLink.getArrayRef(),
554 [this](GlobalValue &GV, IRMover::ValueAdder Add) {
555 addLazyFor(GV, Add);
Teresa Johnson256d6fe2016-10-12 18:39:29 +0000556 },
Peter Collingbournefa65bcf2017-02-03 16:58:19 +0000557 /* IsPerformingImport */ false)) {
Peter Collingbourneb7bfc992016-05-27 05:21:35 +0000558 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
559 DstM.getContext().diagnose(LinkDiagnosticInfo(DS_Error, EIB.message()));
560 HasErrors = true;
561 });
562 }
563 if (HasErrors)
Teresa Johnson46c7bcb2015-11-06 17:50:48 +0000564 return true;
Peter Collingbourneb7bfc992016-05-27 05:21:35 +0000565
Jonas Devlieghere2ebca362017-03-13 18:08:11 +0000566 if (InternalizeCallback)
567 InternalizeCallback(DstM, Internalize);
Teresa Johnson46c7bcb2015-11-06 17:50:48 +0000568
Anton Korobeynikov9f2ee702008-03-05 23:21:39 +0000569 return false;
570}
Chris Lattner52f7e902001-10-13 07:03:50 +0000571
Rafael Espindola7a1fc2d2015-12-14 23:17:03 +0000572Linker::Linker(Module &M) : Mover(M) {}
Rafael Espindolac7c35a92013-05-04 03:48:37 +0000573
Jonas Devlieghere2ebca362017-03-13 18:08:11 +0000574bool Linker::linkInModule(
575 std::unique_ptr<Module> Src, unsigned Flags,
576 std::function<void(Module &, const StringSet<> &)> InternalizeCallback) {
577 ModuleLinker ModLinker(Mover, std::move(Src), Flags,
578 std::move(InternalizeCallback));
Teresa Johnson18f59c52015-12-18 19:28:59 +0000579 return ModLinker.run();
Rafael Espindolad912be92015-12-16 23:16:33 +0000580}
581
Chris Lattner1afcace2011-07-09 17:41:24 +0000582//===----------------------------------------------------------------------===//
583// LinkModules entrypoint.
584//===----------------------------------------------------------------------===//
585
Rafael Espindolae250b132014-10-27 02:35:46 +0000586/// This function links two modules together, with the resulting Dest module
587/// modified to be the composite of the two input modules. If an error occurs,
588/// true is returned and ErrorMsg (if not null) is set to indicate the problem.
589/// Upon failure, the Dest module could be in a modified state, and shouldn't be
590/// relied on to be consistent.
Jonas Devlieghere2ebca362017-03-13 18:08:11 +0000591bool Linker::linkModules(
592 Module &Dest, std::unique_ptr<Module> Src, unsigned Flags,
593 std::function<void(Module &, const StringSet<> &)> InternalizeCallback) {
Rafael Espindola7a1fc2d2015-12-14 23:17:03 +0000594 Linker L(Dest);
Jonas Devlieghere2ebca362017-03-13 18:08:11 +0000595 return L.linkInModule(std::move(Src), Flags, std::move(InternalizeCallback));
Rafael Espindola0660f172014-10-27 23:02:10 +0000596}
597
Bill Wendlingf24fde22012-05-09 08:55:40 +0000598//===----------------------------------------------------------------------===//
599// C API.
600//===----------------------------------------------------------------------===//
601
Rafael Espindolad912be92015-12-16 23:16:33 +0000602LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src) {
603 Module *D = unwrap(Dest);
604 std::unique_ptr<Module> M(unwrap(Src));
605 return Linker::linkModules(*D, std::move(M));
606}