blob: 9de3be412d757443c654c6f8a3fe4f69fbb4cfb8 [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
Chandler Carruth6cc07df2014-03-06 03:42:23 +000014#include "llvm/Linker/Linker.h"
Rafael Espindolacaabe222015-12-10 14:19:35 +000015#include "LinkDiagnosticInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm-c/Linker.h"
Bill Wendling66f02412012-02-11 11:38:06 +000017#include "llvm/ADT/SetVector.h"
Rafael Espindolacaabe222015-12-10 14:19:35 +000018#include "llvm/ADT/StringSet.h"
Rafael Espindolad12b4a32014-10-25 04:06:10 +000019#include "llvm/IR/DiagnosticPrinter.h"
Rafael Espindola9d2bfc42015-12-14 23:17:03 +000020#include "llvm/IR/LLVMContext.h"
Reid Spencer361e5132004-11-12 20:37:43 +000021using namespace llvm;
22
Chris Lattnereee6f992008-06-16 21:00:18 +000023namespace {
Rafael Espindolac84f6082014-11-25 06:11:24 +000024
25/// This is an implementation class for the LinkModules function, which is the
26/// entrypoint for this file.
27class ModuleLinker {
Rafael Espindolacaabe222015-12-10 14:19:35 +000028 IRMover &Mover;
Rafael Espindola0e309fe2015-12-01 19:50:54 +000029 Module &SrcM;
Rafael Espindolac84f6082014-11-25 06:11:24 +000030
Rafael Espindola4b5ec262015-12-02 22:59:04 +000031 SetVector<GlobalValue *> ValuesToLink;
Rafael Espindolacaabe222015-12-10 14:19:35 +000032 StringSet<> Internalize;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000033
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +000034 /// For symbol clashes, prefer those from Src.
Artem Belevich020d4fb2015-09-01 17:55:55 +000035 unsigned Flags;
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +000036
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000037 /// Function index passed into ModuleLinker for using in function
38 /// importing/exporting handling.
Mehdi Amini8220e8a2015-11-23 01:59:16 +000039 const FunctionInfoIndex *ImportIndex;
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000040
Teresa Johnson4f04d852015-12-21 17:33:24 +000041 /// Functions to import from source module, all other functions are
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000042 /// imported as declarations instead of definitions.
Teresa Johnson4f04d852015-12-21 17:33:24 +000043 DenseSet<const GlobalValue *> *FunctionsToImport;
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000044
45 /// Set to true if the given FunctionInfoIndex contains any functions
46 /// from this source module, in which case we must conservatively assume
47 /// that any of its functions may be imported into another module
48 /// as part of a different backend compilation process.
Rafael Espindolaaf714762015-12-01 23:06:26 +000049 bool HasExportedFunctions = false;
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000050
Teresa Johnsone5a61912015-12-17 17:14:09 +000051 /// Association between metadata value id and temporary metadata that
52 /// remains unmapped after function importing. Saved during function
53 /// importing and consumed during the metadata linking postpass.
54 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap;
55
Rafael Espindolacaabe222015-12-10 14:19:35 +000056 /// Used as the callback for lazy linking.
57 /// The mover has just hit GV and we have to decide if it, and other members
58 /// of the same comdat, should be linked. Every member to be linked is passed
59 /// to Add.
60 void addLazyFor(GlobalValue &GV, IRMover::ValueAdder Add);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +000061
Artem Belevich020d4fb2015-09-01 17:55:55 +000062 bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
63 bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
64 bool shouldInternalizeLinkedSymbols() {
65 return Flags & Linker::InternalizeLinkedSymbols;
66 }
67
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +000068 /// Check if we should promote the given local value to global scope.
69 bool doPromoteLocalToGlobal(const GlobalValue *SGV);
70
Rafael Espindolac84f6082014-11-25 06:11:24 +000071 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
72 const GlobalValue &Src);
Rafael Espindolaed6dc372014-05-09 14:39:25 +000073
Rafael Espindolacaabe222015-12-10 14:19:35 +000074 /// Should we have mover and linker error diag info?
Rafael Espindolac84f6082014-11-25 06:11:24 +000075 bool emitError(const Twine &Message) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +000076 SrcM.getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
Rafael Espindolac84f6082014-11-25 06:11:24 +000077 return true;
78 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +000079
Rafael Espindola0e309fe2015-12-01 19:50:54 +000080 bool getComdatLeader(Module &M, StringRef ComdatName,
Rafael Espindolac84f6082014-11-25 06:11:24 +000081 const GlobalVariable *&GVar);
82 bool computeResultingSelectionKind(StringRef ComdatName,
83 Comdat::SelectionKind Src,
84 Comdat::SelectionKind Dst,
85 Comdat::SelectionKind &Result,
86 bool &LinkFromSrc);
87 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
88 ComdatsChosen;
89 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
90 bool &LinkFromSrc);
Teresa Johnson2d5fb8c2015-11-10 21:09:06 +000091 // Keep track of the global value members of each comdat in source.
92 DenseMap<const Comdat *, std::vector<GlobalValue *>> ComdatMembers;
Rafael Espindola4160f5d2014-10-27 23:02:10 +000093
Rafael Espindolac84f6082014-11-25 06:11:24 +000094 /// Given a global in the source module, return the global in the
95 /// destination module that is being linked to, if any.
96 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
Rafael Espindolacaabe222015-12-10 14:19:35 +000097 Module &DstM = Mover.getModule();
Rafael Espindolac84f6082014-11-25 06:11:24 +000098 // If the source has no name it can't link. If it has local linkage,
99 // there is no name match-up going on.
Teresa Johnsonb098f0c2015-11-24 19:46:58 +0000100 if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(getLinkage(SrcGV)))
Rafael Espindolac84f6082014-11-25 06:11:24 +0000101 return nullptr;
Eli Bendersky7da92ed2014-02-20 22:19:24 +0000102
Rafael Espindolac84f6082014-11-25 06:11:24 +0000103 // Otherwise see if we have a match in the destination module's symtab.
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000104 GlobalValue *DGV = DstM.getNamedValue(getName(SrcGV));
Rafael Espindolac84f6082014-11-25 06:11:24 +0000105 if (!DGV)
106 return nullptr;
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000107
Rafael Espindolac84f6082014-11-25 06:11:24 +0000108 // If we found a global with the same name in the dest module, but it has
109 // internal linkage, we are really not doing any linkage here.
110 if (DGV->hasLocalLinkage())
111 return nullptr;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000112
Rafael Espindolac84f6082014-11-25 06:11:24 +0000113 // Otherwise, we do in fact link to the destination global.
114 return DGV;
115 }
Rafael Espindolaed6dc372014-05-09 14:39:25 +0000116
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000117 bool linkIfNeeded(GlobalValue &GV);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000118
119 /// Helper methods to check if we are importing from or potentially
120 /// exporting from the current source module.
Teresa Johnson4f04d852015-12-21 17:33:24 +0000121 bool isPerformingImport() const { return FunctionsToImport != nullptr; }
Teresa Johnson4a9bf582015-12-17 16:34:53 +0000122 bool isModuleExporting() const { return HasExportedFunctions; }
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000123
124 /// If we are importing from the source module, checks if we should
125 /// import SGV as a definition, otherwise import as a declaration.
126 bool doImportAsDefinition(const GlobalValue *SGV);
127
128 /// Get the name for SGV that should be used in the linked destination
129 /// module. Specifically, this handles the case where we need to rename
130 /// a local that is being promoted to global scope.
131 std::string getName(const GlobalValue *SGV);
132
Rafael Espindolacaabe222015-12-10 14:19:35 +0000133 /// Process globals so that they can be used in ThinLTO. This includes
134 /// promoting local variables so that they can be reference externally by
135 /// thin lto imported globals and converting strong external globals to
136 /// available_externally.
137 void processGlobalsForThinLTO();
138 void processGlobalForThinLTO(GlobalValue &GV);
139
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000140 /// Get the new linkage for SGV that should be used in the linked destination
141 /// module. Specifically, for ThinLTO importing or exporting it may need
142 /// to be adjusted.
143 GlobalValue::LinkageTypes getLinkage(const GlobalValue *SGV);
144
Rafael Espindolad57f9f02015-12-08 14:54:49 +0000145public:
Rafael Espindolacaabe222015-12-10 14:19:35 +0000146 ModuleLinker(IRMover &Mover, Module &SrcM, unsigned Flags,
Rafael Espindolad57f9f02015-12-08 14:54:49 +0000147 const FunctionInfoIndex *Index = nullptr,
Teresa Johnsone5a61912015-12-17 17:14:09 +0000148 DenseSet<const GlobalValue *> *FunctionsToImport = nullptr,
149 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap = nullptr)
Rafael Espindolacaabe222015-12-10 14:19:35 +0000150 : Mover(Mover), SrcM(SrcM), Flags(Flags), ImportIndex(Index),
Teresa Johnson4f04d852015-12-21 17:33:24 +0000151 FunctionsToImport(FunctionsToImport),
152 ValIDToTempMDMap(ValIDToTempMDMap) {
153 assert((ImportIndex || !FunctionsToImport) &&
Rafael Espindolad57f9f02015-12-08 14:54:49 +0000154 "Expect a FunctionInfoIndex when importing");
155 // If we have a FunctionInfoIndex but no function to import,
156 // then this is the primary module being compiled in a ThinLTO
157 // backend compilation, and we need to see if it has functions that
158 // may be exported to another backend compilation.
Teresa Johnson4f04d852015-12-21 17:33:24 +0000159 if (ImportIndex && !FunctionsToImport)
Rafael Espindolad57f9f02015-12-08 14:54:49 +0000160 HasExportedFunctions = ImportIndex->hasExportedFunctions(SrcM);
Teresa Johnson4f04d852015-12-21 17:33:24 +0000161 assert((ValIDToTempMDMap || !FunctionsToImport) &&
Teresa Johnsone5a61912015-12-17 17:14:09 +0000162 "Function importing must provide a ValIDToTempMDMap");
Rafael Espindolad57f9f02015-12-08 14:54:49 +0000163 }
164
165 bool run();
Rafael Espindolac84f6082014-11-25 06:11:24 +0000166};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000167}
Bill Wendlingd48b7782012-02-28 04:01:21 +0000168
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000169bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
170 if (!isPerformingImport())
171 return false;
Teresa Johnson3cd81612015-11-10 18:20:11 +0000172 auto *GA = dyn_cast<GlobalAlias>(SGV);
173 if (GA) {
174 if (GA->hasWeakAnyLinkage())
175 return false;
Rafael Espindola89345772015-11-26 19:22:59 +0000176 const GlobalObject *GO = GA->getBaseObject();
177 if (!GO->hasLinkOnceODRLinkage())
178 return false;
179 return doImportAsDefinition(GO);
Teresa Johnson3cd81612015-11-10 18:20:11 +0000180 }
Teresa Johnsondfbebc32015-11-10 18:26:31 +0000181 // Always import GlobalVariable definitions, except for the special
182 // case of WeakAny which are imported as ExternalWeak declarations
183 // (see comments in ModuleLinker::getLinkage). The linkage changes
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000184 // described in ModuleLinker::getLinkage ensure the correct behavior (e.g.
185 // global variables with external linkage are transformed to
Teresa Johnson3cd81612015-11-10 18:20:11 +0000186 // available_externally definitions, which are ultimately turned into
187 // declarations after the EliminateAvailableExternally pass).
Craig Topper66059c92015-11-18 07:07:59 +0000188 if (isa<GlobalVariable>(SGV) && !SGV->isDeclaration() &&
Teresa Johnson3cd81612015-11-10 18:20:11 +0000189 !SGV->hasWeakAnyLinkage())
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000190 return true;
191 // Only import the function requested for importing.
192 auto *SF = dyn_cast<Function>(SGV);
Teresa Johnson4f04d852015-12-21 17:33:24 +0000193 if (SF && FunctionsToImport->count(SF))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000194 return true;
195 // Otherwise no.
196 return false;
197}
198
199bool ModuleLinker::doPromoteLocalToGlobal(const GlobalValue *SGV) {
200 assert(SGV->hasLocalLinkage());
201 // Both the imported references and the original local variable must
202 // be promoted.
203 if (!isPerformingImport() && !isModuleExporting())
204 return false;
205
206 // Local const variables never need to be promoted unless they are address
207 // taken. The imported uses can simply use the clone created in this module.
208 // For now we are conservative in determining which variables are not
209 // address taken by checking the unnamed addr flag. To be more aggressive,
210 // the address taken information must be checked earlier during parsing
211 // of the module and recorded in the function index for use when importing
212 // from that module.
213 auto *GVar = dyn_cast<GlobalVariable>(SGV);
214 if (GVar && GVar->isConstant() && GVar->hasUnnamedAddr())
215 return false;
216
217 // Eventually we only need to promote functions in the exporting module that
218 // are referenced by a potentially exported function (i.e. one that is in the
219 // function index).
220 return true;
221}
222
223std::string ModuleLinker::getName(const GlobalValue *SGV) {
224 // For locals that must be promoted to global scope, ensure that
225 // the promoted name uniquely identifies the copy in the original module,
226 // using the ID assigned during combined index creation. When importing,
227 // we rename all locals (not just those that are promoted) in order to
228 // avoid naming conflicts between locals imported from different modules.
229 if (SGV->hasLocalLinkage() &&
230 (doPromoteLocalToGlobal(SGV) || isPerformingImport()))
231 return FunctionInfoIndex::getGlobalNameForLocal(
232 SGV->getName(),
233 ImportIndex->getModuleId(SGV->getParent()->getModuleIdentifier()));
234 return SGV->getName();
235}
236
237GlobalValue::LinkageTypes ModuleLinker::getLinkage(const GlobalValue *SGV) {
238 // Any local variable that is referenced by an exported function needs
239 // to be promoted to global scope. Since we don't currently know which
240 // functions reference which local variables/functions, we must treat
241 // all as potentially exported if this module is exporting anything.
242 if (isModuleExporting()) {
243 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
244 return GlobalValue::ExternalLinkage;
245 return SGV->getLinkage();
246 }
247
248 // Otherwise, if we aren't importing, no linkage change is needed.
249 if (!isPerformingImport())
250 return SGV->getLinkage();
251
252 switch (SGV->getLinkage()) {
253 case GlobalValue::ExternalLinkage:
254 // External defnitions are converted to available_externally
255 // definitions upon import, so that they are available for inlining
256 // and/or optimization, but are turned into declarations later
257 // during the EliminateAvailableExternally pass.
Teresa Johnson3cd81612015-11-10 18:20:11 +0000258 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000259 return GlobalValue::AvailableExternallyLinkage;
260 // An imported external declaration stays external.
261 return SGV->getLinkage();
262
263 case GlobalValue::AvailableExternallyLinkage:
264 // An imported available_externally definition converts
265 // to external if imported as a declaration.
266 if (!doImportAsDefinition(SGV))
267 return GlobalValue::ExternalLinkage;
268 // An imported available_externally declaration stays that way.
269 return SGV->getLinkage();
270
271 case GlobalValue::LinkOnceAnyLinkage:
272 case GlobalValue::LinkOnceODRLinkage:
273 // These both stay the same when importing the definition.
274 // The ThinLTO pass will eventually force-import their definitions.
275 return SGV->getLinkage();
276
277 case GlobalValue::WeakAnyLinkage:
278 // Can't import weak_any definitions correctly, or we might change the
279 // program semantics, since the linker will pick the first weak_any
280 // definition and importing would change the order they are seen by the
281 // linker. The module linking caller needs to enforce this.
282 assert(!doImportAsDefinition(SGV));
283 // If imported as a declaration, it becomes external_weak.
284 return GlobalValue::ExternalWeakLinkage;
285
286 case GlobalValue::WeakODRLinkage:
287 // For weak_odr linkage, there is a guarantee that all copies will be
288 // equivalent, so the issue described above for weak_any does not exist,
289 // and the definition can be imported. It can be treated similarly
290 // to an imported externally visible global value.
Teresa Johnson3cd81612015-11-10 18:20:11 +0000291 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000292 return GlobalValue::AvailableExternallyLinkage;
293 else
294 return GlobalValue::ExternalLinkage;
295
296 case GlobalValue::AppendingLinkage:
297 // It would be incorrect to import an appending linkage variable,
298 // since it would cause global constructors/destructors to be
299 // executed multiple times. This should have already been handled
Teresa Johnson1e20a652015-12-03 18:20:05 +0000300 // by linkIfNeeded, and we will assert in shouldLinkFromSource
301 // if we try to import, so we simply return AppendingLinkage here
302 // as this helper is called more widely in getLinkedToGlobal.
303 return GlobalValue::AppendingLinkage;
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000304
305 case GlobalValue::InternalLinkage:
306 case GlobalValue::PrivateLinkage:
307 // If we are promoting the local to global scope, it is handled
308 // similarly to a normal externally visible global.
309 if (doPromoteLocalToGlobal(SGV)) {
Teresa Johnson3cd81612015-11-10 18:20:11 +0000310 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000311 return GlobalValue::AvailableExternallyLinkage;
312 else
313 return GlobalValue::ExternalLinkage;
314 }
315 // A non-promoted imported local definition stays local.
316 // The ThinLTO pass will eventually force-import their definitions.
317 return SGV->getLinkage();
318
319 case GlobalValue::ExternalWeakLinkage:
320 // External weak doesn't apply to definitions, must be a declaration.
321 assert(!doImportAsDefinition(SGV));
322 // Linkage stays external_weak.
323 return SGV->getLinkage();
324
325 case GlobalValue::CommonLinkage:
326 // Linkage stays common on definitions.
327 // The ThinLTO pass will eventually force-import their definitions.
328 return SGV->getLinkage();
329 }
330
331 llvm_unreachable("unknown linkage type");
332}
333
Rafael Espindolaeb5e0a72015-11-29 14:33:06 +0000334static GlobalValue::VisibilityTypes
335getMinVisibility(GlobalValue::VisibilityTypes A,
336 GlobalValue::VisibilityTypes B) {
337 if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
338 return GlobalValue::HiddenVisibility;
339 if (A == GlobalValue::ProtectedVisibility ||
340 B == GlobalValue::ProtectedVisibility)
341 return GlobalValue::ProtectedVisibility;
342 return GlobalValue::DefaultVisibility;
343}
344
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000345bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
David Majnemerdad0a642014-06-27 18:19:56 +0000346 const GlobalVariable *&GVar) {
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000347 const GlobalValue *GVal = M.getNamedValue(ComdatName);
David Majnemerdad0a642014-06-27 18:19:56 +0000348 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
349 GVal = GA->getBaseObject();
350 if (!GVal)
351 // We cannot resolve the size of the aliasee yet.
352 return emitError("Linking COMDATs named '" + ComdatName +
353 "': COMDAT key involves incomputable alias size.");
354 }
355
356 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
357 if (!GVar)
358 return emitError(
359 "Linking COMDATs named '" + ComdatName +
360 "': GlobalVariable required for data dependent selection!");
361
362 return false;
363}
364
365bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
366 Comdat::SelectionKind Src,
367 Comdat::SelectionKind Dst,
368 Comdat::SelectionKind &Result,
369 bool &LinkFromSrc) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000370 Module &DstM = Mover.getModule();
David Majnemerdad0a642014-06-27 18:19:56 +0000371 // The ability to mix Comdat::SelectionKind::Any with
372 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
373 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
374 Dst == Comdat::SelectionKind::Largest;
375 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
376 Src == Comdat::SelectionKind::Largest;
377 if (DstAnyOrLargest && SrcAnyOrLargest) {
378 if (Dst == Comdat::SelectionKind::Largest ||
379 Src == Comdat::SelectionKind::Largest)
380 Result = Comdat::SelectionKind::Largest;
381 else
382 Result = Comdat::SelectionKind::Any;
383 } else if (Src == Dst) {
384 Result = Dst;
385 } else {
386 return emitError("Linking COMDATs named '" + ComdatName +
387 "': invalid selection kinds!");
388 }
389
390 switch (Result) {
391 case Comdat::SelectionKind::Any:
392 // Go with Dst.
393 LinkFromSrc = false;
394 break;
395 case Comdat::SelectionKind::NoDuplicates:
396 return emitError("Linking COMDATs named '" + ComdatName +
397 "': noduplicates has been violated!");
398 case Comdat::SelectionKind::ExactMatch:
399 case Comdat::SelectionKind::Largest:
400 case Comdat::SelectionKind::SameSize: {
401 const GlobalVariable *DstGV;
402 const GlobalVariable *SrcGV;
403 if (getComdatLeader(DstM, ComdatName, DstGV) ||
404 getComdatLeader(SrcM, ComdatName, SrcGV))
405 return true;
406
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000407 const DataLayout &DstDL = DstM.getDataLayout();
408 const DataLayout &SrcDL = SrcM.getDataLayout();
David Majnemerdad0a642014-06-27 18:19:56 +0000409 uint64_t DstSize =
Mehdi Amini46a43552015-03-04 18:43:29 +0000410 DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
David Majnemerdad0a642014-06-27 18:19:56 +0000411 uint64_t SrcSize =
Mehdi Amini46a43552015-03-04 18:43:29 +0000412 SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
David Majnemerdad0a642014-06-27 18:19:56 +0000413 if (Result == Comdat::SelectionKind::ExactMatch) {
414 if (SrcGV->getInitializer() != DstGV->getInitializer())
415 return emitError("Linking COMDATs named '" + ComdatName +
416 "': ExactMatch violated!");
417 LinkFromSrc = false;
418 } else if (Result == Comdat::SelectionKind::Largest) {
419 LinkFromSrc = SrcSize > DstSize;
420 } else if (Result == Comdat::SelectionKind::SameSize) {
421 if (SrcSize != DstSize)
422 return emitError("Linking COMDATs named '" + ComdatName +
423 "': SameSize violated!");
424 LinkFromSrc = false;
425 } else {
426 llvm_unreachable("unknown selection kind");
427 }
428 break;
429 }
430 }
431
432 return false;
433}
434
435bool ModuleLinker::getComdatResult(const Comdat *SrcC,
436 Comdat::SelectionKind &Result,
437 bool &LinkFromSrc) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000438 Module &DstM = Mover.getModule();
Rafael Espindolab16196a2014-08-11 17:07:34 +0000439 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
David Majnemerdad0a642014-06-27 18:19:56 +0000440 StringRef ComdatName = SrcC->getName();
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000441 Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
David Majnemerdad0a642014-06-27 18:19:56 +0000442 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000443
Rafael Espindolab16196a2014-08-11 17:07:34 +0000444 if (DstCI == ComdatSymTab.end()) {
445 // Use the comdat if it is only available in one of the modules.
446 LinkFromSrc = true;
447 Result = SSK;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000448 return false;
Rafael Espindolab16196a2014-08-11 17:07:34 +0000449 }
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000450
451 const Comdat *DstC = &DstCI->second;
Rafael Espindola2ef3f292014-08-11 16:55:42 +0000452 Comdat::SelectionKind DSK = DstC->getSelectionKind();
453 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
454 LinkFromSrc);
David Majnemerdad0a642014-06-27 18:19:56 +0000455}
James Molloyf6f121e2013-05-28 15:17:05 +0000456
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000457bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
458 const GlobalValue &Dest,
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000459 const GlobalValue &Src) {
Teresa Johnsone5a61912015-12-17 17:14:09 +0000460
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000461 // Should we unconditionally use the Src?
Artem Belevich020d4fb2015-09-01 17:55:55 +0000462 if (shouldOverrideFromSrc()) {
Duncan P. N. Exon Smithe8681232015-04-22 04:11:00 +0000463 LinkFromSrc = true;
464 return false;
465 }
466
Rafael Espindola778fcc72014-11-02 13:28:57 +0000467 // We always have to add Src if it has appending linkage.
468 if (Src.hasAppendingLinkage()) {
Teresa Johnson1e20a652015-12-03 18:20:05 +0000469 // Should have prevented importing for appending linkage in linkIfNeeded.
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000470 assert(!isPerformingImport());
Rafael Espindola778fcc72014-11-02 13:28:57 +0000471 LinkFromSrc = true;
472 return false;
473 }
474
Rafael Espindolad4bcefc2014-10-24 18:13:04 +0000475 bool SrcIsDeclaration = Src.isDeclarationForLinker();
476 bool DestIsDeclaration = Dest.isDeclarationForLinker();
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000477
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000478 if (isPerformingImport()) {
479 if (isa<Function>(&Src)) {
Teresa Johnson4f04d852015-12-21 17:33:24 +0000480 // For functions, LinkFromSrc iff this is a function requested
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000481 // for importing. For variables, decide below normally.
Teresa Johnson4f04d852015-12-21 17:33:24 +0000482 LinkFromSrc = FunctionsToImport->count(&Src);
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +0000483 return false;
484 }
485
486 // Check if this is an alias with an already existing definition
487 // in Dest, which must have come from a prior importing pass from
488 // the same Src module. Unlike imported function and variable
489 // definitions, which are imported as available_externally and are
490 // not definitions for the linker, that is not a valid linkage for
491 // imported aliases which must be definitions. Simply use the existing
492 // Dest copy.
493 if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
494 assert(isa<GlobalAlias>(&Dest));
495 LinkFromSrc = false;
496 return false;
497 }
498 }
499
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000500 if (SrcIsDeclaration) {
501 // If Src is external or if both Src & Dest are external.. Just link the
502 // external globals, we aren't adding anything.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000503 if (Src.hasDLLImportStorageClass()) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000504 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000505 LinkFromSrc = DestIsDeclaration;
506 return false;
507 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000508 // If the Dest is weak, use the source linkage.
Rafael Espindolaed11bd22015-12-09 22:44:00 +0000509 if (Dest.hasExternalWeakLinkage()) {
510 LinkFromSrc = true;
511 return false;
512 }
513 // Link an available_externally over a declaration.
514 LinkFromSrc = !Src.isDeclaration() && Dest.isDeclaration();
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000515 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000516 }
517
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000518 if (DestIsDeclaration) {
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000519 // If Dest is external but Src is not:
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000520 LinkFromSrc = true;
521 return false;
522 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000523
Rafael Espindola09106052014-09-09 15:59:12 +0000524 if (Src.hasCommonLinkage()) {
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000525 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
526 LinkFromSrc = true;
Rafael Espindola09106052014-09-09 15:59:12 +0000527 return false;
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000528 }
529
530 if (!Dest.hasCommonLinkage()) {
531 LinkFromSrc = false;
532 return false;
533 }
Rafael Espindola09106052014-09-09 15:59:12 +0000534
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000535 const DataLayout &DL = Dest.getParent()->getDataLayout();
Rafael Espindola09106052014-09-09 15:59:12 +0000536 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
537 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000538 LinkFromSrc = SrcSize > DestSize;
539 return false;
Rafael Espindola09106052014-09-09 15:59:12 +0000540 }
541
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000542 if (Src.isWeakForLinker()) {
543 assert(!Dest.hasExternalWeakLinkage());
544 assert(!Dest.hasAvailableExternallyLinkage());
Rafael Espindola09106052014-09-09 15:59:12 +0000545
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000546 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
547 LinkFromSrc = true;
548 return false;
549 }
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000550
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000551 LinkFromSrc = false;
Rafael Espindola09106052014-09-09 15:59:12 +0000552 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000553 }
554
555 if (Dest.isWeakForLinker()) {
556 assert(Src.hasExternalLinkage());
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000557 LinkFromSrc = true;
558 return false;
Rafael Espindoladbb0bd12014-09-09 15:21:00 +0000559 }
560
561 assert(!Src.hasExternalWeakLinkage());
562 assert(!Dest.hasExternalWeakLinkage());
563 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
564 "Unexpected linkage type!");
565 return emitError("Linking globals named '" + Src.getName() +
566 "': symbol multiply defined!");
567}
568
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000569bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
570 GlobalValue *DGV = getLinkedToGlobal(&GV);
571
572 if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
573 return false;
574
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000575 if (DGV && !GV.hasLocalLinkage() && !GV.hasAppendingLinkage()) {
576 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
577 auto *SGVar = dyn_cast<GlobalVariable>(&GV);
578 if (DGVar && SGVar) {
579 if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
580 (!DGVar->isConstant() || !SGVar->isConstant())) {
581 DGVar->setConstant(false);
582 SGVar->setConstant(false);
583 }
584 if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
585 unsigned Align = std::max(DGVar->getAlignment(), SGVar->getAlignment());
586 SGVar->setAlignment(Align);
587 DGVar->setAlignment(Align);
588 }
589 }
590
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000591 GlobalValue::VisibilityTypes Visibility =
592 getMinVisibility(DGV->getVisibility(), GV.getVisibility());
593 DGV->setVisibility(Visibility);
594 GV.setVisibility(Visibility);
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000595
596 bool HasUnnamedAddr = GV.hasUnnamedAddr() && DGV->hasUnnamedAddr();
597 DGV->setUnnamedAddr(HasUnnamedAddr);
598 GV.setUnnamedAddr(HasUnnamedAddr);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000599 }
600
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000601 // Don't want to append to global_ctors list, for example, when we
602 // are importing for ThinLTO, otherwise the global ctors and dtors
603 // get executed multiple times for local variables (the latter causing
604 // double frees).
605 if (GV.hasAppendingLinkage() && isPerformingImport())
606 return false;
607
608 if (isPerformingImport() && !doImportAsDefinition(&GV))
609 return false;
610
611 if (!DGV && !shouldOverrideFromSrc() &&
612 (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
613 GV.hasAvailableExternallyLinkage()))
614 return false;
615
Rafael Espindolabd03c502015-12-07 16:31:41 +0000616 if (GV.isDeclaration())
617 return false;
618
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000619 if (const Comdat *SC = GV.getComdat()) {
620 bool LinkFromSrc;
621 Comdat::SelectionKind SK;
622 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000623 if (LinkFromSrc)
624 ValuesToLink.insert(&GV);
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000625 return false;
626 }
Rafael Espindola4b5ec262015-12-02 22:59:04 +0000627
628 bool LinkFromSrc = true;
629 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
630 return true;
631 if (LinkFromSrc)
632 ValuesToLink.insert(&GV);
633 return false;
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000634}
635
Rafael Espindolacaabe222015-12-10 14:19:35 +0000636void ModuleLinker::addLazyFor(GlobalValue &GV, IRMover::ValueAdder Add) {
637 // Add these to the internalize list
638 if (!GV.hasLinkOnceLinkage())
639 return;
640
641 if (shouldInternalizeLinkedSymbols())
642 Internalize.insert(GV.getName());
643 Add(GV);
644
645 const Comdat *SC = GV.getComdat();
646 if (!SC)
647 return;
648 for (GlobalValue *GV2 : ComdatMembers[SC]) {
649 if (!GV2->hasLocalLinkage() && shouldInternalizeLinkedSymbols())
650 Internalize.insert(GV2->getName());
651 Add(*GV2);
652 }
653}
654
655void ModuleLinker::processGlobalForThinLTO(GlobalValue &GV) {
656 if (GV.hasLocalLinkage() &&
657 (doPromoteLocalToGlobal(&GV) || isPerformingImport())) {
658 GV.setName(getName(&GV));
659 GV.setLinkage(getLinkage(&GV));
660 if (!GV.hasLocalLinkage())
661 GV.setVisibility(GlobalValue::HiddenVisibility);
662 if (isModuleExporting())
663 ValuesToLink.insert(&GV);
664 return;
665 }
666 GV.setLinkage(getLinkage(&GV));
667}
668
669void ModuleLinker::processGlobalsForThinLTO() {
670 for (GlobalVariable &GV : SrcM.globals())
671 processGlobalForThinLTO(GV);
672 for (Function &SF : SrcM)
673 processGlobalForThinLTO(SF);
674 for (GlobalAlias &GA : SrcM.aliases())
675 processGlobalForThinLTO(GA);
676}
677
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000678bool ModuleLinker::run() {
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000679 for (const auto &SMEC : SrcM.getComdatSymbolTable()) {
David Majnemerdad0a642014-06-27 18:19:56 +0000680 const Comdat &C = SMEC.getValue();
681 if (ComdatsChosen.count(&C))
682 continue;
683 Comdat::SelectionKind SK;
684 bool LinkFromSrc;
685 if (getComdatResult(&C, SK, LinkFromSrc))
686 return true;
687 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
688 }
689
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000690 for (GlobalVariable &GV : SrcM.globals())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000691 if (const Comdat *SC = GV.getComdat())
692 ComdatMembers[SC].push_back(&GV);
693
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000694 for (Function &SF : SrcM)
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000695 if (const Comdat *SC = SF.getComdat())
696 ComdatMembers[SC].push_back(&SF);
697
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000698 for (GlobalAlias &GA : SrcM.aliases())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000699 if (const Comdat *SC = GA.getComdat())
700 ComdatMembers[SC].push_back(&GA);
701
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000702 // Insert all of the globals in src into the DstM module... without linking
703 // initializers (which could refer to functions not yet mapped over).
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000704 for (GlobalVariable &GV : SrcM.globals())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000705 if (linkIfNeeded(GV))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000706 return true;
707
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000708 for (Function &SF : SrcM)
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000709 if (linkIfNeeded(SF))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000710 return true;
711
Rafael Espindola0e309fe2015-12-01 19:50:54 +0000712 for (GlobalAlias &GA : SrcM.aliases())
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000713 if (linkIfNeeded(GA))
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000714 return true;
715
Rafael Espindolacaabe222015-12-10 14:19:35 +0000716 processGlobalsForThinLTO();
717
718 for (unsigned I = 0; I < ValuesToLink.size(); ++I) {
719 GlobalValue *GV = ValuesToLink[I];
720 const Comdat *SC = GV->getComdat();
721 if (!SC)
722 continue;
723 for (GlobalValue *GV2 : ComdatMembers[SC])
724 ValuesToLink.insert(GV2);
Rafael Espindolabeadd562014-12-08 18:05:48 +0000725 }
726
Rafael Espindolacaabe222015-12-10 14:19:35 +0000727 if (shouldInternalizeLinkedSymbols()) {
728 for (GlobalValue *GV : ValuesToLink)
729 Internalize.insert(GV->getName());
730 }
Teresa Johnson10632932015-11-06 17:50:53 +0000731
Rafael Espindolaf81c7b02015-12-10 16:35:06 +0000732 if (Mover.move(SrcM, ValuesToLink.getArrayRef(),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000733 [this](GlobalValue &GV, IRMover::ValueAdder Add) {
734 addLazyFor(GV, Add);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000735 },
736 ValIDToTempMDMap, false))
Teresa Johnson189b2522015-11-06 17:50:48 +0000737 return true;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000738 Module &DstM = Mover.getModule();
739 for (auto &P : Internalize) {
740 GlobalValue *GV = DstM.getNamedValue(P.first());
741 GV->setLinkage(GlobalValue::InternalLinkage);
742 }
Teresa Johnson189b2522015-11-06 17:50:48 +0000743
Anton Korobeynikov26098882008-03-05 23:21:39 +0000744 return false;
745}
Reid Spencer361e5132004-11-12 20:37:43 +0000746
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000747Linker::Linker(Module &M) : Mover(M) {}
Rafael Espindola3df61b72013-05-04 03:48:37 +0000748
Rafael Espindola434e9562015-12-16 23:16:33 +0000749bool Linker::linkInModule(std::unique_ptr<Module> Src, unsigned Flags,
Mehdi Amini8220e8a2015-11-23 01:59:16 +0000750 const FunctionInfoIndex *Index,
Teresa Johnsone5a61912015-12-17 17:14:09 +0000751 DenseSet<const GlobalValue *> *FunctionsToImport,
752 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap) {
Teresa Johnsonbef54362015-12-18 19:28:59 +0000753 ModuleLinker ModLinker(Mover, *Src, Flags, Index, FunctionsToImport,
Teresa Johnsone5a61912015-12-17 17:14:09 +0000754 ValIDToTempMDMap);
Teresa Johnsonbef54362015-12-18 19:28:59 +0000755 return ModLinker.run();
Rafael Espindola434e9562015-12-16 23:16:33 +0000756}
757
758bool Linker::linkInModuleForCAPI(Module &Src) {
Teresa Johnsonbef54362015-12-18 19:28:59 +0000759 ModuleLinker ModLinker(Mover, Src, 0, nullptr, nullptr);
760 return ModLinker.run();
Rafael Espindola3df61b72013-05-04 03:48:37 +0000761}
762
Teresa Johnsone5a61912015-12-17 17:14:09 +0000763bool Linker::linkInMetadata(Module &Src,
764 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap) {
765 SetVector<GlobalValue *> ValuesToLink;
766 if (Mover.move(
767 Src, ValuesToLink.getArrayRef(),
768 [this](GlobalValue &GV, IRMover::ValueAdder Add) { assert(false); },
769 ValIDToTempMDMap, true))
770 return true;
771 return false;
772}
773
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000774//===----------------------------------------------------------------------===//
775// LinkModules entrypoint.
776//===----------------------------------------------------------------------===//
777
Rafael Espindola18c89412014-10-27 02:35:46 +0000778/// This function links two modules together, with the resulting Dest module
779/// modified to be the composite of the two input modules. If an error occurs,
780/// true is returned and ErrorMsg (if not null) is set to indicate the problem.
781/// Upon failure, the Dest module could be in a modified state, and shouldn't be
782/// relied on to be consistent.
Rafael Espindola434e9562015-12-16 23:16:33 +0000783bool Linker::linkModules(Module &Dest, std::unique_ptr<Module> Src,
784 unsigned Flags) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000785 Linker L(Dest);
Rafael Espindola434e9562015-12-16 23:16:33 +0000786 return L.linkInModule(std::move(Src), Flags);
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000787}
788
Teresa Johnsonbae7e752015-12-04 23:40:22 +0000789std::unique_ptr<Module>
Rafael Espindola434e9562015-12-16 23:16:33 +0000790llvm::renameModuleForThinLTO(std::unique_ptr<Module> M,
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000791 const FunctionInfoIndex *Index) {
Teresa Johnsonbae7e752015-12-04 23:40:22 +0000792 std::unique_ptr<llvm::Module> RenamedModule(
793 new llvm::Module(M->getModuleIdentifier(), M->getContext()));
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000794 Linker L(*RenamedModule.get());
Rafael Espindola434e9562015-12-16 23:16:33 +0000795 if (L.linkInModule(std::move(M), llvm::Linker::Flags::None, Index))
Teresa Johnsonbae7e752015-12-04 23:40:22 +0000796 return nullptr;
797 return RenamedModule;
798}
799
Bill Wendlinga3aeb982012-05-09 08:55:40 +0000800//===----------------------------------------------------------------------===//
801// C API.
802//===----------------------------------------------------------------------===//
803
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000804static void diagnosticHandler(const DiagnosticInfo &DI, void *C) {
805 auto *Message = reinterpret_cast<std::string *>(C);
806 raw_string_ostream Stream(*Message);
807 DiagnosticPrinterRawOStream DP(Stream);
808 DI.print(DP);
809}
810
Bill Wendlinga3aeb982012-05-09 08:55:40 +0000811LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
Juergen Ributzkaa57d5882015-03-02 18:59:38 +0000812 LLVMLinkerMode Unused, char **OutMessages) {
Rafael Espindola98ab63c2014-10-25 04:31:08 +0000813 Module *D = unwrap(Dest);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000814 LLVMContext &Ctx = D->getContext();
815
816 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
817 Ctx.getDiagnosticHandler();
818 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
Rafael Espindola98ab63c2014-10-25 04:31:08 +0000819 std::string Message;
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000820 Ctx.setDiagnosticHandler(diagnosticHandler, &Message, true);
Rafael Espindola4160f5d2014-10-27 23:02:10 +0000821
Rafael Espindola434e9562015-12-16 23:16:33 +0000822 Linker L(*D);
823 Module *M = unwrap(Src);
824 LLVMBool Result = L.linkInModuleForCAPI(*M);
Rafael Espindola98ab63c2014-10-25 04:31:08 +0000825
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000826 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext, true);
827
828 if (OutMessages && Result)
Rafael Espindola98ab63c2014-10-25 04:31:08 +0000829 *OutMessages = strdup(Message.c_str());
Bill Wendlinga3aeb982012-05-09 08:55:40 +0000830 return Result;
831}
Rafael Espindola434e9562015-12-16 23:16:33 +0000832
833LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src) {
834 Module *D = unwrap(Dest);
835 std::unique_ptr<Module> M(unwrap(Src));
836 return Linker::linkModules(*D, std::move(M));
837}