blob: 07785d7a50f01bbb1fbef5db9d7093903856810c [file] [log] [blame]
Mikhail Glushenkov59a5afa2009-03-03 10:04:23 +00001//===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
Misha Brukman10468d82005-04-21 22:55:34 +00002//
Reid Spencer361e5132004-11-12 20:37:43 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukman10468d82005-04-21 22:55:34 +00007//
Reid Spencer361e5132004-11-12 20:37:43 +00008//===----------------------------------------------------------------------===//
9//
10// This file implements the LLVM module linker.
11//
Reid Spencer361e5132004-11-12 20:37:43 +000012//===----------------------------------------------------------------------===//
13
Rafael Espindolacaabe222015-12-10 14:19:35 +000014#include "LinkDiagnosticInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm-c/Linker.h"
Bill Wendling66f02412012-02-11 11:38:06 +000016#include "llvm/ADT/SetVector.h"
Rafael Espindolacaabe222015-12-10 14:19:35 +000017#include "llvm/ADT/StringSet.h"
Rafael Espindolad12b4a32014-10-25 04:06:10 +000018#include "llvm/IR/DiagnosticPrinter.h"
Rafael Espindola9d2bfc42015-12-14 23:17:03 +000019#include "llvm/IR/LLVMContext.h"
Teresa Johnson488a8002016-02-10 18:11:31 +000020#include "llvm/Linker/Linker.h"
21#include "llvm/Transforms/Utils/FunctionImportUtils.h"
Reid Spencer361e5132004-11-12 20:37:43 +000022using namespace llvm;
23
Chris Lattnereee6f992008-06-16 21:00:18 +000024namespace {
Rafael Espindolac84f6082014-11-25 06:11:24 +000025
26/// This is an implementation class for the LinkModules function, which is the
27/// entrypoint for this file.
28class ModuleLinker {
Rafael Espindolacaabe222015-12-10 14:19:35 +000029 IRMover &Mover;
Rafael Espindola40358fb2016-02-16 18:50:12 +000030 std::unique_ptr<Module> SrcM;
Rafael Espindolac84f6082014-11-25 06:11:24 +000031
Rafael Espindola4b5ec262015-12-02 22:59:04 +000032 SetVector<GlobalValue *> ValuesToLink;
Rafael Espindolacaabe222015-12-10 14:19:35 +000033 StringSet<> Internalize;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000034
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +000035 /// For symbol clashes, prefer those from Src.
Artem Belevich020d4fb2015-09-01 17:55:55 +000036 unsigned Flags;
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +000037
Teresa Johnson4f04d852015-12-21 17:33:24 +000038 /// Functions to import from source module, all other functions are
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000039 /// imported as declarations instead of definitions.
Mehdi Amini8d051852016-03-19 00:40:31 +000040 DenseSet<const GlobalValue *> *GlobalsToImport;
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000041
Rafael Espindolacaabe222015-12-10 14:19:35 +000042 /// Used as the callback for lazy linking.
43 /// The mover has just hit GV and we have to decide if it, and other members
44 /// of the same comdat, should be linked. Every member to be linked is passed
45 /// to Add.
46 void addLazyFor(GlobalValue &GV, IRMover::ValueAdder Add);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +000047
Artem Belevich020d4fb2015-09-01 17:55:55 +000048 bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
49 bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
50 bool shouldInternalizeLinkedSymbols() {
51 return Flags & Linker::InternalizeLinkedSymbols;
52 }
53
Rafael Espindolac84f6082014-11-25 06:11:24 +000054 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
55 const GlobalValue &Src);
Rafael Espindolaed6dc372014-05-09 14:39:25 +000056
Rafael Espindolacaabe222015-12-10 14:19:35 +000057 /// Should we have mover and linker error diag info?
Rafael Espindolac84f6082014-11-25 06:11:24 +000058 bool emitError(const Twine &Message) {
Rafael Espindola40358fb2016-02-16 18:50:12 +000059 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
Rafael Espindolac84f6082014-11-25 06:11:24 +000060 return true;
61 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +000062
Rafael Espindola0e309fe2015-12-01 19:50:54 +000063 bool getComdatLeader(Module &M, StringRef ComdatName,
Rafael Espindolac84f6082014-11-25 06:11:24 +000064 const GlobalVariable *&GVar);
65 bool computeResultingSelectionKind(StringRef ComdatName,
66 Comdat::SelectionKind Src,
67 Comdat::SelectionKind Dst,
68 Comdat::SelectionKind &Result,
69 bool &LinkFromSrc);
70 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
71 ComdatsChosen;
72 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
73 bool &LinkFromSrc);
Rafael Espindola1ee9fbd2016-03-24 00:06:03 +000074 // Keep track of the lazy linked global members of each comdat in source.
75 DenseMap<const Comdat *, std::vector<GlobalValue *>> LazyComdatMembers;
Rafael Espindola4160f5d2014-10-27 23:02:10 +000076
Rafael Espindolac84f6082014-11-25 06:11:24 +000077 /// Given a global in the source module, return the global in the
78 /// destination module that is being linked to, if any.
79 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
Rafael Espindolacaabe222015-12-10 14:19:35 +000080 Module &DstM = Mover.getModule();
Rafael Espindolac84f6082014-11-25 06:11:24 +000081 // If the source has no name it can't link. If it has local linkage,
82 // there is no name match-up going on.
Teresa Johnson4504c1b2016-01-08 15:00:00 +000083 if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(SrcGV->getLinkage()))
Rafael Espindolac84f6082014-11-25 06:11:24 +000084 return nullptr;
Eli Bendersky7da92ed2014-02-20 22:19:24 +000085
Rafael Espindolac84f6082014-11-25 06:11:24 +000086 // Otherwise see if we have a match in the destination module's symtab.
Teresa Johnson4504c1b2016-01-08 15:00:00 +000087 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
Rafael Espindolac84f6082014-11-25 06:11:24 +000088 if (!DGV)
89 return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000090
Rafael Espindolac84f6082014-11-25 06:11:24 +000091 // If we found a global with the same name in the dest module, but it has
92 // internal linkage, we are really not doing any linkage here.
93 if (DGV->hasLocalLinkage())
94 return nullptr;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +000095
Rafael Espindolac84f6082014-11-25 06:11:24 +000096 // Otherwise, we do in fact link to the destination global.
97 return DGV;
98 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +000099
Rafael Espindola370d5282016-03-22 21:35:47 +0000100 /// Drop GV if it is a member of a comdat that we are dropping.
101 /// This can happen with COFF's largest selection kind.
102 void dropReplacedComdat(GlobalValue &GV,
103 const DenseSet<const Comdat *> &ReplacedDstComdats);
104
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000105 bool linkIfNeeded(GlobalValue &GV);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000106
Teresa Johnson4504c1b2016-01-08 15:00:00 +0000107 /// Helper method to check if we are importing from the current source
108 /// module.
Mehdi Amini8d051852016-03-19 00:40:31 +0000109 bool isPerformingImport() const { return GlobalsToImport != nullptr; }
Teresa Johnson4504c1b2016-01-08 15:00:00 +0000110
111 /// If we are importing from the source module, checks if we should
112 /// import SGV as a definition, otherwise import as a declaration.
113 bool doImportAsDefinition(const GlobalValue *SGV);
114
115public:
Rafael Espindola40358fb2016-02-16 18:50:12 +0000116 ModuleLinker(IRMover &Mover, std::unique_ptr<Module> SrcM, unsigned Flags,
Teresa Johnsonb703c772016-03-29 18:24:19 +0000117 DenseSet<const GlobalValue *> *GlobalsToImport = nullptr)
Mehdi Amini8d051852016-03-19 00:40:31 +0000118 : Mover(Mover), SrcM(std::move(SrcM)), Flags(Flags),
Teresa Johnsonb703c772016-03-29 18:24:19 +0000119 GlobalsToImport(GlobalsToImport) {}
Teresa Johnson4504c1b2016-01-08 15:00:00 +0000120
121 bool run();
122};
Teresa Johnson4504c1b2016-01-08 15:00:00 +0000123}
124
125bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
126 if (!isPerformingImport())
127 return false;
Mehdi Amini8d051852016-03-19 00:40:31 +0000128 return FunctionImportGlobalProcessing::doImportAsDefinition(SGV,
129 GlobalsToImport);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000130}
131
Rafael Espindolaeb5e0a72015-11-29 14:33:06 +0000132static GlobalValue::VisibilityTypes
133getMinVisibility(GlobalValue::VisibilityTypes A,
134 GlobalValue::VisibilityTypes B) {
135 if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
136 return GlobalValue::HiddenVisibility;
137 if (A == GlobalValue::ProtectedVisibility ||
138 B == GlobalValue::ProtectedVisibility)
139 return GlobalValue::ProtectedVisibility;
140 return GlobalValue::DefaultVisibility;
141}
142
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000143bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
David Majnemerdad0a642014-06-27 18:19:56 +0000144 const GlobalVariable *&GVar) {
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000145 const GlobalValue *GVal = M.getNamedValue(ComdatName);
David Majnemerdad0a642014-06-27 18:19:56 +0000146 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
147 GVal = GA->getBaseObject();
148 if (!GVal)
149 // We cannot resolve the size of the aliasee yet.
150 return emitError("Linking COMDATs named '" + ComdatName +
151 "': COMDAT key involves incomputable alias size.");
152 }
153
154 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
155 if (!GVar)
156 return emitError(
157 "Linking COMDATs named '" + ComdatName +
158 "': GlobalVariable required for data dependent selection!");
159
160 return false;
161}
162
163bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
164 Comdat::SelectionKind Src,
165 Comdat::SelectionKind Dst,
166 Comdat::SelectionKind &Result,
167 bool &LinkFromSrc) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000168 Module &DstM = Mover.getModule();
David Majnemerdad0a642014-06-27 18:19:56 +0000169 // The ability to mix Comdat::SelectionKind::Any with
170 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
171 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
172 Dst == Comdat::SelectionKind::Largest;
173 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
174 Src == Comdat::SelectionKind::Largest;
175 if (DstAnyOrLargest && SrcAnyOrLargest) {
176 if (Dst == Comdat::SelectionKind::Largest ||
177 Src == Comdat::SelectionKind::Largest)
178 Result = Comdat::SelectionKind::Largest;
179 else
180 Result = Comdat::SelectionKind::Any;
181 } else if (Src == Dst) {
182 Result = Dst;
183 } else {
184 return emitError("Linking COMDATs named '" + ComdatName +
185 "': invalid selection kinds!");
186 }
187
188 switch (Result) {
189 case Comdat::SelectionKind::Any:
190 // Go with Dst.
191 LinkFromSrc = false;
192 break;
193 case Comdat::SelectionKind::NoDuplicates:
194 return emitError("Linking COMDATs named '" + ComdatName +
195 "': noduplicates has been violated!");
196 case Comdat::SelectionKind::ExactMatch:
197 case Comdat::SelectionKind::Largest:
198 case Comdat::SelectionKind::SameSize: {
199 const GlobalVariable *DstGV;
200 const GlobalVariable *SrcGV;
201 if (getComdatLeader(DstM, ComdatName, DstGV) ||
Rafael Espindola40358fb2016-02-16 18:50:12 +0000202 getComdatLeader(*SrcM, ComdatName, SrcGV))
David Majnemerdad0a642014-06-27 18:19:56 +0000203 return true;
204
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000205 const DataLayout &DstDL = DstM.getDataLayout();
Rafael Espindola40358fb2016-02-16 18:50:12 +0000206 const DataLayout &SrcDL = SrcM->getDataLayout();
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000207 uint64_t DstSize = DstDL.getTypeAllocSize(DstGV->getValueType());
208 uint64_t SrcSize = SrcDL.getTypeAllocSize(SrcGV->getValueType());
David Majnemerdad0a642014-06-27 18:19:56 +0000209 if (Result == Comdat::SelectionKind::ExactMatch) {
210 if (SrcGV->getInitializer() != DstGV->getInitializer())
211 return emitError("Linking COMDATs named '" + ComdatName +
212 "': ExactMatch violated!");
213 LinkFromSrc = false;
214 } else if (Result == Comdat::SelectionKind::Largest) {
215 LinkFromSrc = SrcSize > DstSize;
216 } else if (Result == Comdat::SelectionKind::SameSize) {
217 if (SrcSize != DstSize)
218 return emitError("Linking COMDATs named '" + ComdatName +
219 "': SameSize violated!");
220 LinkFromSrc = false;
221 } else {
222 llvm_unreachable("unknown selection kind");
223 }
224 break;
225 }
226 }
227
228 return false;
229}
230
231bool ModuleLinker::getComdatResult(const Comdat *SrcC,
232 Comdat::SelectionKind &Result,
233 bool &LinkFromSrc) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000234 Module &DstM = Mover.getModule();
Rafael Espindolab16196a2014-08-11 17:07:34 +0000235 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
David Majnemerdad0a642014-06-27 18:19:56 +0000236 StringRef ComdatName = SrcC->getName();
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000237 Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
David Majnemerdad0a642014-06-27 18:19:56 +0000238 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000239
Rafael Espindolab16196a2014-08-11 17:07:34 +0000240 if (DstCI == ComdatSymTab.end()) {
241 // Use the comdat if it is only available in one of the modules.
242 LinkFromSrc = true;
243 Result = SSK;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000244 return false;
Rafael Espindolab16196a2014-08-11 17:07:34 +0000245 }
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000246
247 const Comdat *DstC = &DstCI->second;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000248 Comdat::SelectionKind DSK = DstC->getSelectionKind();
249 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
250 LinkFromSrc);
David Majnemerdad0a642014-06-27 18:19:56 +0000251}
James Molloyf6f121e2013-05-28 15:17:05 +0000252
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000253bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
254 const GlobalValue &Dest,
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000255 const GlobalValue &Src) {
Teresa Johnsone5a61912015-12-17 17:14:09 +0000256
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000257 // Should we unconditionally use the Src?
Artem Belevich020d4fb2015-09-01 17:55:55 +0000258 if (shouldOverrideFromSrc()) {
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000259 LinkFromSrc = true;
260 return false;
261 }
262
Rafael Espindola778fcc72014-11-02 13:28:57 +0000263 // We always have to add Src if it has appending linkage.
264 if (Src.hasAppendingLinkage()) {
Teresa Johnson1e20a652015-12-03 18:20:05 +0000265 // Should have prevented importing for appending linkage in linkIfNeeded.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000266 assert(!isPerformingImport());
Rafael Espindola778fcc72014-11-02 13:28:57 +0000267 LinkFromSrc = true;
268 return false;
269 }
270
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000271 bool SrcIsDeclaration = Src.isDeclarationForLinker();
272 bool DestIsDeclaration = Dest.isDeclarationForLinker();
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000273
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000274 if (isPerformingImport()) {
275 if (isa<Function>(&Src)) {
Teresa Johnson4f04d852015-12-21 17:33:24 +0000276 // For functions, LinkFromSrc iff this is a function requested
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000277 // for importing. For variables, decide below normally.
Mehdi Amini8d051852016-03-19 00:40:31 +0000278 LinkFromSrc = GlobalsToImport->count(&Src);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000279 return false;
280 }
281
282 // Check if this is an alias with an already existing definition
283 // in Dest, which must have come from a prior importing pass from
284 // the same Src module. Unlike imported function and variable
285 // definitions, which are imported as available_externally and are
286 // not definitions for the linker, that is not a valid linkage for
287 // imported aliases which must be definitions. Simply use the existing
288 // Dest copy.
289 if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
290 assert(isa<GlobalAlias>(&Dest));
291 LinkFromSrc = false;
292 return false;
293 }
294 }
295
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000296 if (SrcIsDeclaration) {
297 // If Src is external or if both Src & Dest are external.. Just link the
298 // external globals, we aren't adding anything.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000299 if (Src.hasDLLImportStorageClass()) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000300 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000301 LinkFromSrc = DestIsDeclaration;
302 return false;
303 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000304 // If the Dest is weak, use the source linkage.
Rafael Espindolaed11bd22015-12-09 22:44:00 +0000305 if (Dest.hasExternalWeakLinkage()) {
306 LinkFromSrc = true;
307 return false;
308 }
309 // Link an available_externally over a declaration.
310 LinkFromSrc = !Src.isDeclaration() && Dest.isDeclaration();
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000311 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000312 }
313
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000314 if (DestIsDeclaration) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000315 // If Dest is external but Src is not:
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000316 LinkFromSrc = true;
317 return false;
318 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000319
Rafael Espindola09106052014-09-09 15:59:12 +0000320 if (Src.hasCommonLinkage()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000321 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
322 LinkFromSrc = true;
Rafael Espindola09106052014-09-09 15:59:12 +0000323 return false;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000324 }
325
326 if (!Dest.hasCommonLinkage()) {
327 LinkFromSrc = false;
328 return false;
329 }
Rafael Espindola09106052014-09-09 15:59:12 +0000330
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000331 const DataLayout &DL = Dest.getParent()->getDataLayout();
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000332 uint64_t DestSize = DL.getTypeAllocSize(Dest.getValueType());
333 uint64_t SrcSize = DL.getTypeAllocSize(Src.getValueType());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000334 LinkFromSrc = SrcSize > DestSize;
335 return false;
Rafael Espindola09106052014-09-09 15:59:12 +0000336 }
337
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000338 if (Src.isWeakForLinker()) {
339 assert(!Dest.hasExternalWeakLinkage());
340 assert(!Dest.hasAvailableExternallyLinkage());
Rafael Espindola09106052014-09-09 15:59:12 +0000341
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000342 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
343 LinkFromSrc = true;
344 return false;
345 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000346
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000347 LinkFromSrc = false;
Rafael Espindola09106052014-09-09 15:59:12 +0000348 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000349 }
350
351 if (Dest.isWeakForLinker()) {
352 assert(Src.hasExternalLinkage());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000353 LinkFromSrc = true;
354 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000355 }
356
357 assert(!Src.hasExternalWeakLinkage());
358 assert(!Dest.hasExternalWeakLinkage());
359 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
360 "Unexpected linkage type!");
361 return emitError("Linking globals named '" + Src.getName() +
362 "': symbol multiply defined!");
363}
364
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000365bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
366 GlobalValue *DGV = getLinkedToGlobal(&GV);
367
368 if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
369 return false;
370
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000371 if (DGV && !GV.hasLocalLinkage() && !GV.hasAppendingLinkage()) {
372 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
373 auto *SGVar = dyn_cast<GlobalVariable>(&GV);
374 if (DGVar && SGVar) {
375 if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
376 (!DGVar->isConstant() || !SGVar->isConstant())) {
377 DGVar->setConstant(false);
378 SGVar->setConstant(false);
379 }
380 if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
381 unsigned Align = std::max(DGVar->getAlignment(), SGVar->getAlignment());
382 SGVar->setAlignment(Align);
383 DGVar->setAlignment(Align);
384 }
385 }
386
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000387 GlobalValue::VisibilityTypes Visibility =
388 getMinVisibility(DGV->getVisibility(), GV.getVisibility());
389 DGV->setVisibility(Visibility);
390 GV.setVisibility(Visibility);
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000391
392 bool HasUnnamedAddr = GV.hasUnnamedAddr() && DGV->hasUnnamedAddr();
393 DGV->setUnnamedAddr(HasUnnamedAddr);
394 GV.setUnnamedAddr(HasUnnamedAddr);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000395 }
396
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000397 // Don't want to append to global_ctors list, for example, when we
398 // are importing for ThinLTO, otherwise the global ctors and dtors
399 // get executed multiple times for local variables (the latter causing
400 // double frees).
401 if (GV.hasAppendingLinkage() && isPerformingImport())
402 return false;
403
Mehdi Amini8d051852016-03-19 00:40:31 +0000404 if (isPerformingImport()) {
405 if (!doImportAsDefinition(&GV))
406 return false;
407 } else if (!DGV && !shouldOverrideFromSrc() &&
408 (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
409 GV.hasAvailableExternallyLinkage()))
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000410 return false;
411
Rafael Espindolabd03c502015-12-07 16:31:41 +0000412 if (GV.isDeclaration())
413 return false;
414
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000415 if (const Comdat *SC = GV.getComdat()) {
416 bool LinkFromSrc;
417 Comdat::SelectionKind SK;
418 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
Rafael Espindolaf2e71242016-03-23 21:16:33 +0000419 if (!LinkFromSrc)
420 return false;
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000421 }
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000422
423 bool LinkFromSrc = true;
424 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
425 return true;
426 if (LinkFromSrc)
427 ValuesToLink.insert(&GV);
428 return false;
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000429}
430
Rafael Espindolacaabe222015-12-10 14:19:35 +0000431void ModuleLinker::addLazyFor(GlobalValue &GV, IRMover::ValueAdder Add) {
432 // Add these to the internalize list
433 if (!GV.hasLinkOnceLinkage())
434 return;
435
436 if (shouldInternalizeLinkedSymbols())
437 Internalize.insert(GV.getName());
438 Add(GV);
439
440 const Comdat *SC = GV.getComdat();
441 if (!SC)
442 return;
Rafael Espindola1ee9fbd2016-03-24 00:06:03 +0000443 for (GlobalValue *GV2 : LazyComdatMembers[SC]) {
Rafael Espindolae1c42ac2016-03-24 15:23:01 +0000444 GlobalValue *DGV = getLinkedToGlobal(GV2);
445 bool LinkFromSrc = true;
446 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
447 return;
448 if (!LinkFromSrc)
449 continue;
Rafael Espindola1ee9fbd2016-03-24 00:06:03 +0000450 if (shouldInternalizeLinkedSymbols())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000451 Internalize.insert(GV2->getName());
452 Add(*GV2);
453 }
454}
455
Rafael Espindola370d5282016-03-22 21:35:47 +0000456void ModuleLinker::dropReplacedComdat(
457 GlobalValue &GV, const DenseSet<const Comdat *> &ReplacedDstComdats) {
458 Comdat *C = GV.getComdat();
459 if (!C)
460 return;
461 if (!ReplacedDstComdats.count(C))
462 return;
463 if (GV.use_empty()) {
464 GV.eraseFromParent();
465 return;
466 }
467
468 if (auto *F = dyn_cast<Function>(&GV)) {
469 F->deleteBody();
470 } else if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {
471 Var->setInitializer(nullptr);
472 } else {
473 auto &Alias = cast<GlobalAlias>(GV);
474 Module &M = *Alias.getParent();
475 PointerType &Ty = *cast<PointerType>(Alias.getType());
476 GlobalValue *Declaration;
477 if (auto *FTy = dyn_cast<FunctionType>(Alias.getValueType())) {
478 Declaration = Function::Create(FTy, GlobalValue::ExternalLinkage, "", &M);
479 } else {
480 Declaration =
481 new GlobalVariable(M, Ty.getElementType(), /*isConstant*/ false,
482 GlobalValue::ExternalLinkage,
483 /*Initializer*/ nullptr);
484 }
485 Declaration->takeName(&Alias);
486 Alias.replaceAllUsesWith(Declaration);
487 Alias.eraseFromParent();
488 }
489}
490
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000491bool ModuleLinker::run() {
Rafael Espindola370d5282016-03-22 21:35:47 +0000492 Module &DstM = Mover.getModule();
493 DenseSet<const Comdat *> ReplacedDstComdats;
494
Rafael Espindola40358fb2016-02-16 18:50:12 +0000495 for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
David Majnemerdad0a642014-06-27 18:19:56 +0000496 const Comdat &C = SMEC.getValue();
497 if (ComdatsChosen.count(&C))
498 continue;
499 Comdat::SelectionKind SK;
500 bool LinkFromSrc;
501 if (getComdatResult(&C, SK, LinkFromSrc))
502 return true;
503 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
Rafael Espindola370d5282016-03-22 21:35:47 +0000504
505 if (!LinkFromSrc)
506 continue;
507
508 Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
509 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(C.getName());
510 if (DstCI == ComdatSymTab.end())
511 continue;
512
513 // The source comdat is replacing the dest one.
514 const Comdat *DstC = &DstCI->second;
515 ReplacedDstComdats.insert(DstC);
516 }
517
518 // Alias have to go first, since we are not able to find their comdats
519 // otherwise.
520 for (auto I = DstM.alias_begin(), E = DstM.alias_end(); I != E;) {
521 GlobalAlias &GV = *I++;
522 dropReplacedComdat(GV, ReplacedDstComdats);
523 }
524
525 for (auto I = DstM.global_begin(), E = DstM.global_end(); I != E;) {
526 GlobalVariable &GV = *I++;
527 dropReplacedComdat(GV, ReplacedDstComdats);
528 }
529
530 for (auto I = DstM.begin(), E = DstM.end(); I != E;) {
531 Function &GV = *I++;
532 dropReplacedComdat(GV, ReplacedDstComdats);
David Majnemerdad0a642014-06-27 18:19:56 +0000533 }
534
Rafael Espindola40358fb2016-02-16 18:50:12 +0000535 for (GlobalVariable &GV : SrcM->globals())
Rafael Espindola1ee9fbd2016-03-24 00:06:03 +0000536 if (GV.hasLinkOnceLinkage())
537 if (const Comdat *SC = GV.getComdat())
538 LazyComdatMembers[SC].push_back(&GV);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000539
Rafael Espindola40358fb2016-02-16 18:50:12 +0000540 for (Function &SF : *SrcM)
Rafael Espindola1ee9fbd2016-03-24 00:06:03 +0000541 if (SF.hasLinkOnceLinkage())
542 if (const Comdat *SC = SF.getComdat())
543 LazyComdatMembers[SC].push_back(&SF);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000544
Rafael Espindola40358fb2016-02-16 18:50:12 +0000545 for (GlobalAlias &GA : SrcM->aliases())
Rafael Espindola1ee9fbd2016-03-24 00:06:03 +0000546 if (GA.hasLinkOnceLinkage())
547 if (const Comdat *SC = GA.getComdat())
548 LazyComdatMembers[SC].push_back(&GA);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000549
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000550 // Insert all of the globals in src into the DstM module... without linking
551 // initializers (which could refer to functions not yet mapped over).
Rafael Espindola40358fb2016-02-16 18:50:12 +0000552 for (GlobalVariable &GV : SrcM->globals())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000553 if (linkIfNeeded(GV))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000554 return true;
555
Rafael Espindola40358fb2016-02-16 18:50:12 +0000556 for (Function &SF : *SrcM)
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000557 if (linkIfNeeded(SF))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000558 return true;
559
Rafael Espindola40358fb2016-02-16 18:50:12 +0000560 for (GlobalAlias &GA : SrcM->aliases())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000561 if (linkIfNeeded(GA))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000562 return true;
563
Rafael Espindolacaabe222015-12-10 14:19:35 +0000564 for (unsigned I = 0; I < ValuesToLink.size(); ++I) {
565 GlobalValue *GV = ValuesToLink[I];
566 const Comdat *SC = GV->getComdat();
567 if (!SC)
568 continue;
Rafael Espindola42e03232016-03-24 14:58:44 +0000569 for (GlobalValue *GV2 : LazyComdatMembers[SC]) {
570 GlobalValue *DGV = getLinkedToGlobal(GV2);
571 bool LinkFromSrc = true;
572 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
573 return true;
574 if (LinkFromSrc)
575 ValuesToLink.insert(GV2);
576 }
Rafael Espindolabeadd562014-12-08 18:05:48 +0000577 }
578
Rafael Espindolacaabe222015-12-10 14:19:35 +0000579 if (shouldInternalizeLinkedSymbols()) {
580 for (GlobalValue *GV : ValuesToLink)
581 Internalize.insert(GV->getName());
582 }
Teresa Johnson10632932015-11-06 17:50:53 +0000583
Rafael Espindola40358fb2016-02-16 18:50:12 +0000584 if (Mover.move(std::move(SrcM), ValuesToLink.getArrayRef(),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000585 [this](GlobalValue &GV, IRMover::ValueAdder Add) {
586 addLazyFor(GV, Add);
Teresa Johnsonb703c772016-03-29 18:24:19 +0000587 }))
Teresa Johnson189b2522015-11-06 17:50:48 +0000588 return true;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000589 for (auto &P : Internalize) {
590 GlobalValue *GV = DstM.getNamedValue(P.first());
591 GV->setLinkage(GlobalValue::InternalLinkage);
592 }
Teresa Johnson189b2522015-11-06 17:50:48 +0000593
Anton Korobeynikov26098882008-03-05 23:21:39 +0000594 return false;
595}
Reid Spencer361e5132004-11-12 20:37:43 +0000596
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000597Linker::Linker(Module &M) : Mover(M) {}
Rafael Espindola3df61b72013-05-04 03:48:37 +0000598
Rafael Espindola434e9562015-12-16 23:16:33 +0000599bool Linker::linkInModule(std::unique_ptr<Module> Src, unsigned Flags,
Teresa Johnsonb703c772016-03-29 18:24:19 +0000600 DenseSet<const GlobalValue *> *GlobalsToImport) {
601 ModuleLinker ModLinker(Mover, std::move(Src), Flags, GlobalsToImport);
Teresa Johnsonbef54362015-12-18 19:28:59 +0000602 return ModLinker.run();
Rafael Espindola434e9562015-12-16 23:16:33 +0000603}
604
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000605//===----------------------------------------------------------------------===//
606// LinkModules entrypoint.
607//===----------------------------------------------------------------------===//
608
Rafael Espindola18c89412014-10-27 02:35:46 +0000609/// This function links two modules together, with the resulting Dest module
610/// modified to be the composite of the two input modules. If an error occurs,
611/// true is returned and ErrorMsg (if not null) is set to indicate the problem.
612/// Upon failure, the Dest module could be in a modified state, and shouldn't be
613/// relied on to be consistent.
Rafael Espindola434e9562015-12-16 23:16:33 +0000614bool Linker::linkModules(Module &Dest, std::unique_ptr<Module> Src,
615 unsigned Flags) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000616 Linker L(Dest);
Rafael Espindola434e9562015-12-16 23:16:33 +0000617 return L.linkInModule(std::move(Src), Flags);
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000618}
619
Bill Wendlinga3aeb982012-05-09 08:55:40 +0000620//===----------------------------------------------------------------------===//
621// C API.
622//===----------------------------------------------------------------------===//
623
Rafael Espindola434e9562015-12-16 23:16:33 +0000624LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src) {
625 Module *D = unwrap(Dest);
626 std::unique_ptr<Module> M(unwrap(Src));
627 return Linker::linkModules(*D, std::move(M));
628}