blob: 2ee0b9664a372565a2780a6aaae6968ac07ed17c [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);
Teresa Johnson2d5fb8c2015-11-10 21:09:06 +000079 // Keep track of the global value members of each comdat in source.
80 DenseMap<const Comdat *, std::vector<GlobalValue *>> ComdatMembers;
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 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,
Mehdi Amini8d051852016-03-19 00:40:31 +0000117 DenseSet<const GlobalValue *> *GlobalsToImport = nullptr,
Teresa Johnson4504c1b2016-01-08 15:00:00 +0000118 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap = nullptr)
Mehdi Amini8d051852016-03-19 00:40:31 +0000119 : Mover(Mover), SrcM(std::move(SrcM)), Flags(Flags),
120 GlobalsToImport(GlobalsToImport), ValIDToTempMDMap(ValIDToTempMDMap) {}
Teresa Johnson4504c1b2016-01-08 15:00:00 +0000121
122 bool run();
123};
Teresa Johnson4504c1b2016-01-08 15:00:00 +0000124}
125
126bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
127 if (!isPerformingImport())
128 return false;
Mehdi Amini8d051852016-03-19 00:40:31 +0000129 return FunctionImportGlobalProcessing::doImportAsDefinition(SGV,
130 GlobalsToImport);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000131}
132
Rafael Espindolaeb5e0a72015-11-29 14:33:06 +0000133static GlobalValue::VisibilityTypes
134getMinVisibility(GlobalValue::VisibilityTypes A,
135 GlobalValue::VisibilityTypes B) {
136 if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
137 return GlobalValue::HiddenVisibility;
138 if (A == GlobalValue::ProtectedVisibility ||
139 B == GlobalValue::ProtectedVisibility)
140 return GlobalValue::ProtectedVisibility;
141 return GlobalValue::DefaultVisibility;
142}
143
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000144bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
David Majnemerdad0a642014-06-27 18:19:56 +0000145 const GlobalVariable *&GVar) {
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000146 const GlobalValue *GVal = M.getNamedValue(ComdatName);
David Majnemerdad0a642014-06-27 18:19:56 +0000147 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
148 GVal = GA->getBaseObject();
149 if (!GVal)
150 // We cannot resolve the size of the aliasee yet.
151 return emitError("Linking COMDATs named '" + ComdatName +
152 "': COMDAT key involves incomputable alias size.");
153 }
154
155 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
156 if (!GVar)
157 return emitError(
158 "Linking COMDATs named '" + ComdatName +
159 "': GlobalVariable required for data dependent selection!");
160
161 return false;
162}
163
164bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
165 Comdat::SelectionKind Src,
166 Comdat::SelectionKind Dst,
167 Comdat::SelectionKind &Result,
168 bool &LinkFromSrc) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000169 Module &DstM = Mover.getModule();
David Majnemerdad0a642014-06-27 18:19:56 +0000170 // The ability to mix Comdat::SelectionKind::Any with
171 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
172 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
173 Dst == Comdat::SelectionKind::Largest;
174 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
175 Src == Comdat::SelectionKind::Largest;
176 if (DstAnyOrLargest && SrcAnyOrLargest) {
177 if (Dst == Comdat::SelectionKind::Largest ||
178 Src == Comdat::SelectionKind::Largest)
179 Result = Comdat::SelectionKind::Largest;
180 else
181 Result = Comdat::SelectionKind::Any;
182 } else if (Src == Dst) {
183 Result = Dst;
184 } else {
185 return emitError("Linking COMDATs named '" + ComdatName +
186 "': invalid selection kinds!");
187 }
188
189 switch (Result) {
190 case Comdat::SelectionKind::Any:
191 // Go with Dst.
192 LinkFromSrc = false;
193 break;
194 case Comdat::SelectionKind::NoDuplicates:
195 return emitError("Linking COMDATs named '" + ComdatName +
196 "': noduplicates has been violated!");
197 case Comdat::SelectionKind::ExactMatch:
198 case Comdat::SelectionKind::Largest:
199 case Comdat::SelectionKind::SameSize: {
200 const GlobalVariable *DstGV;
201 const GlobalVariable *SrcGV;
202 if (getComdatLeader(DstM, ComdatName, DstGV) ||
Rafael Espindola40358fb2016-02-16 18:50:12 +0000203 getComdatLeader(*SrcM, ComdatName, SrcGV))
David Majnemerdad0a642014-06-27 18:19:56 +0000204 return true;
205
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000206 const DataLayout &DstDL = DstM.getDataLayout();
Rafael Espindola40358fb2016-02-16 18:50:12 +0000207 const DataLayout &SrcDL = SrcM->getDataLayout();
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000208 uint64_t DstSize = DstDL.getTypeAllocSize(DstGV->getValueType());
209 uint64_t SrcSize = SrcDL.getTypeAllocSize(SrcGV->getValueType());
David Majnemerdad0a642014-06-27 18:19:56 +0000210 if (Result == Comdat::SelectionKind::ExactMatch) {
211 if (SrcGV->getInitializer() != DstGV->getInitializer())
212 return emitError("Linking COMDATs named '" + ComdatName +
213 "': ExactMatch violated!");
214 LinkFromSrc = false;
215 } else if (Result == Comdat::SelectionKind::Largest) {
216 LinkFromSrc = SrcSize > DstSize;
217 } else if (Result == Comdat::SelectionKind::SameSize) {
218 if (SrcSize != DstSize)
219 return emitError("Linking COMDATs named '" + ComdatName +
220 "': SameSize violated!");
221 LinkFromSrc = false;
222 } else {
223 llvm_unreachable("unknown selection kind");
224 }
225 break;
226 }
227 }
228
229 return false;
230}
231
232bool ModuleLinker::getComdatResult(const Comdat *SrcC,
233 Comdat::SelectionKind &Result,
234 bool &LinkFromSrc) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000235 Module &DstM = Mover.getModule();
Rafael Espindolab16196a2014-08-11 17:07:34 +0000236 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
David Majnemerdad0a642014-06-27 18:19:56 +0000237 StringRef ComdatName = SrcC->getName();
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000238 Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
David Majnemerdad0a642014-06-27 18:19:56 +0000239 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000240
Rafael Espindolab16196a2014-08-11 17:07:34 +0000241 if (DstCI == ComdatSymTab.end()) {
242 // Use the comdat if it is only available in one of the modules.
243 LinkFromSrc = true;
244 Result = SSK;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000245 return false;
Rafael Espindolab16196a2014-08-11 17:07:34 +0000246 }
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000247
248 const Comdat *DstC = &DstCI->second;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000249 Comdat::SelectionKind DSK = DstC->getSelectionKind();
250 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
251 LinkFromSrc);
David Majnemerdad0a642014-06-27 18:19:56 +0000252}
James Molloyf6f121e2013-05-28 15:17:05 +0000253
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000254bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
255 const GlobalValue &Dest,
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000256 const GlobalValue &Src) {
Teresa Johnsone5a61912015-12-17 17:14:09 +0000257
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000258 // Should we unconditionally use the Src?
Artem Belevich020d4fb2015-09-01 17:55:55 +0000259 if (shouldOverrideFromSrc()) {
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000260 LinkFromSrc = true;
261 return false;
262 }
263
Rafael Espindola778fcc72014-11-02 13:28:57 +0000264 // We always have to add Src if it has appending linkage.
265 if (Src.hasAppendingLinkage()) {
Teresa Johnson1e20a652015-12-03 18:20:05 +0000266 // Should have prevented importing for appending linkage in linkIfNeeded.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000267 assert(!isPerformingImport());
Rafael Espindola778fcc72014-11-02 13:28:57 +0000268 LinkFromSrc = true;
269 return false;
270 }
271
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000272 bool SrcIsDeclaration = Src.isDeclarationForLinker();
273 bool DestIsDeclaration = Dest.isDeclarationForLinker();
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000274
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000275 if (isPerformingImport()) {
276 if (isa<Function>(&Src)) {
Teresa Johnson4f04d852015-12-21 17:33:24 +0000277 // For functions, LinkFromSrc iff this is a function requested
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000278 // for importing. For variables, decide below normally.
Mehdi Amini8d051852016-03-19 00:40:31 +0000279 LinkFromSrc = GlobalsToImport->count(&Src);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000280 return false;
281 }
282
283 // Check if this is an alias with an already existing definition
284 // in Dest, which must have come from a prior importing pass from
285 // the same Src module. Unlike imported function and variable
286 // definitions, which are imported as available_externally and are
287 // not definitions for the linker, that is not a valid linkage for
288 // imported aliases which must be definitions. Simply use the existing
289 // Dest copy.
290 if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
291 assert(isa<GlobalAlias>(&Dest));
292 LinkFromSrc = false;
293 return false;
294 }
295 }
296
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000297 if (SrcIsDeclaration) {
298 // If Src is external or if both Src & Dest are external.. Just link the
299 // external globals, we aren't adding anything.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000300 if (Src.hasDLLImportStorageClass()) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000301 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000302 LinkFromSrc = DestIsDeclaration;
303 return false;
304 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000305 // If the Dest is weak, use the source linkage.
Rafael Espindolaed11bd22015-12-09 22:44:00 +0000306 if (Dest.hasExternalWeakLinkage()) {
307 LinkFromSrc = true;
308 return false;
309 }
310 // Link an available_externally over a declaration.
311 LinkFromSrc = !Src.isDeclaration() && Dest.isDeclaration();
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000312 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000313 }
314
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000315 if (DestIsDeclaration) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000316 // If Dest is external but Src is not:
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000317 LinkFromSrc = true;
318 return false;
319 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000320
Rafael Espindola09106052014-09-09 15:59:12 +0000321 if (Src.hasCommonLinkage()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000322 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
323 LinkFromSrc = true;
Rafael Espindola09106052014-09-09 15:59:12 +0000324 return false;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000325 }
326
327 if (!Dest.hasCommonLinkage()) {
328 LinkFromSrc = false;
329 return false;
330 }
Rafael Espindola09106052014-09-09 15:59:12 +0000331
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000332 const DataLayout &DL = Dest.getParent()->getDataLayout();
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000333 uint64_t DestSize = DL.getTypeAllocSize(Dest.getValueType());
334 uint64_t SrcSize = DL.getTypeAllocSize(Src.getValueType());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000335 LinkFromSrc = SrcSize > DestSize;
336 return false;
Rafael Espindola09106052014-09-09 15:59:12 +0000337 }
338
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000339 if (Src.isWeakForLinker()) {
340 assert(!Dest.hasExternalWeakLinkage());
341 assert(!Dest.hasAvailableExternallyLinkage());
Rafael Espindola09106052014-09-09 15:59:12 +0000342
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000343 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
344 LinkFromSrc = true;
345 return false;
346 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000347
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000348 LinkFromSrc = false;
Rafael Espindola09106052014-09-09 15:59:12 +0000349 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000350 }
351
352 if (Dest.isWeakForLinker()) {
353 assert(Src.hasExternalLinkage());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000354 LinkFromSrc = true;
355 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000356 }
357
358 assert(!Src.hasExternalWeakLinkage());
359 assert(!Dest.hasExternalWeakLinkage());
360 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
361 "Unexpected linkage type!");
362 return emitError("Linking globals named '" + Src.getName() +
363 "': symbol multiply defined!");
364}
365
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000366bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
367 GlobalValue *DGV = getLinkedToGlobal(&GV);
368
369 if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
370 return false;
371
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000372 if (DGV && !GV.hasLocalLinkage() && !GV.hasAppendingLinkage()) {
373 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
374 auto *SGVar = dyn_cast<GlobalVariable>(&GV);
375 if (DGVar && SGVar) {
376 if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
377 (!DGVar->isConstant() || !SGVar->isConstant())) {
378 DGVar->setConstant(false);
379 SGVar->setConstant(false);
380 }
381 if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
382 unsigned Align = std::max(DGVar->getAlignment(), SGVar->getAlignment());
383 SGVar->setAlignment(Align);
384 DGVar->setAlignment(Align);
385 }
386 }
387
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000388 GlobalValue::VisibilityTypes Visibility =
389 getMinVisibility(DGV->getVisibility(), GV.getVisibility());
390 DGV->setVisibility(Visibility);
391 GV.setVisibility(Visibility);
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000392
393 bool HasUnnamedAddr = GV.hasUnnamedAddr() && DGV->hasUnnamedAddr();
394 DGV->setUnnamedAddr(HasUnnamedAddr);
395 GV.setUnnamedAddr(HasUnnamedAddr);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000396 }
397
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000398 // Don't want to append to global_ctors list, for example, when we
399 // are importing for ThinLTO, otherwise the global ctors and dtors
400 // get executed multiple times for local variables (the latter causing
401 // double frees).
402 if (GV.hasAppendingLinkage() && isPerformingImport())
403 return false;
404
Mehdi Amini8d051852016-03-19 00:40:31 +0000405 if (isPerformingImport()) {
406 if (!doImportAsDefinition(&GV))
407 return false;
408 } else if (!DGV && !shouldOverrideFromSrc() &&
409 (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
410 GV.hasAvailableExternallyLinkage()))
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000411 return false;
412
Rafael Espindolabd03c502015-12-07 16:31:41 +0000413 if (GV.isDeclaration())
414 return false;
415
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000416 if (const Comdat *SC = GV.getComdat()) {
417 bool LinkFromSrc;
418 Comdat::SelectionKind SK;
419 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000420 if (LinkFromSrc)
421 ValuesToLink.insert(&GV);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000422 return false;
423 }
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000424
425 bool LinkFromSrc = true;
426 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
427 return true;
428 if (LinkFromSrc)
429 ValuesToLink.insert(&GV);
430 return false;
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000431}
432
Rafael Espindolacaabe222015-12-10 14:19:35 +0000433void ModuleLinker::addLazyFor(GlobalValue &GV, IRMover::ValueAdder Add) {
434 // Add these to the internalize list
435 if (!GV.hasLinkOnceLinkage())
436 return;
437
438 if (shouldInternalizeLinkedSymbols())
439 Internalize.insert(GV.getName());
440 Add(GV);
441
442 const Comdat *SC = GV.getComdat();
443 if (!SC)
444 return;
445 for (GlobalValue *GV2 : ComdatMembers[SC]) {
446 if (!GV2->hasLocalLinkage() && shouldInternalizeLinkedSymbols())
447 Internalize.insert(GV2->getName());
448 Add(*GV2);
449 }
450}
451
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000452bool ModuleLinker::run() {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000453 for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
David Majnemerdad0a642014-06-27 18:19:56 +0000454 const Comdat &C = SMEC.getValue();
455 if (ComdatsChosen.count(&C))
456 continue;
457 Comdat::SelectionKind SK;
458 bool LinkFromSrc;
459 if (getComdatResult(&C, SK, LinkFromSrc))
460 return true;
461 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
462 }
463
Rafael Espindola40358fb2016-02-16 18:50:12 +0000464 for (GlobalVariable &GV : SrcM->globals())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000465 if (const Comdat *SC = GV.getComdat())
466 ComdatMembers[SC].push_back(&GV);
467
Rafael Espindola40358fb2016-02-16 18:50:12 +0000468 for (Function &SF : *SrcM)
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000469 if (const Comdat *SC = SF.getComdat())
470 ComdatMembers[SC].push_back(&SF);
471
Rafael Espindola40358fb2016-02-16 18:50:12 +0000472 for (GlobalAlias &GA : SrcM->aliases())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000473 if (const Comdat *SC = GA.getComdat())
474 ComdatMembers[SC].push_back(&GA);
475
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000476 // Insert all of the globals in src into the DstM module... without linking
477 // initializers (which could refer to functions not yet mapped over).
Rafael Espindola40358fb2016-02-16 18:50:12 +0000478 for (GlobalVariable &GV : SrcM->globals())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000479 if (linkIfNeeded(GV))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000480 return true;
481
Rafael Espindola40358fb2016-02-16 18:50:12 +0000482 for (Function &SF : *SrcM)
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000483 if (linkIfNeeded(SF))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000484 return true;
485
Rafael Espindola40358fb2016-02-16 18:50:12 +0000486 for (GlobalAlias &GA : SrcM->aliases())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000487 if (linkIfNeeded(GA))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000488 return true;
489
Rafael Espindolacaabe222015-12-10 14:19:35 +0000490 for (unsigned I = 0; I < ValuesToLink.size(); ++I) {
491 GlobalValue *GV = ValuesToLink[I];
492 const Comdat *SC = GV->getComdat();
493 if (!SC)
494 continue;
495 for (GlobalValue *GV2 : ComdatMembers[SC])
496 ValuesToLink.insert(GV2);
Rafael Espindolabeadd562014-12-08 18:05:48 +0000497 }
498
Rafael Espindolacaabe222015-12-10 14:19:35 +0000499 if (shouldInternalizeLinkedSymbols()) {
500 for (GlobalValue *GV : ValuesToLink)
501 Internalize.insert(GV->getName());
502 }
Teresa Johnson10632932015-11-06 17:50:53 +0000503
Rafael Espindola40358fb2016-02-16 18:50:12 +0000504 if (Mover.move(std::move(SrcM), ValuesToLink.getArrayRef(),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000505 [this](GlobalValue &GV, IRMover::ValueAdder Add) {
506 addLazyFor(GV, Add);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000507 },
508 ValIDToTempMDMap, false))
Teresa Johnson189b2522015-11-06 17:50:48 +0000509 return true;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000510 Module &DstM = Mover.getModule();
511 for (auto &P : Internalize) {
512 GlobalValue *GV = DstM.getNamedValue(P.first());
513 GV->setLinkage(GlobalValue::InternalLinkage);
514 }
Teresa Johnson189b2522015-11-06 17:50:48 +0000515
Anton Korobeynikov26098882008-03-05 23:21:39 +0000516 return false;
517}
Reid Spencer361e5132004-11-12 20:37:43 +0000518
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000519Linker::Linker(Module &M) : Mover(M) {}
Rafael Espindola3df61b72013-05-04 03:48:37 +0000520
Rafael Espindola434e9562015-12-16 23:16:33 +0000521bool Linker::linkInModule(std::unique_ptr<Module> Src, unsigned Flags,
Mehdi Amini8d051852016-03-19 00:40:31 +0000522 DenseSet<const GlobalValue *> *GlobalsToImport,
Teresa Johnsone5a61912015-12-17 17:14:09 +0000523 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap) {
Mehdi Amini8d051852016-03-19 00:40:31 +0000524 ModuleLinker ModLinker(Mover, std::move(Src), Flags, GlobalsToImport,
Teresa Johnsone5a61912015-12-17 17:14:09 +0000525 ValIDToTempMDMap);
Teresa Johnsonbef54362015-12-18 19:28:59 +0000526 return ModLinker.run();
Rafael Espindola434e9562015-12-16 23:16:33 +0000527}
528
Rafael Espindola40358fb2016-02-16 18:50:12 +0000529bool Linker::linkInMetadata(std::unique_ptr<Module> Src,
Teresa Johnsone5a61912015-12-17 17:14:09 +0000530 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap) {
531 SetVector<GlobalValue *> ValuesToLink;
532 if (Mover.move(
Rafael Espindola40358fb2016-02-16 18:50:12 +0000533 std::move(Src), ValuesToLink.getArrayRef(),
Teresa Johnsone5a61912015-12-17 17:14:09 +0000534 [this](GlobalValue &GV, IRMover::ValueAdder Add) { assert(false); },
535 ValIDToTempMDMap, true))
536 return true;
537 return false;
538}
539
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000540//===----------------------------------------------------------------------===//
541// LinkModules entrypoint.
542//===----------------------------------------------------------------------===//
543
Rafael Espindola18c89412014-10-27 02:35:46 +0000544/// This function links two modules together, with the resulting Dest module
545/// modified to be the composite of the two input modules. If an error occurs,
546/// true is returned and ErrorMsg (if not null) is set to indicate the problem.
547/// Upon failure, the Dest module could be in a modified state, and shouldn't be
548/// relied on to be consistent.
Rafael Espindola434e9562015-12-16 23:16:33 +0000549bool Linker::linkModules(Module &Dest, std::unique_ptr<Module> Src,
550 unsigned Flags) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000551 Linker L(Dest);
Rafael Espindola434e9562015-12-16 23:16:33 +0000552 return L.linkInModule(std::move(Src), Flags);
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000553}
554
Bill Wendlinga3aeb982012-05-09 08:55:40 +0000555//===----------------------------------------------------------------------===//
556// C API.
557//===----------------------------------------------------------------------===//
558
Rafael Espindola434e9562015-12-16 23:16:33 +0000559LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src) {
560 Module *D = unwrap(Dest);
561 std::unique_ptr<Module> M(unwrap(Src));
562 return Linker::linkModules(*D, std::move(M));
563}