blob: f6e0f060cc0981d597674093093534da73a3e0fe [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
Teresa Johnsone5a61912015-12-17 17:14:09 +000042 /// Association between metadata value id and temporary metadata that
43 /// remains unmapped after function importing. Saved during function
44 /// importing and consumed during the metadata linking postpass.
45 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap;
46
Rafael Espindolacaabe222015-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.
51 void addLazyFor(GlobalValue &GV, IRMover::ValueAdder Add);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +000052
Artem Belevich020d4fb2015-09-01 17:55:55 +000053 bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
54 bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
55 bool shouldInternalizeLinkedSymbols() {
56 return Flags & Linker::InternalizeLinkedSymbols;
57 }
58
Rafael Espindolac84f6082014-11-25 06:11:24 +000059 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
60 const GlobalValue &Src);
Rafael Espindolaed6dc372014-05-09 14:39:25 +000061
Rafael Espindolacaabe222015-12-10 14:19:35 +000062 /// Should we have mover and linker error diag info?
Rafael Espindolac84f6082014-11-25 06:11:24 +000063 bool emitError(const Twine &Message) {
Rafael Espindola40358fb2016-02-16 18:50:12 +000064 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
Rafael Espindolac84f6082014-11-25 06:11:24 +000065 return true;
66 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +000067
Rafael Espindola0e309fe2015-12-01 19:50:54 +000068 bool getComdatLeader(Module &M, StringRef ComdatName,
Rafael Espindolac84f6082014-11-25 06:11:24 +000069 const GlobalVariable *&GVar);
70 bool computeResultingSelectionKind(StringRef ComdatName,
71 Comdat::SelectionKind Src,
72 Comdat::SelectionKind Dst,
73 Comdat::SelectionKind &Result,
74 bool &LinkFromSrc);
75 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
76 ComdatsChosen;
77 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
78 bool &LinkFromSrc);
Rafael Espindola1ee9fbd2016-03-24 00:06:03 +000079 // Keep track of the lazy linked global members of each comdat in source.
80 DenseMap<const Comdat *, std::vector<GlobalValue *>> LazyComdatMembers;
Rafael Espindola4160f5d2014-10-27 23:02:10 +000081
Rafael Espindolac84f6082014-11-25 06:11:24 +000082 /// Given a global in the source module, return the global in the
83 /// destination module that is being linked to, if any.
84 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
Rafael Espindolacaabe222015-12-10 14:19:35 +000085 Module &DstM = Mover.getModule();
Rafael Espindolac84f6082014-11-25 06:11:24 +000086 // If the source has no name it can't link. If it has local linkage,
87 // there is no name match-up going on.
Teresa Johnson4504c1b2016-01-08 15:00:00 +000088 if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(SrcGV->getLinkage()))
Rafael Espindolac84f6082014-11-25 06:11:24 +000089 return nullptr;
Eli Bendersky7da92ed2014-02-20 22:19:24 +000090
Rafael Espindolac84f6082014-11-25 06:11:24 +000091 // Otherwise see if we have a match in the destination module's symtab.
Teresa Johnson4504c1b2016-01-08 15:00:00 +000092 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
Rafael Espindolac84f6082014-11-25 06:11:24 +000093 if (!DGV)
94 return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +000095
Rafael Espindolac84f6082014-11-25 06:11:24 +000096 // If we found a global with the same name in the dest module, but it has
97 // internal linkage, we are really not doing any linkage here.
98 if (DGV->hasLocalLinkage())
99 return nullptr;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000100
Rafael Espindolac84f6082014-11-25 06:11:24 +0000101 // Otherwise, we do in fact link to the destination global.
102 return DGV;
103 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000104
Rafael Espindola370d5282016-03-22 21:35:47 +0000105 /// Drop GV if it is a member of a comdat that we are dropping.
106 /// This can happen with COFF's largest selection kind.
107 void dropReplacedComdat(GlobalValue &GV,
108 const DenseSet<const Comdat *> &ReplacedDstComdats);
109
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000110 bool linkIfNeeded(GlobalValue &GV);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000111
Teresa Johnson4504c1b2016-01-08 15:00:00 +0000112 /// Helper method to check if we are importing from the current source
113 /// module.
Mehdi Amini8d051852016-03-19 00:40:31 +0000114 bool isPerformingImport() const { return GlobalsToImport != nullptr; }
Teresa Johnson4504c1b2016-01-08 15:00:00 +0000115
116 /// If we are importing from the source module, checks if we should
117 /// import SGV as a definition, otherwise import as a declaration.
118 bool doImportAsDefinition(const GlobalValue *SGV);
119
120public:
Rafael Espindola40358fb2016-02-16 18:50:12 +0000121 ModuleLinker(IRMover &Mover, std::unique_ptr<Module> SrcM, unsigned Flags,
Mehdi Amini8d051852016-03-19 00:40:31 +0000122 DenseSet<const GlobalValue *> *GlobalsToImport = nullptr,
Teresa Johnson4504c1b2016-01-08 15:00:00 +0000123 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap = nullptr)
Mehdi Amini8d051852016-03-19 00:40:31 +0000124 : Mover(Mover), SrcM(std::move(SrcM)), Flags(Flags),
125 GlobalsToImport(GlobalsToImport), ValIDToTempMDMap(ValIDToTempMDMap) {}
Teresa Johnson4504c1b2016-01-08 15:00:00 +0000126
127 bool run();
128};
Teresa Johnson4504c1b2016-01-08 15:00:00 +0000129}
130
131bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
132 if (!isPerformingImport())
133 return false;
Mehdi Amini8d051852016-03-19 00:40:31 +0000134 return FunctionImportGlobalProcessing::doImportAsDefinition(SGV,
135 GlobalsToImport);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000136}
137
Rafael Espindolaeb5e0a72015-11-29 14:33:06 +0000138static GlobalValue::VisibilityTypes
139getMinVisibility(GlobalValue::VisibilityTypes A,
140 GlobalValue::VisibilityTypes B) {
141 if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
142 return GlobalValue::HiddenVisibility;
143 if (A == GlobalValue::ProtectedVisibility ||
144 B == GlobalValue::ProtectedVisibility)
145 return GlobalValue::ProtectedVisibility;
146 return GlobalValue::DefaultVisibility;
147}
148
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000149bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
David Majnemerdad0a642014-06-27 18:19:56 +0000150 const GlobalVariable *&GVar) {
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000151 const GlobalValue *GVal = M.getNamedValue(ComdatName);
David Majnemerdad0a642014-06-27 18:19:56 +0000152 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
153 GVal = GA->getBaseObject();
154 if (!GVal)
155 // We cannot resolve the size of the aliasee yet.
156 return emitError("Linking COMDATs named '" + ComdatName +
157 "': COMDAT key involves incomputable alias size.");
158 }
159
160 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
161 if (!GVar)
162 return emitError(
163 "Linking COMDATs named '" + ComdatName +
164 "': GlobalVariable required for data dependent selection!");
165
166 return false;
167}
168
169bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
170 Comdat::SelectionKind Src,
171 Comdat::SelectionKind Dst,
172 Comdat::SelectionKind &Result,
173 bool &LinkFromSrc) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000174 Module &DstM = Mover.getModule();
David Majnemerdad0a642014-06-27 18:19:56 +0000175 // The ability to mix Comdat::SelectionKind::Any with
176 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
177 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
178 Dst == Comdat::SelectionKind::Largest;
179 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
180 Src == Comdat::SelectionKind::Largest;
181 if (DstAnyOrLargest && SrcAnyOrLargest) {
182 if (Dst == Comdat::SelectionKind::Largest ||
183 Src == Comdat::SelectionKind::Largest)
184 Result = Comdat::SelectionKind::Largest;
185 else
186 Result = Comdat::SelectionKind::Any;
187 } else if (Src == Dst) {
188 Result = Dst;
189 } else {
190 return emitError("Linking COMDATs named '" + ComdatName +
191 "': invalid selection kinds!");
192 }
193
194 switch (Result) {
195 case Comdat::SelectionKind::Any:
196 // Go with Dst.
197 LinkFromSrc = false;
198 break;
199 case Comdat::SelectionKind::NoDuplicates:
200 return emitError("Linking COMDATs named '" + ComdatName +
201 "': noduplicates has been violated!");
202 case Comdat::SelectionKind::ExactMatch:
203 case Comdat::SelectionKind::Largest:
204 case Comdat::SelectionKind::SameSize: {
205 const GlobalVariable *DstGV;
206 const GlobalVariable *SrcGV;
207 if (getComdatLeader(DstM, ComdatName, DstGV) ||
Rafael Espindola40358fb2016-02-16 18:50:12 +0000208 getComdatLeader(*SrcM, ComdatName, SrcGV))
David Majnemerdad0a642014-06-27 18:19:56 +0000209 return true;
210
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000211 const DataLayout &DstDL = DstM.getDataLayout();
Rafael Espindola40358fb2016-02-16 18:50:12 +0000212 const DataLayout &SrcDL = SrcM->getDataLayout();
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000213 uint64_t DstSize = DstDL.getTypeAllocSize(DstGV->getValueType());
214 uint64_t SrcSize = SrcDL.getTypeAllocSize(SrcGV->getValueType());
David Majnemerdad0a642014-06-27 18:19:56 +0000215 if (Result == Comdat::SelectionKind::ExactMatch) {
216 if (SrcGV->getInitializer() != DstGV->getInitializer())
217 return emitError("Linking COMDATs named '" + ComdatName +
218 "': ExactMatch violated!");
219 LinkFromSrc = false;
220 } else if (Result == Comdat::SelectionKind::Largest) {
221 LinkFromSrc = SrcSize > DstSize;
222 } else if (Result == Comdat::SelectionKind::SameSize) {
223 if (SrcSize != DstSize)
224 return emitError("Linking COMDATs named '" + ComdatName +
225 "': SameSize violated!");
226 LinkFromSrc = false;
227 } else {
228 llvm_unreachable("unknown selection kind");
229 }
230 break;
231 }
232 }
233
234 return false;
235}
236
237bool ModuleLinker::getComdatResult(const Comdat *SrcC,
238 Comdat::SelectionKind &Result,
239 bool &LinkFromSrc) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000240 Module &DstM = Mover.getModule();
Rafael Espindolab16196a2014-08-11 17:07:34 +0000241 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
David Majnemerdad0a642014-06-27 18:19:56 +0000242 StringRef ComdatName = SrcC->getName();
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000243 Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
David Majnemerdad0a642014-06-27 18:19:56 +0000244 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000245
Rafael Espindolab16196a2014-08-11 17:07:34 +0000246 if (DstCI == ComdatSymTab.end()) {
247 // Use the comdat if it is only available in one of the modules.
248 LinkFromSrc = true;
249 Result = SSK;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000250 return false;
Rafael Espindolab16196a2014-08-11 17:07:34 +0000251 }
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000252
253 const Comdat *DstC = &DstCI->second;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000254 Comdat::SelectionKind DSK = DstC->getSelectionKind();
255 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
256 LinkFromSrc);
David Majnemerdad0a642014-06-27 18:19:56 +0000257}
James Molloyf6f121e2013-05-28 15:17:05 +0000258
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000259bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
260 const GlobalValue &Dest,
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000261 const GlobalValue &Src) {
Teresa Johnsone5a61912015-12-17 17:14:09 +0000262
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000263 // Should we unconditionally use the Src?
Artem Belevich020d4fb2015-09-01 17:55:55 +0000264 if (shouldOverrideFromSrc()) {
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000265 LinkFromSrc = true;
266 return false;
267 }
268
Rafael Espindola778fcc72014-11-02 13:28:57 +0000269 // We always have to add Src if it has appending linkage.
270 if (Src.hasAppendingLinkage()) {
Teresa Johnson1e20a652015-12-03 18:20:05 +0000271 // Should have prevented importing for appending linkage in linkIfNeeded.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000272 assert(!isPerformingImport());
Rafael Espindola778fcc72014-11-02 13:28:57 +0000273 LinkFromSrc = true;
274 return false;
275 }
276
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000277 bool SrcIsDeclaration = Src.isDeclarationForLinker();
278 bool DestIsDeclaration = Dest.isDeclarationForLinker();
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000279
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000280 if (isPerformingImport()) {
281 if (isa<Function>(&Src)) {
Teresa Johnson4f04d852015-12-21 17:33:24 +0000282 // For functions, LinkFromSrc iff this is a function requested
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000283 // for importing. For variables, decide below normally.
Mehdi Amini8d051852016-03-19 00:40:31 +0000284 LinkFromSrc = GlobalsToImport->count(&Src);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000285 return false;
286 }
287
288 // Check if this is an alias with an already existing definition
289 // in Dest, which must have come from a prior importing pass from
290 // the same Src module. Unlike imported function and variable
291 // definitions, which are imported as available_externally and are
292 // not definitions for the linker, that is not a valid linkage for
293 // imported aliases which must be definitions. Simply use the existing
294 // Dest copy.
295 if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
296 assert(isa<GlobalAlias>(&Dest));
297 LinkFromSrc = false;
298 return false;
299 }
300 }
301
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000302 if (SrcIsDeclaration) {
303 // If Src is external or if both Src & Dest are external.. Just link the
304 // external globals, we aren't adding anything.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000305 if (Src.hasDLLImportStorageClass()) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000306 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000307 LinkFromSrc = DestIsDeclaration;
308 return false;
309 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000310 // If the Dest is weak, use the source linkage.
Rafael Espindolaed11bd22015-12-09 22:44:00 +0000311 if (Dest.hasExternalWeakLinkage()) {
312 LinkFromSrc = true;
313 return false;
314 }
315 // Link an available_externally over a declaration.
316 LinkFromSrc = !Src.isDeclaration() && Dest.isDeclaration();
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000317 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000318 }
319
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000320 if (DestIsDeclaration) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000321 // If Dest is external but Src is not:
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000322 LinkFromSrc = true;
323 return false;
324 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000325
Rafael Espindola09106052014-09-09 15:59:12 +0000326 if (Src.hasCommonLinkage()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000327 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
328 LinkFromSrc = true;
Rafael Espindola09106052014-09-09 15:59:12 +0000329 return false;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000330 }
331
332 if (!Dest.hasCommonLinkage()) {
333 LinkFromSrc = false;
334 return false;
335 }
Rafael Espindola09106052014-09-09 15:59:12 +0000336
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000337 const DataLayout &DL = Dest.getParent()->getDataLayout();
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000338 uint64_t DestSize = DL.getTypeAllocSize(Dest.getValueType());
339 uint64_t SrcSize = DL.getTypeAllocSize(Src.getValueType());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000340 LinkFromSrc = SrcSize > DestSize;
341 return false;
Rafael Espindola09106052014-09-09 15:59:12 +0000342 }
343
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000344 if (Src.isWeakForLinker()) {
345 assert(!Dest.hasExternalWeakLinkage());
346 assert(!Dest.hasAvailableExternallyLinkage());
Rafael Espindola09106052014-09-09 15:59:12 +0000347
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000348 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
349 LinkFromSrc = true;
350 return false;
351 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000352
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000353 LinkFromSrc = false;
Rafael Espindola09106052014-09-09 15:59:12 +0000354 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000355 }
356
357 if (Dest.isWeakForLinker()) {
358 assert(Src.hasExternalLinkage());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000359 LinkFromSrc = true;
360 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000361 }
362
363 assert(!Src.hasExternalWeakLinkage());
364 assert(!Dest.hasExternalWeakLinkage());
365 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
366 "Unexpected linkage type!");
367 return emitError("Linking globals named '" + Src.getName() +
368 "': symbol multiply defined!");
369}
370
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000371bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
372 GlobalValue *DGV = getLinkedToGlobal(&GV);
373
374 if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
375 return false;
376
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000377 if (DGV && !GV.hasLocalLinkage() && !GV.hasAppendingLinkage()) {
378 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
379 auto *SGVar = dyn_cast<GlobalVariable>(&GV);
380 if (DGVar && SGVar) {
381 if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
382 (!DGVar->isConstant() || !SGVar->isConstant())) {
383 DGVar->setConstant(false);
384 SGVar->setConstant(false);
385 }
386 if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
387 unsigned Align = std::max(DGVar->getAlignment(), SGVar->getAlignment());
388 SGVar->setAlignment(Align);
389 DGVar->setAlignment(Align);
390 }
391 }
392
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000393 GlobalValue::VisibilityTypes Visibility =
394 getMinVisibility(DGV->getVisibility(), GV.getVisibility());
395 DGV->setVisibility(Visibility);
396 GV.setVisibility(Visibility);
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000397
398 bool HasUnnamedAddr = GV.hasUnnamedAddr() && DGV->hasUnnamedAddr();
399 DGV->setUnnamedAddr(HasUnnamedAddr);
400 GV.setUnnamedAddr(HasUnnamedAddr);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000401 }
402
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000403 // Don't want to append to global_ctors list, for example, when we
404 // are importing for ThinLTO, otherwise the global ctors and dtors
405 // get executed multiple times for local variables (the latter causing
406 // double frees).
407 if (GV.hasAppendingLinkage() && isPerformingImport())
408 return false;
409
Mehdi Amini8d051852016-03-19 00:40:31 +0000410 if (isPerformingImport()) {
411 if (!doImportAsDefinition(&GV))
412 return false;
413 } else if (!DGV && !shouldOverrideFromSrc() &&
414 (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
415 GV.hasAvailableExternallyLinkage()))
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000416 return false;
417
Rafael Espindolabd03c502015-12-07 16:31:41 +0000418 if (GV.isDeclaration())
419 return false;
420
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000421 if (const Comdat *SC = GV.getComdat()) {
422 bool LinkFromSrc;
423 Comdat::SelectionKind SK;
424 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
Rafael Espindolaf2e71242016-03-23 21:16:33 +0000425 if (!LinkFromSrc)
426 return false;
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000427 }
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000428
429 bool LinkFromSrc = true;
430 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
431 return true;
432 if (LinkFromSrc)
433 ValuesToLink.insert(&GV);
434 return false;
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000435}
436
Rafael Espindolacaabe222015-12-10 14:19:35 +0000437void ModuleLinker::addLazyFor(GlobalValue &GV, IRMover::ValueAdder Add) {
438 // Add these to the internalize list
439 if (!GV.hasLinkOnceLinkage())
440 return;
441
442 if (shouldInternalizeLinkedSymbols())
443 Internalize.insert(GV.getName());
444 Add(GV);
445
446 const Comdat *SC = GV.getComdat();
447 if (!SC)
448 return;
Rafael Espindola1ee9fbd2016-03-24 00:06:03 +0000449 for (GlobalValue *GV2 : LazyComdatMembers[SC]) {
450 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 Johnsone5a61912015-12-17 17:14:09 +0000587 },
588 ValIDToTempMDMap, false))
Teresa Johnson189b2522015-11-06 17:50:48 +0000589 return true;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000590 for (auto &P : Internalize) {
591 GlobalValue *GV = DstM.getNamedValue(P.first());
592 GV->setLinkage(GlobalValue::InternalLinkage);
593 }
Teresa Johnson189b2522015-11-06 17:50:48 +0000594
Anton Korobeynikov26098882008-03-05 23:21:39 +0000595 return false;
596}
Reid Spencer361e5132004-11-12 20:37:43 +0000597
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000598Linker::Linker(Module &M) : Mover(M) {}
Rafael Espindola3df61b72013-05-04 03:48:37 +0000599
Rafael Espindola434e9562015-12-16 23:16:33 +0000600bool Linker::linkInModule(std::unique_ptr<Module> Src, unsigned Flags,
Mehdi Amini8d051852016-03-19 00:40:31 +0000601 DenseSet<const GlobalValue *> *GlobalsToImport,
Teresa Johnsone5a61912015-12-17 17:14:09 +0000602 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap) {
Mehdi Amini8d051852016-03-19 00:40:31 +0000603 ModuleLinker ModLinker(Mover, std::move(Src), Flags, GlobalsToImport,
Teresa Johnsone5a61912015-12-17 17:14:09 +0000604 ValIDToTempMDMap);
Teresa Johnsonbef54362015-12-18 19:28:59 +0000605 return ModLinker.run();
Rafael Espindola434e9562015-12-16 23:16:33 +0000606}
607
Rafael Espindola40358fb2016-02-16 18:50:12 +0000608bool Linker::linkInMetadata(std::unique_ptr<Module> Src,
Teresa Johnsone5a61912015-12-17 17:14:09 +0000609 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap) {
610 SetVector<GlobalValue *> ValuesToLink;
611 if (Mover.move(
Rafael Espindola40358fb2016-02-16 18:50:12 +0000612 std::move(Src), ValuesToLink.getArrayRef(),
Teresa Johnsone5a61912015-12-17 17:14:09 +0000613 [this](GlobalValue &GV, IRMover::ValueAdder Add) { assert(false); },
614 ValIDToTempMDMap, true))
615 return true;
616 return false;
617}
618
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000619//===----------------------------------------------------------------------===//
620// LinkModules entrypoint.
621//===----------------------------------------------------------------------===//
622
Rafael Espindola18c89412014-10-27 02:35:46 +0000623/// This function links two modules together, with the resulting Dest module
624/// modified to be the composite of the two input modules. If an error occurs,
625/// true is returned and ErrorMsg (if not null) is set to indicate the problem.
626/// Upon failure, the Dest module could be in a modified state, and shouldn't be
627/// relied on to be consistent.
Rafael Espindola434e9562015-12-16 23:16:33 +0000628bool Linker::linkModules(Module &Dest, std::unique_ptr<Module> Src,
629 unsigned Flags) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000630 Linker L(Dest);
Rafael Espindola434e9562015-12-16 23:16:33 +0000631 return L.linkInModule(std::move(Src), Flags);
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000632}
633
Bill Wendlinga3aeb982012-05-09 08:55:40 +0000634//===----------------------------------------------------------------------===//
635// C API.
636//===----------------------------------------------------------------------===//
637
Rafael Espindola434e9562015-12-16 23:16:33 +0000638LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src) {
639 Module *D = unwrap(Dest);
640 std::unique_ptr<Module> M(unwrap(Src));
641 return Linker::linkModules(*D, std::move(M));
642}